ZTWHHH commited on
Commit
e1718c5
·
verified ·
1 Parent(s): 5e719e7

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. evalkit_cambrian/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc-builtins.so.12.1 +3 -0
  3. evalkit_internvl/lib/python3.10/site-packages/aiofiles/__pycache__/base.cpython-310.pyc +0 -0
  4. evalkit_internvl/lib/python3.10/site-packages/aiofiles/__pycache__/ospath.cpython-310.pyc +0 -0
  5. evalkit_internvl/lib/python3.10/site-packages/aiofiles/base.py +113 -0
  6. evalkit_internvl/lib/python3.10/site-packages/aiofiles/threadpool/__init__.py +141 -0
  7. evalkit_internvl/lib/python3.10/site-packages/aiofiles/threadpool/__pycache__/__init__.cpython-310.pyc +0 -0
  8. evalkit_internvl/lib/python3.10/site-packages/aiofiles/threadpool/__pycache__/binary.cpython-310.pyc +0 -0
  9. evalkit_internvl/lib/python3.10/site-packages/aiofiles/threadpool/__pycache__/text.cpython-310.pyc +0 -0
  10. evalkit_internvl/lib/python3.10/site-packages/aiofiles/threadpool/__pycache__/utils.cpython-310.pyc +0 -0
  11. evalkit_internvl/lib/python3.10/site-packages/aiofiles/threadpool/binary.py +104 -0
  12. evalkit_internvl/lib/python3.10/site-packages/aiofiles/threadpool/utils.py +72 -0
  13. evalkit_internvl/lib/python3.10/site-packages/sympy/conftest.py +96 -0
  14. evalkit_internvl/lib/python3.10/site-packages/sympy/discrete/__init__.py +20 -0
  15. evalkit_internvl/lib/python3.10/site-packages/sympy/discrete/recurrences.py +166 -0
  16. evalkit_internvl/lib/python3.10/site-packages/sympy/galgebra.py +1 -0
  17. evalkit_tf437/lib/python3.10/site-packages/diffusers/experimental/__init__.py +1 -0
  18. evalkit_tf437/lib/python3.10/site-packages/diffusers/experimental/__pycache__/__init__.cpython-310.pyc +0 -0
  19. evalkit_tf437/lib/python3.10/site-packages/diffusers/experimental/rl/__pycache__/value_guided_sampling.cpython-310.pyc +0 -0
  20. evalkit_tf437/lib/python3.10/site-packages/diffusers/experimental/rl/value_guided_sampling.py +153 -0
  21. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/__init__.py +88 -0
  22. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/__pycache__/__init__.cpython-310.pyc +0 -0
  23. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/__pycache__/controlnet.cpython-310.pyc +0 -0
  24. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/__pycache__/ip_adapter.cpython-310.pyc +0 -0
  25. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/__pycache__/lora.cpython-310.pyc +0 -0
  26. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/__pycache__/lora_conversion_utils.cpython-310.pyc +0 -0
  27. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/__pycache__/utils.cpython-310.pyc +0 -0
  28. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/autoencoder.py +146 -0
  29. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/controlnet.py +136 -0
  30. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/ip_adapter.py +281 -0
  31. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/lora.py +1349 -0
  32. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/lora_conversion_utils.py +284 -0
  33. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/peft.py +186 -0
  34. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/single_file.py +318 -0
  35. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/single_file_utils.py +1617 -0
  36. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/textual_inversion.py +562 -0
  37. evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/utils.py +59 -0
  38. evalkit_tf437/lib/python3.10/site-packages/diffusers/models/attention_flax.py +494 -0
  39. evalkit_tf437/lib/python3.10/site-packages/diffusers/models/attention_processor.py +0 -0
  40. evalkit_tf437/lib/python3.10/site-packages/diffusers/models/controlnet.py +868 -0
  41. evalkit_tf437/lib/python3.10/site-packages/diffusers/models/controlnet_flax.py +395 -0
  42. evalkit_tf437/lib/python3.10/site-packages/diffusers/models/downsampling.py +334 -0
  43. evalkit_tf437/lib/python3.10/site-packages/diffusers/models/dual_transformer_2d.py +20 -0
  44. evalkit_tf437/lib/python3.10/site-packages/diffusers/models/embeddings.py +914 -0
  45. evalkit_tf437/lib/python3.10/site-packages/diffusers/models/embeddings_flax.py +97 -0
  46. evalkit_tf437/lib/python3.10/site-packages/diffusers/models/lora.py +457 -0
  47. evalkit_tf437/lib/python3.10/site-packages/diffusers/models/modeling_flax_utils.py +566 -0
  48. evalkit_tf437/lib/python3.10/site-packages/diffusers/models/modeling_outputs.py +17 -0
  49. evalkit_tf437/lib/python3.10/site-packages/diffusers/models/modeling_utils.py +1021 -0
  50. evalkit_tf437/lib/python3.10/site-packages/diffusers/models/prior_transformer.py +12 -0
.gitattributes CHANGED
@@ -1606,3 +1606,4 @@ evalkit_internvl/lib/python3.10/site-packages/transformers/models/seamless_m4t_v
1606
  evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/tokenization_utils_base.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1607
  evalkit_internvl/lib/python3.10/site-packages/safetensors/_safetensors_rust.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1608
  evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/trainer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
1606
  evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/tokenization_utils_base.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1607
  evalkit_internvl/lib/python3.10/site-packages/safetensors/_safetensors_rust.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1608
  evalkit_internvl/lib/python3.10/site-packages/transformers/__pycache__/trainer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1609
+ evalkit_cambrian/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc-builtins.so.12.1 filter=lfs diff=lfs merge=lfs -text
evalkit_cambrian/lib/python3.10/site-packages/nvidia/cuda_nvrtc/lib/libnvrtc-builtins.so.12.1 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c5639ce397a9f5b82cd277432d146370674358334a4ce0d33fa9a5ca090ac8a
3
+ size 6842248
evalkit_internvl/lib/python3.10/site-packages/aiofiles/__pycache__/base.cpython-310.pyc ADDED
Binary file (4.57 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/aiofiles/__pycache__/ospath.cpython-310.pyc ADDED
Binary file (983 Bytes). View file
 
evalkit_internvl/lib/python3.10/site-packages/aiofiles/base.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Various base classes."""
2
+ from types import coroutine
3
+ from collections.abc import Coroutine
4
+ from asyncio import get_running_loop
5
+
6
+
7
+ class AsyncBase:
8
+ def __init__(self, file, loop, executor):
9
+ self._file = file
10
+ self._executor = executor
11
+ self._ref_loop = loop
12
+
13
+ @property
14
+ def _loop(self):
15
+ return self._ref_loop or get_running_loop()
16
+
17
+ def __aiter__(self):
18
+ """We are our own iterator."""
19
+ return self
20
+
21
+ def __repr__(self):
22
+ return super().__repr__() + " wrapping " + repr(self._file)
23
+
24
+ async def __anext__(self):
25
+ """Simulate normal file iteration."""
26
+ line = await self.readline()
27
+ if line:
28
+ return line
29
+ else:
30
+ raise StopAsyncIteration
31
+
32
+
33
+ class AsyncIndirectBase(AsyncBase):
34
+ def __init__(self, name, loop, executor, indirect):
35
+ self._indirect = indirect
36
+ self._name = name
37
+ super().__init__(None, loop, executor)
38
+
39
+ @property
40
+ def _file(self):
41
+ return self._indirect()
42
+
43
+ @_file.setter
44
+ def _file(self, v):
45
+ pass # discard writes
46
+
47
+
48
+ class _ContextManager(Coroutine):
49
+ __slots__ = ("_coro", "_obj")
50
+
51
+ def __init__(self, coro):
52
+ self._coro = coro
53
+ self._obj = None
54
+
55
+ def send(self, value):
56
+ return self._coro.send(value)
57
+
58
+ def throw(self, typ, val=None, tb=None):
59
+ if val is None:
60
+ return self._coro.throw(typ)
61
+ elif tb is None:
62
+ return self._coro.throw(typ, val)
63
+ else:
64
+ return self._coro.throw(typ, val, tb)
65
+
66
+ def close(self):
67
+ return self._coro.close()
68
+
69
+ @property
70
+ def gi_frame(self):
71
+ return self._coro.gi_frame
72
+
73
+ @property
74
+ def gi_running(self):
75
+ return self._coro.gi_running
76
+
77
+ @property
78
+ def gi_code(self):
79
+ return self._coro.gi_code
80
+
81
+ def __next__(self):
82
+ return self.send(None)
83
+
84
+ @coroutine
85
+ def __iter__(self):
86
+ resp = yield from self._coro
87
+ return resp
88
+
89
+ def __await__(self):
90
+ resp = yield from self._coro
91
+ return resp
92
+
93
+ async def __anext__(self):
94
+ resp = await self._coro
95
+ return resp
96
+
97
+ async def __aenter__(self):
98
+ self._obj = await self._coro
99
+ return self._obj
100
+
101
+ async def __aexit__(self, exc_type, exc, tb):
102
+ self._obj.close()
103
+ self._obj = None
104
+
105
+
106
+ class AiofilesContextManager(_ContextManager):
107
+ """An adjusted async context manager for aiofiles."""
108
+
109
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
110
+ await get_running_loop().run_in_executor(
111
+ None, self._obj._file.__exit__, exc_type, exc_val, exc_tb
112
+ )
113
+ self._obj = None
evalkit_internvl/lib/python3.10/site-packages/aiofiles/threadpool/__init__.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Handle files using a thread pool executor."""
2
+ import asyncio
3
+ import sys
4
+ from functools import partial, singledispatch
5
+ from io import (
6
+ BufferedIOBase,
7
+ BufferedRandom,
8
+ BufferedReader,
9
+ BufferedWriter,
10
+ FileIO,
11
+ TextIOBase,
12
+ )
13
+ from types import coroutine
14
+
15
+ from ..base import AiofilesContextManager
16
+ from .binary import (
17
+ AsyncBufferedIOBase,
18
+ AsyncBufferedReader,
19
+ AsyncFileIO,
20
+ AsyncIndirectBufferedIOBase,
21
+ )
22
+ from .text import AsyncTextIndirectIOWrapper, AsyncTextIOWrapper
23
+
24
+ sync_open = open
25
+
26
+ __all__ = (
27
+ "open",
28
+ "stdin",
29
+ "stdout",
30
+ "stderr",
31
+ "stdin_bytes",
32
+ "stdout_bytes",
33
+ "stderr_bytes",
34
+ )
35
+
36
+
37
+ def open(
38
+ file,
39
+ mode="r",
40
+ buffering=-1,
41
+ encoding=None,
42
+ errors=None,
43
+ newline=None,
44
+ closefd=True,
45
+ opener=None,
46
+ *,
47
+ loop=None,
48
+ executor=None,
49
+ ):
50
+ return AiofilesContextManager(
51
+ _open(
52
+ file,
53
+ mode=mode,
54
+ buffering=buffering,
55
+ encoding=encoding,
56
+ errors=errors,
57
+ newline=newline,
58
+ closefd=closefd,
59
+ opener=opener,
60
+ loop=loop,
61
+ executor=executor,
62
+ )
63
+ )
64
+
65
+
66
+ @coroutine
67
+ def _open(
68
+ file,
69
+ mode="r",
70
+ buffering=-1,
71
+ encoding=None,
72
+ errors=None,
73
+ newline=None,
74
+ closefd=True,
75
+ opener=None,
76
+ *,
77
+ loop=None,
78
+ executor=None,
79
+ ):
80
+ """Open an asyncio file."""
81
+ if loop is None:
82
+ loop = asyncio.get_running_loop()
83
+ cb = partial(
84
+ sync_open,
85
+ file,
86
+ mode=mode,
87
+ buffering=buffering,
88
+ encoding=encoding,
89
+ errors=errors,
90
+ newline=newline,
91
+ closefd=closefd,
92
+ opener=opener,
93
+ )
94
+ f = yield from loop.run_in_executor(executor, cb)
95
+
96
+ return wrap(f, loop=loop, executor=executor)
97
+
98
+
99
+ @singledispatch
100
+ def wrap(file, *, loop=None, executor=None):
101
+ raise TypeError("Unsupported io type: {}.".format(file))
102
+
103
+
104
+ @wrap.register(TextIOBase)
105
+ def _(file, *, loop=None, executor=None):
106
+ return AsyncTextIOWrapper(file, loop=loop, executor=executor)
107
+
108
+
109
+ @wrap.register(BufferedWriter)
110
+ @wrap.register(BufferedIOBase)
111
+ def _(file, *, loop=None, executor=None):
112
+ return AsyncBufferedIOBase(file, loop=loop, executor=executor)
113
+
114
+
115
+ @wrap.register(BufferedReader)
116
+ @wrap.register(BufferedRandom)
117
+ def _(file, *, loop=None, executor=None):
118
+ return AsyncBufferedReader(file, loop=loop, executor=executor)
119
+
120
+
121
+ @wrap.register(FileIO)
122
+ def _(file, *, loop=None, executor=None):
123
+ return AsyncFileIO(file, loop=loop, executor=executor)
124
+
125
+
126
+ stdin = AsyncTextIndirectIOWrapper("sys.stdin", None, None, indirect=lambda: sys.stdin)
127
+ stdout = AsyncTextIndirectIOWrapper(
128
+ "sys.stdout", None, None, indirect=lambda: sys.stdout
129
+ )
130
+ stderr = AsyncTextIndirectIOWrapper(
131
+ "sys.stderr", None, None, indirect=lambda: sys.stderr
132
+ )
133
+ stdin_bytes = AsyncIndirectBufferedIOBase(
134
+ "sys.stdin.buffer", None, None, indirect=lambda: sys.stdin.buffer
135
+ )
136
+ stdout_bytes = AsyncIndirectBufferedIOBase(
137
+ "sys.stdout.buffer", None, None, indirect=lambda: sys.stdout.buffer
138
+ )
139
+ stderr_bytes = AsyncIndirectBufferedIOBase(
140
+ "sys.stderr.buffer", None, None, indirect=lambda: sys.stderr.buffer
141
+ )
evalkit_internvl/lib/python3.10/site-packages/aiofiles/threadpool/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (3.19 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/aiofiles/threadpool/__pycache__/binary.cpython-310.pyc ADDED
Binary file (2.15 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/aiofiles/threadpool/__pycache__/text.cpython-310.pyc ADDED
Binary file (1.24 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/aiofiles/threadpool/__pycache__/utils.cpython-310.pyc ADDED
Binary file (2.62 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/aiofiles/threadpool/binary.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..base import AsyncBase, AsyncIndirectBase
2
+ from .utils import delegate_to_executor, proxy_method_directly, proxy_property_directly
3
+
4
+
5
+ @delegate_to_executor(
6
+ "close",
7
+ "flush",
8
+ "isatty",
9
+ "read",
10
+ "read1",
11
+ "readinto",
12
+ "readline",
13
+ "readlines",
14
+ "seek",
15
+ "seekable",
16
+ "tell",
17
+ "truncate",
18
+ "writable",
19
+ "write",
20
+ "writelines",
21
+ )
22
+ @proxy_method_directly("detach", "fileno", "readable")
23
+ @proxy_property_directly("closed", "raw", "name", "mode")
24
+ class AsyncBufferedIOBase(AsyncBase):
25
+ """The asyncio executor version of io.BufferedWriter and BufferedIOBase."""
26
+
27
+
28
+ @delegate_to_executor("peek")
29
+ class AsyncBufferedReader(AsyncBufferedIOBase):
30
+ """The asyncio executor version of io.BufferedReader and Random."""
31
+
32
+
33
+ @delegate_to_executor(
34
+ "close",
35
+ "flush",
36
+ "isatty",
37
+ "read",
38
+ "readall",
39
+ "readinto",
40
+ "readline",
41
+ "readlines",
42
+ "seek",
43
+ "seekable",
44
+ "tell",
45
+ "truncate",
46
+ "writable",
47
+ "write",
48
+ "writelines",
49
+ )
50
+ @proxy_method_directly("fileno", "readable")
51
+ @proxy_property_directly("closed", "name", "mode")
52
+ class AsyncFileIO(AsyncBase):
53
+ """The asyncio executor version of io.FileIO."""
54
+
55
+
56
+ @delegate_to_executor(
57
+ "close",
58
+ "flush",
59
+ "isatty",
60
+ "read",
61
+ "read1",
62
+ "readinto",
63
+ "readline",
64
+ "readlines",
65
+ "seek",
66
+ "seekable",
67
+ "tell",
68
+ "truncate",
69
+ "writable",
70
+ "write",
71
+ "writelines",
72
+ )
73
+ @proxy_method_directly("detach", "fileno", "readable")
74
+ @proxy_property_directly("closed", "raw", "name", "mode")
75
+ class AsyncIndirectBufferedIOBase(AsyncIndirectBase):
76
+ """The indirect asyncio executor version of io.BufferedWriter and BufferedIOBase."""
77
+
78
+
79
+ @delegate_to_executor("peek")
80
+ class AsyncIndirectBufferedReader(AsyncIndirectBufferedIOBase):
81
+ """The indirect asyncio executor version of io.BufferedReader and Random."""
82
+
83
+
84
+ @delegate_to_executor(
85
+ "close",
86
+ "flush",
87
+ "isatty",
88
+ "read",
89
+ "readall",
90
+ "readinto",
91
+ "readline",
92
+ "readlines",
93
+ "seek",
94
+ "seekable",
95
+ "tell",
96
+ "truncate",
97
+ "writable",
98
+ "write",
99
+ "writelines",
100
+ )
101
+ @proxy_method_directly("fileno", "readable")
102
+ @proxy_property_directly("closed", "name", "mode")
103
+ class AsyncIndirectFileIO(AsyncIndirectBase):
104
+ """The indirect asyncio executor version of io.FileIO."""
evalkit_internvl/lib/python3.10/site-packages/aiofiles/threadpool/utils.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+
3
+
4
+ def delegate_to_executor(*attrs):
5
+ def cls_builder(cls):
6
+ for attr_name in attrs:
7
+ setattr(cls, attr_name, _make_delegate_method(attr_name))
8
+ return cls
9
+
10
+ return cls_builder
11
+
12
+
13
+ def proxy_method_directly(*attrs):
14
+ def cls_builder(cls):
15
+ for attr_name in attrs:
16
+ setattr(cls, attr_name, _make_proxy_method(attr_name))
17
+ return cls
18
+
19
+ return cls_builder
20
+
21
+
22
+ def proxy_property_directly(*attrs):
23
+ def cls_builder(cls):
24
+ for attr_name in attrs:
25
+ setattr(cls, attr_name, _make_proxy_property(attr_name))
26
+ return cls
27
+
28
+ return cls_builder
29
+
30
+
31
+ def cond_delegate_to_executor(*attrs):
32
+ def cls_builder(cls):
33
+ for attr_name in attrs:
34
+ setattr(cls, attr_name, _make_cond_delegate_method(attr_name))
35
+ return cls
36
+
37
+ return cls_builder
38
+
39
+
40
+ def _make_delegate_method(attr_name):
41
+ async def method(self, *args, **kwargs):
42
+ cb = functools.partial(getattr(self._file, attr_name), *args, **kwargs)
43
+ return await self._loop.run_in_executor(self._executor, cb)
44
+
45
+ return method
46
+
47
+
48
+ def _make_proxy_method(attr_name):
49
+ def method(self, *args, **kwargs):
50
+ return getattr(self._file, attr_name)(*args, **kwargs)
51
+
52
+ return method
53
+
54
+
55
+ def _make_proxy_property(attr_name):
56
+ def proxy_property(self):
57
+ return getattr(self._file, attr_name)
58
+
59
+ return property(proxy_property)
60
+
61
+
62
+ def _make_cond_delegate_method(attr_name):
63
+ """For spooled temp files, delegate only if rolled to file object"""
64
+
65
+ async def method(self, *args, **kwargs):
66
+ if self._file._rolled:
67
+ cb = functools.partial(getattr(self._file, attr_name), *args, **kwargs)
68
+ return await self._loop.run_in_executor(self._executor, cb)
69
+ else:
70
+ return getattr(self._file, attr_name)(*args, **kwargs)
71
+
72
+ return method
evalkit_internvl/lib/python3.10/site-packages/sympy/conftest.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ sys._running_pytest = True # type: ignore
4
+ from sympy.external.importtools import version_tuple
5
+
6
+ import pytest
7
+ from sympy.core.cache import clear_cache, USE_CACHE
8
+ from sympy.external.gmpy import GROUND_TYPES
9
+ from sympy.utilities.misc import ARCH
10
+ import re
11
+
12
+ try:
13
+ import hypothesis
14
+
15
+ hypothesis.settings.register_profile("sympy_hypothesis_profile", deadline=None)
16
+ hypothesis.settings.load_profile("sympy_hypothesis_profile")
17
+ except ImportError:
18
+ raise ImportError(
19
+ "hypothesis is a required dependency to run the SymPy test suite. "
20
+ "Install it with 'pip install hypothesis' or 'conda install -c conda-forge hypothesis'"
21
+ )
22
+
23
+
24
+ sp = re.compile(r"([0-9]+)/([1-9][0-9]*)")
25
+
26
+
27
+ def process_split(config, items):
28
+ split = config.getoption("--split")
29
+ if not split:
30
+ return
31
+ m = sp.match(split)
32
+ if not m:
33
+ raise ValueError(
34
+ "split must be a string of the form a/b " "where a and b are ints."
35
+ )
36
+ i, t = map(int, m.groups())
37
+ start, end = (i - 1) * len(items) // t, i * len(items) // t
38
+
39
+ if i < t:
40
+ # remove elements from end of list first
41
+ del items[end:]
42
+ del items[:start]
43
+
44
+
45
+ def pytest_report_header(config):
46
+ s = "architecture: %s\n" % ARCH
47
+ s += "cache: %s\n" % USE_CACHE
48
+ version = ""
49
+ if GROUND_TYPES == "gmpy":
50
+ import gmpy2
51
+
52
+ version = gmpy2.version()
53
+ elif GROUND_TYPES == "flint":
54
+ try:
55
+ from flint import __version__
56
+ except ImportError:
57
+ version = "unknown"
58
+ else:
59
+ version = f'(python-flint=={__version__})'
60
+ s += "ground types: %s %s\n" % (GROUND_TYPES, version)
61
+ return s
62
+
63
+
64
+ def pytest_terminal_summary(terminalreporter):
65
+ if terminalreporter.stats.get("error", None) or terminalreporter.stats.get(
66
+ "failed", None
67
+ ):
68
+ terminalreporter.write_sep(" ", "DO *NOT* COMMIT!", red=True, bold=True)
69
+
70
+
71
+ def pytest_addoption(parser):
72
+ parser.addoption("--split", action="store", default="", help="split tests")
73
+
74
+
75
+ def pytest_collection_modifyitems(config, items):
76
+ """pytest hook."""
77
+ # handle splits
78
+ process_split(config, items)
79
+
80
+
81
+ @pytest.fixture(autouse=True, scope="module")
82
+ def file_clear_cache():
83
+ clear_cache()
84
+
85
+
86
+ @pytest.fixture(autouse=True, scope="module")
87
+ def check_disabled(request):
88
+ if getattr(request.module, "disabled", False):
89
+ pytest.skip("test requirements not met.")
90
+ elif getattr(request.module, "ipython", False):
91
+ # need to check version and options for ipython tests
92
+ if (
93
+ version_tuple(pytest.__version__) < version_tuple("2.6.3")
94
+ and pytest.config.getvalue("-s") != "no"
95
+ ):
96
+ pytest.skip("run py.test with -s or upgrade to newer version.")
evalkit_internvl/lib/python3.10/site-packages/sympy/discrete/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This module contains functions which operate on discrete sequences.
2
+
3
+ Transforms - ``fft``, ``ifft``, ``ntt``, ``intt``, ``fwht``, ``ifwht``,
4
+ ``mobius_transform``, ``inverse_mobius_transform``
5
+
6
+ Convolutions - ``convolution``, ``convolution_fft``, ``convolution_ntt``,
7
+ ``convolution_fwht``, ``convolution_subset``,
8
+ ``covering_product``, ``intersecting_product``
9
+ """
10
+
11
+ from .transforms import (fft, ifft, ntt, intt, fwht, ifwht,
12
+ mobius_transform, inverse_mobius_transform)
13
+ from .convolutions import convolution, covering_product, intersecting_product
14
+
15
+ __all__ = [
16
+ 'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform',
17
+ 'inverse_mobius_transform',
18
+
19
+ 'convolution', 'covering_product', 'intersecting_product',
20
+ ]
evalkit_internvl/lib/python3.10/site-packages/sympy/discrete/recurrences.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Recurrences
3
+ """
4
+
5
+ from sympy.core import S, sympify
6
+ from sympy.utilities.iterables import iterable
7
+ from sympy.utilities.misc import as_int
8
+
9
+
10
+ def linrec(coeffs, init, n):
11
+ r"""
12
+ Evaluation of univariate linear recurrences of homogeneous type
13
+ having coefficients independent of the recurrence variable.
14
+
15
+ Parameters
16
+ ==========
17
+
18
+ coeffs : iterable
19
+ Coefficients of the recurrence
20
+ init : iterable
21
+ Initial values of the recurrence
22
+ n : Integer
23
+ Point of evaluation for the recurrence
24
+
25
+ Notes
26
+ =====
27
+
28
+ Let `y(n)` be the recurrence of given type, ``c`` be the sequence
29
+ of coefficients, ``b`` be the sequence of initial/base values of the
30
+ recurrence and ``k`` (equal to ``len(c)``) be the order of recurrence.
31
+ Then,
32
+
33
+ .. math :: y(n) = \begin{cases} b_n & 0 \le n < k \\
34
+ c_0 y(n-1) + c_1 y(n-2) + \cdots + c_{k-1} y(n-k) & n \ge k
35
+ \end{cases}
36
+
37
+ Let `x_0, x_1, \ldots, x_n` be a sequence and consider the transformation
38
+ that maps each polynomial `f(x)` to `T(f(x))` where each power `x^i` is
39
+ replaced by the corresponding value `x_i`. The sequence is then a solution
40
+ of the recurrence if and only if `T(x^i p(x)) = 0` for each `i \ge 0` where
41
+ `p(x) = x^k - c_0 x^(k-1) - \cdots - c_{k-1}` is the characteristic
42
+ polynomial.
43
+
44
+ Then `T(f(x)p(x)) = 0` for each polynomial `f(x)` (as it is a linear
45
+ combination of powers `x^i`). Now, if `x^n` is congruent to
46
+ `g(x) = a_0 x^0 + a_1 x^1 + \cdots + a_{k-1} x^{k-1}` modulo `p(x)`, then
47
+ `T(x^n) = x_n` is equal to
48
+ `T(g(x)) = a_0 x_0 + a_1 x_1 + \cdots + a_{k-1} x_{k-1}`.
49
+
50
+ Computation of `x^n`,
51
+ given `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`
52
+ is performed using exponentiation by squaring (refer to [1_]) with
53
+ an additional reduction step performed to retain only first `k` powers
54
+ of `x` in the representation of `x^n`.
55
+
56
+ Examples
57
+ ========
58
+
59
+ >>> from sympy.discrete.recurrences import linrec
60
+ >>> from sympy.abc import x, y, z
61
+
62
+ >>> linrec(coeffs=[1, 1], init=[0, 1], n=10)
63
+ 55
64
+
65
+ >>> linrec(coeffs=[1, 1], init=[x, y], n=10)
66
+ 34*x + 55*y
67
+
68
+ >>> linrec(coeffs=[x, y], init=[0, 1], n=5)
69
+ x**2*y + x*(x**3 + 2*x*y) + y**2
70
+
71
+ >>> linrec(coeffs=[1, 2, 3, 0, 0, 4], init=[x, y, z], n=16)
72
+ 13576*x + 5676*y + 2356*z
73
+
74
+ References
75
+ ==========
76
+
77
+ .. [1] https://en.wikipedia.org/wiki/Exponentiation_by_squaring
78
+ .. [2] https://en.wikipedia.org/w/index.php?title=Modular_exponentiation&section=6#Matrices
79
+
80
+ See Also
81
+ ========
82
+
83
+ sympy.polys.agca.extensions.ExtensionElement.__pow__
84
+
85
+ """
86
+
87
+ if not coeffs:
88
+ return S.Zero
89
+
90
+ if not iterable(coeffs):
91
+ raise TypeError("Expected a sequence of coefficients for"
92
+ " the recurrence")
93
+
94
+ if not iterable(init):
95
+ raise TypeError("Expected a sequence of values for the initialization"
96
+ " of the recurrence")
97
+
98
+ n = as_int(n)
99
+ if n < 0:
100
+ raise ValueError("Point of evaluation of recurrence must be a "
101
+ "non-negative integer")
102
+
103
+ c = [sympify(arg) for arg in coeffs]
104
+ b = [sympify(arg) for arg in init]
105
+ k = len(c)
106
+
107
+ if len(b) > k:
108
+ raise TypeError("Count of initial values should not exceed the "
109
+ "order of the recurrence")
110
+ else:
111
+ b += [S.Zero]*(k - len(b)) # remaining initial values default to zero
112
+
113
+ if n < k:
114
+ return b[n]
115
+ terms = [u*v for u, v in zip(linrec_coeffs(c, n), b)]
116
+ return sum(terms[:-1], terms[-1])
117
+
118
+
119
+ def linrec_coeffs(c, n):
120
+ r"""
121
+ Compute the coefficients of n'th term in linear recursion
122
+ sequence defined by c.
123
+
124
+ `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`.
125
+
126
+ It computes the coefficients by using binary exponentiation.
127
+ This function is used by `linrec` and `_eval_pow_by_cayley`.
128
+
129
+ Parameters
130
+ ==========
131
+
132
+ c = coefficients of the divisor polynomial
133
+ n = exponent of x, so dividend is x^n
134
+
135
+ """
136
+
137
+ k = len(c)
138
+
139
+ def _square_and_reduce(u, offset):
140
+ # squares `(u_0 + u_1 x + u_2 x^2 + \cdots + u_{k-1} x^k)` (and
141
+ # multiplies by `x` if offset is 1) and reduces the above result of
142
+ # length upto `2k` to `k` using the characteristic equation of the
143
+ # recurrence given by, `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`
144
+
145
+ w = [S.Zero]*(2*len(u) - 1 + offset)
146
+ for i, p in enumerate(u):
147
+ for j, q in enumerate(u):
148
+ w[offset + i + j] += p*q
149
+
150
+ for j in range(len(w) - 1, k - 1, -1):
151
+ for i in range(k):
152
+ w[j - i - 1] += w[j]*c[i]
153
+
154
+ return w[:k]
155
+
156
+ def _final_coeffs(n):
157
+ # computes the final coefficient list - `cf` corresponding to the
158
+ # point at which recurrence is to be evalauted - `n`, such that,
159
+ # `y(n) = cf_0 y(k-1) + cf_1 y(k-2) + \cdots + cf_{k-1} y(0)`
160
+
161
+ if n < k:
162
+ return [S.Zero]*n + [S.One] + [S.Zero]*(k - n - 1)
163
+ else:
164
+ return _square_and_reduce(_final_coeffs(n // 2), n % 2)
165
+
166
+ return _final_coeffs(n)
evalkit_internvl/lib/python3.10/site-packages/sympy/galgebra.py ADDED
@@ -0,0 +1 @@
 
 
1
+ raise ImportError("""As of SymPy 1.0 the galgebra module is maintained separately at https://github.com/pygae/galgebra""")
evalkit_tf437/lib/python3.10/site-packages/diffusers/experimental/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .rl import ValueGuidedRLPipeline
evalkit_tf437/lib/python3.10/site-packages/diffusers/experimental/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (229 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/experimental/rl/__pycache__/value_guided_sampling.cpython-310.pyc ADDED
Binary file (4.81 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/experimental/rl/value_guided_sampling.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import numpy as np
16
+ import torch
17
+ import tqdm
18
+
19
+ from ...models.unets.unet_1d import UNet1DModel
20
+ from ...pipelines import DiffusionPipeline
21
+ from ...utils.dummy_pt_objects import DDPMScheduler
22
+ from ...utils.torch_utils import randn_tensor
23
+
24
+
25
+ class ValueGuidedRLPipeline(DiffusionPipeline):
26
+ r"""
27
+ Pipeline for value-guided sampling from a diffusion model trained to predict sequences of states.
28
+
29
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
30
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
31
+
32
+ Parameters:
33
+ value_function ([`UNet1DModel`]):
34
+ A specialized UNet for fine-tuning trajectories base on reward.
35
+ unet ([`UNet1DModel`]):
36
+ UNet architecture to denoise the encoded trajectories.
37
+ scheduler ([`SchedulerMixin`]):
38
+ A scheduler to be used in combination with `unet` to denoise the encoded trajectories. Default for this
39
+ application is [`DDPMScheduler`].
40
+ env ():
41
+ An environment following the OpenAI gym API to act in. For now only Hopper has pretrained models.
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ value_function: UNet1DModel,
47
+ unet: UNet1DModel,
48
+ scheduler: DDPMScheduler,
49
+ env,
50
+ ):
51
+ super().__init__()
52
+
53
+ self.register_modules(value_function=value_function, unet=unet, scheduler=scheduler, env=env)
54
+
55
+ self.data = env.get_dataset()
56
+ self.means = {}
57
+ for key in self.data.keys():
58
+ try:
59
+ self.means[key] = self.data[key].mean()
60
+ except: # noqa: E722
61
+ pass
62
+ self.stds = {}
63
+ for key in self.data.keys():
64
+ try:
65
+ self.stds[key] = self.data[key].std()
66
+ except: # noqa: E722
67
+ pass
68
+ self.state_dim = env.observation_space.shape[0]
69
+ self.action_dim = env.action_space.shape[0]
70
+
71
+ def normalize(self, x_in, key):
72
+ return (x_in - self.means[key]) / self.stds[key]
73
+
74
+ def de_normalize(self, x_in, key):
75
+ return x_in * self.stds[key] + self.means[key]
76
+
77
+ def to_torch(self, x_in):
78
+ if isinstance(x_in, dict):
79
+ return {k: self.to_torch(v) for k, v in x_in.items()}
80
+ elif torch.is_tensor(x_in):
81
+ return x_in.to(self.unet.device)
82
+ return torch.tensor(x_in, device=self.unet.device)
83
+
84
+ def reset_x0(self, x_in, cond, act_dim):
85
+ for key, val in cond.items():
86
+ x_in[:, key, act_dim:] = val.clone()
87
+ return x_in
88
+
89
+ def run_diffusion(self, x, conditions, n_guide_steps, scale):
90
+ batch_size = x.shape[0]
91
+ y = None
92
+ for i in tqdm.tqdm(self.scheduler.timesteps):
93
+ # create batch of timesteps to pass into model
94
+ timesteps = torch.full((batch_size,), i, device=self.unet.device, dtype=torch.long)
95
+ for _ in range(n_guide_steps):
96
+ with torch.enable_grad():
97
+ x.requires_grad_()
98
+
99
+ # permute to match dimension for pre-trained models
100
+ y = self.value_function(x.permute(0, 2, 1), timesteps).sample
101
+ grad = torch.autograd.grad([y.sum()], [x])[0]
102
+
103
+ posterior_variance = self.scheduler._get_variance(i)
104
+ model_std = torch.exp(0.5 * posterior_variance)
105
+ grad = model_std * grad
106
+
107
+ grad[timesteps < 2] = 0
108
+ x = x.detach()
109
+ x = x + scale * grad
110
+ x = self.reset_x0(x, conditions, self.action_dim)
111
+
112
+ prev_x = self.unet(x.permute(0, 2, 1), timesteps).sample.permute(0, 2, 1)
113
+
114
+ # TODO: verify deprecation of this kwarg
115
+ x = self.scheduler.step(prev_x, i, x)["prev_sample"]
116
+
117
+ # apply conditions to the trajectory (set the initial state)
118
+ x = self.reset_x0(x, conditions, self.action_dim)
119
+ x = self.to_torch(x)
120
+ return x, y
121
+
122
+ def __call__(self, obs, batch_size=64, planning_horizon=32, n_guide_steps=2, scale=0.1):
123
+ # normalize the observations and create batch dimension
124
+ obs = self.normalize(obs, "observations")
125
+ obs = obs[None].repeat(batch_size, axis=0)
126
+
127
+ conditions = {0: self.to_torch(obs)}
128
+ shape = (batch_size, planning_horizon, self.state_dim + self.action_dim)
129
+
130
+ # generate initial noise and apply our conditions (to make the trajectories start at current state)
131
+ x1 = randn_tensor(shape, device=self.unet.device)
132
+ x = self.reset_x0(x1, conditions, self.action_dim)
133
+ x = self.to_torch(x)
134
+
135
+ # run the diffusion process
136
+ x, y = self.run_diffusion(x, conditions, n_guide_steps, scale)
137
+
138
+ # sort output trajectories by value
139
+ sorted_idx = y.argsort(0, descending=True).squeeze()
140
+ sorted_values = x[sorted_idx]
141
+ actions = sorted_values[:, :, : self.action_dim]
142
+ actions = actions.detach().cpu().numpy()
143
+ denorm_actions = self.de_normalize(actions, key="actions")
144
+
145
+ # select the action with the highest value
146
+ if y is not None:
147
+ selected_index = 0
148
+ else:
149
+ # if we didn't run value guiding, select a random action
150
+ selected_index = np.random.randint(0, batch_size)
151
+
152
+ denorm_actions = denorm_actions[selected_index, 0]
153
+ return denorm_actions
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/__init__.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING
2
+
3
+ from ..utils import DIFFUSERS_SLOW_IMPORT, _LazyModule, deprecate
4
+ from ..utils.import_utils import is_peft_available, is_torch_available, is_transformers_available
5
+
6
+
7
+ def text_encoder_lora_state_dict(text_encoder):
8
+ deprecate(
9
+ "text_encoder_load_state_dict in `models`",
10
+ "0.27.0",
11
+ "`text_encoder_lora_state_dict` is deprecated and will be removed in 0.27.0. Make sure to retrieve the weights using `get_peft_model`. See https://huggingface.co/docs/peft/v0.6.2/en/quicktour#peftmodel for more information.",
12
+ )
13
+ state_dict = {}
14
+
15
+ for name, module in text_encoder_attn_modules(text_encoder):
16
+ for k, v in module.q_proj.lora_linear_layer.state_dict().items():
17
+ state_dict[f"{name}.q_proj.lora_linear_layer.{k}"] = v
18
+
19
+ for k, v in module.k_proj.lora_linear_layer.state_dict().items():
20
+ state_dict[f"{name}.k_proj.lora_linear_layer.{k}"] = v
21
+
22
+ for k, v in module.v_proj.lora_linear_layer.state_dict().items():
23
+ state_dict[f"{name}.v_proj.lora_linear_layer.{k}"] = v
24
+
25
+ for k, v in module.out_proj.lora_linear_layer.state_dict().items():
26
+ state_dict[f"{name}.out_proj.lora_linear_layer.{k}"] = v
27
+
28
+ return state_dict
29
+
30
+
31
+ if is_transformers_available():
32
+
33
+ def text_encoder_attn_modules(text_encoder):
34
+ deprecate(
35
+ "text_encoder_attn_modules in `models`",
36
+ "0.27.0",
37
+ "`text_encoder_lora_state_dict` is deprecated and will be removed in 0.27.0. Make sure to retrieve the weights using `get_peft_model`. See https://huggingface.co/docs/peft/v0.6.2/en/quicktour#peftmodel for more information.",
38
+ )
39
+ from transformers import CLIPTextModel, CLIPTextModelWithProjection
40
+
41
+ attn_modules = []
42
+
43
+ if isinstance(text_encoder, (CLIPTextModel, CLIPTextModelWithProjection)):
44
+ for i, layer in enumerate(text_encoder.text_model.encoder.layers):
45
+ name = f"text_model.encoder.layers.{i}.self_attn"
46
+ mod = layer.self_attn
47
+ attn_modules.append((name, mod))
48
+ else:
49
+ raise ValueError(f"do not know how to get attention modules for: {text_encoder.__class__.__name__}")
50
+
51
+ return attn_modules
52
+
53
+
54
+ _import_structure = {}
55
+
56
+ if is_torch_available():
57
+ _import_structure["autoencoder"] = ["FromOriginalVAEMixin"]
58
+
59
+ _import_structure["controlnet"] = ["FromOriginalControlNetMixin"]
60
+ _import_structure["unet"] = ["UNet2DConditionLoadersMixin"]
61
+ _import_structure["utils"] = ["AttnProcsLayers"]
62
+ if is_transformers_available():
63
+ _import_structure["single_file"] = ["FromSingleFileMixin"]
64
+ _import_structure["lora"] = ["LoraLoaderMixin", "StableDiffusionXLLoraLoaderMixin"]
65
+ _import_structure["textual_inversion"] = ["TextualInversionLoaderMixin"]
66
+ _import_structure["ip_adapter"] = ["IPAdapterMixin"]
67
+
68
+ _import_structure["peft"] = ["PeftAdapterMixin"]
69
+
70
+
71
+ if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
72
+ if is_torch_available():
73
+ from .autoencoder import FromOriginalVAEMixin
74
+ from .controlnet import FromOriginalControlNetMixin
75
+ from .unet import UNet2DConditionLoadersMixin
76
+ from .utils import AttnProcsLayers
77
+
78
+ if is_transformers_available():
79
+ from .ip_adapter import IPAdapterMixin
80
+ from .lora import LoraLoaderMixin, StableDiffusionXLLoraLoaderMixin
81
+ from .single_file import FromSingleFileMixin
82
+ from .textual_inversion import TextualInversionLoaderMixin
83
+
84
+ from .peft import PeftAdapterMixin
85
+ else:
86
+ import sys
87
+
88
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.85 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/__pycache__/controlnet.cpython-310.pyc ADDED
Binary file (5.84 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/__pycache__/ip_adapter.cpython-310.pyc ADDED
Binary file (9.88 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/__pycache__/lora.cpython-310.pyc ADDED
Binary file (43.9 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/__pycache__/lora_conversion_utils.cpython-310.pyc ADDED
Binary file (7.02 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/__pycache__/utils.cpython-310.pyc ADDED
Binary file (2.11 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/autoencoder.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from huggingface_hub.utils import validate_hf_hub_args
16
+
17
+ from .single_file_utils import (
18
+ create_diffusers_vae_model_from_ldm,
19
+ fetch_ldm_config_and_checkpoint,
20
+ )
21
+
22
+
23
+ class FromOriginalVAEMixin:
24
+ """
25
+ Load pretrained AutoencoderKL weights saved in the `.ckpt` or `.safetensors` format into a [`AutoencoderKL`].
26
+ """
27
+
28
+ @classmethod
29
+ @validate_hf_hub_args
30
+ def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
31
+ r"""
32
+ Instantiate a [`AutoencoderKL`] from pretrained ControlNet weights saved in the original `.ckpt` or
33
+ `.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
34
+
35
+ Parameters:
36
+ pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
37
+ Can be either:
38
+ - A link to the `.ckpt` file (for example
39
+ `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
40
+ - A path to a *file* containing all pipeline weights.
41
+ config_file (`str`, *optional*):
42
+ Filepath to the configuration YAML file associated with the model. If not provided it will default to:
43
+ https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml
44
+ torch_dtype (`str` or `torch.dtype`, *optional*):
45
+ Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
46
+ dtype is automatically derived from the model's weights.
47
+ force_download (`bool`, *optional*, defaults to `False`):
48
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
49
+ cached versions if they exist.
50
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
51
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
52
+ is not used.
53
+ resume_download (`bool`, *optional*, defaults to `False`):
54
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
55
+ incompletely downloaded files are deleted.
56
+ proxies (`Dict[str, str]`, *optional*):
57
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
58
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
59
+ local_files_only (`bool`, *optional*, defaults to `False`):
60
+ Whether to only load local model weights and configuration files or not. If set to True, the model
61
+ won't be downloaded from the Hub.
62
+ token (`str` or *bool*, *optional*):
63
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
64
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
65
+ revision (`str`, *optional*, defaults to `"main"`):
66
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
67
+ allowed by Git.
68
+ image_size (`int`, *optional*, defaults to 512):
69
+ The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
70
+ Diffusion v2 base model. Use 768 for Stable Diffusion v2.
71
+ scaling_factor (`float`, *optional*, defaults to 0.18215):
72
+ The component-wise standard deviation of the trained latent space computed using the first batch of the
73
+ training set. This is used to scale the latent space to have unit variance when training the diffusion
74
+ model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
75
+ diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z
76
+ = 1 / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution
77
+ Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
78
+ kwargs (remaining dictionary of keyword arguments, *optional*):
79
+ Can be used to overwrite load and saveable variables (for example the pipeline components of the
80
+ specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
81
+ method. See example below for more information.
82
+
83
+ <Tip warning={true}>
84
+
85
+ Make sure to pass both `image_size` and `scaling_factor` to `from_single_file()` if you're loading
86
+ a VAE from SDXL or a Stable Diffusion v2 model or higher.
87
+
88
+ </Tip>
89
+
90
+ Examples:
91
+
92
+ ```py
93
+ from diffusers import AutoencoderKL
94
+
95
+ url = "https://huggingface.co/stabilityai/sd-vae-ft-mse-original/blob/main/vae-ft-mse-840000-ema-pruned.safetensors" # can also be local file
96
+ model = AutoencoderKL.from_single_file(url)
97
+ ```
98
+ """
99
+
100
+ original_config_file = kwargs.pop("original_config_file", None)
101
+ config_file = kwargs.pop("config_file", None)
102
+ resume_download = kwargs.pop("resume_download", False)
103
+ force_download = kwargs.pop("force_download", False)
104
+ proxies = kwargs.pop("proxies", None)
105
+ token = kwargs.pop("token", None)
106
+ cache_dir = kwargs.pop("cache_dir", None)
107
+ local_files_only = kwargs.pop("local_files_only", None)
108
+ revision = kwargs.pop("revision", None)
109
+ torch_dtype = kwargs.pop("torch_dtype", None)
110
+
111
+ class_name = cls.__name__
112
+
113
+ if (config_file is not None) and (original_config_file is not None):
114
+ raise ValueError(
115
+ "You cannot pass both `config_file` and `original_config_file` to `from_single_file`. Please use only one of these arguments."
116
+ )
117
+
118
+ original_config_file = original_config_file or config_file
119
+ original_config, checkpoint = fetch_ldm_config_and_checkpoint(
120
+ pretrained_model_link_or_path=pretrained_model_link_or_path,
121
+ class_name=class_name,
122
+ original_config_file=original_config_file,
123
+ resume_download=resume_download,
124
+ force_download=force_download,
125
+ proxies=proxies,
126
+ token=token,
127
+ revision=revision,
128
+ local_files_only=local_files_only,
129
+ cache_dir=cache_dir,
130
+ )
131
+
132
+ image_size = kwargs.pop("image_size", None)
133
+ scaling_factor = kwargs.pop("scaling_factor", None)
134
+ component = create_diffusers_vae_model_from_ldm(
135
+ class_name,
136
+ original_config,
137
+ checkpoint,
138
+ image_size=image_size,
139
+ scaling_factor=scaling_factor,
140
+ torch_dtype=torch_dtype,
141
+ )
142
+ vae = component["vae"]
143
+ if torch_dtype is not None:
144
+ vae = vae.to(torch_dtype)
145
+
146
+ return vae
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/controlnet.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from huggingface_hub.utils import validate_hf_hub_args
16
+
17
+ from .single_file_utils import (
18
+ create_diffusers_controlnet_model_from_ldm,
19
+ fetch_ldm_config_and_checkpoint,
20
+ )
21
+
22
+
23
+ class FromOriginalControlNetMixin:
24
+ """
25
+ Load pretrained ControlNet weights saved in the `.ckpt` or `.safetensors` format into a [`ControlNetModel`].
26
+ """
27
+
28
+ @classmethod
29
+ @validate_hf_hub_args
30
+ def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
31
+ r"""
32
+ Instantiate a [`ControlNetModel`] from pretrained ControlNet weights saved in the original `.ckpt` or
33
+ `.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
34
+
35
+ Parameters:
36
+ pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
37
+ Can be either:
38
+ - A link to the `.ckpt` file (for example
39
+ `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
40
+ - A path to a *file* containing all pipeline weights.
41
+ config_file (`str`, *optional*):
42
+ Filepath to the configuration YAML file associated with the model. If not provided it will default to:
43
+ https://raw.githubusercontent.com/lllyasviel/ControlNet/main/models/cldm_v15.yaml
44
+ torch_dtype (`str` or `torch.dtype`, *optional*):
45
+ Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
46
+ dtype is automatically derived from the model's weights.
47
+ force_download (`bool`, *optional*, defaults to `False`):
48
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
49
+ cached versions if they exist.
50
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
51
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
52
+ is not used.
53
+ resume_download (`bool`, *optional*, defaults to `False`):
54
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
55
+ incompletely downloaded files are deleted.
56
+ proxies (`Dict[str, str]`, *optional*):
57
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
58
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
59
+ local_files_only (`bool`, *optional*, defaults to `False`):
60
+ Whether to only load local model weights and configuration files or not. If set to True, the model
61
+ won't be downloaded from the Hub.
62
+ token (`str` or *bool*, *optional*):
63
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
64
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
65
+ revision (`str`, *optional*, defaults to `"main"`):
66
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
67
+ allowed by Git.
68
+ image_size (`int`, *optional*, defaults to 512):
69
+ The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
70
+ Diffusion v2 base model. Use 768 for Stable Diffusion v2.
71
+ upcast_attention (`bool`, *optional*, defaults to `None`):
72
+ Whether the attention computation should always be upcasted.
73
+ kwargs (remaining dictionary of keyword arguments, *optional*):
74
+ Can be used to overwrite load and saveable variables (for example the pipeline components of the
75
+ specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
76
+ method. See example below for more information.
77
+
78
+ Examples:
79
+
80
+ ```py
81
+ from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
82
+
83
+ url = "https://huggingface.co/lllyasviel/ControlNet-v1-1/blob/main/control_v11p_sd15_canny.pth" # can also be a local path
84
+ model = ControlNetModel.from_single_file(url)
85
+
86
+ url = "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned.safetensors" # can also be a local path
87
+ pipe = StableDiffusionControlNetPipeline.from_single_file(url, controlnet=controlnet)
88
+ ```
89
+ """
90
+ original_config_file = kwargs.pop("original_config_file", None)
91
+ config_file = kwargs.pop("config_file", None)
92
+ resume_download = kwargs.pop("resume_download", False)
93
+ force_download = kwargs.pop("force_download", False)
94
+ proxies = kwargs.pop("proxies", None)
95
+ token = kwargs.pop("token", None)
96
+ cache_dir = kwargs.pop("cache_dir", None)
97
+ local_files_only = kwargs.pop("local_files_only", None)
98
+ revision = kwargs.pop("revision", None)
99
+ torch_dtype = kwargs.pop("torch_dtype", None)
100
+
101
+ class_name = cls.__name__
102
+ if (config_file is not None) and (original_config_file is not None):
103
+ raise ValueError(
104
+ "You cannot pass both `config_file` and `original_config_file` to `from_single_file`. Please use only one of these arguments."
105
+ )
106
+
107
+ original_config_file = config_file or original_config_file
108
+ original_config, checkpoint = fetch_ldm_config_and_checkpoint(
109
+ pretrained_model_link_or_path=pretrained_model_link_or_path,
110
+ class_name=class_name,
111
+ original_config_file=original_config_file,
112
+ resume_download=resume_download,
113
+ force_download=force_download,
114
+ proxies=proxies,
115
+ token=token,
116
+ revision=revision,
117
+ local_files_only=local_files_only,
118
+ cache_dir=cache_dir,
119
+ )
120
+
121
+ upcast_attention = kwargs.pop("upcast_attention", False)
122
+ image_size = kwargs.pop("image_size", None)
123
+
124
+ component = create_diffusers_controlnet_model_from_ldm(
125
+ class_name,
126
+ original_config,
127
+ checkpoint,
128
+ upcast_attention=upcast_attention,
129
+ image_size=image_size,
130
+ torch_dtype=torch_dtype,
131
+ )
132
+ controlnet = component["controlnet"]
133
+ if torch_dtype is not None:
134
+ controlnet = controlnet.to(torch_dtype)
135
+
136
+ return controlnet
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/ip_adapter.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from pathlib import Path
16
+ from typing import Dict, List, Optional, Union
17
+
18
+ import torch
19
+ from huggingface_hub.utils import validate_hf_hub_args
20
+ from safetensors import safe_open
21
+
22
+ from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT
23
+ from ..utils import (
24
+ _get_model_file,
25
+ is_accelerate_available,
26
+ is_torch_version,
27
+ is_transformers_available,
28
+ logging,
29
+ )
30
+
31
+
32
+ if is_transformers_available():
33
+ from transformers import (
34
+ CLIPImageProcessor,
35
+ CLIPVisionModelWithProjection,
36
+ )
37
+
38
+ from ..models.attention_processor import (
39
+ IPAdapterAttnProcessor,
40
+ IPAdapterAttnProcessor2_0,
41
+ )
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ class IPAdapterMixin:
47
+ """Mixin for handling IP Adapters."""
48
+
49
+ @validate_hf_hub_args
50
+ def load_ip_adapter(
51
+ self,
52
+ pretrained_model_name_or_path_or_dict: Union[str, List[str], Dict[str, torch.Tensor]],
53
+ subfolder: Union[str, List[str]],
54
+ weight_name: Union[str, List[str]],
55
+ image_encoder_folder: Optional[str] = "image_encoder",
56
+ **kwargs,
57
+ ):
58
+ """
59
+ Parameters:
60
+ pretrained_model_name_or_path_or_dict (`str` or `List[str]` or `os.PathLike` or `List[os.PathLike]` or `dict` or `List[dict]`):
61
+ Can be either:
62
+
63
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
64
+ the Hub.
65
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
66
+ with [`ModelMixin.save_pretrained`].
67
+ - A [torch state
68
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
69
+ subfolder (`str` or `List[str]`):
70
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
71
+ If a list is passed, it should have the same length as `weight_name`.
72
+ weight_name (`str` or `List[str]`):
73
+ The name of the weight file to load. If a list is passed, it should have the same length as
74
+ `weight_name`.
75
+ image_encoder_folder (`str`, *optional*, defaults to `image_encoder`):
76
+ The subfolder location of the image encoder within a larger model repository on the Hub or locally.
77
+ Pass `None` to not load the image encoder. If the image encoder is located in a folder inside `subfolder`,
78
+ you only need to pass the name of the folder that contains image encoder weights, e.g. `image_encoder_folder="image_encoder"`.
79
+ If the image encoder is located in a folder other than `subfolder`, you should pass the path to the folder that contains image encoder weights,
80
+ for example, `image_encoder_folder="different_subfolder/image_encoder"`.
81
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
82
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
83
+ is not used.
84
+ force_download (`bool`, *optional*, defaults to `False`):
85
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
86
+ cached versions if they exist.
87
+ resume_download (`bool`, *optional*, defaults to `False`):
88
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
89
+ incompletely downloaded files are deleted.
90
+ proxies (`Dict[str, str]`, *optional*):
91
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
92
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
93
+ local_files_only (`bool`, *optional*, defaults to `False`):
94
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
95
+ won't be downloaded from the Hub.
96
+ token (`str` or *bool*, *optional*):
97
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
98
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
99
+ revision (`str`, *optional*, defaults to `"main"`):
100
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
101
+ allowed by Git.
102
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
103
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
104
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
105
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
106
+ argument to `True` will raise an error.
107
+ """
108
+
109
+ # handle the list inputs for multiple IP Adapters
110
+ if not isinstance(weight_name, list):
111
+ weight_name = [weight_name]
112
+
113
+ if not isinstance(pretrained_model_name_or_path_or_dict, list):
114
+ pretrained_model_name_or_path_or_dict = [pretrained_model_name_or_path_or_dict]
115
+ if len(pretrained_model_name_or_path_or_dict) == 1:
116
+ pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict * len(weight_name)
117
+
118
+ if not isinstance(subfolder, list):
119
+ subfolder = [subfolder]
120
+ if len(subfolder) == 1:
121
+ subfolder = subfolder * len(weight_name)
122
+
123
+ if len(weight_name) != len(pretrained_model_name_or_path_or_dict):
124
+ raise ValueError("`weight_name` and `pretrained_model_name_or_path_or_dict` must have the same length.")
125
+
126
+ if len(weight_name) != len(subfolder):
127
+ raise ValueError("`weight_name` and `subfolder` must have the same length.")
128
+
129
+ # Load the main state dict first.
130
+ cache_dir = kwargs.pop("cache_dir", None)
131
+ force_download = kwargs.pop("force_download", False)
132
+ resume_download = kwargs.pop("resume_download", False)
133
+ proxies = kwargs.pop("proxies", None)
134
+ local_files_only = kwargs.pop("local_files_only", None)
135
+ token = kwargs.pop("token", None)
136
+ revision = kwargs.pop("revision", None)
137
+ low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
138
+
139
+ if low_cpu_mem_usage and not is_accelerate_available():
140
+ low_cpu_mem_usage = False
141
+ logger.warning(
142
+ "Cannot initialize model with low cpu memory usage because `accelerate` was not found in the"
143
+ " environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install"
144
+ " `accelerate` for faster and less memory-intense model loading. You can do so with: \n```\npip"
145
+ " install accelerate\n```\n."
146
+ )
147
+
148
+ if low_cpu_mem_usage is True and not is_torch_version(">=", "1.9.0"):
149
+ raise NotImplementedError(
150
+ "Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set"
151
+ " `low_cpu_mem_usage=False`."
152
+ )
153
+
154
+ user_agent = {
155
+ "file_type": "attn_procs_weights",
156
+ "framework": "pytorch",
157
+ }
158
+ state_dicts = []
159
+ for pretrained_model_name_or_path_or_dict, weight_name, subfolder in zip(
160
+ pretrained_model_name_or_path_or_dict, weight_name, subfolder
161
+ ):
162
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
163
+ model_file = _get_model_file(
164
+ pretrained_model_name_or_path_or_dict,
165
+ weights_name=weight_name,
166
+ cache_dir=cache_dir,
167
+ force_download=force_download,
168
+ resume_download=resume_download,
169
+ proxies=proxies,
170
+ local_files_only=local_files_only,
171
+ token=token,
172
+ revision=revision,
173
+ subfolder=subfolder,
174
+ user_agent=user_agent,
175
+ )
176
+ if weight_name.endswith(".safetensors"):
177
+ state_dict = {"image_proj": {}, "ip_adapter": {}}
178
+ with safe_open(model_file, framework="pt", device="cpu") as f:
179
+ for key in f.keys():
180
+ if key.startswith("image_proj."):
181
+ state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
182
+ elif key.startswith("ip_adapter."):
183
+ state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key)
184
+ else:
185
+ state_dict = torch.load(model_file, map_location="cpu")
186
+ else:
187
+ state_dict = pretrained_model_name_or_path_or_dict
188
+
189
+ keys = list(state_dict.keys())
190
+ if keys != ["image_proj", "ip_adapter"]:
191
+ raise ValueError("Required keys are (`image_proj` and `ip_adapter`) missing from the state dict.")
192
+
193
+ state_dicts.append(state_dict)
194
+
195
+ # load CLIP image encoder here if it has not been registered to the pipeline yet
196
+ if hasattr(self, "image_encoder") and getattr(self, "image_encoder", None) is None:
197
+ if image_encoder_folder is not None:
198
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
199
+ logger.info(f"loading image_encoder from {pretrained_model_name_or_path_or_dict}")
200
+ if image_encoder_folder.count("/") == 0:
201
+ image_encoder_subfolder = Path(subfolder, image_encoder_folder).as_posix()
202
+ else:
203
+ image_encoder_subfolder = Path(image_encoder_folder).as_posix()
204
+
205
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(
206
+ pretrained_model_name_or_path_or_dict,
207
+ subfolder=image_encoder_subfolder,
208
+ low_cpu_mem_usage=low_cpu_mem_usage,
209
+ ).to(self.device, dtype=self.dtype)
210
+ self.register_modules(image_encoder=image_encoder)
211
+ else:
212
+ raise ValueError(
213
+ "`image_encoder` cannot be loaded because `pretrained_model_name_or_path_or_dict` is a state dict."
214
+ )
215
+ else:
216
+ logger.warning(
217
+ "image_encoder is not loaded since `image_encoder_folder=None` passed. You will not be able to use `ip_adapter_image` when calling the pipeline with IP-Adapter."
218
+ "Use `ip_adapter_image_embeds` to pass pre-generated image embedding instead."
219
+ )
220
+
221
+ # create feature extractor if it has not been registered to the pipeline yet
222
+ if hasattr(self, "feature_extractor") and getattr(self, "feature_extractor", None) is None:
223
+ feature_extractor = CLIPImageProcessor()
224
+ self.register_modules(feature_extractor=feature_extractor)
225
+
226
+ # load ip-adapter into unet
227
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
228
+ unet._load_ip_adapter_weights(state_dicts, low_cpu_mem_usage=low_cpu_mem_usage)
229
+
230
+ def set_ip_adapter_scale(self, scale):
231
+ """
232
+ Sets the conditioning scale between text and image.
233
+
234
+ Example:
235
+
236
+ ```py
237
+ pipeline.set_ip_adapter_scale(0.5)
238
+ ```
239
+ """
240
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
241
+ for attn_processor in unet.attn_processors.values():
242
+ if isinstance(attn_processor, (IPAdapterAttnProcessor, IPAdapterAttnProcessor2_0)):
243
+ if not isinstance(scale, list):
244
+ scale = [scale] * len(attn_processor.scale)
245
+ if len(attn_processor.scale) != len(scale):
246
+ raise ValueError(
247
+ f"`scale` should be a list of same length as the number if ip-adapters "
248
+ f"Expected {len(attn_processor.scale)} but got {len(scale)}."
249
+ )
250
+ attn_processor.scale = scale
251
+
252
+ def unload_ip_adapter(self):
253
+ """
254
+ Unloads the IP Adapter weights
255
+
256
+ Examples:
257
+
258
+ ```python
259
+ >>> # Assuming `pipeline` is already loaded with the IP Adapter weights.
260
+ >>> pipeline.unload_ip_adapter()
261
+ >>> ...
262
+ ```
263
+ """
264
+ # remove CLIP image encoder
265
+ if hasattr(self, "image_encoder") and getattr(self, "image_encoder", None) is not None:
266
+ self.image_encoder = None
267
+ self.register_to_config(image_encoder=[None, None])
268
+
269
+ # remove feature extractor only when safety_checker is None as safety_checker uses
270
+ # the feature_extractor later
271
+ if not hasattr(self, "safety_checker"):
272
+ if hasattr(self, "feature_extractor") and getattr(self, "feature_extractor", None) is not None:
273
+ self.feature_extractor = None
274
+ self.register_to_config(feature_extractor=[None, None])
275
+
276
+ # remove hidden encoder
277
+ self.unet.encoder_hid_proj = None
278
+ self.config.encoder_hid_dim_type = None
279
+
280
+ # restore original Unet attention processors layers
281
+ self.unet.set_default_attn_processor()
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/lora.py ADDED
@@ -0,0 +1,1349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import inspect
15
+ import os
16
+ from pathlib import Path
17
+ from typing import Callable, Dict, List, Optional, Union
18
+
19
+ import safetensors
20
+ import torch
21
+ from huggingface_hub import model_info
22
+ from huggingface_hub.constants import HF_HUB_OFFLINE
23
+ from huggingface_hub.utils import validate_hf_hub_args
24
+ from packaging import version
25
+ from torch import nn
26
+
27
+ from .. import __version__
28
+ from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT
29
+ from ..utils import (
30
+ USE_PEFT_BACKEND,
31
+ _get_model_file,
32
+ convert_state_dict_to_diffusers,
33
+ convert_state_dict_to_peft,
34
+ convert_unet_state_dict_to_peft,
35
+ delete_adapter_layers,
36
+ get_adapter_name,
37
+ get_peft_kwargs,
38
+ is_accelerate_available,
39
+ is_transformers_available,
40
+ logging,
41
+ recurse_remove_peft_layers,
42
+ scale_lora_layers,
43
+ set_adapter_layers,
44
+ set_weights_and_activate_adapters,
45
+ )
46
+ from .lora_conversion_utils import _convert_kohya_lora_to_diffusers, _maybe_map_sgm_blocks_to_diffusers
47
+
48
+
49
+ if is_transformers_available():
50
+ from transformers import PreTrainedModel
51
+
52
+ from ..models.lora import text_encoder_attn_modules, text_encoder_mlp_modules
53
+
54
+ if is_accelerate_available():
55
+ from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+ TEXT_ENCODER_NAME = "text_encoder"
60
+ UNET_NAME = "unet"
61
+ TRANSFORMER_NAME = "transformer"
62
+
63
+ LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
64
+ LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
65
+
66
+ LORA_DEPRECATION_MESSAGE = "You are using an old version of LoRA backend. This will be deprecated in the next releases in favor of PEFT make sure to install the latest PEFT and transformers packages in the future."
67
+
68
+
69
+ class LoraLoaderMixin:
70
+ r"""
71
+ Load LoRA layers into [`UNet2DConditionModel`] and
72
+ [`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel).
73
+ """
74
+
75
+ text_encoder_name = TEXT_ENCODER_NAME
76
+ unet_name = UNET_NAME
77
+ transformer_name = TRANSFORMER_NAME
78
+ num_fused_loras = 0
79
+
80
+ def load_lora_weights(
81
+ self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], adapter_name=None, **kwargs
82
+ ):
83
+ """
84
+ Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
85
+ `self.text_encoder`.
86
+
87
+ All kwargs are forwarded to `self.lora_state_dict`.
88
+
89
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
90
+
91
+ See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
92
+ `self.unet`.
93
+
94
+ See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
95
+ into `self.text_encoder`.
96
+
97
+ Parameters:
98
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
99
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
100
+ kwargs (`dict`, *optional*):
101
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
102
+ adapter_name (`str`, *optional*):
103
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
104
+ `default_{i}` where i is the total number of adapters being loaded.
105
+ """
106
+ if not USE_PEFT_BACKEND:
107
+ raise ValueError("PEFT backend is required for this method.")
108
+
109
+ # if a dict is passed, copy it instead of modifying it inplace
110
+ if isinstance(pretrained_model_name_or_path_or_dict, dict):
111
+ pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict.copy()
112
+
113
+ # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
114
+ state_dict, network_alphas = self.lora_state_dict(pretrained_model_name_or_path_or_dict, **kwargs)
115
+
116
+ is_correct_format = all("lora" in key for key in state_dict.keys())
117
+ if not is_correct_format:
118
+ raise ValueError("Invalid LoRA checkpoint.")
119
+
120
+ low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
121
+
122
+ self.load_lora_into_unet(
123
+ state_dict,
124
+ network_alphas=network_alphas,
125
+ unet=getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet,
126
+ low_cpu_mem_usage=low_cpu_mem_usage,
127
+ adapter_name=adapter_name,
128
+ _pipeline=self,
129
+ )
130
+ self.load_lora_into_text_encoder(
131
+ state_dict,
132
+ network_alphas=network_alphas,
133
+ text_encoder=getattr(self, self.text_encoder_name)
134
+ if not hasattr(self, "text_encoder")
135
+ else self.text_encoder,
136
+ lora_scale=self.lora_scale,
137
+ low_cpu_mem_usage=low_cpu_mem_usage,
138
+ adapter_name=adapter_name,
139
+ _pipeline=self,
140
+ )
141
+
142
+ @classmethod
143
+ @validate_hf_hub_args
144
+ def lora_state_dict(
145
+ cls,
146
+ pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
147
+ **kwargs,
148
+ ):
149
+ r"""
150
+ Return state dict for lora weights and the network alphas.
151
+
152
+ <Tip warning={true}>
153
+
154
+ We support loading A1111 formatted LoRA checkpoints in a limited capacity.
155
+
156
+ This function is experimental and might change in the future.
157
+
158
+ </Tip>
159
+
160
+ Parameters:
161
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
162
+ Can be either:
163
+
164
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
165
+ the Hub.
166
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
167
+ with [`ModelMixin.save_pretrained`].
168
+ - A [torch state
169
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
170
+
171
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
172
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
173
+ is not used.
174
+ force_download (`bool`, *optional*, defaults to `False`):
175
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
176
+ cached versions if they exist.
177
+ resume_download (`bool`, *optional*, defaults to `False`):
178
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
179
+ incompletely downloaded files are deleted.
180
+ proxies (`Dict[str, str]`, *optional*):
181
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
182
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
183
+ local_files_only (`bool`, *optional*, defaults to `False`):
184
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
185
+ won't be downloaded from the Hub.
186
+ token (`str` or *bool*, *optional*):
187
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
188
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
189
+ revision (`str`, *optional*, defaults to `"main"`):
190
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
191
+ allowed by Git.
192
+ subfolder (`str`, *optional*, defaults to `""`):
193
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
194
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
195
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
196
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
197
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
198
+ argument to `True` will raise an error.
199
+ mirror (`str`, *optional*):
200
+ Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
201
+ guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
202
+ information.
203
+
204
+ """
205
+ # Load the main state dict first which has the LoRA layers for either of
206
+ # UNet and text encoder or both.
207
+ cache_dir = kwargs.pop("cache_dir", None)
208
+ force_download = kwargs.pop("force_download", False)
209
+ resume_download = kwargs.pop("resume_download", False)
210
+ proxies = kwargs.pop("proxies", None)
211
+ local_files_only = kwargs.pop("local_files_only", None)
212
+ token = kwargs.pop("token", None)
213
+ revision = kwargs.pop("revision", None)
214
+ subfolder = kwargs.pop("subfolder", None)
215
+ weight_name = kwargs.pop("weight_name", None)
216
+ unet_config = kwargs.pop("unet_config", None)
217
+ use_safetensors = kwargs.pop("use_safetensors", None)
218
+
219
+ allow_pickle = False
220
+ if use_safetensors is None:
221
+ use_safetensors = True
222
+ allow_pickle = True
223
+
224
+ user_agent = {
225
+ "file_type": "attn_procs_weights",
226
+ "framework": "pytorch",
227
+ }
228
+
229
+ model_file = None
230
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
231
+ # Let's first try to load .safetensors weights
232
+ if (use_safetensors and weight_name is None) or (
233
+ weight_name is not None and weight_name.endswith(".safetensors")
234
+ ):
235
+ try:
236
+ # Here we're relaxing the loading check to enable more Inference API
237
+ # friendliness where sometimes, it's not at all possible to automatically
238
+ # determine `weight_name`.
239
+ if weight_name is None:
240
+ weight_name = cls._best_guess_weight_name(
241
+ pretrained_model_name_or_path_or_dict,
242
+ file_extension=".safetensors",
243
+ local_files_only=local_files_only,
244
+ )
245
+ model_file = _get_model_file(
246
+ pretrained_model_name_or_path_or_dict,
247
+ weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
248
+ cache_dir=cache_dir,
249
+ force_download=force_download,
250
+ resume_download=resume_download,
251
+ proxies=proxies,
252
+ local_files_only=local_files_only,
253
+ token=token,
254
+ revision=revision,
255
+ subfolder=subfolder,
256
+ user_agent=user_agent,
257
+ )
258
+ state_dict = safetensors.torch.load_file(model_file, device="cpu")
259
+ except (IOError, safetensors.SafetensorError) as e:
260
+ if not allow_pickle:
261
+ raise e
262
+ # try loading non-safetensors weights
263
+ model_file = None
264
+ pass
265
+
266
+ if model_file is None:
267
+ if weight_name is None:
268
+ weight_name = cls._best_guess_weight_name(
269
+ pretrained_model_name_or_path_or_dict, file_extension=".bin", local_files_only=local_files_only
270
+ )
271
+ model_file = _get_model_file(
272
+ pretrained_model_name_or_path_or_dict,
273
+ weights_name=weight_name or LORA_WEIGHT_NAME,
274
+ cache_dir=cache_dir,
275
+ force_download=force_download,
276
+ resume_download=resume_download,
277
+ proxies=proxies,
278
+ local_files_only=local_files_only,
279
+ token=token,
280
+ revision=revision,
281
+ subfolder=subfolder,
282
+ user_agent=user_agent,
283
+ )
284
+ state_dict = torch.load(model_file, map_location="cpu")
285
+ else:
286
+ state_dict = pretrained_model_name_or_path_or_dict
287
+
288
+ network_alphas = None
289
+ # TODO: replace it with a method from `state_dict_utils`
290
+ if all(
291
+ (
292
+ k.startswith("lora_te_")
293
+ or k.startswith("lora_unet_")
294
+ or k.startswith("lora_te1_")
295
+ or k.startswith("lora_te2_")
296
+ )
297
+ for k in state_dict.keys()
298
+ ):
299
+ # Map SDXL blocks correctly.
300
+ if unet_config is not None:
301
+ # use unet config to remap block numbers
302
+ state_dict = _maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config)
303
+ state_dict, network_alphas = _convert_kohya_lora_to_diffusers(state_dict)
304
+
305
+ return state_dict, network_alphas
306
+
307
+ @classmethod
308
+ def _best_guess_weight_name(
309
+ cls, pretrained_model_name_or_path_or_dict, file_extension=".safetensors", local_files_only=False
310
+ ):
311
+ if local_files_only or HF_HUB_OFFLINE:
312
+ raise ValueError("When using the offline mode, you must specify a `weight_name`.")
313
+
314
+ targeted_files = []
315
+
316
+ if os.path.isfile(pretrained_model_name_or_path_or_dict):
317
+ return
318
+ elif os.path.isdir(pretrained_model_name_or_path_or_dict):
319
+ targeted_files = [
320
+ f for f in os.listdir(pretrained_model_name_or_path_or_dict) if f.endswith(file_extension)
321
+ ]
322
+ else:
323
+ files_in_repo = model_info(pretrained_model_name_or_path_or_dict).siblings
324
+ targeted_files = [f.rfilename for f in files_in_repo if f.rfilename.endswith(file_extension)]
325
+ if len(targeted_files) == 0:
326
+ return
327
+
328
+ # "scheduler" does not correspond to a LoRA checkpoint.
329
+ # "optimizer" does not correspond to a LoRA checkpoint
330
+ # only top-level checkpoints are considered and not the other ones, hence "checkpoint".
331
+ unallowed_substrings = {"scheduler", "optimizer", "checkpoint"}
332
+ targeted_files = list(
333
+ filter(lambda x: all(substring not in x for substring in unallowed_substrings), targeted_files)
334
+ )
335
+
336
+ if any(f.endswith(LORA_WEIGHT_NAME) for f in targeted_files):
337
+ targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME), targeted_files))
338
+ elif any(f.endswith(LORA_WEIGHT_NAME_SAFE) for f in targeted_files):
339
+ targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME_SAFE), targeted_files))
340
+
341
+ if len(targeted_files) > 1:
342
+ raise ValueError(
343
+ f"Provided path contains more than one weights file in the {file_extension} format. Either specify `weight_name` in `load_lora_weights` or make sure there's only one `.safetensors` or `.bin` file in {pretrained_model_name_or_path_or_dict}."
344
+ )
345
+ weight_name = targeted_files[0]
346
+ return weight_name
347
+
348
+ @classmethod
349
+ def _optionally_disable_offloading(cls, _pipeline):
350
+ """
351
+ Optionally removes offloading in case the pipeline has been already sequentially offloaded to CPU.
352
+
353
+ Args:
354
+ _pipeline (`DiffusionPipeline`):
355
+ The pipeline to disable offloading for.
356
+
357
+ Returns:
358
+ tuple:
359
+ A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True.
360
+ """
361
+ is_model_cpu_offload = False
362
+ is_sequential_cpu_offload = False
363
+
364
+ if _pipeline is not None:
365
+ for _, component in _pipeline.components.items():
366
+ if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
367
+ if not is_model_cpu_offload:
368
+ is_model_cpu_offload = isinstance(component._hf_hook, CpuOffload)
369
+ if not is_sequential_cpu_offload:
370
+ is_sequential_cpu_offload = isinstance(component._hf_hook, AlignDevicesHook)
371
+
372
+ logger.info(
373
+ "Accelerate hooks detected. Since you have called `load_lora_weights()`, the previous hooks will be first removed. Then the LoRA parameters will be loaded and the hooks will be applied again."
374
+ )
375
+ remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
376
+
377
+ return (is_model_cpu_offload, is_sequential_cpu_offload)
378
+
379
+ @classmethod
380
+ def load_lora_into_unet(
381
+ cls, state_dict, network_alphas, unet, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None
382
+ ):
383
+ """
384
+ This will load the LoRA layers specified in `state_dict` into `unet`.
385
+
386
+ Parameters:
387
+ state_dict (`dict`):
388
+ A standard state dict containing the lora layer parameters. The keys can either be indexed directly
389
+ into the unet or prefixed with an additional `unet` which can be used to distinguish between text
390
+ encoder lora layers.
391
+ network_alphas (`Dict[str, float]`):
392
+ See `LoRALinearLayer` for more details.
393
+ unet (`UNet2DConditionModel`):
394
+ The UNet model to load the LoRA layers into.
395
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
396
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
397
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
398
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
399
+ argument to `True` will raise an error.
400
+ adapter_name (`str`, *optional*):
401
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
402
+ `default_{i}` where i is the total number of adapters being loaded.
403
+ """
404
+ if not USE_PEFT_BACKEND:
405
+ raise ValueError("PEFT backend is required for this method.")
406
+
407
+ from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
408
+
409
+ low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
410
+ # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
411
+ # then the `state_dict` keys should have `cls.unet_name` and/or `cls.text_encoder_name` as
412
+ # their prefixes.
413
+ keys = list(state_dict.keys())
414
+
415
+ if all(key.startswith(cls.unet_name) or key.startswith(cls.text_encoder_name) for key in keys):
416
+ # Load the layers corresponding to UNet.
417
+ logger.info(f"Loading {cls.unet_name}.")
418
+
419
+ unet_keys = [k for k in keys if k.startswith(cls.unet_name)]
420
+ state_dict = {k.replace(f"{cls.unet_name}.", ""): v for k, v in state_dict.items() if k in unet_keys}
421
+
422
+ if network_alphas is not None:
423
+ alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.unet_name)]
424
+ network_alphas = {
425
+ k.replace(f"{cls.unet_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
426
+ }
427
+
428
+ else:
429
+ # Otherwise, we're dealing with the old format. This means the `state_dict` should only
430
+ # contain the module names of the `unet` as its keys WITHOUT any prefix.
431
+ if not USE_PEFT_BACKEND:
432
+ warn_message = "You have saved the LoRA weights using the old format. To convert the old LoRA weights to the new format, you can first load them in a dictionary and then create a new dictionary like the following: `new_state_dict = {f'unet.{module_name}': params for module_name, params in old_state_dict.items()}`."
433
+ logger.warning(warn_message)
434
+
435
+ if len(state_dict.keys()) > 0:
436
+ if adapter_name in getattr(unet, "peft_config", {}):
437
+ raise ValueError(
438
+ f"Adapter name {adapter_name} already in use in the Unet - please select a new adapter name."
439
+ )
440
+
441
+ state_dict = convert_unet_state_dict_to_peft(state_dict)
442
+
443
+ if network_alphas is not None:
444
+ # The alphas state dict have the same structure as Unet, thus we convert it to peft format using
445
+ # `convert_unet_state_dict_to_peft` method.
446
+ network_alphas = convert_unet_state_dict_to_peft(network_alphas)
447
+
448
+ rank = {}
449
+ for key, val in state_dict.items():
450
+ if "lora_B" in key:
451
+ rank[key] = val.shape[1]
452
+
453
+ lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict, is_unet=True)
454
+ lora_config = LoraConfig(**lora_config_kwargs)
455
+
456
+ # adapter_name
457
+ if adapter_name is None:
458
+ adapter_name = get_adapter_name(unet)
459
+
460
+ # In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
461
+ # otherwise loading LoRA weights will lead to an error
462
+ is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
463
+
464
+ inject_adapter_in_model(lora_config, unet, adapter_name=adapter_name)
465
+ incompatible_keys = set_peft_model_state_dict(unet, state_dict, adapter_name)
466
+
467
+ if incompatible_keys is not None:
468
+ # check only for unexpected keys
469
+ unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
470
+ if unexpected_keys:
471
+ logger.warning(
472
+ f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
473
+ f" {unexpected_keys}. "
474
+ )
475
+
476
+ # Offload back.
477
+ if is_model_cpu_offload:
478
+ _pipeline.enable_model_cpu_offload()
479
+ elif is_sequential_cpu_offload:
480
+ _pipeline.enable_sequential_cpu_offload()
481
+ # Unsafe code />
482
+
483
+ unet.load_attn_procs(
484
+ state_dict, network_alphas=network_alphas, low_cpu_mem_usage=low_cpu_mem_usage, _pipeline=_pipeline
485
+ )
486
+
487
+ @classmethod
488
+ def load_lora_into_text_encoder(
489
+ cls,
490
+ state_dict,
491
+ network_alphas,
492
+ text_encoder,
493
+ prefix=None,
494
+ lora_scale=1.0,
495
+ low_cpu_mem_usage=None,
496
+ adapter_name=None,
497
+ _pipeline=None,
498
+ ):
499
+ """
500
+ This will load the LoRA layers specified in `state_dict` into `text_encoder`
501
+
502
+ Parameters:
503
+ state_dict (`dict`):
504
+ A standard state dict containing the lora layer parameters. The key should be prefixed with an
505
+ additional `text_encoder` to distinguish between unet lora layers.
506
+ network_alphas (`Dict[str, float]`):
507
+ See `LoRALinearLayer` for more details.
508
+ text_encoder (`CLIPTextModel`):
509
+ The text encoder model to load the LoRA layers into.
510
+ prefix (`str`):
511
+ Expected prefix of the `text_encoder` in the `state_dict`.
512
+ lora_scale (`float`):
513
+ How much to scale the output of the lora linear layer before it is added with the output of the regular
514
+ lora layer.
515
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
516
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
517
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
518
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
519
+ argument to `True` will raise an error.
520
+ adapter_name (`str`, *optional*):
521
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
522
+ `default_{i}` where i is the total number of adapters being loaded.
523
+ """
524
+ if not USE_PEFT_BACKEND:
525
+ raise ValueError("PEFT backend is required for this method.")
526
+
527
+ from peft import LoraConfig
528
+
529
+ low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
530
+
531
+ # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
532
+ # then the `state_dict` keys should have `self.unet_name` and/or `self.text_encoder_name` as
533
+ # their prefixes.
534
+ keys = list(state_dict.keys())
535
+ prefix = cls.text_encoder_name if prefix is None else prefix
536
+
537
+ # Safe prefix to check with.
538
+ if any(cls.text_encoder_name in key for key in keys):
539
+ # Load the layers corresponding to text encoder and make necessary adjustments.
540
+ text_encoder_keys = [k for k in keys if k.startswith(prefix) and k.split(".")[0] == prefix]
541
+ text_encoder_lora_state_dict = {
542
+ k.replace(f"{prefix}.", ""): v for k, v in state_dict.items() if k in text_encoder_keys
543
+ }
544
+
545
+ if len(text_encoder_lora_state_dict) > 0:
546
+ logger.info(f"Loading {prefix}.")
547
+ rank = {}
548
+ text_encoder_lora_state_dict = convert_state_dict_to_diffusers(text_encoder_lora_state_dict)
549
+
550
+ # convert state dict
551
+ text_encoder_lora_state_dict = convert_state_dict_to_peft(text_encoder_lora_state_dict)
552
+
553
+ for name, _ in text_encoder_attn_modules(text_encoder):
554
+ rank_key = f"{name}.out_proj.lora_B.weight"
555
+ rank[rank_key] = text_encoder_lora_state_dict[rank_key].shape[1]
556
+
557
+ patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
558
+ if patch_mlp:
559
+ for name, _ in text_encoder_mlp_modules(text_encoder):
560
+ rank_key_fc1 = f"{name}.fc1.lora_B.weight"
561
+ rank_key_fc2 = f"{name}.fc2.lora_B.weight"
562
+
563
+ rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
564
+ rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
565
+
566
+ if network_alphas is not None:
567
+ alpha_keys = [
568
+ k for k in network_alphas.keys() if k.startswith(prefix) and k.split(".")[0] == prefix
569
+ ]
570
+ network_alphas = {
571
+ k.replace(f"{prefix}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
572
+ }
573
+
574
+ lora_config_kwargs = get_peft_kwargs(rank, network_alphas, text_encoder_lora_state_dict, is_unet=False)
575
+ lora_config = LoraConfig(**lora_config_kwargs)
576
+
577
+ # adapter_name
578
+ if adapter_name is None:
579
+ adapter_name = get_adapter_name(text_encoder)
580
+
581
+ is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
582
+
583
+ # inject LoRA layers and load the state dict
584
+ # in transformers we automatically check whether the adapter name is already in use or not
585
+ text_encoder.load_adapter(
586
+ adapter_name=adapter_name,
587
+ adapter_state_dict=text_encoder_lora_state_dict,
588
+ peft_config=lora_config,
589
+ )
590
+
591
+ # scale LoRA layers with `lora_scale`
592
+ scale_lora_layers(text_encoder, weight=lora_scale)
593
+
594
+ text_encoder.to(device=text_encoder.device, dtype=text_encoder.dtype)
595
+
596
+ # Offload back.
597
+ if is_model_cpu_offload:
598
+ _pipeline.enable_model_cpu_offload()
599
+ elif is_sequential_cpu_offload:
600
+ _pipeline.enable_sequential_cpu_offload()
601
+ # Unsafe code />
602
+
603
+ @classmethod
604
+ def load_lora_into_transformer(
605
+ cls, state_dict, network_alphas, transformer, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None
606
+ ):
607
+ """
608
+ This will load the LoRA layers specified in `state_dict` into `transformer`.
609
+
610
+ Parameters:
611
+ state_dict (`dict`):
612
+ A standard state dict containing the lora layer parameters. The keys can either be indexed directly
613
+ into the unet or prefixed with an additional `unet` which can be used to distinguish between text
614
+ encoder lora layers.
615
+ network_alphas (`Dict[str, float]`):
616
+ See `LoRALinearLayer` for more details.
617
+ unet (`UNet2DConditionModel`):
618
+ The UNet model to load the LoRA layers into.
619
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
620
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
621
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
622
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
623
+ argument to `True` will raise an error.
624
+ adapter_name (`str`, *optional*):
625
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
626
+ `default_{i}` where i is the total number of adapters being loaded.
627
+ """
628
+ from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
629
+
630
+ low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
631
+
632
+ keys = list(state_dict.keys())
633
+
634
+ transformer_keys = [k for k in keys if k.startswith(cls.transformer_name)]
635
+ state_dict = {
636
+ k.replace(f"{cls.transformer_name}.", ""): v for k, v in state_dict.items() if k in transformer_keys
637
+ }
638
+
639
+ if network_alphas is not None:
640
+ alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.transformer_name)]
641
+ network_alphas = {
642
+ k.replace(f"{cls.transformer_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
643
+ }
644
+
645
+ if len(state_dict.keys()) > 0:
646
+ if adapter_name in getattr(transformer, "peft_config", {}):
647
+ raise ValueError(
648
+ f"Adapter name {adapter_name} already in use in the transformer - please select a new adapter name."
649
+ )
650
+
651
+ rank = {}
652
+ for key, val in state_dict.items():
653
+ if "lora_B" in key:
654
+ rank[key] = val.shape[1]
655
+
656
+ lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict)
657
+ lora_config = LoraConfig(**lora_config_kwargs)
658
+
659
+ # adapter_name
660
+ if adapter_name is None:
661
+ adapter_name = get_adapter_name(transformer)
662
+
663
+ # In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
664
+ # otherwise loading LoRA weights will lead to an error
665
+ is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
666
+
667
+ inject_adapter_in_model(lora_config, transformer, adapter_name=adapter_name)
668
+ incompatible_keys = set_peft_model_state_dict(transformer, state_dict, adapter_name)
669
+
670
+ if incompatible_keys is not None:
671
+ # check only for unexpected keys
672
+ unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
673
+ if unexpected_keys:
674
+ logger.warning(
675
+ f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
676
+ f" {unexpected_keys}. "
677
+ )
678
+
679
+ # Offload back.
680
+ if is_model_cpu_offload:
681
+ _pipeline.enable_model_cpu_offload()
682
+ elif is_sequential_cpu_offload:
683
+ _pipeline.enable_sequential_cpu_offload()
684
+ # Unsafe code />
685
+
686
+ @property
687
+ def lora_scale(self) -> float:
688
+ # property function that returns the lora scale which can be set at run time by the pipeline.
689
+ # if _lora_scale has not been set, return 1
690
+ return self._lora_scale if hasattr(self, "_lora_scale") else 1.0
691
+
692
+ def _remove_text_encoder_monkey_patch(self):
693
+ remove_method = recurse_remove_peft_layers
694
+ if hasattr(self, "text_encoder"):
695
+ remove_method(self.text_encoder)
696
+ # In case text encoder have no Lora attached
697
+ if getattr(self.text_encoder, "peft_config", None) is not None:
698
+ del self.text_encoder.peft_config
699
+ self.text_encoder._hf_peft_config_loaded = None
700
+
701
+ if hasattr(self, "text_encoder_2"):
702
+ remove_method(self.text_encoder_2)
703
+ if getattr(self.text_encoder_2, "peft_config", None) is not None:
704
+ del self.text_encoder_2.peft_config
705
+ self.text_encoder_2._hf_peft_config_loaded = None
706
+
707
+ @classmethod
708
+ def save_lora_weights(
709
+ cls,
710
+ save_directory: Union[str, os.PathLike],
711
+ unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
712
+ text_encoder_lora_layers: Dict[str, torch.nn.Module] = None,
713
+ transformer_lora_layers: Dict[str, torch.nn.Module] = None,
714
+ is_main_process: bool = True,
715
+ weight_name: str = None,
716
+ save_function: Callable = None,
717
+ safe_serialization: bool = True,
718
+ ):
719
+ r"""
720
+ Save the LoRA parameters corresponding to the UNet and text encoder.
721
+
722
+ Arguments:
723
+ save_directory (`str` or `os.PathLike`):
724
+ Directory to save LoRA parameters to. Will be created if it doesn't exist.
725
+ unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
726
+ State dict of the LoRA layers corresponding to the `unet`.
727
+ text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
728
+ State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
729
+ encoder LoRA state dict because it comes from 🤗 Transformers.
730
+ is_main_process (`bool`, *optional*, defaults to `True`):
731
+ Whether the process calling this is the main process or not. Useful during distributed training and you
732
+ need to call this function on all processes. In this case, set `is_main_process=True` only on the main
733
+ process to avoid race conditions.
734
+ save_function (`Callable`):
735
+ The function to use to save the state dictionary. Useful during distributed training when you need to
736
+ replace `torch.save` with another method. Can be configured with the environment variable
737
+ `DIFFUSERS_SAVE_MODE`.
738
+ safe_serialization (`bool`, *optional*, defaults to `True`):
739
+ Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
740
+ """
741
+ state_dict = {}
742
+
743
+ def pack_weights(layers, prefix):
744
+ layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
745
+ layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
746
+ return layers_state_dict
747
+
748
+ if not (unet_lora_layers or text_encoder_lora_layers or transformer_lora_layers):
749
+ raise ValueError(
750
+ "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers`, or `transformer_lora_layers`."
751
+ )
752
+
753
+ if unet_lora_layers:
754
+ state_dict.update(pack_weights(unet_lora_layers, cls.unet_name))
755
+
756
+ if text_encoder_lora_layers:
757
+ state_dict.update(pack_weights(text_encoder_lora_layers, cls.text_encoder_name))
758
+
759
+ if transformer_lora_layers:
760
+ state_dict.update(pack_weights(transformer_lora_layers, "transformer"))
761
+
762
+ # Save the model
763
+ cls.write_lora_layers(
764
+ state_dict=state_dict,
765
+ save_directory=save_directory,
766
+ is_main_process=is_main_process,
767
+ weight_name=weight_name,
768
+ save_function=save_function,
769
+ safe_serialization=safe_serialization,
770
+ )
771
+
772
+ @staticmethod
773
+ def write_lora_layers(
774
+ state_dict: Dict[str, torch.Tensor],
775
+ save_directory: str,
776
+ is_main_process: bool,
777
+ weight_name: str,
778
+ save_function: Callable,
779
+ safe_serialization: bool,
780
+ ):
781
+ if os.path.isfile(save_directory):
782
+ logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
783
+ return
784
+
785
+ if save_function is None:
786
+ if safe_serialization:
787
+
788
+ def save_function(weights, filename):
789
+ return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
790
+
791
+ else:
792
+ save_function = torch.save
793
+
794
+ os.makedirs(save_directory, exist_ok=True)
795
+
796
+ if weight_name is None:
797
+ if safe_serialization:
798
+ weight_name = LORA_WEIGHT_NAME_SAFE
799
+ else:
800
+ weight_name = LORA_WEIGHT_NAME
801
+
802
+ save_path = Path(save_directory, weight_name).as_posix()
803
+ save_function(state_dict, save_path)
804
+ logger.info(f"Model weights saved in {save_path}")
805
+
806
+ def unload_lora_weights(self):
807
+ """
808
+ Unloads the LoRA parameters.
809
+
810
+ Examples:
811
+
812
+ ```python
813
+ >>> # Assuming `pipeline` is already loaded with the LoRA parameters.
814
+ >>> pipeline.unload_lora_weights()
815
+ >>> ...
816
+ ```
817
+ """
818
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
819
+
820
+ if not USE_PEFT_BACKEND:
821
+ if version.parse(__version__) > version.parse("0.23"):
822
+ logger.warning(
823
+ "You are using `unload_lora_weights` to disable and unload lora weights. If you want to iteratively enable and disable adapter weights,"
824
+ "you can use `pipe.enable_lora()` or `pipe.disable_lora()`. After installing the latest version of PEFT."
825
+ )
826
+
827
+ for _, module in unet.named_modules():
828
+ if hasattr(module, "set_lora_layer"):
829
+ module.set_lora_layer(None)
830
+ else:
831
+ recurse_remove_peft_layers(unet)
832
+ if hasattr(unet, "peft_config"):
833
+ del unet.peft_config
834
+
835
+ # Safe to call the following regardless of LoRA.
836
+ self._remove_text_encoder_monkey_patch()
837
+
838
+ def fuse_lora(
839
+ self,
840
+ fuse_unet: bool = True,
841
+ fuse_text_encoder: bool = True,
842
+ lora_scale: float = 1.0,
843
+ safe_fusing: bool = False,
844
+ adapter_names: Optional[List[str]] = None,
845
+ ):
846
+ r"""
847
+ Fuses the LoRA parameters into the original parameters of the corresponding blocks.
848
+
849
+ <Tip warning={true}>
850
+
851
+ This is an experimental API.
852
+
853
+ </Tip>
854
+
855
+ Args:
856
+ fuse_unet (`bool`, defaults to `True`): Whether to fuse the UNet LoRA parameters.
857
+ fuse_text_encoder (`bool`, defaults to `True`):
858
+ Whether to fuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
859
+ LoRA parameters then it won't have any effect.
860
+ lora_scale (`float`, defaults to 1.0):
861
+ Controls how much to influence the outputs with the LoRA parameters.
862
+ safe_fusing (`bool`, defaults to `False`):
863
+ Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
864
+ adapter_names (`List[str]`, *optional*):
865
+ Adapter names to be used for fusing. If nothing is passed, all active adapters will be fused.
866
+
867
+ Example:
868
+
869
+ ```py
870
+ from diffusers import DiffusionPipeline
871
+ import torch
872
+
873
+ pipeline = DiffusionPipeline.from_pretrained(
874
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
875
+ ).to("cuda")
876
+ pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
877
+ pipeline.fuse_lora(lora_scale=0.7)
878
+ ```
879
+ """
880
+ from peft.tuners.tuners_utils import BaseTunerLayer
881
+
882
+ if fuse_unet or fuse_text_encoder:
883
+ self.num_fused_loras += 1
884
+ if self.num_fused_loras > 1:
885
+ logger.warning(
886
+ "The current API is supported for operating with a single LoRA file. You are trying to load and fuse more than one LoRA which is not well-supported.",
887
+ )
888
+
889
+ if fuse_unet:
890
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
891
+ unet.fuse_lora(lora_scale, safe_fusing=safe_fusing, adapter_names=adapter_names)
892
+
893
+ def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False, adapter_names=None):
894
+ merge_kwargs = {"safe_merge": safe_fusing}
895
+
896
+ for module in text_encoder.modules():
897
+ if isinstance(module, BaseTunerLayer):
898
+ if lora_scale != 1.0:
899
+ module.scale_layer(lora_scale)
900
+
901
+ # For BC with previous PEFT versions, we need to check the signature
902
+ # of the `merge` method to see if it supports the `adapter_names` argument.
903
+ supported_merge_kwargs = list(inspect.signature(module.merge).parameters)
904
+ if "adapter_names" in supported_merge_kwargs:
905
+ merge_kwargs["adapter_names"] = adapter_names
906
+ elif "adapter_names" not in supported_merge_kwargs and adapter_names is not None:
907
+ raise ValueError(
908
+ "The `adapter_names` argument is not supported with your PEFT version. "
909
+ "Please upgrade to the latest version of PEFT. `pip install -U peft`"
910
+ )
911
+
912
+ module.merge(**merge_kwargs)
913
+
914
+ if fuse_text_encoder:
915
+ if hasattr(self, "text_encoder"):
916
+ fuse_text_encoder_lora(self.text_encoder, lora_scale, safe_fusing, adapter_names=adapter_names)
917
+ if hasattr(self, "text_encoder_2"):
918
+ fuse_text_encoder_lora(self.text_encoder_2, lora_scale, safe_fusing, adapter_names=adapter_names)
919
+
920
+ def unfuse_lora(self, unfuse_unet: bool = True, unfuse_text_encoder: bool = True):
921
+ r"""
922
+ Reverses the effect of
923
+ [`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.fuse_lora).
924
+
925
+ <Tip warning={true}>
926
+
927
+ This is an experimental API.
928
+
929
+ </Tip>
930
+
931
+ Args:
932
+ unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
933
+ unfuse_text_encoder (`bool`, defaults to `True`):
934
+ Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
935
+ LoRA parameters then it won't have any effect.
936
+ """
937
+ from peft.tuners.tuners_utils import BaseTunerLayer
938
+
939
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
940
+ if unfuse_unet:
941
+ for module in unet.modules():
942
+ if isinstance(module, BaseTunerLayer):
943
+ module.unmerge()
944
+
945
+ def unfuse_text_encoder_lora(text_encoder):
946
+ for module in text_encoder.modules():
947
+ if isinstance(module, BaseTunerLayer):
948
+ module.unmerge()
949
+
950
+ if unfuse_text_encoder:
951
+ if hasattr(self, "text_encoder"):
952
+ unfuse_text_encoder_lora(self.text_encoder)
953
+ if hasattr(self, "text_encoder_2"):
954
+ unfuse_text_encoder_lora(self.text_encoder_2)
955
+
956
+ self.num_fused_loras -= 1
957
+
958
+ def set_adapters_for_text_encoder(
959
+ self,
960
+ adapter_names: Union[List[str], str],
961
+ text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
962
+ text_encoder_weights: List[float] = None,
963
+ ):
964
+ """
965
+ Sets the adapter layers for the text encoder.
966
+
967
+ Args:
968
+ adapter_names (`List[str]` or `str`):
969
+ The names of the adapters to use.
970
+ text_encoder (`torch.nn.Module`, *optional*):
971
+ The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
972
+ attribute.
973
+ text_encoder_weights (`List[float]`, *optional*):
974
+ The weights to use for the text encoder. If `None`, the weights are set to `1.0` for all the adapters.
975
+ """
976
+ if not USE_PEFT_BACKEND:
977
+ raise ValueError("PEFT backend is required for this method.")
978
+
979
+ def process_weights(adapter_names, weights):
980
+ if weights is None:
981
+ weights = [1.0] * len(adapter_names)
982
+ elif isinstance(weights, float):
983
+ weights = [weights]
984
+
985
+ if len(adapter_names) != len(weights):
986
+ raise ValueError(
987
+ f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(weights)}"
988
+ )
989
+ return weights
990
+
991
+ adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
992
+ text_encoder_weights = process_weights(adapter_names, text_encoder_weights)
993
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
994
+ if text_encoder is None:
995
+ raise ValueError(
996
+ "The pipeline does not have a default `pipe.text_encoder` class. Please make sure to pass a `text_encoder` instead."
997
+ )
998
+ set_weights_and_activate_adapters(text_encoder, adapter_names, text_encoder_weights)
999
+
1000
+ def disable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
1001
+ """
1002
+ Disables the LoRA layers for the text encoder.
1003
+
1004
+ Args:
1005
+ text_encoder (`torch.nn.Module`, *optional*):
1006
+ The text encoder module to disable the LoRA layers for. If `None`, it will try to get the
1007
+ `text_encoder` attribute.
1008
+ """
1009
+ if not USE_PEFT_BACKEND:
1010
+ raise ValueError("PEFT backend is required for this method.")
1011
+
1012
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
1013
+ if text_encoder is None:
1014
+ raise ValueError("Text Encoder not found.")
1015
+ set_adapter_layers(text_encoder, enabled=False)
1016
+
1017
+ def enable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
1018
+ """
1019
+ Enables the LoRA layers for the text encoder.
1020
+
1021
+ Args:
1022
+ text_encoder (`torch.nn.Module`, *optional*):
1023
+ The text encoder module to enable the LoRA layers for. If `None`, it will try to get the `text_encoder`
1024
+ attribute.
1025
+ """
1026
+ if not USE_PEFT_BACKEND:
1027
+ raise ValueError("PEFT backend is required for this method.")
1028
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
1029
+ if text_encoder is None:
1030
+ raise ValueError("Text Encoder not found.")
1031
+ set_adapter_layers(self.text_encoder, enabled=True)
1032
+
1033
+ def set_adapters(
1034
+ self,
1035
+ adapter_names: Union[List[str], str],
1036
+ adapter_weights: Optional[List[float]] = None,
1037
+ ):
1038
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1039
+ # Handle the UNET
1040
+ unet.set_adapters(adapter_names, adapter_weights)
1041
+
1042
+ # Handle the Text Encoder
1043
+ if hasattr(self, "text_encoder"):
1044
+ self.set_adapters_for_text_encoder(adapter_names, self.text_encoder, adapter_weights)
1045
+ if hasattr(self, "text_encoder_2"):
1046
+ self.set_adapters_for_text_encoder(adapter_names, self.text_encoder_2, adapter_weights)
1047
+
1048
+ def disable_lora(self):
1049
+ if not USE_PEFT_BACKEND:
1050
+ raise ValueError("PEFT backend is required for this method.")
1051
+
1052
+ # Disable unet adapters
1053
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1054
+ unet.disable_lora()
1055
+
1056
+ # Disable text encoder adapters
1057
+ if hasattr(self, "text_encoder"):
1058
+ self.disable_lora_for_text_encoder(self.text_encoder)
1059
+ if hasattr(self, "text_encoder_2"):
1060
+ self.disable_lora_for_text_encoder(self.text_encoder_2)
1061
+
1062
+ def enable_lora(self):
1063
+ if not USE_PEFT_BACKEND:
1064
+ raise ValueError("PEFT backend is required for this method.")
1065
+
1066
+ # Enable unet adapters
1067
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1068
+ unet.enable_lora()
1069
+
1070
+ # Enable text encoder adapters
1071
+ if hasattr(self, "text_encoder"):
1072
+ self.enable_lora_for_text_encoder(self.text_encoder)
1073
+ if hasattr(self, "text_encoder_2"):
1074
+ self.enable_lora_for_text_encoder(self.text_encoder_2)
1075
+
1076
+ def delete_adapters(self, adapter_names: Union[List[str], str]):
1077
+ """
1078
+ Args:
1079
+ Deletes the LoRA layers of `adapter_name` for the unet and text-encoder(s).
1080
+ adapter_names (`Union[List[str], str]`):
1081
+ The names of the adapter to delete. Can be a single string or a list of strings
1082
+ """
1083
+ if not USE_PEFT_BACKEND:
1084
+ raise ValueError("PEFT backend is required for this method.")
1085
+
1086
+ if isinstance(adapter_names, str):
1087
+ adapter_names = [adapter_names]
1088
+
1089
+ # Delete unet adapters
1090
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1091
+ unet.delete_adapters(adapter_names)
1092
+
1093
+ for adapter_name in adapter_names:
1094
+ # Delete text encoder adapters
1095
+ if hasattr(self, "text_encoder"):
1096
+ delete_adapter_layers(self.text_encoder, adapter_name)
1097
+ if hasattr(self, "text_encoder_2"):
1098
+ delete_adapter_layers(self.text_encoder_2, adapter_name)
1099
+
1100
+ def get_active_adapters(self) -> List[str]:
1101
+ """
1102
+ Gets the list of the current active adapters.
1103
+
1104
+ Example:
1105
+
1106
+ ```python
1107
+ from diffusers import DiffusionPipeline
1108
+
1109
+ pipeline = DiffusionPipeline.from_pretrained(
1110
+ "stabilityai/stable-diffusion-xl-base-1.0",
1111
+ ).to("cuda")
1112
+ pipeline.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy")
1113
+ pipeline.get_active_adapters()
1114
+ ```
1115
+ """
1116
+ if not USE_PEFT_BACKEND:
1117
+ raise ValueError(
1118
+ "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
1119
+ )
1120
+
1121
+ from peft.tuners.tuners_utils import BaseTunerLayer
1122
+
1123
+ active_adapters = []
1124
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1125
+ for module in unet.modules():
1126
+ if isinstance(module, BaseTunerLayer):
1127
+ active_adapters = module.active_adapters
1128
+ break
1129
+
1130
+ return active_adapters
1131
+
1132
+ def get_list_adapters(self) -> Dict[str, List[str]]:
1133
+ """
1134
+ Gets the current list of all available adapters in the pipeline.
1135
+ """
1136
+ if not USE_PEFT_BACKEND:
1137
+ raise ValueError(
1138
+ "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
1139
+ )
1140
+
1141
+ set_adapters = {}
1142
+
1143
+ if hasattr(self, "text_encoder") and hasattr(self.text_encoder, "peft_config"):
1144
+ set_adapters["text_encoder"] = list(self.text_encoder.peft_config.keys())
1145
+
1146
+ if hasattr(self, "text_encoder_2") and hasattr(self.text_encoder_2, "peft_config"):
1147
+ set_adapters["text_encoder_2"] = list(self.text_encoder_2.peft_config.keys())
1148
+
1149
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1150
+ if hasattr(self, self.unet_name) and hasattr(unet, "peft_config"):
1151
+ set_adapters[self.unet_name] = list(self.unet.peft_config.keys())
1152
+
1153
+ return set_adapters
1154
+
1155
+ def set_lora_device(self, adapter_names: List[str], device: Union[torch.device, str, int]) -> None:
1156
+ """
1157
+ Moves the LoRAs listed in `adapter_names` to a target device. Useful for offloading the LoRA to the CPU in case
1158
+ you want to load multiple adapters and free some GPU memory.
1159
+
1160
+ Args:
1161
+ adapter_names (`List[str]`):
1162
+ List of adapters to send device to.
1163
+ device (`Union[torch.device, str, int]`):
1164
+ Device to send the adapters to. Can be either a torch device, a str or an integer.
1165
+ """
1166
+ if not USE_PEFT_BACKEND:
1167
+ raise ValueError("PEFT backend is required for this method.")
1168
+
1169
+ from peft.tuners.tuners_utils import BaseTunerLayer
1170
+
1171
+ # Handle the UNET
1172
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1173
+ for unet_module in unet.modules():
1174
+ if isinstance(unet_module, BaseTunerLayer):
1175
+ for adapter_name in adapter_names:
1176
+ unet_module.lora_A[adapter_name].to(device)
1177
+ unet_module.lora_B[adapter_name].to(device)
1178
+
1179
+ # Handle the text encoder
1180
+ modules_to_process = []
1181
+ if hasattr(self, "text_encoder"):
1182
+ modules_to_process.append(self.text_encoder)
1183
+
1184
+ if hasattr(self, "text_encoder_2"):
1185
+ modules_to_process.append(self.text_encoder_2)
1186
+
1187
+ for text_encoder in modules_to_process:
1188
+ # loop over submodules
1189
+ for text_encoder_module in text_encoder.modules():
1190
+ if isinstance(text_encoder_module, BaseTunerLayer):
1191
+ for adapter_name in adapter_names:
1192
+ text_encoder_module.lora_A[adapter_name].to(device)
1193
+ text_encoder_module.lora_B[adapter_name].to(device)
1194
+
1195
+
1196
+ class StableDiffusionXLLoraLoaderMixin(LoraLoaderMixin):
1197
+ """This class overrides `LoraLoaderMixin` with LoRA loading/saving code that's specific to SDXL"""
1198
+
1199
+ # Override to properly handle the loading and unloading of the additional text encoder.
1200
+ def load_lora_weights(
1201
+ self,
1202
+ pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
1203
+ adapter_name: Optional[str] = None,
1204
+ **kwargs,
1205
+ ):
1206
+ """
1207
+ Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
1208
+ `self.text_encoder`.
1209
+
1210
+ All kwargs are forwarded to `self.lora_state_dict`.
1211
+
1212
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
1213
+
1214
+ See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
1215
+ `self.unet`.
1216
+
1217
+ See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
1218
+ into `self.text_encoder`.
1219
+
1220
+ Parameters:
1221
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
1222
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1223
+ adapter_name (`str`, *optional*):
1224
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
1225
+ `default_{i}` where i is the total number of adapters being loaded.
1226
+ kwargs (`dict`, *optional*):
1227
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1228
+ """
1229
+ if not USE_PEFT_BACKEND:
1230
+ raise ValueError("PEFT backend is required for this method.")
1231
+
1232
+ # We could have accessed the unet config from `lora_state_dict()` too. We pass
1233
+ # it here explicitly to be able to tell that it's coming from an SDXL
1234
+ # pipeline.
1235
+
1236
+ # if a dict is passed, copy it instead of modifying it inplace
1237
+ if isinstance(pretrained_model_name_or_path_or_dict, dict):
1238
+ pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict.copy()
1239
+
1240
+ # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
1241
+ state_dict, network_alphas = self.lora_state_dict(
1242
+ pretrained_model_name_or_path_or_dict,
1243
+ unet_config=self.unet.config,
1244
+ **kwargs,
1245
+ )
1246
+ is_correct_format = all("lora" in key for key in state_dict.keys())
1247
+ if not is_correct_format:
1248
+ raise ValueError("Invalid LoRA checkpoint.")
1249
+
1250
+ self.load_lora_into_unet(
1251
+ state_dict, network_alphas=network_alphas, unet=self.unet, adapter_name=adapter_name, _pipeline=self
1252
+ )
1253
+ text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
1254
+ if len(text_encoder_state_dict) > 0:
1255
+ self.load_lora_into_text_encoder(
1256
+ text_encoder_state_dict,
1257
+ network_alphas=network_alphas,
1258
+ text_encoder=self.text_encoder,
1259
+ prefix="text_encoder",
1260
+ lora_scale=self.lora_scale,
1261
+ adapter_name=adapter_name,
1262
+ _pipeline=self,
1263
+ )
1264
+
1265
+ text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
1266
+ if len(text_encoder_2_state_dict) > 0:
1267
+ self.load_lora_into_text_encoder(
1268
+ text_encoder_2_state_dict,
1269
+ network_alphas=network_alphas,
1270
+ text_encoder=self.text_encoder_2,
1271
+ prefix="text_encoder_2",
1272
+ lora_scale=self.lora_scale,
1273
+ adapter_name=adapter_name,
1274
+ _pipeline=self,
1275
+ )
1276
+
1277
+ @classmethod
1278
+ def save_lora_weights(
1279
+ cls,
1280
+ save_directory: Union[str, os.PathLike],
1281
+ unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1282
+ text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1283
+ text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1284
+ is_main_process: bool = True,
1285
+ weight_name: str = None,
1286
+ save_function: Callable = None,
1287
+ safe_serialization: bool = True,
1288
+ ):
1289
+ r"""
1290
+ Save the LoRA parameters corresponding to the UNet and text encoder.
1291
+
1292
+ Arguments:
1293
+ save_directory (`str` or `os.PathLike`):
1294
+ Directory to save LoRA parameters to. Will be created if it doesn't exist.
1295
+ unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1296
+ State dict of the LoRA layers corresponding to the `unet`.
1297
+ text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1298
+ State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
1299
+ encoder LoRA state dict because it comes from 🤗 Transformers.
1300
+ is_main_process (`bool`, *optional*, defaults to `True`):
1301
+ Whether the process calling this is the main process or not. Useful during distributed training and you
1302
+ need to call this function on all processes. In this case, set `is_main_process=True` only on the main
1303
+ process to avoid race conditions.
1304
+ save_function (`Callable`):
1305
+ The function to use to save the state dictionary. Useful during distributed training when you need to
1306
+ replace `torch.save` with another method. Can be configured with the environment variable
1307
+ `DIFFUSERS_SAVE_MODE`.
1308
+ safe_serialization (`bool`, *optional*, defaults to `True`):
1309
+ Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
1310
+ """
1311
+ state_dict = {}
1312
+
1313
+ def pack_weights(layers, prefix):
1314
+ layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
1315
+ layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
1316
+ return layers_state_dict
1317
+
1318
+ if not (unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers):
1319
+ raise ValueError(
1320
+ "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`."
1321
+ )
1322
+
1323
+ if unet_lora_layers:
1324
+ state_dict.update(pack_weights(unet_lora_layers, "unet"))
1325
+
1326
+ if text_encoder_lora_layers and text_encoder_2_lora_layers:
1327
+ state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
1328
+ state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
1329
+
1330
+ cls.write_lora_layers(
1331
+ state_dict=state_dict,
1332
+ save_directory=save_directory,
1333
+ is_main_process=is_main_process,
1334
+ weight_name=weight_name,
1335
+ save_function=save_function,
1336
+ safe_serialization=safe_serialization,
1337
+ )
1338
+
1339
+ def _remove_text_encoder_monkey_patch(self):
1340
+ recurse_remove_peft_layers(self.text_encoder)
1341
+ # TODO: @younesbelkada handle this in transformers side
1342
+ if getattr(self.text_encoder, "peft_config", None) is not None:
1343
+ del self.text_encoder.peft_config
1344
+ self.text_encoder._hf_peft_config_loaded = None
1345
+
1346
+ recurse_remove_peft_layers(self.text_encoder_2)
1347
+ if getattr(self.text_encoder_2, "peft_config", None) is not None:
1348
+ del self.text_encoder_2.peft_config
1349
+ self.text_encoder_2._hf_peft_config_loaded = None
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/lora_conversion_utils.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import re
16
+
17
+ from ..utils import logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ def _maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config, delimiter="_", block_slice_pos=5):
24
+ # 1. get all state_dict_keys
25
+ all_keys = list(state_dict.keys())
26
+ sgm_patterns = ["input_blocks", "middle_block", "output_blocks"]
27
+
28
+ # 2. check if needs remapping, if not return original dict
29
+ is_in_sgm_format = False
30
+ for key in all_keys:
31
+ if any(p in key for p in sgm_patterns):
32
+ is_in_sgm_format = True
33
+ break
34
+
35
+ if not is_in_sgm_format:
36
+ return state_dict
37
+
38
+ # 3. Else remap from SGM patterns
39
+ new_state_dict = {}
40
+ inner_block_map = ["resnets", "attentions", "upsamplers"]
41
+
42
+ # Retrieves # of down, mid and up blocks
43
+ input_block_ids, middle_block_ids, output_block_ids = set(), set(), set()
44
+
45
+ for layer in all_keys:
46
+ if "text" in layer:
47
+ new_state_dict[layer] = state_dict.pop(layer)
48
+ else:
49
+ layer_id = int(layer.split(delimiter)[:block_slice_pos][-1])
50
+ if sgm_patterns[0] in layer:
51
+ input_block_ids.add(layer_id)
52
+ elif sgm_patterns[1] in layer:
53
+ middle_block_ids.add(layer_id)
54
+ elif sgm_patterns[2] in layer:
55
+ output_block_ids.add(layer_id)
56
+ else:
57
+ raise ValueError(f"Checkpoint not supported because layer {layer} not supported.")
58
+
59
+ input_blocks = {
60
+ layer_id: [key for key in state_dict if f"input_blocks{delimiter}{layer_id}" in key]
61
+ for layer_id in input_block_ids
62
+ }
63
+ middle_blocks = {
64
+ layer_id: [key for key in state_dict if f"middle_block{delimiter}{layer_id}" in key]
65
+ for layer_id in middle_block_ids
66
+ }
67
+ output_blocks = {
68
+ layer_id: [key for key in state_dict if f"output_blocks{delimiter}{layer_id}" in key]
69
+ for layer_id in output_block_ids
70
+ }
71
+
72
+ # Rename keys accordingly
73
+ for i in input_block_ids:
74
+ block_id = (i - 1) // (unet_config.layers_per_block + 1)
75
+ layer_in_block_id = (i - 1) % (unet_config.layers_per_block + 1)
76
+
77
+ for key in input_blocks[i]:
78
+ inner_block_id = int(key.split(delimiter)[block_slice_pos])
79
+ inner_block_key = inner_block_map[inner_block_id] if "op" not in key else "downsamplers"
80
+ inner_layers_in_block = str(layer_in_block_id) if "op" not in key else "0"
81
+ new_key = delimiter.join(
82
+ key.split(delimiter)[: block_slice_pos - 1]
83
+ + [str(block_id), inner_block_key, inner_layers_in_block]
84
+ + key.split(delimiter)[block_slice_pos + 1 :]
85
+ )
86
+ new_state_dict[new_key] = state_dict.pop(key)
87
+
88
+ for i in middle_block_ids:
89
+ key_part = None
90
+ if i == 0:
91
+ key_part = [inner_block_map[0], "0"]
92
+ elif i == 1:
93
+ key_part = [inner_block_map[1], "0"]
94
+ elif i == 2:
95
+ key_part = [inner_block_map[0], "1"]
96
+ else:
97
+ raise ValueError(f"Invalid middle block id {i}.")
98
+
99
+ for key in middle_blocks[i]:
100
+ new_key = delimiter.join(
101
+ key.split(delimiter)[: block_slice_pos - 1] + key_part + key.split(delimiter)[block_slice_pos:]
102
+ )
103
+ new_state_dict[new_key] = state_dict.pop(key)
104
+
105
+ for i in output_block_ids:
106
+ block_id = i // (unet_config.layers_per_block + 1)
107
+ layer_in_block_id = i % (unet_config.layers_per_block + 1)
108
+
109
+ for key in output_blocks[i]:
110
+ inner_block_id = int(key.split(delimiter)[block_slice_pos])
111
+ inner_block_key = inner_block_map[inner_block_id]
112
+ inner_layers_in_block = str(layer_in_block_id) if inner_block_id < 2 else "0"
113
+ new_key = delimiter.join(
114
+ key.split(delimiter)[: block_slice_pos - 1]
115
+ + [str(block_id), inner_block_key, inner_layers_in_block]
116
+ + key.split(delimiter)[block_slice_pos + 1 :]
117
+ )
118
+ new_state_dict[new_key] = state_dict.pop(key)
119
+
120
+ if len(state_dict) > 0:
121
+ raise ValueError("At this point all state dict entries have to be converted.")
122
+
123
+ return new_state_dict
124
+
125
+
126
+ def _convert_kohya_lora_to_diffusers(state_dict, unet_name="unet", text_encoder_name="text_encoder"):
127
+ unet_state_dict = {}
128
+ te_state_dict = {}
129
+ te2_state_dict = {}
130
+ network_alphas = {}
131
+
132
+ # every down weight has a corresponding up weight and potentially an alpha weight
133
+ lora_keys = [k for k in state_dict.keys() if k.endswith("lora_down.weight")]
134
+ for key in lora_keys:
135
+ lora_name = key.split(".")[0]
136
+ lora_name_up = lora_name + ".lora_up.weight"
137
+ lora_name_alpha = lora_name + ".alpha"
138
+
139
+ if lora_name.startswith("lora_unet_"):
140
+ diffusers_name = key.replace("lora_unet_", "").replace("_", ".")
141
+
142
+ if "input.blocks" in diffusers_name:
143
+ diffusers_name = diffusers_name.replace("input.blocks", "down_blocks")
144
+ else:
145
+ diffusers_name = diffusers_name.replace("down.blocks", "down_blocks")
146
+
147
+ if "middle.block" in diffusers_name:
148
+ diffusers_name = diffusers_name.replace("middle.block", "mid_block")
149
+ else:
150
+ diffusers_name = diffusers_name.replace("mid.block", "mid_block")
151
+ if "output.blocks" in diffusers_name:
152
+ diffusers_name = diffusers_name.replace("output.blocks", "up_blocks")
153
+ else:
154
+ diffusers_name = diffusers_name.replace("up.blocks", "up_blocks")
155
+
156
+ diffusers_name = diffusers_name.replace("transformer.blocks", "transformer_blocks")
157
+ diffusers_name = diffusers_name.replace("to.q.lora", "to_q_lora")
158
+ diffusers_name = diffusers_name.replace("to.k.lora", "to_k_lora")
159
+ diffusers_name = diffusers_name.replace("to.v.lora", "to_v_lora")
160
+ diffusers_name = diffusers_name.replace("to.out.0.lora", "to_out_lora")
161
+ diffusers_name = diffusers_name.replace("proj.in", "proj_in")
162
+ diffusers_name = diffusers_name.replace("proj.out", "proj_out")
163
+ diffusers_name = diffusers_name.replace("emb.layers", "time_emb_proj")
164
+
165
+ # SDXL specificity.
166
+ if "emb" in diffusers_name and "time.emb.proj" not in diffusers_name:
167
+ pattern = r"\.\d+(?=\D*$)"
168
+ diffusers_name = re.sub(pattern, "", diffusers_name, count=1)
169
+ if ".in." in diffusers_name:
170
+ diffusers_name = diffusers_name.replace("in.layers.2", "conv1")
171
+ if ".out." in diffusers_name:
172
+ diffusers_name = diffusers_name.replace("out.layers.3", "conv2")
173
+ if "downsamplers" in diffusers_name or "upsamplers" in diffusers_name:
174
+ diffusers_name = diffusers_name.replace("op", "conv")
175
+ if "skip" in diffusers_name:
176
+ diffusers_name = diffusers_name.replace("skip.connection", "conv_shortcut")
177
+
178
+ # LyCORIS specificity.
179
+ if "time.emb.proj" in diffusers_name:
180
+ diffusers_name = diffusers_name.replace("time.emb.proj", "time_emb_proj")
181
+ if "conv.shortcut" in diffusers_name:
182
+ diffusers_name = diffusers_name.replace("conv.shortcut", "conv_shortcut")
183
+
184
+ # General coverage.
185
+ if "transformer_blocks" in diffusers_name:
186
+ if "attn1" in diffusers_name or "attn2" in diffusers_name:
187
+ diffusers_name = diffusers_name.replace("attn1", "attn1.processor")
188
+ diffusers_name = diffusers_name.replace("attn2", "attn2.processor")
189
+ unet_state_dict[diffusers_name] = state_dict.pop(key)
190
+ unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
191
+ elif "ff" in diffusers_name:
192
+ unet_state_dict[diffusers_name] = state_dict.pop(key)
193
+ unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
194
+ elif any(key in diffusers_name for key in ("proj_in", "proj_out")):
195
+ unet_state_dict[diffusers_name] = state_dict.pop(key)
196
+ unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
197
+ else:
198
+ unet_state_dict[diffusers_name] = state_dict.pop(key)
199
+ unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
200
+
201
+ elif lora_name.startswith("lora_te_"):
202
+ diffusers_name = key.replace("lora_te_", "").replace("_", ".")
203
+ diffusers_name = diffusers_name.replace("text.model", "text_model")
204
+ diffusers_name = diffusers_name.replace("self.attn", "self_attn")
205
+ diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
206
+ diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
207
+ diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
208
+ diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
209
+ if "self_attn" in diffusers_name:
210
+ te_state_dict[diffusers_name] = state_dict.pop(key)
211
+ te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
212
+ elif "mlp" in diffusers_name:
213
+ # Be aware that this is the new diffusers convention and the rest of the code might
214
+ # not utilize it yet.
215
+ diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
216
+ te_state_dict[diffusers_name] = state_dict.pop(key)
217
+ te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
218
+
219
+ # (sayakpaul): Duplicate code. Needs to be cleaned.
220
+ elif lora_name.startswith("lora_te1_"):
221
+ diffusers_name = key.replace("lora_te1_", "").replace("_", ".")
222
+ diffusers_name = diffusers_name.replace("text.model", "text_model")
223
+ diffusers_name = diffusers_name.replace("self.attn", "self_attn")
224
+ diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
225
+ diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
226
+ diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
227
+ diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
228
+ if "self_attn" in diffusers_name:
229
+ te_state_dict[diffusers_name] = state_dict.pop(key)
230
+ te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
231
+ elif "mlp" in diffusers_name:
232
+ # Be aware that this is the new diffusers convention and the rest of the code might
233
+ # not utilize it yet.
234
+ diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
235
+ te_state_dict[diffusers_name] = state_dict.pop(key)
236
+ te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
237
+
238
+ # (sayakpaul): Duplicate code. Needs to be cleaned.
239
+ elif lora_name.startswith("lora_te2_"):
240
+ diffusers_name = key.replace("lora_te2_", "").replace("_", ".")
241
+ diffusers_name = diffusers_name.replace("text.model", "text_model")
242
+ diffusers_name = diffusers_name.replace("self.attn", "self_attn")
243
+ diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
244
+ diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
245
+ diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
246
+ diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
247
+ if "self_attn" in diffusers_name:
248
+ te2_state_dict[diffusers_name] = state_dict.pop(key)
249
+ te2_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
250
+ elif "mlp" in diffusers_name:
251
+ # Be aware that this is the new diffusers convention and the rest of the code might
252
+ # not utilize it yet.
253
+ diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
254
+ te2_state_dict[diffusers_name] = state_dict.pop(key)
255
+ te2_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
256
+
257
+ # Rename the alphas so that they can be mapped appropriately.
258
+ if lora_name_alpha in state_dict:
259
+ alpha = state_dict.pop(lora_name_alpha).item()
260
+ if lora_name_alpha.startswith("lora_unet_"):
261
+ prefix = "unet."
262
+ elif lora_name_alpha.startswith(("lora_te_", "lora_te1_")):
263
+ prefix = "text_encoder."
264
+ else:
265
+ prefix = "text_encoder_2."
266
+ new_name = prefix + diffusers_name.split(".lora.")[0] + ".alpha"
267
+ network_alphas.update({new_name: alpha})
268
+
269
+ if len(state_dict) > 0:
270
+ raise ValueError(f"The following keys have not been correctly be renamed: \n\n {', '.join(state_dict.keys())}")
271
+
272
+ logger.info("Kohya-style checkpoint detected.")
273
+ unet_state_dict = {f"{unet_name}.{module_name}": params for module_name, params in unet_state_dict.items()}
274
+ te_state_dict = {f"{text_encoder_name}.{module_name}": params for module_name, params in te_state_dict.items()}
275
+ te2_state_dict = (
276
+ {f"text_encoder_2.{module_name}": params for module_name, params in te2_state_dict.items()}
277
+ if len(te2_state_dict) > 0
278
+ else None
279
+ )
280
+ if te2_state_dict is not None:
281
+ te_state_dict.update(te2_state_dict)
282
+
283
+ new_state_dict = {**unet_state_dict, **te_state_dict}
284
+ return new_state_dict, network_alphas
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/peft.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ from typing import List, Union
16
+
17
+ from ..utils import MIN_PEFT_VERSION, check_peft_version, is_peft_available
18
+
19
+
20
+ class PeftAdapterMixin:
21
+ """
22
+ A class containing all functions for loading and using adapters weights that are supported in PEFT library. For
23
+ more details about adapters and injecting them in a transformer-based model, check out the PEFT [documentation](https://huggingface.co/docs/peft/index).
24
+
25
+ Install the latest version of PEFT, and use this mixin to:
26
+
27
+ - Attach new adapters in the model.
28
+ - Attach multiple adapters and iteratively activate/deactivate them.
29
+ - Activate/deactivate all adapters from the model.
30
+ - Get a list of the active adapters.
31
+ """
32
+
33
+ _hf_peft_config_loaded = False
34
+
35
+ def add_adapter(self, adapter_config, adapter_name: str = "default") -> None:
36
+ r"""
37
+ Adds a new adapter to the current model for training. If no adapter name is passed, a default name is assigned
38
+ to the adapter to follow the convention of the PEFT library.
39
+
40
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them in the PEFT
41
+ [documentation](https://huggingface.co/docs/peft).
42
+
43
+ Args:
44
+ adapter_config (`[~peft.PeftConfig]`):
45
+ The configuration of the adapter to add; supported adapters are non-prefix tuning and adaption prompt
46
+ methods.
47
+ adapter_name (`str`, *optional*, defaults to `"default"`):
48
+ The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
49
+ """
50
+ check_peft_version(min_version=MIN_PEFT_VERSION)
51
+
52
+ if not is_peft_available():
53
+ raise ImportError("PEFT is not available. Please install PEFT to use this function: `pip install peft`.")
54
+
55
+ from peft import PeftConfig, inject_adapter_in_model
56
+
57
+ if not self._hf_peft_config_loaded:
58
+ self._hf_peft_config_loaded = True
59
+ elif adapter_name in self.peft_config:
60
+ raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
61
+
62
+ if not isinstance(adapter_config, PeftConfig):
63
+ raise ValueError(
64
+ f"adapter_config should be an instance of PeftConfig. Got {type(adapter_config)} instead."
65
+ )
66
+
67
+ # Unlike transformers, here we don't need to retrieve the name_or_path of the unet as the loading logic is
68
+ # handled by the `load_lora_layers` or `LoraLoaderMixin`. Therefore we set it to `None` here.
69
+ adapter_config.base_model_name_or_path = None
70
+ inject_adapter_in_model(adapter_config, self, adapter_name)
71
+ self.set_adapter(adapter_name)
72
+
73
+ def set_adapter(self, adapter_name: Union[str, List[str]]) -> None:
74
+ """
75
+ Sets a specific adapter by forcing the model to only use that adapter and disables the other adapters.
76
+
77
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
78
+ [documentation](https://huggingface.co/docs/peft).
79
+
80
+ Args:
81
+ adapter_name (Union[str, List[str]])):
82
+ The list of adapters to set or the adapter name in the case of a single adapter.
83
+ """
84
+ check_peft_version(min_version=MIN_PEFT_VERSION)
85
+
86
+ if not self._hf_peft_config_loaded:
87
+ raise ValueError("No adapter loaded. Please load an adapter first.")
88
+
89
+ if isinstance(adapter_name, str):
90
+ adapter_name = [adapter_name]
91
+
92
+ missing = set(adapter_name) - set(self.peft_config)
93
+ if len(missing) > 0:
94
+ raise ValueError(
95
+ f"Following adapter(s) could not be found: {', '.join(missing)}. Make sure you are passing the correct adapter name(s)."
96
+ f" current loaded adapters are: {list(self.peft_config.keys())}"
97
+ )
98
+
99
+ from peft.tuners.tuners_utils import BaseTunerLayer
100
+
101
+ _adapters_has_been_set = False
102
+
103
+ for _, module in self.named_modules():
104
+ if isinstance(module, BaseTunerLayer):
105
+ if hasattr(module, "set_adapter"):
106
+ module.set_adapter(adapter_name)
107
+ # Previous versions of PEFT does not support multi-adapter inference
108
+ elif not hasattr(module, "set_adapter") and len(adapter_name) != 1:
109
+ raise ValueError(
110
+ "You are trying to set multiple adapters and you have a PEFT version that does not support multi-adapter inference. Please upgrade to the latest version of PEFT."
111
+ " `pip install -U peft` or `pip install -U git+https://github.com/huggingface/peft.git`"
112
+ )
113
+ else:
114
+ module.active_adapter = adapter_name
115
+ _adapters_has_been_set = True
116
+
117
+ if not _adapters_has_been_set:
118
+ raise ValueError(
119
+ "Did not succeeded in setting the adapter. Please make sure you are using a model that supports adapters."
120
+ )
121
+
122
+ def disable_adapters(self) -> None:
123
+ r"""
124
+ Disable all adapters attached to the model and fallback to inference with the base model only.
125
+
126
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
127
+ [documentation](https://huggingface.co/docs/peft).
128
+ """
129
+ check_peft_version(min_version=MIN_PEFT_VERSION)
130
+
131
+ if not self._hf_peft_config_loaded:
132
+ raise ValueError("No adapter loaded. Please load an adapter first.")
133
+
134
+ from peft.tuners.tuners_utils import BaseTunerLayer
135
+
136
+ for _, module in self.named_modules():
137
+ if isinstance(module, BaseTunerLayer):
138
+ if hasattr(module, "enable_adapters"):
139
+ module.enable_adapters(enabled=False)
140
+ else:
141
+ # support for older PEFT versions
142
+ module.disable_adapters = True
143
+
144
+ def enable_adapters(self) -> None:
145
+ """
146
+ Enable adapters that are attached to the model. The model uses `self.active_adapters()` to retrieve the
147
+ list of adapters to enable.
148
+
149
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
150
+ [documentation](https://huggingface.co/docs/peft).
151
+ """
152
+ check_peft_version(min_version=MIN_PEFT_VERSION)
153
+
154
+ if not self._hf_peft_config_loaded:
155
+ raise ValueError("No adapter loaded. Please load an adapter first.")
156
+
157
+ from peft.tuners.tuners_utils import BaseTunerLayer
158
+
159
+ for _, module in self.named_modules():
160
+ if isinstance(module, BaseTunerLayer):
161
+ if hasattr(module, "enable_adapters"):
162
+ module.enable_adapters(enabled=True)
163
+ else:
164
+ # support for older PEFT versions
165
+ module.disable_adapters = False
166
+
167
+ def active_adapters(self) -> List[str]:
168
+ """
169
+ Gets the current list of active adapters of the model.
170
+
171
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
172
+ [documentation](https://huggingface.co/docs/peft).
173
+ """
174
+ check_peft_version(min_version=MIN_PEFT_VERSION)
175
+
176
+ if not is_peft_available():
177
+ raise ImportError("PEFT is not available. Please install PEFT to use this function: `pip install peft`.")
178
+
179
+ if not self._hf_peft_config_loaded:
180
+ raise ValueError("No adapter loaded. Please load an adapter first.")
181
+
182
+ from peft.tuners.tuners_utils import BaseTunerLayer
183
+
184
+ for _, module in self.named_modules():
185
+ if isinstance(module, BaseTunerLayer):
186
+ return module.active_adapter
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/single_file.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from huggingface_hub.utils import validate_hf_hub_args
16
+
17
+ from ..utils import is_transformers_available, logging
18
+ from .single_file_utils import (
19
+ create_diffusers_unet_model_from_ldm,
20
+ create_diffusers_vae_model_from_ldm,
21
+ create_scheduler_from_ldm,
22
+ create_text_encoders_and_tokenizers_from_ldm,
23
+ fetch_ldm_config_and_checkpoint,
24
+ infer_model_type,
25
+ )
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ # Pipelines that support the SDXL Refiner checkpoint
31
+ REFINER_PIPELINES = [
32
+ "StableDiffusionXLImg2ImgPipeline",
33
+ "StableDiffusionXLInpaintPipeline",
34
+ "StableDiffusionXLControlNetImg2ImgPipeline",
35
+ ]
36
+
37
+ if is_transformers_available():
38
+ from transformers import AutoFeatureExtractor
39
+
40
+
41
+ def build_sub_model_components(
42
+ pipeline_components,
43
+ pipeline_class_name,
44
+ component_name,
45
+ original_config,
46
+ checkpoint,
47
+ local_files_only=False,
48
+ load_safety_checker=False,
49
+ model_type=None,
50
+ image_size=None,
51
+ torch_dtype=None,
52
+ **kwargs,
53
+ ):
54
+ if component_name in pipeline_components:
55
+ return {}
56
+
57
+ if component_name == "unet":
58
+ num_in_channels = kwargs.pop("num_in_channels", None)
59
+ upcast_attention = kwargs.pop("upcast_attention", None)
60
+
61
+ unet_components = create_diffusers_unet_model_from_ldm(
62
+ pipeline_class_name,
63
+ original_config,
64
+ checkpoint,
65
+ num_in_channels=num_in_channels,
66
+ image_size=image_size,
67
+ torch_dtype=torch_dtype,
68
+ model_type=model_type,
69
+ upcast_attention=upcast_attention,
70
+ )
71
+ return unet_components
72
+
73
+ if component_name == "vae":
74
+ scaling_factor = kwargs.get("scaling_factor", None)
75
+ vae_components = create_diffusers_vae_model_from_ldm(
76
+ pipeline_class_name,
77
+ original_config,
78
+ checkpoint,
79
+ image_size,
80
+ scaling_factor,
81
+ torch_dtype,
82
+ model_type=model_type,
83
+ )
84
+ return vae_components
85
+
86
+ if component_name == "scheduler":
87
+ scheduler_type = kwargs.get("scheduler_type", "ddim")
88
+ prediction_type = kwargs.get("prediction_type", None)
89
+
90
+ scheduler_components = create_scheduler_from_ldm(
91
+ pipeline_class_name,
92
+ original_config,
93
+ checkpoint,
94
+ scheduler_type=scheduler_type,
95
+ prediction_type=prediction_type,
96
+ model_type=model_type,
97
+ )
98
+
99
+ return scheduler_components
100
+
101
+ if component_name in ["text_encoder", "text_encoder_2", "tokenizer", "tokenizer_2"]:
102
+ text_encoder_components = create_text_encoders_and_tokenizers_from_ldm(
103
+ original_config,
104
+ checkpoint,
105
+ model_type=model_type,
106
+ local_files_only=local_files_only,
107
+ torch_dtype=torch_dtype,
108
+ )
109
+ return text_encoder_components
110
+
111
+ if component_name == "safety_checker":
112
+ if load_safety_checker:
113
+ from ..pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
114
+
115
+ safety_checker = StableDiffusionSafetyChecker.from_pretrained(
116
+ "CompVis/stable-diffusion-safety-checker", local_files_only=local_files_only, torch_dtype=torch_dtype
117
+ )
118
+ else:
119
+ safety_checker = None
120
+ return {"safety_checker": safety_checker}
121
+
122
+ if component_name == "feature_extractor":
123
+ if load_safety_checker:
124
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
125
+ "CompVis/stable-diffusion-safety-checker", local_files_only=local_files_only
126
+ )
127
+ else:
128
+ feature_extractor = None
129
+ return {"feature_extractor": feature_extractor}
130
+
131
+ return
132
+
133
+
134
+ def set_additional_components(
135
+ pipeline_class_name,
136
+ original_config,
137
+ checkpoint=None,
138
+ model_type=None,
139
+ ):
140
+ components = {}
141
+ if pipeline_class_name in REFINER_PIPELINES:
142
+ model_type = infer_model_type(original_config, checkpoint=checkpoint, model_type=model_type)
143
+ is_refiner = model_type == "SDXL-Refiner"
144
+ components.update(
145
+ {
146
+ "requires_aesthetics_score": is_refiner,
147
+ "force_zeros_for_empty_prompt": False if is_refiner else True,
148
+ }
149
+ )
150
+
151
+ return components
152
+
153
+
154
+ class FromSingleFileMixin:
155
+ """
156
+ Load model weights saved in the `.ckpt` format into a [`DiffusionPipeline`].
157
+ """
158
+
159
+ @classmethod
160
+ @validate_hf_hub_args
161
+ def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
162
+ r"""
163
+ Instantiate a [`DiffusionPipeline`] from pretrained pipeline weights saved in the `.ckpt` or `.safetensors`
164
+ format. The pipeline is set in evaluation mode (`model.eval()`) by default.
165
+
166
+ Parameters:
167
+ pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
168
+ Can be either:
169
+ - A link to the `.ckpt` file (for example
170
+ `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
171
+ - A path to a *file* containing all pipeline weights.
172
+ torch_dtype (`str` or `torch.dtype`, *optional*):
173
+ Override the default `torch.dtype` and load the model with another dtype.
174
+ force_download (`bool`, *optional*, defaults to `False`):
175
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
176
+ cached versions if they exist.
177
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
178
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
179
+ is not used.
180
+ resume_download (`bool`, *optional*, defaults to `False`):
181
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
182
+ incompletely downloaded files are deleted.
183
+ proxies (`Dict[str, str]`, *optional*):
184
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
185
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
186
+ local_files_only (`bool`, *optional*, defaults to `False`):
187
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
188
+ won't be downloaded from the Hub.
189
+ token (`str` or *bool*, *optional*):
190
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
191
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
192
+ revision (`str`, *optional*, defaults to `"main"`):
193
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
194
+ allowed by Git.
195
+ original_config_file (`str`, *optional*):
196
+ The path to the original config file that was used to train the model. If not provided, the config file
197
+ will be inferred from the checkpoint file.
198
+ model_type (`str`, *optional*):
199
+ The type of model to load. If not provided, the model type will be inferred from the checkpoint file.
200
+ image_size (`int`, *optional*):
201
+ The size of the image output. It's used to configure the `sample_size` parameter of the UNet and VAE model.
202
+ load_safety_checker (`bool`, *optional*, defaults to `False`):
203
+ Whether to load the safety checker model or not. By default, the safety checker is not loaded unless a `safety_checker` component is passed to the `kwargs`.
204
+ num_in_channels (`int`, *optional*):
205
+ Specify the number of input channels for the UNet model. Read more about how to configure UNet model with this parameter
206
+ [here](https://huggingface.co/docs/diffusers/training/adapt_a_model#configure-unet2dconditionmodel-parameters).
207
+ scaling_factor (`float`, *optional*):
208
+ The scaling factor to use for the VAE model. If not provided, it is inferred from the config file first.
209
+ If the scaling factor is not found in the config file, the default value 0.18215 is used.
210
+ scheduler_type (`str`, *optional*):
211
+ The type of scheduler to load. If not provided, the scheduler type will be inferred from the checkpoint file.
212
+ prediction_type (`str`, *optional*):
213
+ The type of prediction to load. If not provided, the prediction type will be inferred from the checkpoint file.
214
+ kwargs (remaining dictionary of keyword arguments, *optional*):
215
+ Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline
216
+ class). The overwritten components are passed directly to the pipelines `__init__` method. See example
217
+ below for more information.
218
+
219
+ Examples:
220
+
221
+ ```py
222
+ >>> from diffusers import StableDiffusionPipeline
223
+
224
+ >>> # Download pipeline from huggingface.co and cache.
225
+ >>> pipeline = StableDiffusionPipeline.from_single_file(
226
+ ... "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
227
+ ... )
228
+
229
+ >>> # Download pipeline from local file
230
+ >>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
231
+ >>> pipeline = StableDiffusionPipeline.from_single_file("./v1-5-pruned-emaonly")
232
+
233
+ >>> # Enable float16 and move to GPU
234
+ >>> pipeline = StableDiffusionPipeline.from_single_file(
235
+ ... "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
236
+ ... torch_dtype=torch.float16,
237
+ ... )
238
+ >>> pipeline.to("cuda")
239
+ ```
240
+ """
241
+ original_config_file = kwargs.pop("original_config_file", None)
242
+ resume_download = kwargs.pop("resume_download", False)
243
+ force_download = kwargs.pop("force_download", False)
244
+ proxies = kwargs.pop("proxies", None)
245
+ token = kwargs.pop("token", None)
246
+ cache_dir = kwargs.pop("cache_dir", None)
247
+ local_files_only = kwargs.pop("local_files_only", False)
248
+ revision = kwargs.pop("revision", None)
249
+ torch_dtype = kwargs.pop("torch_dtype", None)
250
+
251
+ class_name = cls.__name__
252
+
253
+ original_config, checkpoint = fetch_ldm_config_and_checkpoint(
254
+ pretrained_model_link_or_path=pretrained_model_link_or_path,
255
+ class_name=class_name,
256
+ original_config_file=original_config_file,
257
+ resume_download=resume_download,
258
+ force_download=force_download,
259
+ proxies=proxies,
260
+ token=token,
261
+ revision=revision,
262
+ local_files_only=local_files_only,
263
+ cache_dir=cache_dir,
264
+ )
265
+
266
+ from ..pipelines.pipeline_utils import _get_pipeline_class
267
+
268
+ pipeline_class = _get_pipeline_class(
269
+ cls,
270
+ config=None,
271
+ cache_dir=cache_dir,
272
+ )
273
+
274
+ expected_modules, optional_kwargs = cls._get_signature_keys(pipeline_class)
275
+ passed_class_obj = {k: kwargs.pop(k) for k in expected_modules if k in kwargs}
276
+ passed_pipe_kwargs = {k: kwargs.pop(k) for k in optional_kwargs if k in kwargs}
277
+
278
+ model_type = kwargs.pop("model_type", None)
279
+ image_size = kwargs.pop("image_size", None)
280
+ load_safety_checker = (kwargs.pop("load_safety_checker", False)) or (
281
+ passed_class_obj.get("safety_checker", None) is not None
282
+ )
283
+
284
+ init_kwargs = {}
285
+ for name in expected_modules:
286
+ if name in passed_class_obj:
287
+ init_kwargs[name] = passed_class_obj[name]
288
+ else:
289
+ components = build_sub_model_components(
290
+ init_kwargs,
291
+ class_name,
292
+ name,
293
+ original_config,
294
+ checkpoint,
295
+ model_type=model_type,
296
+ image_size=image_size,
297
+ load_safety_checker=load_safety_checker,
298
+ local_files_only=local_files_only,
299
+ torch_dtype=torch_dtype,
300
+ **kwargs,
301
+ )
302
+ if not components:
303
+ continue
304
+ init_kwargs.update(components)
305
+
306
+ additional_components = set_additional_components(
307
+ class_name, original_config, checkpoint=checkpoint, model_type=model_type
308
+ )
309
+ if additional_components:
310
+ init_kwargs.update(additional_components)
311
+
312
+ init_kwargs.update(passed_pipe_kwargs)
313
+ pipe = pipeline_class(**init_kwargs)
314
+
315
+ if torch_dtype is not None:
316
+ pipe.to(dtype=torch_dtype)
317
+
318
+ return pipe
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/single_file_utils.py ADDED
@@ -0,0 +1,1617 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Conversion script for the Stable Diffusion checkpoints."""
16
+
17
+ import os
18
+ import re
19
+ from contextlib import nullcontext
20
+ from io import BytesIO
21
+ from urllib.parse import urlparse
22
+
23
+ import requests
24
+ import yaml
25
+
26
+ from ..models.modeling_utils import load_state_dict
27
+ from ..schedulers import (
28
+ DDIMScheduler,
29
+ DDPMScheduler,
30
+ DPMSolverMultistepScheduler,
31
+ EDMDPMSolverMultistepScheduler,
32
+ EulerAncestralDiscreteScheduler,
33
+ EulerDiscreteScheduler,
34
+ HeunDiscreteScheduler,
35
+ LMSDiscreteScheduler,
36
+ PNDMScheduler,
37
+ )
38
+ from ..utils import is_accelerate_available, is_transformers_available, logging
39
+ from ..utils.hub_utils import _get_model_file
40
+
41
+
42
+ if is_transformers_available():
43
+ from transformers import (
44
+ CLIPTextConfig,
45
+ CLIPTextModel,
46
+ CLIPTextModelWithProjection,
47
+ CLIPTokenizer,
48
+ )
49
+
50
+ if is_accelerate_available():
51
+ from accelerate import init_empty_weights
52
+
53
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
54
+
55
+ CONFIG_URLS = {
56
+ "v1": "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml",
57
+ "v2": "https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/v2-inference-v.yaml",
58
+ "xl": "https://raw.githubusercontent.com/Stability-AI/generative-models/main/configs/inference/sd_xl_base.yaml",
59
+ "xl_refiner": "https://raw.githubusercontent.com/Stability-AI/generative-models/main/configs/inference/sd_xl_refiner.yaml",
60
+ "upscale": "https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/x4-upscaling.yaml",
61
+ "controlnet": "https://raw.githubusercontent.com/lllyasviel/ControlNet/main/models/cldm_v15.yaml",
62
+ }
63
+
64
+ CHECKPOINT_KEY_NAMES = {
65
+ "v2": "model.diffusion_model.input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight",
66
+ "xl_base": "conditioner.embedders.1.model.transformer.resblocks.9.mlp.c_proj.bias",
67
+ "xl_refiner": "conditioner.embedders.0.model.transformer.resblocks.9.mlp.c_proj.bias",
68
+ }
69
+
70
+ SCHEDULER_DEFAULT_CONFIG = {
71
+ "beta_schedule": "scaled_linear",
72
+ "beta_start": 0.00085,
73
+ "beta_end": 0.012,
74
+ "interpolation_type": "linear",
75
+ "num_train_timesteps": 1000,
76
+ "prediction_type": "epsilon",
77
+ "sample_max_value": 1.0,
78
+ "set_alpha_to_one": False,
79
+ "skip_prk_steps": True,
80
+ "steps_offset": 1,
81
+ "timestep_spacing": "leading",
82
+ }
83
+
84
+
85
+ STABLE_CASCADE_DEFAULT_CONFIGS = {
86
+ "stage_c": {"pretrained_model_name_or_path": "diffusers/stable-cascade-configs", "subfolder": "prior"},
87
+ "stage_c_lite": {"pretrained_model_name_or_path": "diffusers/stable-cascade-configs", "subfolder": "prior_lite"},
88
+ "stage_b": {"pretrained_model_name_or_path": "diffusers/stable-cascade-configs", "subfolder": "decoder"},
89
+ "stage_b_lite": {"pretrained_model_name_or_path": "diffusers/stable-cascade-configs", "subfolder": "decoder_lite"},
90
+ }
91
+
92
+
93
+ def convert_stable_cascade_unet_single_file_to_diffusers(original_state_dict):
94
+ is_stage_c = "clip_txt_mapper.weight" in original_state_dict
95
+
96
+ if is_stage_c:
97
+ state_dict = {}
98
+ for key in original_state_dict.keys():
99
+ if key.endswith("in_proj_weight"):
100
+ weights = original_state_dict[key].chunk(3, 0)
101
+ state_dict[key.replace("attn.in_proj_weight", "to_q.weight")] = weights[0]
102
+ state_dict[key.replace("attn.in_proj_weight", "to_k.weight")] = weights[1]
103
+ state_dict[key.replace("attn.in_proj_weight", "to_v.weight")] = weights[2]
104
+ elif key.endswith("in_proj_bias"):
105
+ weights = original_state_dict[key].chunk(3, 0)
106
+ state_dict[key.replace("attn.in_proj_bias", "to_q.bias")] = weights[0]
107
+ state_dict[key.replace("attn.in_proj_bias", "to_k.bias")] = weights[1]
108
+ state_dict[key.replace("attn.in_proj_bias", "to_v.bias")] = weights[2]
109
+ elif key.endswith("out_proj.weight"):
110
+ weights = original_state_dict[key]
111
+ state_dict[key.replace("attn.out_proj.weight", "to_out.0.weight")] = weights
112
+ elif key.endswith("out_proj.bias"):
113
+ weights = original_state_dict[key]
114
+ state_dict[key.replace("attn.out_proj.bias", "to_out.0.bias")] = weights
115
+ else:
116
+ state_dict[key] = original_state_dict[key]
117
+ else:
118
+ state_dict = {}
119
+ for key in original_state_dict.keys():
120
+ if key.endswith("in_proj_weight"):
121
+ weights = original_state_dict[key].chunk(3, 0)
122
+ state_dict[key.replace("attn.in_proj_weight", "to_q.weight")] = weights[0]
123
+ state_dict[key.replace("attn.in_proj_weight", "to_k.weight")] = weights[1]
124
+ state_dict[key.replace("attn.in_proj_weight", "to_v.weight")] = weights[2]
125
+ elif key.endswith("in_proj_bias"):
126
+ weights = original_state_dict[key].chunk(3, 0)
127
+ state_dict[key.replace("attn.in_proj_bias", "to_q.bias")] = weights[0]
128
+ state_dict[key.replace("attn.in_proj_bias", "to_k.bias")] = weights[1]
129
+ state_dict[key.replace("attn.in_proj_bias", "to_v.bias")] = weights[2]
130
+ elif key.endswith("out_proj.weight"):
131
+ weights = original_state_dict[key]
132
+ state_dict[key.replace("attn.out_proj.weight", "to_out.0.weight")] = weights
133
+ elif key.endswith("out_proj.bias"):
134
+ weights = original_state_dict[key]
135
+ state_dict[key.replace("attn.out_proj.bias", "to_out.0.bias")] = weights
136
+ # rename clip_mapper to clip_txt_pooled_mapper
137
+ elif key.endswith("clip_mapper.weight"):
138
+ weights = original_state_dict[key]
139
+ state_dict[key.replace("clip_mapper.weight", "clip_txt_pooled_mapper.weight")] = weights
140
+ elif key.endswith("clip_mapper.bias"):
141
+ weights = original_state_dict[key]
142
+ state_dict[key.replace("clip_mapper.bias", "clip_txt_pooled_mapper.bias")] = weights
143
+ else:
144
+ state_dict[key] = original_state_dict[key]
145
+
146
+ return state_dict
147
+
148
+
149
+ def infer_stable_cascade_single_file_config(checkpoint):
150
+ is_stage_c = "clip_txt_mapper.weight" in checkpoint
151
+ is_stage_b = "down_blocks.1.0.channelwise.0.weight" in checkpoint
152
+
153
+ if is_stage_c and (checkpoint["clip_txt_mapper.weight"].shape[0] == 1536):
154
+ config_type = "stage_c_lite"
155
+ elif is_stage_c and (checkpoint["clip_txt_mapper.weight"].shape[0] == 2048):
156
+ config_type = "stage_c"
157
+ elif is_stage_b and checkpoint["down_blocks.1.0.channelwise.0.weight"].shape[-1] == 576:
158
+ config_type = "stage_b_lite"
159
+ elif is_stage_b and checkpoint["down_blocks.1.0.channelwise.0.weight"].shape[-1] == 640:
160
+ config_type = "stage_b"
161
+
162
+ return STABLE_CASCADE_DEFAULT_CONFIGS[config_type]
163
+
164
+
165
+ DIFFUSERS_TO_LDM_MAPPING = {
166
+ "unet": {
167
+ "layers": {
168
+ "time_embedding.linear_1.weight": "time_embed.0.weight",
169
+ "time_embedding.linear_1.bias": "time_embed.0.bias",
170
+ "time_embedding.linear_2.weight": "time_embed.2.weight",
171
+ "time_embedding.linear_2.bias": "time_embed.2.bias",
172
+ "conv_in.weight": "input_blocks.0.0.weight",
173
+ "conv_in.bias": "input_blocks.0.0.bias",
174
+ "conv_norm_out.weight": "out.0.weight",
175
+ "conv_norm_out.bias": "out.0.bias",
176
+ "conv_out.weight": "out.2.weight",
177
+ "conv_out.bias": "out.2.bias",
178
+ },
179
+ "class_embed_type": {
180
+ "class_embedding.linear_1.weight": "label_emb.0.0.weight",
181
+ "class_embedding.linear_1.bias": "label_emb.0.0.bias",
182
+ "class_embedding.linear_2.weight": "label_emb.0.2.weight",
183
+ "class_embedding.linear_2.bias": "label_emb.0.2.bias",
184
+ },
185
+ "addition_embed_type": {
186
+ "add_embedding.linear_1.weight": "label_emb.0.0.weight",
187
+ "add_embedding.linear_1.bias": "label_emb.0.0.bias",
188
+ "add_embedding.linear_2.weight": "label_emb.0.2.weight",
189
+ "add_embedding.linear_2.bias": "label_emb.0.2.bias",
190
+ },
191
+ },
192
+ "controlnet": {
193
+ "layers": {
194
+ "time_embedding.linear_1.weight": "time_embed.0.weight",
195
+ "time_embedding.linear_1.bias": "time_embed.0.bias",
196
+ "time_embedding.linear_2.weight": "time_embed.2.weight",
197
+ "time_embedding.linear_2.bias": "time_embed.2.bias",
198
+ "conv_in.weight": "input_blocks.0.0.weight",
199
+ "conv_in.bias": "input_blocks.0.0.bias",
200
+ "controlnet_cond_embedding.conv_in.weight": "input_hint_block.0.weight",
201
+ "controlnet_cond_embedding.conv_in.bias": "input_hint_block.0.bias",
202
+ "controlnet_cond_embedding.conv_out.weight": "input_hint_block.14.weight",
203
+ "controlnet_cond_embedding.conv_out.bias": "input_hint_block.14.bias",
204
+ },
205
+ "class_embed_type": {
206
+ "class_embedding.linear_1.weight": "label_emb.0.0.weight",
207
+ "class_embedding.linear_1.bias": "label_emb.0.0.bias",
208
+ "class_embedding.linear_2.weight": "label_emb.0.2.weight",
209
+ "class_embedding.linear_2.bias": "label_emb.0.2.bias",
210
+ },
211
+ "addition_embed_type": {
212
+ "add_embedding.linear_1.weight": "label_emb.0.0.weight",
213
+ "add_embedding.linear_1.bias": "label_emb.0.0.bias",
214
+ "add_embedding.linear_2.weight": "label_emb.0.2.weight",
215
+ "add_embedding.linear_2.bias": "label_emb.0.2.bias",
216
+ },
217
+ },
218
+ "vae": {
219
+ "encoder.conv_in.weight": "encoder.conv_in.weight",
220
+ "encoder.conv_in.bias": "encoder.conv_in.bias",
221
+ "encoder.conv_out.weight": "encoder.conv_out.weight",
222
+ "encoder.conv_out.bias": "encoder.conv_out.bias",
223
+ "encoder.conv_norm_out.weight": "encoder.norm_out.weight",
224
+ "encoder.conv_norm_out.bias": "encoder.norm_out.bias",
225
+ "decoder.conv_in.weight": "decoder.conv_in.weight",
226
+ "decoder.conv_in.bias": "decoder.conv_in.bias",
227
+ "decoder.conv_out.weight": "decoder.conv_out.weight",
228
+ "decoder.conv_out.bias": "decoder.conv_out.bias",
229
+ "decoder.conv_norm_out.weight": "decoder.norm_out.weight",
230
+ "decoder.conv_norm_out.bias": "decoder.norm_out.bias",
231
+ "quant_conv.weight": "quant_conv.weight",
232
+ "quant_conv.bias": "quant_conv.bias",
233
+ "post_quant_conv.weight": "post_quant_conv.weight",
234
+ "post_quant_conv.bias": "post_quant_conv.bias",
235
+ },
236
+ "openclip": {
237
+ "layers": {
238
+ "text_model.embeddings.position_embedding.weight": "positional_embedding",
239
+ "text_model.embeddings.token_embedding.weight": "token_embedding.weight",
240
+ "text_model.final_layer_norm.weight": "ln_final.weight",
241
+ "text_model.final_layer_norm.bias": "ln_final.bias",
242
+ "text_projection.weight": "text_projection",
243
+ },
244
+ "transformer": {
245
+ "text_model.encoder.layers.": "resblocks.",
246
+ "layer_norm1": "ln_1",
247
+ "layer_norm2": "ln_2",
248
+ ".fc1.": ".c_fc.",
249
+ ".fc2.": ".c_proj.",
250
+ ".self_attn": ".attn",
251
+ "transformer.text_model.final_layer_norm.": "ln_final.",
252
+ "transformer.text_model.embeddings.token_embedding.weight": "token_embedding.weight",
253
+ "transformer.text_model.embeddings.position_embedding.weight": "positional_embedding",
254
+ },
255
+ },
256
+ }
257
+
258
+ LDM_VAE_KEY = "first_stage_model."
259
+ LDM_VAE_DEFAULT_SCALING_FACTOR = 0.18215
260
+ PLAYGROUND_VAE_SCALING_FACTOR = 0.5
261
+ LDM_UNET_KEY = "model.diffusion_model."
262
+ LDM_CONTROLNET_KEY = "control_model."
263
+ LDM_CLIP_PREFIX_TO_REMOVE = ["cond_stage_model.transformer.", "conditioner.embedders.0.transformer."]
264
+ LDM_OPEN_CLIP_TEXT_PROJECTION_DIM = 1024
265
+
266
+ SD_2_TEXT_ENCODER_KEYS_TO_IGNORE = [
267
+ "cond_stage_model.model.transformer.resblocks.23.attn.in_proj_bias",
268
+ "cond_stage_model.model.transformer.resblocks.23.attn.in_proj_weight",
269
+ "cond_stage_model.model.transformer.resblocks.23.attn.out_proj.bias",
270
+ "cond_stage_model.model.transformer.resblocks.23.attn.out_proj.weight",
271
+ "cond_stage_model.model.transformer.resblocks.23.ln_1.bias",
272
+ "cond_stage_model.model.transformer.resblocks.23.ln_1.weight",
273
+ "cond_stage_model.model.transformer.resblocks.23.ln_2.bias",
274
+ "cond_stage_model.model.transformer.resblocks.23.ln_2.weight",
275
+ "cond_stage_model.model.transformer.resblocks.23.mlp.c_fc.bias",
276
+ "cond_stage_model.model.transformer.resblocks.23.mlp.c_fc.weight",
277
+ "cond_stage_model.model.transformer.resblocks.23.mlp.c_proj.bias",
278
+ "cond_stage_model.model.transformer.resblocks.23.mlp.c_proj.weight",
279
+ "cond_stage_model.model.text_projection",
280
+ ]
281
+
282
+
283
+ VALID_URL_PREFIXES = ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]
284
+
285
+
286
+ def _extract_repo_id_and_weights_name(pretrained_model_name_or_path):
287
+ pattern = r"([^/]+)/([^/]+)/(?:blob/main/)?(.+)"
288
+ weights_name = None
289
+ repo_id = (None,)
290
+ for prefix in VALID_URL_PREFIXES:
291
+ pretrained_model_name_or_path = pretrained_model_name_or_path.replace(prefix, "")
292
+ match = re.match(pattern, pretrained_model_name_or_path)
293
+ if not match:
294
+ return repo_id, weights_name
295
+
296
+ repo_id = f"{match.group(1)}/{match.group(2)}"
297
+ weights_name = match.group(3)
298
+
299
+ return repo_id, weights_name
300
+
301
+
302
+ def fetch_ldm_config_and_checkpoint(
303
+ pretrained_model_link_or_path,
304
+ class_name,
305
+ original_config_file=None,
306
+ resume_download=False,
307
+ force_download=False,
308
+ proxies=None,
309
+ token=None,
310
+ cache_dir=None,
311
+ local_files_only=None,
312
+ revision=None,
313
+ ):
314
+ checkpoint = load_single_file_model_checkpoint(
315
+ pretrained_model_link_or_path,
316
+ resume_download=resume_download,
317
+ force_download=force_download,
318
+ proxies=proxies,
319
+ token=token,
320
+ cache_dir=cache_dir,
321
+ local_files_only=local_files_only,
322
+ revision=revision,
323
+ )
324
+ original_config = fetch_original_config(class_name, checkpoint, original_config_file)
325
+
326
+ return original_config, checkpoint
327
+
328
+
329
+ def load_single_file_model_checkpoint(
330
+ pretrained_model_link_or_path,
331
+ resume_download=False,
332
+ force_download=False,
333
+ proxies=None,
334
+ token=None,
335
+ cache_dir=None,
336
+ local_files_only=None,
337
+ revision=None,
338
+ ):
339
+ if os.path.isfile(pretrained_model_link_or_path):
340
+ checkpoint = load_state_dict(pretrained_model_link_or_path)
341
+ else:
342
+ repo_id, weights_name = _extract_repo_id_and_weights_name(pretrained_model_link_or_path)
343
+ checkpoint_path = _get_model_file(
344
+ repo_id,
345
+ weights_name=weights_name,
346
+ force_download=force_download,
347
+ cache_dir=cache_dir,
348
+ resume_download=resume_download,
349
+ proxies=proxies,
350
+ local_files_only=local_files_only,
351
+ token=token,
352
+ revision=revision,
353
+ )
354
+ checkpoint = load_state_dict(checkpoint_path)
355
+
356
+ # some checkpoints contain the model state dict under a "state_dict" key
357
+ while "state_dict" in checkpoint:
358
+ checkpoint = checkpoint["state_dict"]
359
+
360
+ return checkpoint
361
+
362
+
363
+ def infer_original_config_file(class_name, checkpoint):
364
+ if CHECKPOINT_KEY_NAMES["v2"] in checkpoint and checkpoint[CHECKPOINT_KEY_NAMES["v2"]].shape[-1] == 1024:
365
+ config_url = CONFIG_URLS["v2"]
366
+
367
+ elif CHECKPOINT_KEY_NAMES["xl_base"] in checkpoint:
368
+ config_url = CONFIG_URLS["xl"]
369
+
370
+ elif CHECKPOINT_KEY_NAMES["xl_refiner"] in checkpoint:
371
+ config_url = CONFIG_URLS["xl_refiner"]
372
+
373
+ elif class_name == "StableDiffusionUpscalePipeline":
374
+ config_url = CONFIG_URLS["upscale"]
375
+
376
+ elif class_name == "ControlNetModel":
377
+ config_url = CONFIG_URLS["controlnet"]
378
+
379
+ else:
380
+ config_url = CONFIG_URLS["v1"]
381
+
382
+ original_config_file = BytesIO(requests.get(config_url).content)
383
+
384
+ return original_config_file
385
+
386
+
387
+ def fetch_original_config(pipeline_class_name, checkpoint, original_config_file=None):
388
+ def is_valid_url(url):
389
+ result = urlparse(url)
390
+ if result.scheme and result.netloc:
391
+ return True
392
+
393
+ return False
394
+
395
+ if original_config_file is None:
396
+ original_config_file = infer_original_config_file(pipeline_class_name, checkpoint)
397
+
398
+ elif os.path.isfile(original_config_file):
399
+ with open(original_config_file, "r") as fp:
400
+ original_config_file = fp.read()
401
+
402
+ elif is_valid_url(original_config_file):
403
+ original_config_file = BytesIO(requests.get(original_config_file).content)
404
+
405
+ else:
406
+ raise ValueError("Invalid `original_config_file` provided. Please set it to a valid file path or URL.")
407
+
408
+ original_config = yaml.safe_load(original_config_file)
409
+
410
+ return original_config
411
+
412
+
413
+ def infer_model_type(original_config, checkpoint, model_type=None):
414
+ if model_type is not None:
415
+ return model_type
416
+
417
+ has_cond_stage_config = (
418
+ "cond_stage_config" in original_config["model"]["params"]
419
+ and original_config["model"]["params"]["cond_stage_config"] is not None
420
+ )
421
+ has_network_config = (
422
+ "network_config" in original_config["model"]["params"]
423
+ and original_config["model"]["params"]["network_config"] is not None
424
+ )
425
+
426
+ if has_cond_stage_config:
427
+ model_type = original_config["model"]["params"]["cond_stage_config"]["target"].split(".")[-1]
428
+
429
+ elif has_network_config:
430
+ context_dim = original_config["model"]["params"]["network_config"]["params"]["context_dim"]
431
+ if "edm_mean" in checkpoint and "edm_std" in checkpoint:
432
+ model_type = "Playground"
433
+ elif context_dim == 2048:
434
+ model_type = "SDXL"
435
+ else:
436
+ model_type = "SDXL-Refiner"
437
+ else:
438
+ raise ValueError("Unable to infer model type from config")
439
+
440
+ logger.debug(f"No `model_type` given, `model_type` inferred as: {model_type}")
441
+
442
+ return model_type
443
+
444
+
445
+ def get_default_scheduler_config():
446
+ return SCHEDULER_DEFAULT_CONFIG
447
+
448
+
449
+ def set_image_size(pipeline_class_name, original_config, checkpoint, image_size=None, model_type=None):
450
+ if image_size:
451
+ return image_size
452
+
453
+ global_step = checkpoint["global_step"] if "global_step" in checkpoint else None
454
+ model_type = infer_model_type(original_config, checkpoint, model_type)
455
+
456
+ if pipeline_class_name == "StableDiffusionUpscalePipeline":
457
+ image_size = original_config["model"]["params"]["unet_config"]["params"]["image_size"]
458
+ return image_size
459
+
460
+ elif model_type in ["SDXL", "SDXL-Refiner", "Playground"]:
461
+ image_size = 1024
462
+ return image_size
463
+
464
+ elif (
465
+ "parameterization" in original_config["model"]["params"]
466
+ and original_config["model"]["params"]["parameterization"] == "v"
467
+ ):
468
+ # NOTE: For stable diffusion 2 base one has to pass `image_size==512`
469
+ # as it relies on a brittle global step parameter here
470
+ image_size = 512 if global_step == 875000 else 768
471
+ return image_size
472
+
473
+ else:
474
+ image_size = 512
475
+ return image_size
476
+
477
+
478
+ # Copied from diffusers.pipelines.stable_diffusion.convert_from_ckpt.conv_attn_to_linear
479
+ def conv_attn_to_linear(checkpoint):
480
+ keys = list(checkpoint.keys())
481
+ attn_keys = ["query.weight", "key.weight", "value.weight"]
482
+ for key in keys:
483
+ if ".".join(key.split(".")[-2:]) in attn_keys:
484
+ if checkpoint[key].ndim > 2:
485
+ checkpoint[key] = checkpoint[key][:, :, 0, 0]
486
+ elif "proj_attn.weight" in key:
487
+ if checkpoint[key].ndim > 2:
488
+ checkpoint[key] = checkpoint[key][:, :, 0]
489
+
490
+
491
+ def create_unet_diffusers_config(original_config, image_size: int):
492
+ """
493
+ Creates a config for the diffusers based on the config of the LDM model.
494
+ """
495
+ if (
496
+ "unet_config" in original_config["model"]["params"]
497
+ and original_config["model"]["params"]["unet_config"] is not None
498
+ ):
499
+ unet_params = original_config["model"]["params"]["unet_config"]["params"]
500
+ else:
501
+ unet_params = original_config["model"]["params"]["network_config"]["params"]
502
+
503
+ vae_params = original_config["model"]["params"]["first_stage_config"]["params"]["ddconfig"]
504
+ block_out_channels = [unet_params["model_channels"] * mult for mult in unet_params["channel_mult"]]
505
+
506
+ down_block_types = []
507
+ resolution = 1
508
+ for i in range(len(block_out_channels)):
509
+ block_type = "CrossAttnDownBlock2D" if resolution in unet_params["attention_resolutions"] else "DownBlock2D"
510
+ down_block_types.append(block_type)
511
+ if i != len(block_out_channels) - 1:
512
+ resolution *= 2
513
+
514
+ up_block_types = []
515
+ for i in range(len(block_out_channels)):
516
+ block_type = "CrossAttnUpBlock2D" if resolution in unet_params["attention_resolutions"] else "UpBlock2D"
517
+ up_block_types.append(block_type)
518
+ resolution //= 2
519
+
520
+ if unet_params["transformer_depth"] is not None:
521
+ transformer_layers_per_block = (
522
+ unet_params["transformer_depth"]
523
+ if isinstance(unet_params["transformer_depth"], int)
524
+ else list(unet_params["transformer_depth"])
525
+ )
526
+ else:
527
+ transformer_layers_per_block = 1
528
+
529
+ vae_scale_factor = 2 ** (len(vae_params["ch_mult"]) - 1)
530
+
531
+ head_dim = unet_params["num_heads"] if "num_heads" in unet_params else None
532
+ use_linear_projection = (
533
+ unet_params["use_linear_in_transformer"] if "use_linear_in_transformer" in unet_params else False
534
+ )
535
+ if use_linear_projection:
536
+ # stable diffusion 2-base-512 and 2-768
537
+ if head_dim is None:
538
+ head_dim_mult = unet_params["model_channels"] // unet_params["num_head_channels"]
539
+ head_dim = [head_dim_mult * c for c in list(unet_params["channel_mult"])]
540
+
541
+ class_embed_type = None
542
+ addition_embed_type = None
543
+ addition_time_embed_dim = None
544
+ projection_class_embeddings_input_dim = None
545
+ context_dim = None
546
+
547
+ if unet_params["context_dim"] is not None:
548
+ context_dim = (
549
+ unet_params["context_dim"]
550
+ if isinstance(unet_params["context_dim"], int)
551
+ else unet_params["context_dim"][0]
552
+ )
553
+
554
+ if "num_classes" in unet_params:
555
+ if unet_params["num_classes"] == "sequential":
556
+ if context_dim in [2048, 1280]:
557
+ # SDXL
558
+ addition_embed_type = "text_time"
559
+ addition_time_embed_dim = 256
560
+ else:
561
+ class_embed_type = "projection"
562
+ assert "adm_in_channels" in unet_params
563
+ projection_class_embeddings_input_dim = unet_params["adm_in_channels"]
564
+
565
+ config = {
566
+ "sample_size": image_size // vae_scale_factor,
567
+ "in_channels": unet_params["in_channels"],
568
+ "down_block_types": down_block_types,
569
+ "block_out_channels": block_out_channels,
570
+ "layers_per_block": unet_params["num_res_blocks"],
571
+ "cross_attention_dim": context_dim,
572
+ "attention_head_dim": head_dim,
573
+ "use_linear_projection": use_linear_projection,
574
+ "class_embed_type": class_embed_type,
575
+ "addition_embed_type": addition_embed_type,
576
+ "addition_time_embed_dim": addition_time_embed_dim,
577
+ "projection_class_embeddings_input_dim": projection_class_embeddings_input_dim,
578
+ "transformer_layers_per_block": transformer_layers_per_block,
579
+ }
580
+
581
+ if "disable_self_attentions" in unet_params:
582
+ config["only_cross_attention"] = unet_params["disable_self_attentions"]
583
+
584
+ if "num_classes" in unet_params and isinstance(unet_params["num_classes"], int):
585
+ config["num_class_embeds"] = unet_params["num_classes"]
586
+
587
+ config["out_channels"] = unet_params["out_channels"]
588
+ config["up_block_types"] = up_block_types
589
+
590
+ return config
591
+
592
+
593
+ def create_controlnet_diffusers_config(original_config, image_size: int):
594
+ unet_params = original_config["model"]["params"]["control_stage_config"]["params"]
595
+ diffusers_unet_config = create_unet_diffusers_config(original_config, image_size=image_size)
596
+
597
+ controlnet_config = {
598
+ "conditioning_channels": unet_params["hint_channels"],
599
+ "in_channels": diffusers_unet_config["in_channels"],
600
+ "down_block_types": diffusers_unet_config["down_block_types"],
601
+ "block_out_channels": diffusers_unet_config["block_out_channels"],
602
+ "layers_per_block": diffusers_unet_config["layers_per_block"],
603
+ "cross_attention_dim": diffusers_unet_config["cross_attention_dim"],
604
+ "attention_head_dim": diffusers_unet_config["attention_head_dim"],
605
+ "use_linear_projection": diffusers_unet_config["use_linear_projection"],
606
+ "class_embed_type": diffusers_unet_config["class_embed_type"],
607
+ "addition_embed_type": diffusers_unet_config["addition_embed_type"],
608
+ "addition_time_embed_dim": diffusers_unet_config["addition_time_embed_dim"],
609
+ "projection_class_embeddings_input_dim": diffusers_unet_config["projection_class_embeddings_input_dim"],
610
+ "transformer_layers_per_block": diffusers_unet_config["transformer_layers_per_block"],
611
+ }
612
+
613
+ return controlnet_config
614
+
615
+
616
+ def create_vae_diffusers_config(original_config, image_size, scaling_factor=None, latents_mean=None, latents_std=None):
617
+ """
618
+ Creates a config for the diffusers based on the config of the LDM model.
619
+ """
620
+ vae_params = original_config["model"]["params"]["first_stage_config"]["params"]["ddconfig"]
621
+ if (scaling_factor is None) and (latents_mean is not None) and (latents_std is not None):
622
+ scaling_factor = PLAYGROUND_VAE_SCALING_FACTOR
623
+ elif (scaling_factor is None) and ("scale_factor" in original_config["model"]["params"]):
624
+ scaling_factor = original_config["model"]["params"]["scale_factor"]
625
+ elif scaling_factor is None:
626
+ scaling_factor = LDM_VAE_DEFAULT_SCALING_FACTOR
627
+
628
+ block_out_channels = [vae_params["ch"] * mult for mult in vae_params["ch_mult"]]
629
+ down_block_types = ["DownEncoderBlock2D"] * len(block_out_channels)
630
+ up_block_types = ["UpDecoderBlock2D"] * len(block_out_channels)
631
+
632
+ config = {
633
+ "sample_size": image_size,
634
+ "in_channels": vae_params["in_channels"],
635
+ "out_channels": vae_params["out_ch"],
636
+ "down_block_types": down_block_types,
637
+ "up_block_types": up_block_types,
638
+ "block_out_channels": block_out_channels,
639
+ "latent_channels": vae_params["z_channels"],
640
+ "layers_per_block": vae_params["num_res_blocks"],
641
+ "scaling_factor": scaling_factor,
642
+ }
643
+ if latents_mean is not None and latents_std is not None:
644
+ config.update({"latents_mean": latents_mean, "latents_std": latents_std})
645
+
646
+ return config
647
+
648
+
649
+ def update_unet_resnet_ldm_to_diffusers(ldm_keys, new_checkpoint, checkpoint, mapping=None):
650
+ for ldm_key in ldm_keys:
651
+ diffusers_key = (
652
+ ldm_key.replace("in_layers.0", "norm1")
653
+ .replace("in_layers.2", "conv1")
654
+ .replace("out_layers.0", "norm2")
655
+ .replace("out_layers.3", "conv2")
656
+ .replace("emb_layers.1", "time_emb_proj")
657
+ .replace("skip_connection", "conv_shortcut")
658
+ )
659
+ if mapping:
660
+ diffusers_key = diffusers_key.replace(mapping["old"], mapping["new"])
661
+ new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
662
+
663
+
664
+ def update_unet_attention_ldm_to_diffusers(ldm_keys, new_checkpoint, checkpoint, mapping):
665
+ for ldm_key in ldm_keys:
666
+ diffusers_key = ldm_key.replace(mapping["old"], mapping["new"])
667
+ new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
668
+
669
+
670
+ def convert_ldm_unet_checkpoint(checkpoint, config, extract_ema=False):
671
+ """
672
+ Takes a state dict and a config, and returns a converted checkpoint.
673
+ """
674
+ # extract state_dict for UNet
675
+ unet_state_dict = {}
676
+ keys = list(checkpoint.keys())
677
+ unet_key = LDM_UNET_KEY
678
+
679
+ # at least a 100 parameters have to start with `model_ema` in order for the checkpoint to be EMA
680
+ if sum(k.startswith("model_ema") for k in keys) > 100 and extract_ema:
681
+ logger.warning("Checkpoint has both EMA and non-EMA weights.")
682
+ logger.warning(
683
+ "In this conversion only the EMA weights are extracted. If you want to instead extract the non-EMA"
684
+ " weights (useful to continue fine-tuning), please make sure to remove the `--extract_ema` flag."
685
+ )
686
+ for key in keys:
687
+ if key.startswith("model.diffusion_model"):
688
+ flat_ema_key = "model_ema." + "".join(key.split(".")[1:])
689
+ unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(flat_ema_key)
690
+ else:
691
+ if sum(k.startswith("model_ema") for k in keys) > 100:
692
+ logger.warning(
693
+ "In this conversion only the non-EMA weights are extracted. If you want to instead extract the EMA"
694
+ " weights (usually better for inference), please make sure to add the `--extract_ema` flag."
695
+ )
696
+ for key in keys:
697
+ if key.startswith(unet_key):
698
+ unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(key)
699
+
700
+ new_checkpoint = {}
701
+ ldm_unet_keys = DIFFUSERS_TO_LDM_MAPPING["unet"]["layers"]
702
+ for diffusers_key, ldm_key in ldm_unet_keys.items():
703
+ if ldm_key not in unet_state_dict:
704
+ continue
705
+ new_checkpoint[diffusers_key] = unet_state_dict[ldm_key]
706
+
707
+ if ("class_embed_type" in config) and (config["class_embed_type"] in ["timestep", "projection"]):
708
+ class_embed_keys = DIFFUSERS_TO_LDM_MAPPING["unet"]["class_embed_type"]
709
+ for diffusers_key, ldm_key in class_embed_keys.items():
710
+ new_checkpoint[diffusers_key] = unet_state_dict[ldm_key]
711
+
712
+ if ("addition_embed_type" in config) and (config["addition_embed_type"] == "text_time"):
713
+ addition_embed_keys = DIFFUSERS_TO_LDM_MAPPING["unet"]["addition_embed_type"]
714
+ for diffusers_key, ldm_key in addition_embed_keys.items():
715
+ new_checkpoint[diffusers_key] = unet_state_dict[ldm_key]
716
+
717
+ # Relevant to StableDiffusionUpscalePipeline
718
+ if "num_class_embeds" in config:
719
+ if (config["num_class_embeds"] is not None) and ("label_emb.weight" in unet_state_dict):
720
+ new_checkpoint["class_embedding.weight"] = unet_state_dict["label_emb.weight"]
721
+
722
+ # Retrieves the keys for the input blocks only
723
+ num_input_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "input_blocks" in layer})
724
+ input_blocks = {
725
+ layer_id: [key for key in unet_state_dict if f"input_blocks.{layer_id}" in key]
726
+ for layer_id in range(num_input_blocks)
727
+ }
728
+
729
+ # Retrieves the keys for the middle blocks only
730
+ num_middle_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "middle_block" in layer})
731
+ middle_blocks = {
732
+ layer_id: [key for key in unet_state_dict if f"middle_block.{layer_id}" in key]
733
+ for layer_id in range(num_middle_blocks)
734
+ }
735
+
736
+ # Retrieves the keys for the output blocks only
737
+ num_output_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "output_blocks" in layer})
738
+ output_blocks = {
739
+ layer_id: [key for key in unet_state_dict if f"output_blocks.{layer_id}" in key]
740
+ for layer_id in range(num_output_blocks)
741
+ }
742
+
743
+ # Down blocks
744
+ for i in range(1, num_input_blocks):
745
+ block_id = (i - 1) // (config["layers_per_block"] + 1)
746
+ layer_in_block_id = (i - 1) % (config["layers_per_block"] + 1)
747
+
748
+ resnets = [
749
+ key for key in input_blocks[i] if f"input_blocks.{i}.0" in key and f"input_blocks.{i}.0.op" not in key
750
+ ]
751
+ update_unet_resnet_ldm_to_diffusers(
752
+ resnets,
753
+ new_checkpoint,
754
+ unet_state_dict,
755
+ {"old": f"input_blocks.{i}.0", "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}"},
756
+ )
757
+
758
+ if f"input_blocks.{i}.0.op.weight" in unet_state_dict:
759
+ new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.weight"] = unet_state_dict.pop(
760
+ f"input_blocks.{i}.0.op.weight"
761
+ )
762
+ new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.bias"] = unet_state_dict.pop(
763
+ f"input_blocks.{i}.0.op.bias"
764
+ )
765
+
766
+ attentions = [key for key in input_blocks[i] if f"input_blocks.{i}.1" in key]
767
+ if attentions:
768
+ update_unet_attention_ldm_to_diffusers(
769
+ attentions,
770
+ new_checkpoint,
771
+ unet_state_dict,
772
+ {"old": f"input_blocks.{i}.1", "new": f"down_blocks.{block_id}.attentions.{layer_in_block_id}"},
773
+ )
774
+
775
+ # Mid blocks
776
+ resnet_0 = middle_blocks[0]
777
+ attentions = middle_blocks[1]
778
+ resnet_1 = middle_blocks[2]
779
+
780
+ update_unet_resnet_ldm_to_diffusers(
781
+ resnet_0, new_checkpoint, unet_state_dict, mapping={"old": "middle_block.0", "new": "mid_block.resnets.0"}
782
+ )
783
+ update_unet_resnet_ldm_to_diffusers(
784
+ resnet_1, new_checkpoint, unet_state_dict, mapping={"old": "middle_block.2", "new": "mid_block.resnets.1"}
785
+ )
786
+ update_unet_attention_ldm_to_diffusers(
787
+ attentions, new_checkpoint, unet_state_dict, mapping={"old": "middle_block.1", "new": "mid_block.attentions.0"}
788
+ )
789
+
790
+ # Up Blocks
791
+ for i in range(num_output_blocks):
792
+ block_id = i // (config["layers_per_block"] + 1)
793
+ layer_in_block_id = i % (config["layers_per_block"] + 1)
794
+
795
+ resnets = [
796
+ key for key in output_blocks[i] if f"output_blocks.{i}.0" in key and f"output_blocks.{i}.0.op" not in key
797
+ ]
798
+ update_unet_resnet_ldm_to_diffusers(
799
+ resnets,
800
+ new_checkpoint,
801
+ unet_state_dict,
802
+ {"old": f"output_blocks.{i}.0", "new": f"up_blocks.{block_id}.resnets.{layer_in_block_id}"},
803
+ )
804
+
805
+ attentions = [
806
+ key for key in output_blocks[i] if f"output_blocks.{i}.1" in key and f"output_blocks.{i}.1.conv" not in key
807
+ ]
808
+ if attentions:
809
+ update_unet_attention_ldm_to_diffusers(
810
+ attentions,
811
+ new_checkpoint,
812
+ unet_state_dict,
813
+ {"old": f"output_blocks.{i}.1", "new": f"up_blocks.{block_id}.attentions.{layer_in_block_id}"},
814
+ )
815
+
816
+ if f"output_blocks.{i}.1.conv.weight" in unet_state_dict:
817
+ new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.weight"] = unet_state_dict[
818
+ f"output_blocks.{i}.1.conv.weight"
819
+ ]
820
+ new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.bias"] = unet_state_dict[
821
+ f"output_blocks.{i}.1.conv.bias"
822
+ ]
823
+ if f"output_blocks.{i}.2.conv.weight" in unet_state_dict:
824
+ new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.weight"] = unet_state_dict[
825
+ f"output_blocks.{i}.2.conv.weight"
826
+ ]
827
+ new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.bias"] = unet_state_dict[
828
+ f"output_blocks.{i}.2.conv.bias"
829
+ ]
830
+
831
+ return new_checkpoint
832
+
833
+
834
+ def convert_controlnet_checkpoint(
835
+ checkpoint,
836
+ config,
837
+ ):
838
+ # Some controlnet ckpt files are distributed independently from the rest of the
839
+ # model components i.e. https://huggingface.co/thibaud/controlnet-sd21/
840
+ if "time_embed.0.weight" in checkpoint:
841
+ controlnet_state_dict = checkpoint
842
+
843
+ else:
844
+ controlnet_state_dict = {}
845
+ keys = list(checkpoint.keys())
846
+ controlnet_key = LDM_CONTROLNET_KEY
847
+ for key in keys:
848
+ if key.startswith(controlnet_key):
849
+ controlnet_state_dict[key.replace(controlnet_key, "")] = checkpoint.pop(key)
850
+
851
+ new_checkpoint = {}
852
+ ldm_controlnet_keys = DIFFUSERS_TO_LDM_MAPPING["controlnet"]["layers"]
853
+ for diffusers_key, ldm_key in ldm_controlnet_keys.items():
854
+ if ldm_key not in controlnet_state_dict:
855
+ continue
856
+ new_checkpoint[diffusers_key] = controlnet_state_dict[ldm_key]
857
+
858
+ # Retrieves the keys for the input blocks only
859
+ num_input_blocks = len(
860
+ {".".join(layer.split(".")[:2]) for layer in controlnet_state_dict if "input_blocks" in layer}
861
+ )
862
+ input_blocks = {
863
+ layer_id: [key for key in controlnet_state_dict if f"input_blocks.{layer_id}" in key]
864
+ for layer_id in range(num_input_blocks)
865
+ }
866
+
867
+ # Down blocks
868
+ for i in range(1, num_input_blocks):
869
+ block_id = (i - 1) // (config["layers_per_block"] + 1)
870
+ layer_in_block_id = (i - 1) % (config["layers_per_block"] + 1)
871
+
872
+ resnets = [
873
+ key for key in input_blocks[i] if f"input_blocks.{i}.0" in key and f"input_blocks.{i}.0.op" not in key
874
+ ]
875
+ update_unet_resnet_ldm_to_diffusers(
876
+ resnets,
877
+ new_checkpoint,
878
+ controlnet_state_dict,
879
+ {"old": f"input_blocks.{i}.0", "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}"},
880
+ )
881
+
882
+ if f"input_blocks.{i}.0.op.weight" in controlnet_state_dict:
883
+ new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.weight"] = controlnet_state_dict.pop(
884
+ f"input_blocks.{i}.0.op.weight"
885
+ )
886
+ new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.bias"] = controlnet_state_dict.pop(
887
+ f"input_blocks.{i}.0.op.bias"
888
+ )
889
+
890
+ attentions = [key for key in input_blocks[i] if f"input_blocks.{i}.1" in key]
891
+ if attentions:
892
+ update_unet_attention_ldm_to_diffusers(
893
+ attentions,
894
+ new_checkpoint,
895
+ controlnet_state_dict,
896
+ {"old": f"input_blocks.{i}.1", "new": f"down_blocks.{block_id}.attentions.{layer_in_block_id}"},
897
+ )
898
+
899
+ # controlnet down blocks
900
+ for i in range(num_input_blocks):
901
+ new_checkpoint[f"controlnet_down_blocks.{i}.weight"] = controlnet_state_dict.pop(f"zero_convs.{i}.0.weight")
902
+ new_checkpoint[f"controlnet_down_blocks.{i}.bias"] = controlnet_state_dict.pop(f"zero_convs.{i}.0.bias")
903
+
904
+ # Retrieves the keys for the middle blocks only
905
+ num_middle_blocks = len(
906
+ {".".join(layer.split(".")[:2]) for layer in controlnet_state_dict if "middle_block" in layer}
907
+ )
908
+ middle_blocks = {
909
+ layer_id: [key for key in controlnet_state_dict if f"middle_block.{layer_id}" in key]
910
+ for layer_id in range(num_middle_blocks)
911
+ }
912
+ if middle_blocks:
913
+ resnet_0 = middle_blocks[0]
914
+ attentions = middle_blocks[1]
915
+ resnet_1 = middle_blocks[2]
916
+
917
+ update_unet_resnet_ldm_to_diffusers(
918
+ resnet_0,
919
+ new_checkpoint,
920
+ controlnet_state_dict,
921
+ mapping={"old": "middle_block.0", "new": "mid_block.resnets.0"},
922
+ )
923
+ update_unet_resnet_ldm_to_diffusers(
924
+ resnet_1,
925
+ new_checkpoint,
926
+ controlnet_state_dict,
927
+ mapping={"old": "middle_block.2", "new": "mid_block.resnets.1"},
928
+ )
929
+ update_unet_attention_ldm_to_diffusers(
930
+ attentions,
931
+ new_checkpoint,
932
+ controlnet_state_dict,
933
+ mapping={"old": "middle_block.1", "new": "mid_block.attentions.0"},
934
+ )
935
+
936
+ # mid block
937
+ new_checkpoint["controlnet_mid_block.weight"] = controlnet_state_dict.pop("middle_block_out.0.weight")
938
+ new_checkpoint["controlnet_mid_block.bias"] = controlnet_state_dict.pop("middle_block_out.0.bias")
939
+
940
+ # controlnet cond embedding blocks
941
+ cond_embedding_blocks = {
942
+ ".".join(layer.split(".")[:2])
943
+ for layer in controlnet_state_dict
944
+ if "input_hint_block" in layer and ("input_hint_block.0" not in layer) and ("input_hint_block.14" not in layer)
945
+ }
946
+ num_cond_embedding_blocks = len(cond_embedding_blocks)
947
+
948
+ for idx in range(1, num_cond_embedding_blocks + 1):
949
+ diffusers_idx = idx - 1
950
+ cond_block_id = 2 * idx
951
+
952
+ new_checkpoint[f"controlnet_cond_embedding.blocks.{diffusers_idx}.weight"] = controlnet_state_dict.pop(
953
+ f"input_hint_block.{cond_block_id}.weight"
954
+ )
955
+ new_checkpoint[f"controlnet_cond_embedding.blocks.{diffusers_idx}.bias"] = controlnet_state_dict.pop(
956
+ f"input_hint_block.{cond_block_id}.bias"
957
+ )
958
+
959
+ return new_checkpoint
960
+
961
+
962
+ def create_diffusers_controlnet_model_from_ldm(
963
+ pipeline_class_name, original_config, checkpoint, upcast_attention=False, image_size=None, torch_dtype=None
964
+ ):
965
+ # import here to avoid circular imports
966
+ from ..models import ControlNetModel
967
+
968
+ image_size = set_image_size(pipeline_class_name, original_config, checkpoint, image_size=image_size)
969
+
970
+ diffusers_config = create_controlnet_diffusers_config(original_config, image_size=image_size)
971
+ diffusers_config["upcast_attention"] = upcast_attention
972
+
973
+ diffusers_format_controlnet_checkpoint = convert_controlnet_checkpoint(checkpoint, diffusers_config)
974
+
975
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
976
+ with ctx():
977
+ controlnet = ControlNetModel(**diffusers_config)
978
+
979
+ if is_accelerate_available():
980
+ from ..models.modeling_utils import load_model_dict_into_meta
981
+
982
+ unexpected_keys = load_model_dict_into_meta(
983
+ controlnet, diffusers_format_controlnet_checkpoint, dtype=torch_dtype
984
+ )
985
+ if controlnet._keys_to_ignore_on_load_unexpected is not None:
986
+ for pat in controlnet._keys_to_ignore_on_load_unexpected:
987
+ unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
988
+
989
+ if len(unexpected_keys) > 0:
990
+ logger.warning(
991
+ f"Some weights of the model checkpoint were not used when initializing {controlnet.__name__}: \n {[', '.join(unexpected_keys)]}"
992
+ )
993
+ else:
994
+ controlnet.load_state_dict(diffusers_format_controlnet_checkpoint)
995
+
996
+ if torch_dtype is not None:
997
+ controlnet = controlnet.to(torch_dtype)
998
+
999
+ return {"controlnet": controlnet}
1000
+
1001
+
1002
+ def update_vae_resnet_ldm_to_diffusers(keys, new_checkpoint, checkpoint, mapping):
1003
+ for ldm_key in keys:
1004
+ diffusers_key = ldm_key.replace(mapping["old"], mapping["new"]).replace("nin_shortcut", "conv_shortcut")
1005
+ new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
1006
+
1007
+
1008
+ def update_vae_attentions_ldm_to_diffusers(keys, new_checkpoint, checkpoint, mapping):
1009
+ for ldm_key in keys:
1010
+ diffusers_key = (
1011
+ ldm_key.replace(mapping["old"], mapping["new"])
1012
+ .replace("norm.weight", "group_norm.weight")
1013
+ .replace("norm.bias", "group_norm.bias")
1014
+ .replace("q.weight", "to_q.weight")
1015
+ .replace("q.bias", "to_q.bias")
1016
+ .replace("k.weight", "to_k.weight")
1017
+ .replace("k.bias", "to_k.bias")
1018
+ .replace("v.weight", "to_v.weight")
1019
+ .replace("v.bias", "to_v.bias")
1020
+ .replace("proj_out.weight", "to_out.0.weight")
1021
+ .replace("proj_out.bias", "to_out.0.bias")
1022
+ )
1023
+ new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
1024
+
1025
+ # proj_attn.weight has to be converted from conv 1D to linear
1026
+ shape = new_checkpoint[diffusers_key].shape
1027
+
1028
+ if len(shape) == 3:
1029
+ new_checkpoint[diffusers_key] = new_checkpoint[diffusers_key][:, :, 0]
1030
+ elif len(shape) == 4:
1031
+ new_checkpoint[diffusers_key] = new_checkpoint[diffusers_key][:, :, 0, 0]
1032
+
1033
+
1034
+ def convert_ldm_vae_checkpoint(checkpoint, config):
1035
+ # extract state dict for VAE
1036
+ # remove the LDM_VAE_KEY prefix from the ldm checkpoint keys so that it is easier to map them to diffusers keys
1037
+ vae_state_dict = {}
1038
+ keys = list(checkpoint.keys())
1039
+ vae_key = LDM_VAE_KEY if any(k.startswith(LDM_VAE_KEY) for k in keys) else ""
1040
+ for key in keys:
1041
+ if key.startswith(vae_key):
1042
+ vae_state_dict[key.replace(vae_key, "")] = checkpoint.get(key)
1043
+
1044
+ new_checkpoint = {}
1045
+ vae_diffusers_ldm_map = DIFFUSERS_TO_LDM_MAPPING["vae"]
1046
+ for diffusers_key, ldm_key in vae_diffusers_ldm_map.items():
1047
+ if ldm_key not in vae_state_dict:
1048
+ continue
1049
+ new_checkpoint[diffusers_key] = vae_state_dict[ldm_key]
1050
+
1051
+ # Retrieves the keys for the encoder down blocks only
1052
+ num_down_blocks = len(config["down_block_types"])
1053
+ down_blocks = {
1054
+ layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in range(num_down_blocks)
1055
+ }
1056
+
1057
+ for i in range(num_down_blocks):
1058
+ resnets = [key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key]
1059
+ update_vae_resnet_ldm_to_diffusers(
1060
+ resnets,
1061
+ new_checkpoint,
1062
+ vae_state_dict,
1063
+ mapping={"old": f"down.{i}.block", "new": f"down_blocks.{i}.resnets"},
1064
+ )
1065
+ if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:
1066
+ new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.weight"] = vae_state_dict.pop(
1067
+ f"encoder.down.{i}.downsample.conv.weight"
1068
+ )
1069
+ new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.bias"] = vae_state_dict.pop(
1070
+ f"encoder.down.{i}.downsample.conv.bias"
1071
+ )
1072
+
1073
+ mid_resnets = [key for key in vae_state_dict if "encoder.mid.block" in key]
1074
+ num_mid_res_blocks = 2
1075
+ for i in range(1, num_mid_res_blocks + 1):
1076
+ resnets = [key for key in mid_resnets if f"encoder.mid.block_{i}" in key]
1077
+ update_vae_resnet_ldm_to_diffusers(
1078
+ resnets,
1079
+ new_checkpoint,
1080
+ vae_state_dict,
1081
+ mapping={"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"},
1082
+ )
1083
+
1084
+ mid_attentions = [key for key in vae_state_dict if "encoder.mid.attn" in key]
1085
+ update_vae_attentions_ldm_to_diffusers(
1086
+ mid_attentions, new_checkpoint, vae_state_dict, mapping={"old": "mid.attn_1", "new": "mid_block.attentions.0"}
1087
+ )
1088
+
1089
+ # Retrieves the keys for the decoder up blocks only
1090
+ num_up_blocks = len(config["up_block_types"])
1091
+ up_blocks = {
1092
+ layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in range(num_up_blocks)
1093
+ }
1094
+
1095
+ for i in range(num_up_blocks):
1096
+ block_id = num_up_blocks - 1 - i
1097
+ resnets = [
1098
+ key for key in up_blocks[block_id] if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key
1099
+ ]
1100
+ update_vae_resnet_ldm_to_diffusers(
1101
+ resnets,
1102
+ new_checkpoint,
1103
+ vae_state_dict,
1104
+ mapping={"old": f"up.{block_id}.block", "new": f"up_blocks.{i}.resnets"},
1105
+ )
1106
+ if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:
1107
+ new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.weight"] = vae_state_dict[
1108
+ f"decoder.up.{block_id}.upsample.conv.weight"
1109
+ ]
1110
+ new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.bias"] = vae_state_dict[
1111
+ f"decoder.up.{block_id}.upsample.conv.bias"
1112
+ ]
1113
+
1114
+ mid_resnets = [key for key in vae_state_dict if "decoder.mid.block" in key]
1115
+ num_mid_res_blocks = 2
1116
+ for i in range(1, num_mid_res_blocks + 1):
1117
+ resnets = [key for key in mid_resnets if f"decoder.mid.block_{i}" in key]
1118
+ update_vae_resnet_ldm_to_diffusers(
1119
+ resnets,
1120
+ new_checkpoint,
1121
+ vae_state_dict,
1122
+ mapping={"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"},
1123
+ )
1124
+
1125
+ mid_attentions = [key for key in vae_state_dict if "decoder.mid.attn" in key]
1126
+ update_vae_attentions_ldm_to_diffusers(
1127
+ mid_attentions, new_checkpoint, vae_state_dict, mapping={"old": "mid.attn_1", "new": "mid_block.attentions.0"}
1128
+ )
1129
+ conv_attn_to_linear(new_checkpoint)
1130
+
1131
+ return new_checkpoint
1132
+
1133
+
1134
+ def create_text_encoder_from_ldm_clip_checkpoint(config_name, checkpoint, local_files_only=False, torch_dtype=None):
1135
+ try:
1136
+ config = CLIPTextConfig.from_pretrained(config_name, local_files_only=local_files_only)
1137
+ except Exception:
1138
+ raise ValueError(
1139
+ f"With local_files_only set to {local_files_only}, you must first locally save the configuration in the following path: 'openai/clip-vit-large-patch14'."
1140
+ )
1141
+
1142
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
1143
+ with ctx():
1144
+ text_model = CLIPTextModel(config)
1145
+
1146
+ keys = list(checkpoint.keys())
1147
+ text_model_dict = {}
1148
+
1149
+ remove_prefixes = LDM_CLIP_PREFIX_TO_REMOVE
1150
+
1151
+ for key in keys:
1152
+ for prefix in remove_prefixes:
1153
+ if key.startswith(prefix):
1154
+ diffusers_key = key.replace(prefix, "")
1155
+ text_model_dict[diffusers_key] = checkpoint[key]
1156
+
1157
+ if is_accelerate_available():
1158
+ from ..models.modeling_utils import load_model_dict_into_meta
1159
+
1160
+ unexpected_keys = load_model_dict_into_meta(text_model, text_model_dict, dtype=torch_dtype)
1161
+ if text_model._keys_to_ignore_on_load_unexpected is not None:
1162
+ for pat in text_model._keys_to_ignore_on_load_unexpected:
1163
+ unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
1164
+
1165
+ if len(unexpected_keys) > 0:
1166
+ logger.warning(
1167
+ f"Some weights of the model checkpoint were not used when initializing {text_model.__class__.__name__}: \n {[', '.join(unexpected_keys)]}"
1168
+ )
1169
+ else:
1170
+ if not (hasattr(text_model, "embeddings") and hasattr(text_model.embeddings.position_ids)):
1171
+ text_model_dict.pop("text_model.embeddings.position_ids", None)
1172
+
1173
+ text_model.load_state_dict(text_model_dict)
1174
+
1175
+ if torch_dtype is not None:
1176
+ text_model = text_model.to(torch_dtype)
1177
+
1178
+ return text_model
1179
+
1180
+
1181
+ def create_text_encoder_from_open_clip_checkpoint(
1182
+ config_name,
1183
+ checkpoint,
1184
+ prefix="cond_stage_model.model.",
1185
+ has_projection=False,
1186
+ local_files_only=False,
1187
+ torch_dtype=None,
1188
+ **config_kwargs,
1189
+ ):
1190
+ try:
1191
+ config = CLIPTextConfig.from_pretrained(config_name, **config_kwargs, local_files_only=local_files_only)
1192
+ except Exception:
1193
+ raise ValueError(
1194
+ f"With local_files_only set to {local_files_only}, you must first locally save the configuration in the following path: '{config_name}'."
1195
+ )
1196
+
1197
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
1198
+ with ctx():
1199
+ text_model = CLIPTextModelWithProjection(config) if has_projection else CLIPTextModel(config)
1200
+
1201
+ text_model_dict = {}
1202
+ text_proj_key = prefix + "text_projection"
1203
+ text_proj_dim = (
1204
+ int(checkpoint[text_proj_key].shape[0]) if text_proj_key in checkpoint else LDM_OPEN_CLIP_TEXT_PROJECTION_DIM
1205
+ )
1206
+ text_model_dict["text_model.embeddings.position_ids"] = text_model.text_model.embeddings.get_buffer("position_ids")
1207
+
1208
+ keys = list(checkpoint.keys())
1209
+ keys_to_ignore = SD_2_TEXT_ENCODER_KEYS_TO_IGNORE
1210
+
1211
+ openclip_diffusers_ldm_map = DIFFUSERS_TO_LDM_MAPPING["openclip"]["layers"]
1212
+ for diffusers_key, ldm_key in openclip_diffusers_ldm_map.items():
1213
+ ldm_key = prefix + ldm_key
1214
+ if ldm_key not in checkpoint:
1215
+ continue
1216
+ if ldm_key in keys_to_ignore:
1217
+ continue
1218
+ if ldm_key.endswith("text_projection"):
1219
+ text_model_dict[diffusers_key] = checkpoint[ldm_key].T.contiguous()
1220
+ else:
1221
+ text_model_dict[diffusers_key] = checkpoint[ldm_key]
1222
+
1223
+ for key in keys:
1224
+ if key in keys_to_ignore:
1225
+ continue
1226
+
1227
+ if not key.startswith(prefix + "transformer."):
1228
+ continue
1229
+
1230
+ diffusers_key = key.replace(prefix + "transformer.", "")
1231
+ transformer_diffusers_to_ldm_map = DIFFUSERS_TO_LDM_MAPPING["openclip"]["transformer"]
1232
+ for new_key, old_key in transformer_diffusers_to_ldm_map.items():
1233
+ diffusers_key = (
1234
+ diffusers_key.replace(old_key, new_key).replace(".in_proj_weight", "").replace(".in_proj_bias", "")
1235
+ )
1236
+
1237
+ if key.endswith(".in_proj_weight"):
1238
+ weight_value = checkpoint[key]
1239
+
1240
+ text_model_dict[diffusers_key + ".q_proj.weight"] = weight_value[:text_proj_dim, :]
1241
+ text_model_dict[diffusers_key + ".k_proj.weight"] = weight_value[text_proj_dim : text_proj_dim * 2, :]
1242
+ text_model_dict[diffusers_key + ".v_proj.weight"] = weight_value[text_proj_dim * 2 :, :]
1243
+
1244
+ elif key.endswith(".in_proj_bias"):
1245
+ weight_value = checkpoint[key]
1246
+ text_model_dict[diffusers_key + ".q_proj.bias"] = weight_value[:text_proj_dim]
1247
+ text_model_dict[diffusers_key + ".k_proj.bias"] = weight_value[text_proj_dim : text_proj_dim * 2]
1248
+ text_model_dict[diffusers_key + ".v_proj.bias"] = weight_value[text_proj_dim * 2 :]
1249
+ else:
1250
+ text_model_dict[diffusers_key] = checkpoint[key]
1251
+
1252
+ if is_accelerate_available():
1253
+ from ..models.modeling_utils import load_model_dict_into_meta
1254
+
1255
+ unexpected_keys = load_model_dict_into_meta(text_model, text_model_dict, dtype=torch_dtype)
1256
+ if text_model._keys_to_ignore_on_load_unexpected is not None:
1257
+ for pat in text_model._keys_to_ignore_on_load_unexpected:
1258
+ unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
1259
+
1260
+ if len(unexpected_keys) > 0:
1261
+ logger.warning(
1262
+ f"Some weights of the model checkpoint were not used when initializing {text_model.__class__.__name__}: \n {[', '.join(unexpected_keys)]}"
1263
+ )
1264
+
1265
+ else:
1266
+ if not (hasattr(text_model, "embeddings") and hasattr(text_model.embeddings.position_ids)):
1267
+ text_model_dict.pop("text_model.embeddings.position_ids", None)
1268
+
1269
+ text_model.load_state_dict(text_model_dict)
1270
+
1271
+ if torch_dtype is not None:
1272
+ text_model = text_model.to(torch_dtype)
1273
+
1274
+ return text_model
1275
+
1276
+
1277
+ def create_diffusers_unet_model_from_ldm(
1278
+ pipeline_class_name,
1279
+ original_config,
1280
+ checkpoint,
1281
+ num_in_channels=None,
1282
+ upcast_attention=None,
1283
+ extract_ema=False,
1284
+ image_size=None,
1285
+ torch_dtype=None,
1286
+ model_type=None,
1287
+ ):
1288
+ from ..models import UNet2DConditionModel
1289
+
1290
+ if num_in_channels is None:
1291
+ if pipeline_class_name in [
1292
+ "StableDiffusionInpaintPipeline",
1293
+ "StableDiffusionControlNetInpaintPipeline",
1294
+ "StableDiffusionXLInpaintPipeline",
1295
+ "StableDiffusionXLControlNetInpaintPipeline",
1296
+ ]:
1297
+ num_in_channels = 9
1298
+
1299
+ elif pipeline_class_name == "StableDiffusionUpscalePipeline":
1300
+ num_in_channels = 7
1301
+
1302
+ else:
1303
+ num_in_channels = 4
1304
+
1305
+ image_size = set_image_size(
1306
+ pipeline_class_name, original_config, checkpoint, image_size=image_size, model_type=model_type
1307
+ )
1308
+ unet_config = create_unet_diffusers_config(original_config, image_size=image_size)
1309
+ unet_config["in_channels"] = num_in_channels
1310
+ if upcast_attention is not None:
1311
+ unet_config["upcast_attention"] = upcast_attention
1312
+
1313
+ diffusers_format_unet_checkpoint = convert_ldm_unet_checkpoint(checkpoint, unet_config, extract_ema=extract_ema)
1314
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
1315
+
1316
+ with ctx():
1317
+ unet = UNet2DConditionModel(**unet_config)
1318
+
1319
+ if is_accelerate_available():
1320
+ from ..models.modeling_utils import load_model_dict_into_meta
1321
+
1322
+ unexpected_keys = load_model_dict_into_meta(unet, diffusers_format_unet_checkpoint, dtype=torch_dtype)
1323
+ if unet._keys_to_ignore_on_load_unexpected is not None:
1324
+ for pat in unet._keys_to_ignore_on_load_unexpected:
1325
+ unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
1326
+
1327
+ if len(unexpected_keys) > 0:
1328
+ logger.warning(
1329
+ f"Some weights of the model checkpoint were not used when initializing {unet.__name__}: \n {[', '.join(unexpected_keys)]}"
1330
+ )
1331
+ else:
1332
+ unet.load_state_dict(diffusers_format_unet_checkpoint)
1333
+
1334
+ if torch_dtype is not None:
1335
+ unet = unet.to(torch_dtype)
1336
+
1337
+ return {"unet": unet}
1338
+
1339
+
1340
+ def create_diffusers_vae_model_from_ldm(
1341
+ pipeline_class_name,
1342
+ original_config,
1343
+ checkpoint,
1344
+ image_size=None,
1345
+ scaling_factor=None,
1346
+ torch_dtype=None,
1347
+ model_type=None,
1348
+ ):
1349
+ # import here to avoid circular imports
1350
+ from ..models import AutoencoderKL
1351
+
1352
+ image_size = set_image_size(
1353
+ pipeline_class_name, original_config, checkpoint, image_size=image_size, model_type=model_type
1354
+ )
1355
+ model_type = infer_model_type(original_config, checkpoint, model_type)
1356
+
1357
+ if model_type == "Playground":
1358
+ edm_mean = (
1359
+ checkpoint["edm_mean"].to(dtype=torch_dtype).tolist() if torch_dtype else checkpoint["edm_mean"].tolist()
1360
+ )
1361
+ edm_std = (
1362
+ checkpoint["edm_std"].to(dtype=torch_dtype).tolist() if torch_dtype else checkpoint["edm_std"].tolist()
1363
+ )
1364
+ else:
1365
+ edm_mean = None
1366
+ edm_std = None
1367
+
1368
+ vae_config = create_vae_diffusers_config(
1369
+ original_config,
1370
+ image_size=image_size,
1371
+ scaling_factor=scaling_factor,
1372
+ latents_mean=edm_mean,
1373
+ latents_std=edm_std,
1374
+ )
1375
+ diffusers_format_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config)
1376
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
1377
+
1378
+ with ctx():
1379
+ vae = AutoencoderKL(**vae_config)
1380
+
1381
+ if is_accelerate_available():
1382
+ from ..models.modeling_utils import load_model_dict_into_meta
1383
+
1384
+ unexpected_keys = load_model_dict_into_meta(vae, diffusers_format_vae_checkpoint, dtype=torch_dtype)
1385
+ if vae._keys_to_ignore_on_load_unexpected is not None:
1386
+ for pat in vae._keys_to_ignore_on_load_unexpected:
1387
+ unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
1388
+
1389
+ if len(unexpected_keys) > 0:
1390
+ logger.warning(
1391
+ f"Some weights of the model checkpoint were not used when initializing {vae.__name__}: \n {[', '.join(unexpected_keys)]}"
1392
+ )
1393
+ else:
1394
+ vae.load_state_dict(diffusers_format_vae_checkpoint)
1395
+
1396
+ if torch_dtype is not None:
1397
+ vae = vae.to(torch_dtype)
1398
+
1399
+ return {"vae": vae}
1400
+
1401
+
1402
+ def create_text_encoders_and_tokenizers_from_ldm(
1403
+ original_config,
1404
+ checkpoint,
1405
+ model_type=None,
1406
+ local_files_only=False,
1407
+ torch_dtype=None,
1408
+ ):
1409
+ model_type = infer_model_type(original_config, checkpoint=checkpoint, model_type=model_type)
1410
+
1411
+ if model_type == "FrozenOpenCLIPEmbedder":
1412
+ config_name = "stabilityai/stable-diffusion-2"
1413
+ config_kwargs = {"subfolder": "text_encoder"}
1414
+
1415
+ try:
1416
+ text_encoder = create_text_encoder_from_open_clip_checkpoint(
1417
+ config_name, checkpoint, local_files_only=local_files_only, torch_dtype=torch_dtype, **config_kwargs
1418
+ )
1419
+ tokenizer = CLIPTokenizer.from_pretrained(
1420
+ config_name, subfolder="tokenizer", local_files_only=local_files_only
1421
+ )
1422
+ except Exception:
1423
+ raise ValueError(
1424
+ f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder in the following path: '{config_name}'."
1425
+ )
1426
+ else:
1427
+ return {"text_encoder": text_encoder, "tokenizer": tokenizer}
1428
+
1429
+ elif model_type == "FrozenCLIPEmbedder":
1430
+ try:
1431
+ config_name = "openai/clip-vit-large-patch14"
1432
+ text_encoder = create_text_encoder_from_ldm_clip_checkpoint(
1433
+ config_name,
1434
+ checkpoint,
1435
+ local_files_only=local_files_only,
1436
+ torch_dtype=torch_dtype,
1437
+ )
1438
+ tokenizer = CLIPTokenizer.from_pretrained(config_name, local_files_only=local_files_only)
1439
+
1440
+ except Exception:
1441
+ raise ValueError(
1442
+ f"With local_files_only set to {local_files_only}, you must first locally save the tokenizer in the following path: '{config_name}'."
1443
+ )
1444
+ else:
1445
+ return {"text_encoder": text_encoder, "tokenizer": tokenizer}
1446
+
1447
+ elif model_type == "SDXL-Refiner":
1448
+ config_name = "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k"
1449
+ config_kwargs = {"projection_dim": 1280}
1450
+ prefix = "conditioner.embedders.0.model."
1451
+
1452
+ try:
1453
+ tokenizer_2 = CLIPTokenizer.from_pretrained(config_name, pad_token="!", local_files_only=local_files_only)
1454
+ text_encoder_2 = create_text_encoder_from_open_clip_checkpoint(
1455
+ config_name,
1456
+ checkpoint,
1457
+ prefix=prefix,
1458
+ has_projection=True,
1459
+ local_files_only=local_files_only,
1460
+ torch_dtype=torch_dtype,
1461
+ **config_kwargs,
1462
+ )
1463
+ except Exception:
1464
+ raise ValueError(
1465
+ f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder_2 and tokenizer_2 in the following path: {config_name} with `pad_token` set to '!'."
1466
+ )
1467
+
1468
+ else:
1469
+ return {
1470
+ "text_encoder": None,
1471
+ "tokenizer": None,
1472
+ "tokenizer_2": tokenizer_2,
1473
+ "text_encoder_2": text_encoder_2,
1474
+ }
1475
+
1476
+ elif model_type in ["SDXL", "Playground"]:
1477
+ try:
1478
+ config_name = "openai/clip-vit-large-patch14"
1479
+ tokenizer = CLIPTokenizer.from_pretrained(config_name, local_files_only=local_files_only)
1480
+ text_encoder = create_text_encoder_from_ldm_clip_checkpoint(
1481
+ config_name, checkpoint, local_files_only=local_files_only, torch_dtype=torch_dtype
1482
+ )
1483
+
1484
+ except Exception:
1485
+ raise ValueError(
1486
+ f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder and tokenizer in the following path: 'openai/clip-vit-large-patch14'."
1487
+ )
1488
+
1489
+ try:
1490
+ config_name = "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k"
1491
+ config_kwargs = {"projection_dim": 1280}
1492
+ prefix = "conditioner.embedders.1.model."
1493
+ tokenizer_2 = CLIPTokenizer.from_pretrained(config_name, pad_token="!", local_files_only=local_files_only)
1494
+ text_encoder_2 = create_text_encoder_from_open_clip_checkpoint(
1495
+ config_name,
1496
+ checkpoint,
1497
+ prefix=prefix,
1498
+ has_projection=True,
1499
+ local_files_only=local_files_only,
1500
+ torch_dtype=torch_dtype,
1501
+ **config_kwargs,
1502
+ )
1503
+ except Exception:
1504
+ raise ValueError(
1505
+ f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder_2 and tokenizer_2 in the following path: {config_name} with `pad_token` set to '!'."
1506
+ )
1507
+
1508
+ return {
1509
+ "tokenizer": tokenizer,
1510
+ "text_encoder": text_encoder,
1511
+ "tokenizer_2": tokenizer_2,
1512
+ "text_encoder_2": text_encoder_2,
1513
+ }
1514
+
1515
+ return
1516
+
1517
+
1518
+ def create_scheduler_from_ldm(
1519
+ pipeline_class_name,
1520
+ original_config,
1521
+ checkpoint,
1522
+ prediction_type=None,
1523
+ scheduler_type="ddim",
1524
+ model_type=None,
1525
+ ):
1526
+ scheduler_config = get_default_scheduler_config()
1527
+ model_type = infer_model_type(original_config, checkpoint=checkpoint, model_type=model_type)
1528
+
1529
+ global_step = checkpoint["global_step"] if "global_step" in checkpoint else None
1530
+
1531
+ num_train_timesteps = getattr(original_config["model"]["params"], "timesteps", None) or 1000
1532
+ scheduler_config["num_train_timesteps"] = num_train_timesteps
1533
+
1534
+ if (
1535
+ "parameterization" in original_config["model"]["params"]
1536
+ and original_config["model"]["params"]["parameterization"] == "v"
1537
+ ):
1538
+ if prediction_type is None:
1539
+ # NOTE: For stable diffusion 2 base it is recommended to pass `prediction_type=="epsilon"`
1540
+ # as it relies on a brittle global step parameter here
1541
+ prediction_type = "epsilon" if global_step == 875000 else "v_prediction"
1542
+
1543
+ else:
1544
+ prediction_type = prediction_type or "epsilon"
1545
+
1546
+ scheduler_config["prediction_type"] = prediction_type
1547
+
1548
+ if model_type in ["SDXL", "SDXL-Refiner"]:
1549
+ scheduler_type = "euler"
1550
+ elif model_type == "Playground":
1551
+ scheduler_type = "edm_dpm_solver_multistep"
1552
+ else:
1553
+ beta_start = original_config["model"]["params"].get("linear_start", 0.02)
1554
+ beta_end = original_config["model"]["params"].get("linear_end", 0.085)
1555
+ scheduler_config["beta_start"] = beta_start
1556
+ scheduler_config["beta_end"] = beta_end
1557
+ scheduler_config["beta_schedule"] = "scaled_linear"
1558
+ scheduler_config["clip_sample"] = False
1559
+ scheduler_config["set_alpha_to_one"] = False
1560
+
1561
+ if scheduler_type == "pndm":
1562
+ scheduler_config["skip_prk_steps"] = True
1563
+ scheduler = PNDMScheduler.from_config(scheduler_config)
1564
+
1565
+ elif scheduler_type == "lms":
1566
+ scheduler = LMSDiscreteScheduler.from_config(scheduler_config)
1567
+
1568
+ elif scheduler_type == "heun":
1569
+ scheduler = HeunDiscreteScheduler.from_config(scheduler_config)
1570
+
1571
+ elif scheduler_type == "euler":
1572
+ scheduler = EulerDiscreteScheduler.from_config(scheduler_config)
1573
+
1574
+ elif scheduler_type == "euler-ancestral":
1575
+ scheduler = EulerAncestralDiscreteScheduler.from_config(scheduler_config)
1576
+
1577
+ elif scheduler_type == "dpm":
1578
+ scheduler = DPMSolverMultistepScheduler.from_config(scheduler_config)
1579
+
1580
+ elif scheduler_type == "ddim":
1581
+ scheduler = DDIMScheduler.from_config(scheduler_config)
1582
+
1583
+ elif scheduler_type == "edm_dpm_solver_multistep":
1584
+ scheduler_config = {
1585
+ "algorithm_type": "dpmsolver++",
1586
+ "dynamic_thresholding_ratio": 0.995,
1587
+ "euler_at_final": False,
1588
+ "final_sigmas_type": "zero",
1589
+ "lower_order_final": True,
1590
+ "num_train_timesteps": 1000,
1591
+ "prediction_type": "epsilon",
1592
+ "rho": 7.0,
1593
+ "sample_max_value": 1.0,
1594
+ "sigma_data": 0.5,
1595
+ "sigma_max": 80.0,
1596
+ "sigma_min": 0.002,
1597
+ "solver_order": 2,
1598
+ "solver_type": "midpoint",
1599
+ "thresholding": False,
1600
+ }
1601
+ scheduler = EDMDPMSolverMultistepScheduler(**scheduler_config)
1602
+
1603
+ else:
1604
+ raise ValueError(f"Scheduler of type {scheduler_type} doesn't exist!")
1605
+
1606
+ if pipeline_class_name == "StableDiffusionUpscalePipeline":
1607
+ scheduler = DDIMScheduler.from_pretrained("stabilityai/stable-diffusion-x4-upscaler", subfolder="scheduler")
1608
+ low_res_scheduler = DDPMScheduler.from_pretrained(
1609
+ "stabilityai/stable-diffusion-x4-upscaler", subfolder="low_res_scheduler"
1610
+ )
1611
+
1612
+ return {
1613
+ "scheduler": scheduler,
1614
+ "low_res_scheduler": low_res_scheduler,
1615
+ }
1616
+
1617
+ return {"scheduler": scheduler}
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/textual_inversion.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Dict, List, Optional, Union
15
+
16
+ import safetensors
17
+ import torch
18
+ from huggingface_hub.utils import validate_hf_hub_args
19
+ from torch import nn
20
+
21
+ from ..utils import _get_model_file, is_accelerate_available, is_transformers_available, logging
22
+
23
+
24
+ if is_transformers_available():
25
+ from transformers import PreTrainedModel, PreTrainedTokenizer
26
+
27
+ if is_accelerate_available():
28
+ from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+ TEXT_INVERSION_NAME = "learned_embeds.bin"
33
+ TEXT_INVERSION_NAME_SAFE = "learned_embeds.safetensors"
34
+
35
+
36
+ @validate_hf_hub_args
37
+ def load_textual_inversion_state_dicts(pretrained_model_name_or_paths, **kwargs):
38
+ cache_dir = kwargs.pop("cache_dir", None)
39
+ force_download = kwargs.pop("force_download", False)
40
+ resume_download = kwargs.pop("resume_download", False)
41
+ proxies = kwargs.pop("proxies", None)
42
+ local_files_only = kwargs.pop("local_files_only", None)
43
+ token = kwargs.pop("token", None)
44
+ revision = kwargs.pop("revision", None)
45
+ subfolder = kwargs.pop("subfolder", None)
46
+ weight_name = kwargs.pop("weight_name", None)
47
+ use_safetensors = kwargs.pop("use_safetensors", None)
48
+
49
+ allow_pickle = False
50
+ if use_safetensors is None:
51
+ use_safetensors = True
52
+ allow_pickle = True
53
+
54
+ user_agent = {
55
+ "file_type": "text_inversion",
56
+ "framework": "pytorch",
57
+ }
58
+ state_dicts = []
59
+ for pretrained_model_name_or_path in pretrained_model_name_or_paths:
60
+ if not isinstance(pretrained_model_name_or_path, (dict, torch.Tensor)):
61
+ # 3.1. Load textual inversion file
62
+ model_file = None
63
+
64
+ # Let's first try to load .safetensors weights
65
+ if (use_safetensors and weight_name is None) or (
66
+ weight_name is not None and weight_name.endswith(".safetensors")
67
+ ):
68
+ try:
69
+ model_file = _get_model_file(
70
+ pretrained_model_name_or_path,
71
+ weights_name=weight_name or TEXT_INVERSION_NAME_SAFE,
72
+ cache_dir=cache_dir,
73
+ force_download=force_download,
74
+ resume_download=resume_download,
75
+ proxies=proxies,
76
+ local_files_only=local_files_only,
77
+ token=token,
78
+ revision=revision,
79
+ subfolder=subfolder,
80
+ user_agent=user_agent,
81
+ )
82
+ state_dict = safetensors.torch.load_file(model_file, device="cpu")
83
+ except Exception as e:
84
+ if not allow_pickle:
85
+ raise e
86
+
87
+ model_file = None
88
+
89
+ if model_file is None:
90
+ model_file = _get_model_file(
91
+ pretrained_model_name_or_path,
92
+ weights_name=weight_name or TEXT_INVERSION_NAME,
93
+ cache_dir=cache_dir,
94
+ force_download=force_download,
95
+ resume_download=resume_download,
96
+ proxies=proxies,
97
+ local_files_only=local_files_only,
98
+ token=token,
99
+ revision=revision,
100
+ subfolder=subfolder,
101
+ user_agent=user_agent,
102
+ )
103
+ state_dict = torch.load(model_file, map_location="cpu")
104
+ else:
105
+ state_dict = pretrained_model_name_or_path
106
+
107
+ state_dicts.append(state_dict)
108
+
109
+ return state_dicts
110
+
111
+
112
+ class TextualInversionLoaderMixin:
113
+ r"""
114
+ Load Textual Inversion tokens and embeddings to the tokenizer and text encoder.
115
+ """
116
+
117
+ def maybe_convert_prompt(self, prompt: Union[str, List[str]], tokenizer: "PreTrainedTokenizer"): # noqa: F821
118
+ r"""
119
+ Processes prompts that include a special token corresponding to a multi-vector textual inversion embedding to
120
+ be replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
121
+ inversion token or if the textual inversion token is a single vector, the input prompt is returned.
122
+
123
+ Parameters:
124
+ prompt (`str` or list of `str`):
125
+ The prompt or prompts to guide the image generation.
126
+ tokenizer (`PreTrainedTokenizer`):
127
+ The tokenizer responsible for encoding the prompt into input tokens.
128
+
129
+ Returns:
130
+ `str` or list of `str`: The converted prompt
131
+ """
132
+ if not isinstance(prompt, List):
133
+ prompts = [prompt]
134
+ else:
135
+ prompts = prompt
136
+
137
+ prompts = [self._maybe_convert_prompt(p, tokenizer) for p in prompts]
138
+
139
+ if not isinstance(prompt, List):
140
+ return prompts[0]
141
+
142
+ return prompts
143
+
144
+ def _maybe_convert_prompt(self, prompt: str, tokenizer: "PreTrainedTokenizer"): # noqa: F821
145
+ r"""
146
+ Maybe convert a prompt into a "multi vector"-compatible prompt. If the prompt includes a token that corresponds
147
+ to a multi-vector textual inversion embedding, this function will process the prompt so that the special token
148
+ is replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
149
+ inversion token or a textual inversion token that is a single vector, the input prompt is simply returned.
150
+
151
+ Parameters:
152
+ prompt (`str`):
153
+ The prompt to guide the image generation.
154
+ tokenizer (`PreTrainedTokenizer`):
155
+ The tokenizer responsible for encoding the prompt into input tokens.
156
+
157
+ Returns:
158
+ `str`: The converted prompt
159
+ """
160
+ tokens = tokenizer.tokenize(prompt)
161
+ unique_tokens = set(tokens)
162
+ for token in unique_tokens:
163
+ if token in tokenizer.added_tokens_encoder:
164
+ replacement = token
165
+ i = 1
166
+ while f"{token}_{i}" in tokenizer.added_tokens_encoder:
167
+ replacement += f" {token}_{i}"
168
+ i += 1
169
+
170
+ prompt = prompt.replace(token, replacement)
171
+
172
+ return prompt
173
+
174
+ def _check_text_inv_inputs(self, tokenizer, text_encoder, pretrained_model_name_or_paths, tokens):
175
+ if tokenizer is None:
176
+ raise ValueError(
177
+ f"{self.__class__.__name__} requires `self.tokenizer` or passing a `tokenizer` of type `PreTrainedTokenizer` for calling"
178
+ f" `{self.load_textual_inversion.__name__}`"
179
+ )
180
+
181
+ if text_encoder is None:
182
+ raise ValueError(
183
+ f"{self.__class__.__name__} requires `self.text_encoder` or passing a `text_encoder` of type `PreTrainedModel` for calling"
184
+ f" `{self.load_textual_inversion.__name__}`"
185
+ )
186
+
187
+ if len(pretrained_model_name_or_paths) > 1 and len(pretrained_model_name_or_paths) != len(tokens):
188
+ raise ValueError(
189
+ f"You have passed a list of models of length {len(pretrained_model_name_or_paths)}, and list of tokens of length {len(tokens)} "
190
+ f"Make sure both lists have the same length."
191
+ )
192
+
193
+ valid_tokens = [t for t in tokens if t is not None]
194
+ if len(set(valid_tokens)) < len(valid_tokens):
195
+ raise ValueError(f"You have passed a list of tokens that contains duplicates: {tokens}")
196
+
197
+ @staticmethod
198
+ def _retrieve_tokens_and_embeddings(tokens, state_dicts, tokenizer):
199
+ all_tokens = []
200
+ all_embeddings = []
201
+ for state_dict, token in zip(state_dicts, tokens):
202
+ if isinstance(state_dict, torch.Tensor):
203
+ if token is None:
204
+ raise ValueError(
205
+ "You are trying to load a textual inversion embedding that has been saved as a PyTorch tensor. Make sure to pass the name of the corresponding token in this case: `token=...`."
206
+ )
207
+ loaded_token = token
208
+ embedding = state_dict
209
+ elif len(state_dict) == 1:
210
+ # diffusers
211
+ loaded_token, embedding = next(iter(state_dict.items()))
212
+ elif "string_to_param" in state_dict:
213
+ # A1111
214
+ loaded_token = state_dict["name"]
215
+ embedding = state_dict["string_to_param"]["*"]
216
+ else:
217
+ raise ValueError(
218
+ f"Loaded state dictionary is incorrect: {state_dict}. \n\n"
219
+ "Please verify that the loaded state dictionary of the textual embedding either only has a single key or includes the `string_to_param`"
220
+ " input key."
221
+ )
222
+
223
+ if token is not None and loaded_token != token:
224
+ logger.info(f"The loaded token: {loaded_token} is overwritten by the passed token {token}.")
225
+ else:
226
+ token = loaded_token
227
+
228
+ if token in tokenizer.get_vocab():
229
+ raise ValueError(
230
+ f"Token {token} already in tokenizer vocabulary. Please choose a different token name or remove {token} and embedding from the tokenizer and text encoder."
231
+ )
232
+
233
+ all_tokens.append(token)
234
+ all_embeddings.append(embedding)
235
+
236
+ return all_tokens, all_embeddings
237
+
238
+ @staticmethod
239
+ def _extend_tokens_and_embeddings(tokens, embeddings, tokenizer):
240
+ all_tokens = []
241
+ all_embeddings = []
242
+
243
+ for embedding, token in zip(embeddings, tokens):
244
+ if f"{token}_1" in tokenizer.get_vocab():
245
+ multi_vector_tokens = [token]
246
+ i = 1
247
+ while f"{token}_{i}" in tokenizer.added_tokens_encoder:
248
+ multi_vector_tokens.append(f"{token}_{i}")
249
+ i += 1
250
+
251
+ raise ValueError(
252
+ f"Multi-vector Token {multi_vector_tokens} already in tokenizer vocabulary. Please choose a different token name or remove the {multi_vector_tokens} and embedding from the tokenizer and text encoder."
253
+ )
254
+
255
+ is_multi_vector = len(embedding.shape) > 1 and embedding.shape[0] > 1
256
+ if is_multi_vector:
257
+ all_tokens += [token] + [f"{token}_{i}" for i in range(1, embedding.shape[0])]
258
+ all_embeddings += [e for e in embedding] # noqa: C416
259
+ else:
260
+ all_tokens += [token]
261
+ all_embeddings += [embedding[0]] if len(embedding.shape) > 1 else [embedding]
262
+
263
+ return all_tokens, all_embeddings
264
+
265
+ @validate_hf_hub_args
266
+ def load_textual_inversion(
267
+ self,
268
+ pretrained_model_name_or_path: Union[str, List[str], Dict[str, torch.Tensor], List[Dict[str, torch.Tensor]]],
269
+ token: Optional[Union[str, List[str]]] = None,
270
+ tokenizer: Optional["PreTrainedTokenizer"] = None, # noqa: F821
271
+ text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
272
+ **kwargs,
273
+ ):
274
+ r"""
275
+ Load Textual Inversion embeddings into the text encoder of [`StableDiffusionPipeline`] (both 🤗 Diffusers and
276
+ Automatic1111 formats are supported).
277
+
278
+ Parameters:
279
+ pretrained_model_name_or_path (`str` or `os.PathLike` or `List[str or os.PathLike]` or `Dict` or `List[Dict]`):
280
+ Can be either one of the following or a list of them:
281
+
282
+ - A string, the *model id* (for example `sd-concepts-library/low-poly-hd-logos-icons`) of a
283
+ pretrained model hosted on the Hub.
284
+ - A path to a *directory* (for example `./my_text_inversion_directory/`) containing the textual
285
+ inversion weights.
286
+ - A path to a *file* (for example `./my_text_inversions.pt`) containing textual inversion weights.
287
+ - A [torch state
288
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
289
+
290
+ token (`str` or `List[str]`, *optional*):
291
+ Override the token to use for the textual inversion weights. If `pretrained_model_name_or_path` is a
292
+ list, then `token` must also be a list of equal length.
293
+ text_encoder ([`~transformers.CLIPTextModel`], *optional*):
294
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
295
+ If not specified, function will take self.tokenizer.
296
+ tokenizer ([`~transformers.CLIPTokenizer`], *optional*):
297
+ A `CLIPTokenizer` to tokenize text. If not specified, function will take self.tokenizer.
298
+ weight_name (`str`, *optional*):
299
+ Name of a custom weight file. This should be used when:
300
+
301
+ - The saved textual inversion file is in 🤗 Diffusers format, but was saved under a specific weight
302
+ name such as `text_inv.bin`.
303
+ - The saved textual inversion file is in the Automatic1111 format.
304
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
305
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
306
+ is not used.
307
+ force_download (`bool`, *optional*, defaults to `False`):
308
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
309
+ cached versions if they exist.
310
+ resume_download (`bool`, *optional*, defaults to `False`):
311
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
312
+ incompletely downloaded files are deleted.
313
+ proxies (`Dict[str, str]`, *optional*):
314
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
315
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
316
+ local_files_only (`bool`, *optional*, defaults to `False`):
317
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
318
+ won't be downloaded from the Hub.
319
+ token (`str` or *bool*, *optional*):
320
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
321
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
322
+ revision (`str`, *optional*, defaults to `"main"`):
323
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
324
+ allowed by Git.
325
+ subfolder (`str`, *optional*, defaults to `""`):
326
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
327
+ mirror (`str`, *optional*):
328
+ Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
329
+ guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
330
+ information.
331
+
332
+ Example:
333
+
334
+ To load a Textual Inversion embedding vector in 🤗 Diffusers format:
335
+
336
+ ```py
337
+ from diffusers import StableDiffusionPipeline
338
+ import torch
339
+
340
+ model_id = "runwayml/stable-diffusion-v1-5"
341
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
342
+
343
+ pipe.load_textual_inversion("sd-concepts-library/cat-toy")
344
+
345
+ prompt = "A <cat-toy> backpack"
346
+
347
+ image = pipe(prompt, num_inference_steps=50).images[0]
348
+ image.save("cat-backpack.png")
349
+ ```
350
+
351
+ To load a Textual Inversion embedding vector in Automatic1111 format, make sure to download the vector first
352
+ (for example from [civitAI](https://civitai.com/models/3036?modelVersionId=9857)) and then load the vector
353
+ locally:
354
+
355
+ ```py
356
+ from diffusers import StableDiffusionPipeline
357
+ import torch
358
+
359
+ model_id = "runwayml/stable-diffusion-v1-5"
360
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
361
+
362
+ pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")
363
+
364
+ prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."
365
+
366
+ image = pipe(prompt, num_inference_steps=50).images[0]
367
+ image.save("character.png")
368
+ ```
369
+
370
+ """
371
+ # 1. Set correct tokenizer and text encoder
372
+ tokenizer = tokenizer or getattr(self, "tokenizer", None)
373
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
374
+
375
+ # 2. Normalize inputs
376
+ pretrained_model_name_or_paths = (
377
+ [pretrained_model_name_or_path]
378
+ if not isinstance(pretrained_model_name_or_path, list)
379
+ else pretrained_model_name_or_path
380
+ )
381
+ tokens = [token] if not isinstance(token, list) else token
382
+ if tokens[0] is None:
383
+ tokens = tokens * len(pretrained_model_name_or_paths)
384
+
385
+ # 3. Check inputs
386
+ self._check_text_inv_inputs(tokenizer, text_encoder, pretrained_model_name_or_paths, tokens)
387
+
388
+ # 4. Load state dicts of textual embeddings
389
+ state_dicts = load_textual_inversion_state_dicts(pretrained_model_name_or_paths, **kwargs)
390
+
391
+ # 4.1 Handle the special case when state_dict is a tensor that contains n embeddings for n tokens
392
+ if len(tokens) > 1 and len(state_dicts) == 1:
393
+ if isinstance(state_dicts[0], torch.Tensor):
394
+ state_dicts = list(state_dicts[0])
395
+ if len(tokens) != len(state_dicts):
396
+ raise ValueError(
397
+ f"You have passed a state_dict contains {len(state_dicts)} embeddings, and list of tokens of length {len(tokens)} "
398
+ f"Make sure both have the same length."
399
+ )
400
+
401
+ # 4. Retrieve tokens and embeddings
402
+ tokens, embeddings = self._retrieve_tokens_and_embeddings(tokens, state_dicts, tokenizer)
403
+
404
+ # 5. Extend tokens and embeddings for multi vector
405
+ tokens, embeddings = self._extend_tokens_and_embeddings(tokens, embeddings, tokenizer)
406
+
407
+ # 6. Make sure all embeddings have the correct size
408
+ expected_emb_dim = text_encoder.get_input_embeddings().weight.shape[-1]
409
+ if any(expected_emb_dim != emb.shape[-1] for emb in embeddings):
410
+ raise ValueError(
411
+ "Loaded embeddings are of incorrect shape. Expected each textual inversion embedding "
412
+ "to be of shape {input_embeddings.shape[-1]}, but are {embeddings.shape[-1]} "
413
+ )
414
+
415
+ # 7. Now we can be sure that loading the embedding matrix works
416
+ # < Unsafe code:
417
+
418
+ # 7.1 Offload all hooks in case the pipeline was cpu offloaded before make sure, we offload and onload again
419
+ is_model_cpu_offload = False
420
+ is_sequential_cpu_offload = False
421
+ for _, component in self.components.items():
422
+ if isinstance(component, nn.Module):
423
+ if hasattr(component, "_hf_hook"):
424
+ is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
425
+ is_sequential_cpu_offload = isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
426
+ logger.info(
427
+ "Accelerate hooks detected. Since you have called `load_textual_inversion()`, the previous hooks will be first removed. Then the textual inversion parameters will be loaded and the hooks will be applied again."
428
+ )
429
+ remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
430
+
431
+ # 7.2 save expected device and dtype
432
+ device = text_encoder.device
433
+ dtype = text_encoder.dtype
434
+
435
+ # 7.3 Increase token embedding matrix
436
+ text_encoder.resize_token_embeddings(len(tokenizer) + len(tokens))
437
+ input_embeddings = text_encoder.get_input_embeddings().weight
438
+
439
+ # 7.4 Load token and embedding
440
+ for token, embedding in zip(tokens, embeddings):
441
+ # add tokens and get ids
442
+ tokenizer.add_tokens(token)
443
+ token_id = tokenizer.convert_tokens_to_ids(token)
444
+ input_embeddings.data[token_id] = embedding
445
+ logger.info(f"Loaded textual inversion embedding for {token}.")
446
+
447
+ input_embeddings.to(dtype=dtype, device=device)
448
+
449
+ # 7.5 Offload the model again
450
+ if is_model_cpu_offload:
451
+ self.enable_model_cpu_offload()
452
+ elif is_sequential_cpu_offload:
453
+ self.enable_sequential_cpu_offload()
454
+
455
+ # / Unsafe Code >
456
+
457
+ def unload_textual_inversion(
458
+ self,
459
+ tokens: Optional[Union[str, List[str]]] = None,
460
+ tokenizer: Optional["PreTrainedTokenizer"] = None,
461
+ text_encoder: Optional["PreTrainedModel"] = None,
462
+ ):
463
+ r"""
464
+ Unload Textual Inversion embeddings from the text encoder of [`StableDiffusionPipeline`]
465
+
466
+ Example:
467
+ ```py
468
+ from diffusers import AutoPipelineForText2Image
469
+ import torch
470
+
471
+ pipeline = AutoPipelineForText2Image.from_pretrained("runwayml/stable-diffusion-v1-5")
472
+
473
+ # Example 1
474
+ pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")
475
+ pipeline.load_textual_inversion("sd-concepts-library/moeb-style")
476
+
477
+ # Remove all token embeddings
478
+ pipeline.unload_textual_inversion()
479
+
480
+ # Example 2
481
+ pipeline.load_textual_inversion("sd-concepts-library/moeb-style")
482
+ pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")
483
+
484
+ # Remove just one token
485
+ pipeline.unload_textual_inversion("<moe-bius>")
486
+
487
+ # Example 3: unload from SDXL
488
+ pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0")
489
+ embedding_path = hf_hub_download(repo_id="linoyts/web_y2k", filename="web_y2k_emb.safetensors", repo_type="model")
490
+
491
+ # load embeddings to the text encoders
492
+ state_dict = load_file(embedding_path)
493
+
494
+ # load embeddings of text_encoder 1 (CLIP ViT-L/14)
495
+ pipeline.load_textual_inversion(state_dict["clip_l"], token=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder, tokenizer=pipeline.tokenizer)
496
+ # load embeddings of text_encoder 2 (CLIP ViT-G/14)
497
+ pipeline.load_textual_inversion(state_dict["clip_g"], token=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder_2, tokenizer=pipeline.tokenizer_2)
498
+
499
+ # Unload explicitly from both text encoders abd tokenizers
500
+ pipeline.unload_textual_inversion(tokens=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder, tokenizer=pipeline.tokenizer)
501
+ pipeline.unload_textual_inversion(tokens=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder_2, tokenizer=pipeline.tokenizer_2)
502
+
503
+ ```
504
+ """
505
+
506
+ tokenizer = tokenizer or getattr(self, "tokenizer", None)
507
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
508
+
509
+ # Get textual inversion tokens and ids
510
+ token_ids = []
511
+ last_special_token_id = None
512
+
513
+ if tokens:
514
+ if isinstance(tokens, str):
515
+ tokens = [tokens]
516
+ for added_token_id, added_token in tokenizer.added_tokens_decoder.items():
517
+ if not added_token.special:
518
+ if added_token.content in tokens:
519
+ token_ids.append(added_token_id)
520
+ else:
521
+ last_special_token_id = added_token_id
522
+ if len(token_ids) == 0:
523
+ raise ValueError("No tokens to remove found")
524
+ else:
525
+ tokens = []
526
+ for added_token_id, added_token in tokenizer.added_tokens_decoder.items():
527
+ if not added_token.special:
528
+ token_ids.append(added_token_id)
529
+ tokens.append(added_token.content)
530
+ else:
531
+ last_special_token_id = added_token_id
532
+
533
+ # Delete from tokenizer
534
+ for token_id, token_to_remove in zip(token_ids, tokens):
535
+ del tokenizer._added_tokens_decoder[token_id]
536
+ del tokenizer._added_tokens_encoder[token_to_remove]
537
+
538
+ # Make all token ids sequential in tokenizer
539
+ key_id = 1
540
+ for token_id in tokenizer.added_tokens_decoder:
541
+ if token_id > last_special_token_id and token_id > last_special_token_id + key_id:
542
+ token = tokenizer._added_tokens_decoder[token_id]
543
+ tokenizer._added_tokens_decoder[last_special_token_id + key_id] = token
544
+ del tokenizer._added_tokens_decoder[token_id]
545
+ tokenizer._added_tokens_encoder[token.content] = last_special_token_id + key_id
546
+ key_id += 1
547
+ tokenizer._update_trie()
548
+
549
+ # Delete from text encoder
550
+ text_embedding_dim = text_encoder.get_input_embeddings().embedding_dim
551
+ temp_text_embedding_weights = text_encoder.get_input_embeddings().weight
552
+ text_embedding_weights = temp_text_embedding_weights[: last_special_token_id + 1]
553
+ to_append = []
554
+ for i in range(last_special_token_id + 1, temp_text_embedding_weights.shape[0]):
555
+ if i not in token_ids:
556
+ to_append.append(temp_text_embedding_weights[i].unsqueeze(0))
557
+ if len(to_append) > 0:
558
+ to_append = torch.cat(to_append, dim=0)
559
+ text_embedding_weights = torch.cat([text_embedding_weights, to_append], dim=0)
560
+ text_embeddings_filtered = nn.Embedding(text_embedding_weights.shape[0], text_embedding_dim)
561
+ text_embeddings_filtered.weight.data = text_embedding_weights
562
+ text_encoder.set_input_embeddings(text_embeddings_filtered)
evalkit_tf437/lib/python3.10/site-packages/diffusers/loaders/utils.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Dict
16
+
17
+ import torch
18
+
19
+
20
+ class AttnProcsLayers(torch.nn.Module):
21
+ def __init__(self, state_dict: Dict[str, torch.Tensor]):
22
+ super().__init__()
23
+ self.layers = torch.nn.ModuleList(state_dict.values())
24
+ self.mapping = dict(enumerate(state_dict.keys()))
25
+ self.rev_mapping = {v: k for k, v in enumerate(state_dict.keys())}
26
+
27
+ # .processor for unet, .self_attn for text encoder
28
+ self.split_keys = [".processor", ".self_attn"]
29
+
30
+ # we add a hook to state_dict() and load_state_dict() so that the
31
+ # naming fits with `unet.attn_processors`
32
+ def map_to(module, state_dict, *args, **kwargs):
33
+ new_state_dict = {}
34
+ for key, value in state_dict.items():
35
+ num = int(key.split(".")[1]) # 0 is always "layers"
36
+ new_key = key.replace(f"layers.{num}", module.mapping[num])
37
+ new_state_dict[new_key] = value
38
+
39
+ return new_state_dict
40
+
41
+ def remap_key(key, state_dict):
42
+ for k in self.split_keys:
43
+ if k in key:
44
+ return key.split(k)[0] + k
45
+
46
+ raise ValueError(
47
+ f"There seems to be a problem with the state_dict: {set(state_dict.keys())}. {key} has to have one of {self.split_keys}."
48
+ )
49
+
50
+ def map_from(module, state_dict, *args, **kwargs):
51
+ all_keys = list(state_dict.keys())
52
+ for key in all_keys:
53
+ replace_key = remap_key(key, state_dict)
54
+ new_key = key.replace(replace_key, f"layers.{module.rev_mapping[replace_key]}")
55
+ state_dict[new_key] = state_dict[key]
56
+ del state_dict[key]
57
+
58
+ self._register_state_dict_hook(map_to)
59
+ self._register_load_state_dict_pre_hook(map_from, with_module=True)
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/attention_flax.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import functools
16
+ import math
17
+
18
+ import flax.linen as nn
19
+ import jax
20
+ import jax.numpy as jnp
21
+
22
+
23
+ def _query_chunk_attention(query, key, value, precision, key_chunk_size: int = 4096):
24
+ """Multi-head dot product attention with a limited number of queries."""
25
+ num_kv, num_heads, k_features = key.shape[-3:]
26
+ v_features = value.shape[-1]
27
+ key_chunk_size = min(key_chunk_size, num_kv)
28
+ query = query / jnp.sqrt(k_features)
29
+
30
+ @functools.partial(jax.checkpoint, prevent_cse=False)
31
+ def summarize_chunk(query, key, value):
32
+ attn_weights = jnp.einsum("...qhd,...khd->...qhk", query, key, precision=precision)
33
+
34
+ max_score = jnp.max(attn_weights, axis=-1, keepdims=True)
35
+ max_score = jax.lax.stop_gradient(max_score)
36
+ exp_weights = jnp.exp(attn_weights - max_score)
37
+
38
+ exp_values = jnp.einsum("...vhf,...qhv->...qhf", value, exp_weights, precision=precision)
39
+ max_score = jnp.einsum("...qhk->...qh", max_score)
40
+
41
+ return (exp_values, exp_weights.sum(axis=-1), max_score)
42
+
43
+ def chunk_scanner(chunk_idx):
44
+ # julienne key array
45
+ key_chunk = jax.lax.dynamic_slice(
46
+ operand=key,
47
+ start_indices=[0] * (key.ndim - 3) + [chunk_idx, 0, 0], # [...,k,h,d]
48
+ slice_sizes=list(key.shape[:-3]) + [key_chunk_size, num_heads, k_features], # [...,k,h,d]
49
+ )
50
+
51
+ # julienne value array
52
+ value_chunk = jax.lax.dynamic_slice(
53
+ operand=value,
54
+ start_indices=[0] * (value.ndim - 3) + [chunk_idx, 0, 0], # [...,v,h,d]
55
+ slice_sizes=list(value.shape[:-3]) + [key_chunk_size, num_heads, v_features], # [...,v,h,d]
56
+ )
57
+
58
+ return summarize_chunk(query, key_chunk, value_chunk)
59
+
60
+ chunk_values, chunk_weights, chunk_max = jax.lax.map(f=chunk_scanner, xs=jnp.arange(0, num_kv, key_chunk_size))
61
+
62
+ global_max = jnp.max(chunk_max, axis=0, keepdims=True)
63
+ max_diffs = jnp.exp(chunk_max - global_max)
64
+
65
+ chunk_values *= jnp.expand_dims(max_diffs, axis=-1)
66
+ chunk_weights *= max_diffs
67
+
68
+ all_values = chunk_values.sum(axis=0)
69
+ all_weights = jnp.expand_dims(chunk_weights, -1).sum(axis=0)
70
+
71
+ return all_values / all_weights
72
+
73
+
74
+ def jax_memory_efficient_attention(
75
+ query, key, value, precision=jax.lax.Precision.HIGHEST, query_chunk_size: int = 1024, key_chunk_size: int = 4096
76
+ ):
77
+ r"""
78
+ Flax Memory-efficient multi-head dot product attention. https://arxiv.org/abs/2112.05682v2
79
+ https://github.com/AminRezaei0x443/memory-efficient-attention
80
+
81
+ Args:
82
+ query (`jnp.ndarray`): (batch..., query_length, head, query_key_depth_per_head)
83
+ key (`jnp.ndarray`): (batch..., key_value_length, head, query_key_depth_per_head)
84
+ value (`jnp.ndarray`): (batch..., key_value_length, head, value_depth_per_head)
85
+ precision (`jax.lax.Precision`, *optional*, defaults to `jax.lax.Precision.HIGHEST`):
86
+ numerical precision for computation
87
+ query_chunk_size (`int`, *optional*, defaults to 1024):
88
+ chunk size to divide query array value must divide query_length equally without remainder
89
+ key_chunk_size (`int`, *optional*, defaults to 4096):
90
+ chunk size to divide key and value array value must divide key_value_length equally without remainder
91
+
92
+ Returns:
93
+ (`jnp.ndarray`) with shape of (batch..., query_length, head, value_depth_per_head)
94
+ """
95
+ num_q, num_heads, q_features = query.shape[-3:]
96
+
97
+ def chunk_scanner(chunk_idx, _):
98
+ # julienne query array
99
+ query_chunk = jax.lax.dynamic_slice(
100
+ operand=query,
101
+ start_indices=([0] * (query.ndim - 3)) + [chunk_idx, 0, 0], # [...,q,h,d]
102
+ slice_sizes=list(query.shape[:-3]) + [min(query_chunk_size, num_q), num_heads, q_features], # [...,q,h,d]
103
+ )
104
+
105
+ return (
106
+ chunk_idx + query_chunk_size, # unused ignore it
107
+ _query_chunk_attention(
108
+ query=query_chunk, key=key, value=value, precision=precision, key_chunk_size=key_chunk_size
109
+ ),
110
+ )
111
+
112
+ _, res = jax.lax.scan(
113
+ f=chunk_scanner,
114
+ init=0,
115
+ xs=None,
116
+ length=math.ceil(num_q / query_chunk_size), # start counter # stop counter
117
+ )
118
+
119
+ return jnp.concatenate(res, axis=-3) # fuse the chunked result back
120
+
121
+
122
+ class FlaxAttention(nn.Module):
123
+ r"""
124
+ A Flax multi-head attention module as described in: https://arxiv.org/abs/1706.03762
125
+
126
+ Parameters:
127
+ query_dim (:obj:`int`):
128
+ Input hidden states dimension
129
+ heads (:obj:`int`, *optional*, defaults to 8):
130
+ Number of heads
131
+ dim_head (:obj:`int`, *optional*, defaults to 64):
132
+ Hidden states dimension inside each head
133
+ dropout (:obj:`float`, *optional*, defaults to 0.0):
134
+ Dropout rate
135
+ use_memory_efficient_attention (`bool`, *optional*, defaults to `False`):
136
+ enable memory efficient attention https://arxiv.org/abs/2112.05682
137
+ split_head_dim (`bool`, *optional*, defaults to `False`):
138
+ Whether to split the head dimension into a new axis for the self-attention computation. In most cases,
139
+ enabling this flag should speed up the computation for Stable Diffusion 2.x and Stable Diffusion XL.
140
+ dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
141
+ Parameters `dtype`
142
+
143
+ """
144
+
145
+ query_dim: int
146
+ heads: int = 8
147
+ dim_head: int = 64
148
+ dropout: float = 0.0
149
+ use_memory_efficient_attention: bool = False
150
+ split_head_dim: bool = False
151
+ dtype: jnp.dtype = jnp.float32
152
+
153
+ def setup(self):
154
+ inner_dim = self.dim_head * self.heads
155
+ self.scale = self.dim_head**-0.5
156
+
157
+ # Weights were exported with old names {to_q, to_k, to_v, to_out}
158
+ self.query = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, name="to_q")
159
+ self.key = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, name="to_k")
160
+ self.value = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, name="to_v")
161
+
162
+ self.proj_attn = nn.Dense(self.query_dim, dtype=self.dtype, name="to_out_0")
163
+ self.dropout_layer = nn.Dropout(rate=self.dropout)
164
+
165
+ def reshape_heads_to_batch_dim(self, tensor):
166
+ batch_size, seq_len, dim = tensor.shape
167
+ head_size = self.heads
168
+ tensor = tensor.reshape(batch_size, seq_len, head_size, dim // head_size)
169
+ tensor = jnp.transpose(tensor, (0, 2, 1, 3))
170
+ tensor = tensor.reshape(batch_size * head_size, seq_len, dim // head_size)
171
+ return tensor
172
+
173
+ def reshape_batch_dim_to_heads(self, tensor):
174
+ batch_size, seq_len, dim = tensor.shape
175
+ head_size = self.heads
176
+ tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim)
177
+ tensor = jnp.transpose(tensor, (0, 2, 1, 3))
178
+ tensor = tensor.reshape(batch_size // head_size, seq_len, dim * head_size)
179
+ return tensor
180
+
181
+ def __call__(self, hidden_states, context=None, deterministic=True):
182
+ context = hidden_states if context is None else context
183
+
184
+ query_proj = self.query(hidden_states)
185
+ key_proj = self.key(context)
186
+ value_proj = self.value(context)
187
+
188
+ if self.split_head_dim:
189
+ b = hidden_states.shape[0]
190
+ query_states = jnp.reshape(query_proj, (b, -1, self.heads, self.dim_head))
191
+ key_states = jnp.reshape(key_proj, (b, -1, self.heads, self.dim_head))
192
+ value_states = jnp.reshape(value_proj, (b, -1, self.heads, self.dim_head))
193
+ else:
194
+ query_states = self.reshape_heads_to_batch_dim(query_proj)
195
+ key_states = self.reshape_heads_to_batch_dim(key_proj)
196
+ value_states = self.reshape_heads_to_batch_dim(value_proj)
197
+
198
+ if self.use_memory_efficient_attention:
199
+ query_states = query_states.transpose(1, 0, 2)
200
+ key_states = key_states.transpose(1, 0, 2)
201
+ value_states = value_states.transpose(1, 0, 2)
202
+
203
+ # this if statement create a chunk size for each layer of the unet
204
+ # the chunk size is equal to the query_length dimension of the deepest layer of the unet
205
+
206
+ flatten_latent_dim = query_states.shape[-3]
207
+ if flatten_latent_dim % 64 == 0:
208
+ query_chunk_size = int(flatten_latent_dim / 64)
209
+ elif flatten_latent_dim % 16 == 0:
210
+ query_chunk_size = int(flatten_latent_dim / 16)
211
+ elif flatten_latent_dim % 4 == 0:
212
+ query_chunk_size = int(flatten_latent_dim / 4)
213
+ else:
214
+ query_chunk_size = int(flatten_latent_dim)
215
+
216
+ hidden_states = jax_memory_efficient_attention(
217
+ query_states, key_states, value_states, query_chunk_size=query_chunk_size, key_chunk_size=4096 * 4
218
+ )
219
+
220
+ hidden_states = hidden_states.transpose(1, 0, 2)
221
+ else:
222
+ # compute attentions
223
+ if self.split_head_dim:
224
+ attention_scores = jnp.einsum("b t n h, b f n h -> b n f t", key_states, query_states)
225
+ else:
226
+ attention_scores = jnp.einsum("b i d, b j d->b i j", query_states, key_states)
227
+
228
+ attention_scores = attention_scores * self.scale
229
+ attention_probs = nn.softmax(attention_scores, axis=-1 if self.split_head_dim else 2)
230
+
231
+ # attend to values
232
+ if self.split_head_dim:
233
+ hidden_states = jnp.einsum("b n f t, b t n h -> b f n h", attention_probs, value_states)
234
+ b = hidden_states.shape[0]
235
+ hidden_states = jnp.reshape(hidden_states, (b, -1, self.heads * self.dim_head))
236
+ else:
237
+ hidden_states = jnp.einsum("b i j, b j d -> b i d", attention_probs, value_states)
238
+ hidden_states = self.reshape_batch_dim_to_heads(hidden_states)
239
+
240
+ hidden_states = self.proj_attn(hidden_states)
241
+ return self.dropout_layer(hidden_states, deterministic=deterministic)
242
+
243
+
244
+ class FlaxBasicTransformerBlock(nn.Module):
245
+ r"""
246
+ A Flax transformer block layer with `GLU` (Gated Linear Unit) activation function as described in:
247
+ https://arxiv.org/abs/1706.03762
248
+
249
+
250
+ Parameters:
251
+ dim (:obj:`int`):
252
+ Inner hidden states dimension
253
+ n_heads (:obj:`int`):
254
+ Number of heads
255
+ d_head (:obj:`int`):
256
+ Hidden states dimension inside each head
257
+ dropout (:obj:`float`, *optional*, defaults to 0.0):
258
+ Dropout rate
259
+ only_cross_attention (`bool`, defaults to `False`):
260
+ Whether to only apply cross attention.
261
+ dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
262
+ Parameters `dtype`
263
+ use_memory_efficient_attention (`bool`, *optional*, defaults to `False`):
264
+ enable memory efficient attention https://arxiv.org/abs/2112.05682
265
+ split_head_dim (`bool`, *optional*, defaults to `False`):
266
+ Whether to split the head dimension into a new axis for the self-attention computation. In most cases,
267
+ enabling this flag should speed up the computation for Stable Diffusion 2.x and Stable Diffusion XL.
268
+ """
269
+
270
+ dim: int
271
+ n_heads: int
272
+ d_head: int
273
+ dropout: float = 0.0
274
+ only_cross_attention: bool = False
275
+ dtype: jnp.dtype = jnp.float32
276
+ use_memory_efficient_attention: bool = False
277
+ split_head_dim: bool = False
278
+
279
+ def setup(self):
280
+ # self attention (or cross_attention if only_cross_attention is True)
281
+ self.attn1 = FlaxAttention(
282
+ self.dim,
283
+ self.n_heads,
284
+ self.d_head,
285
+ self.dropout,
286
+ self.use_memory_efficient_attention,
287
+ self.split_head_dim,
288
+ dtype=self.dtype,
289
+ )
290
+ # cross attention
291
+ self.attn2 = FlaxAttention(
292
+ self.dim,
293
+ self.n_heads,
294
+ self.d_head,
295
+ self.dropout,
296
+ self.use_memory_efficient_attention,
297
+ self.split_head_dim,
298
+ dtype=self.dtype,
299
+ )
300
+ self.ff = FlaxFeedForward(dim=self.dim, dropout=self.dropout, dtype=self.dtype)
301
+ self.norm1 = nn.LayerNorm(epsilon=1e-5, dtype=self.dtype)
302
+ self.norm2 = nn.LayerNorm(epsilon=1e-5, dtype=self.dtype)
303
+ self.norm3 = nn.LayerNorm(epsilon=1e-5, dtype=self.dtype)
304
+ self.dropout_layer = nn.Dropout(rate=self.dropout)
305
+
306
+ def __call__(self, hidden_states, context, deterministic=True):
307
+ # self attention
308
+ residual = hidden_states
309
+ if self.only_cross_attention:
310
+ hidden_states = self.attn1(self.norm1(hidden_states), context, deterministic=deterministic)
311
+ else:
312
+ hidden_states = self.attn1(self.norm1(hidden_states), deterministic=deterministic)
313
+ hidden_states = hidden_states + residual
314
+
315
+ # cross attention
316
+ residual = hidden_states
317
+ hidden_states = self.attn2(self.norm2(hidden_states), context, deterministic=deterministic)
318
+ hidden_states = hidden_states + residual
319
+
320
+ # feed forward
321
+ residual = hidden_states
322
+ hidden_states = self.ff(self.norm3(hidden_states), deterministic=deterministic)
323
+ hidden_states = hidden_states + residual
324
+
325
+ return self.dropout_layer(hidden_states, deterministic=deterministic)
326
+
327
+
328
+ class FlaxTransformer2DModel(nn.Module):
329
+ r"""
330
+ A Spatial Transformer layer with Gated Linear Unit (GLU) activation function as described in:
331
+ https://arxiv.org/pdf/1506.02025.pdf
332
+
333
+
334
+ Parameters:
335
+ in_channels (:obj:`int`):
336
+ Input number of channels
337
+ n_heads (:obj:`int`):
338
+ Number of heads
339
+ d_head (:obj:`int`):
340
+ Hidden states dimension inside each head
341
+ depth (:obj:`int`, *optional*, defaults to 1):
342
+ Number of transformers block
343
+ dropout (:obj:`float`, *optional*, defaults to 0.0):
344
+ Dropout rate
345
+ use_linear_projection (`bool`, defaults to `False`): tbd
346
+ only_cross_attention (`bool`, defaults to `False`): tbd
347
+ dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
348
+ Parameters `dtype`
349
+ use_memory_efficient_attention (`bool`, *optional*, defaults to `False`):
350
+ enable memory efficient attention https://arxiv.org/abs/2112.05682
351
+ split_head_dim (`bool`, *optional*, defaults to `False`):
352
+ Whether to split the head dimension into a new axis for the self-attention computation. In most cases,
353
+ enabling this flag should speed up the computation for Stable Diffusion 2.x and Stable Diffusion XL.
354
+ """
355
+
356
+ in_channels: int
357
+ n_heads: int
358
+ d_head: int
359
+ depth: int = 1
360
+ dropout: float = 0.0
361
+ use_linear_projection: bool = False
362
+ only_cross_attention: bool = False
363
+ dtype: jnp.dtype = jnp.float32
364
+ use_memory_efficient_attention: bool = False
365
+ split_head_dim: bool = False
366
+
367
+ def setup(self):
368
+ self.norm = nn.GroupNorm(num_groups=32, epsilon=1e-5)
369
+
370
+ inner_dim = self.n_heads * self.d_head
371
+ if self.use_linear_projection:
372
+ self.proj_in = nn.Dense(inner_dim, dtype=self.dtype)
373
+ else:
374
+ self.proj_in = nn.Conv(
375
+ inner_dim,
376
+ kernel_size=(1, 1),
377
+ strides=(1, 1),
378
+ padding="VALID",
379
+ dtype=self.dtype,
380
+ )
381
+
382
+ self.transformer_blocks = [
383
+ FlaxBasicTransformerBlock(
384
+ inner_dim,
385
+ self.n_heads,
386
+ self.d_head,
387
+ dropout=self.dropout,
388
+ only_cross_attention=self.only_cross_attention,
389
+ dtype=self.dtype,
390
+ use_memory_efficient_attention=self.use_memory_efficient_attention,
391
+ split_head_dim=self.split_head_dim,
392
+ )
393
+ for _ in range(self.depth)
394
+ ]
395
+
396
+ if self.use_linear_projection:
397
+ self.proj_out = nn.Dense(inner_dim, dtype=self.dtype)
398
+ else:
399
+ self.proj_out = nn.Conv(
400
+ inner_dim,
401
+ kernel_size=(1, 1),
402
+ strides=(1, 1),
403
+ padding="VALID",
404
+ dtype=self.dtype,
405
+ )
406
+
407
+ self.dropout_layer = nn.Dropout(rate=self.dropout)
408
+
409
+ def __call__(self, hidden_states, context, deterministic=True):
410
+ batch, height, width, channels = hidden_states.shape
411
+ residual = hidden_states
412
+ hidden_states = self.norm(hidden_states)
413
+ if self.use_linear_projection:
414
+ hidden_states = hidden_states.reshape(batch, height * width, channels)
415
+ hidden_states = self.proj_in(hidden_states)
416
+ else:
417
+ hidden_states = self.proj_in(hidden_states)
418
+ hidden_states = hidden_states.reshape(batch, height * width, channels)
419
+
420
+ for transformer_block in self.transformer_blocks:
421
+ hidden_states = transformer_block(hidden_states, context, deterministic=deterministic)
422
+
423
+ if self.use_linear_projection:
424
+ hidden_states = self.proj_out(hidden_states)
425
+ hidden_states = hidden_states.reshape(batch, height, width, channels)
426
+ else:
427
+ hidden_states = hidden_states.reshape(batch, height, width, channels)
428
+ hidden_states = self.proj_out(hidden_states)
429
+
430
+ hidden_states = hidden_states + residual
431
+ return self.dropout_layer(hidden_states, deterministic=deterministic)
432
+
433
+
434
+ class FlaxFeedForward(nn.Module):
435
+ r"""
436
+ Flax module that encapsulates two Linear layers separated by a non-linearity. It is the counterpart of PyTorch's
437
+ [`FeedForward`] class, with the following simplifications:
438
+ - The activation function is currently hardcoded to a gated linear unit from:
439
+ https://arxiv.org/abs/2002.05202
440
+ - `dim_out` is equal to `dim`.
441
+ - The number of hidden dimensions is hardcoded to `dim * 4` in [`FlaxGELU`].
442
+
443
+ Parameters:
444
+ dim (:obj:`int`):
445
+ Inner hidden states dimension
446
+ dropout (:obj:`float`, *optional*, defaults to 0.0):
447
+ Dropout rate
448
+ dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
449
+ Parameters `dtype`
450
+ """
451
+
452
+ dim: int
453
+ dropout: float = 0.0
454
+ dtype: jnp.dtype = jnp.float32
455
+
456
+ def setup(self):
457
+ # The second linear layer needs to be called
458
+ # net_2 for now to match the index of the Sequential layer
459
+ self.net_0 = FlaxGEGLU(self.dim, self.dropout, self.dtype)
460
+ self.net_2 = nn.Dense(self.dim, dtype=self.dtype)
461
+
462
+ def __call__(self, hidden_states, deterministic=True):
463
+ hidden_states = self.net_0(hidden_states, deterministic=deterministic)
464
+ hidden_states = self.net_2(hidden_states)
465
+ return hidden_states
466
+
467
+
468
+ class FlaxGEGLU(nn.Module):
469
+ r"""
470
+ Flax implementation of a Linear layer followed by the variant of the gated linear unit activation function from
471
+ https://arxiv.org/abs/2002.05202.
472
+
473
+ Parameters:
474
+ dim (:obj:`int`):
475
+ Input hidden states dimension
476
+ dropout (:obj:`float`, *optional*, defaults to 0.0):
477
+ Dropout rate
478
+ dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
479
+ Parameters `dtype`
480
+ """
481
+
482
+ dim: int
483
+ dropout: float = 0.0
484
+ dtype: jnp.dtype = jnp.float32
485
+
486
+ def setup(self):
487
+ inner_dim = self.dim * 4
488
+ self.proj = nn.Dense(inner_dim * 2, dtype=self.dtype)
489
+ self.dropout_layer = nn.Dropout(rate=self.dropout)
490
+
491
+ def __call__(self, hidden_states, deterministic=True):
492
+ hidden_states = self.proj(hidden_states)
493
+ hidden_linear, hidden_gelu = jnp.split(hidden_states, 2, axis=2)
494
+ return self.dropout_layer(hidden_linear * nn.gelu(hidden_gelu), deterministic=deterministic)
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/attention_processor.py ADDED
The diff for this file is too large to render. See raw diff
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/controlnet.py ADDED
@@ -0,0 +1,868 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from dataclasses import dataclass
15
+ from typing import Any, Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ from torch import nn
19
+ from torch.nn import functional as F
20
+
21
+ from ..configuration_utils import ConfigMixin, register_to_config
22
+ from ..loaders import FromOriginalControlNetMixin
23
+ from ..utils import BaseOutput, logging
24
+ from .attention_processor import (
25
+ ADDED_KV_ATTENTION_PROCESSORS,
26
+ CROSS_ATTENTION_PROCESSORS,
27
+ AttentionProcessor,
28
+ AttnAddedKVProcessor,
29
+ AttnProcessor,
30
+ )
31
+ from .embeddings import TextImageProjection, TextImageTimeEmbedding, TextTimeEmbedding, TimestepEmbedding, Timesteps
32
+ from .modeling_utils import ModelMixin
33
+ from .unets.unet_2d_blocks import (
34
+ CrossAttnDownBlock2D,
35
+ DownBlock2D,
36
+ UNetMidBlock2D,
37
+ UNetMidBlock2DCrossAttn,
38
+ get_down_block,
39
+ )
40
+ from .unets.unet_2d_condition import UNet2DConditionModel
41
+
42
+
43
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
44
+
45
+
46
+ @dataclass
47
+ class ControlNetOutput(BaseOutput):
48
+ """
49
+ The output of [`ControlNetModel`].
50
+
51
+ Args:
52
+ down_block_res_samples (`tuple[torch.Tensor]`):
53
+ A tuple of downsample activations at different resolutions for each downsampling block. Each tensor should
54
+ be of shape `(batch_size, channel * resolution, height //resolution, width // resolution)`. Output can be
55
+ used to condition the original UNet's downsampling activations.
56
+ mid_down_block_re_sample (`torch.Tensor`):
57
+ The activation of the midde block (the lowest sample resolution). Each tensor should be of shape
58
+ `(batch_size, channel * lowest_resolution, height // lowest_resolution, width // lowest_resolution)`.
59
+ Output can be used to condition the original UNet's middle block activation.
60
+ """
61
+
62
+ down_block_res_samples: Tuple[torch.Tensor]
63
+ mid_block_res_sample: torch.Tensor
64
+
65
+
66
+ class ControlNetConditioningEmbedding(nn.Module):
67
+ """
68
+ Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
69
+ [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
70
+ training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
71
+ convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
72
+ (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
73
+ model) to encode image-space conditions ... into feature maps ..."
74
+ """
75
+
76
+ def __init__(
77
+ self,
78
+ conditioning_embedding_channels: int,
79
+ conditioning_channels: int = 3,
80
+ block_out_channels: Tuple[int, ...] = (16, 32, 96, 256),
81
+ ):
82
+ super().__init__()
83
+
84
+ self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
85
+
86
+ self.blocks = nn.ModuleList([])
87
+
88
+ for i in range(len(block_out_channels) - 1):
89
+ channel_in = block_out_channels[i]
90
+ channel_out = block_out_channels[i + 1]
91
+ self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
92
+ self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
93
+
94
+ self.conv_out = zero_module(
95
+ nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
96
+ )
97
+
98
+ def forward(self, conditioning):
99
+ embedding = self.conv_in(conditioning)
100
+ embedding = F.silu(embedding)
101
+
102
+ for block in self.blocks:
103
+ embedding = block(embedding)
104
+ embedding = F.silu(embedding)
105
+
106
+ embedding = self.conv_out(embedding)
107
+
108
+ return embedding
109
+
110
+
111
+ class ControlNetModel(ModelMixin, ConfigMixin, FromOriginalControlNetMixin):
112
+ """
113
+ A ControlNet model.
114
+
115
+ Args:
116
+ in_channels (`int`, defaults to 4):
117
+ The number of channels in the input sample.
118
+ flip_sin_to_cos (`bool`, defaults to `True`):
119
+ Whether to flip the sin to cos in the time embedding.
120
+ freq_shift (`int`, defaults to 0):
121
+ The frequency shift to apply to the time embedding.
122
+ down_block_types (`tuple[str]`, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
123
+ The tuple of downsample blocks to use.
124
+ only_cross_attention (`Union[bool, Tuple[bool]]`, defaults to `False`):
125
+ block_out_channels (`tuple[int]`, defaults to `(320, 640, 1280, 1280)`):
126
+ The tuple of output channels for each block.
127
+ layers_per_block (`int`, defaults to 2):
128
+ The number of layers per block.
129
+ downsample_padding (`int`, defaults to 1):
130
+ The padding to use for the downsampling convolution.
131
+ mid_block_scale_factor (`float`, defaults to 1):
132
+ The scale factor to use for the mid block.
133
+ act_fn (`str`, defaults to "silu"):
134
+ The activation function to use.
135
+ norm_num_groups (`int`, *optional*, defaults to 32):
136
+ The number of groups to use for the normalization. If None, normalization and activation layers is skipped
137
+ in post-processing.
138
+ norm_eps (`float`, defaults to 1e-5):
139
+ The epsilon to use for the normalization.
140
+ cross_attention_dim (`int`, defaults to 1280):
141
+ The dimension of the cross attention features.
142
+ transformer_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
143
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
144
+ [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
145
+ [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
146
+ encoder_hid_dim (`int`, *optional*, defaults to None):
147
+ If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
148
+ dimension to `cross_attention_dim`.
149
+ encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
150
+ If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
151
+ embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
152
+ attention_head_dim (`Union[int, Tuple[int]]`, defaults to 8):
153
+ The dimension of the attention heads.
154
+ use_linear_projection (`bool`, defaults to `False`):
155
+ class_embed_type (`str`, *optional*, defaults to `None`):
156
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from None,
157
+ `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
158
+ addition_embed_type (`str`, *optional*, defaults to `None`):
159
+ Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
160
+ "text". "text" will use the `TextTimeEmbedding` layer.
161
+ num_class_embeds (`int`, *optional*, defaults to 0):
162
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
163
+ class conditioning with `class_embed_type` equal to `None`.
164
+ upcast_attention (`bool`, defaults to `False`):
165
+ resnet_time_scale_shift (`str`, defaults to `"default"`):
166
+ Time scale shift config for ResNet blocks (see `ResnetBlock2D`). Choose from `default` or `scale_shift`.
167
+ projection_class_embeddings_input_dim (`int`, *optional*, defaults to `None`):
168
+ The dimension of the `class_labels` input when `class_embed_type="projection"`. Required when
169
+ `class_embed_type="projection"`.
170
+ controlnet_conditioning_channel_order (`str`, defaults to `"rgb"`):
171
+ The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
172
+ conditioning_embedding_out_channels (`tuple[int]`, *optional*, defaults to `(16, 32, 96, 256)`):
173
+ The tuple of output channel for each block in the `conditioning_embedding` layer.
174
+ global_pool_conditions (`bool`, defaults to `False`):
175
+ TODO(Patrick) - unused parameter.
176
+ addition_embed_type_num_heads (`int`, defaults to 64):
177
+ The number of heads to use for the `TextTimeEmbedding` layer.
178
+ """
179
+
180
+ _supports_gradient_checkpointing = True
181
+
182
+ @register_to_config
183
+ def __init__(
184
+ self,
185
+ in_channels: int = 4,
186
+ conditioning_channels: int = 3,
187
+ flip_sin_to_cos: bool = True,
188
+ freq_shift: int = 0,
189
+ down_block_types: Tuple[str, ...] = (
190
+ "CrossAttnDownBlock2D",
191
+ "CrossAttnDownBlock2D",
192
+ "CrossAttnDownBlock2D",
193
+ "DownBlock2D",
194
+ ),
195
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
196
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
197
+ block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
198
+ layers_per_block: int = 2,
199
+ downsample_padding: int = 1,
200
+ mid_block_scale_factor: float = 1,
201
+ act_fn: str = "silu",
202
+ norm_num_groups: Optional[int] = 32,
203
+ norm_eps: float = 1e-5,
204
+ cross_attention_dim: int = 1280,
205
+ transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
206
+ encoder_hid_dim: Optional[int] = None,
207
+ encoder_hid_dim_type: Optional[str] = None,
208
+ attention_head_dim: Union[int, Tuple[int, ...]] = 8,
209
+ num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None,
210
+ use_linear_projection: bool = False,
211
+ class_embed_type: Optional[str] = None,
212
+ addition_embed_type: Optional[str] = None,
213
+ addition_time_embed_dim: Optional[int] = None,
214
+ num_class_embeds: Optional[int] = None,
215
+ upcast_attention: bool = False,
216
+ resnet_time_scale_shift: str = "default",
217
+ projection_class_embeddings_input_dim: Optional[int] = None,
218
+ controlnet_conditioning_channel_order: str = "rgb",
219
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
220
+ global_pool_conditions: bool = False,
221
+ addition_embed_type_num_heads: int = 64,
222
+ ):
223
+ super().__init__()
224
+
225
+ # If `num_attention_heads` is not defined (which is the case for most models)
226
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
227
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
228
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
229
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
230
+ # which is why we correct for the naming here.
231
+ num_attention_heads = num_attention_heads or attention_head_dim
232
+
233
+ # Check inputs
234
+ if len(block_out_channels) != len(down_block_types):
235
+ raise ValueError(
236
+ f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
237
+ )
238
+
239
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
240
+ raise ValueError(
241
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
242
+ )
243
+
244
+ if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
245
+ raise ValueError(
246
+ f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}."
247
+ )
248
+
249
+ if isinstance(transformer_layers_per_block, int):
250
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
251
+
252
+ # input
253
+ conv_in_kernel = 3
254
+ conv_in_padding = (conv_in_kernel - 1) // 2
255
+ self.conv_in = nn.Conv2d(
256
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
257
+ )
258
+
259
+ # time
260
+ time_embed_dim = block_out_channels[0] * 4
261
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
262
+ timestep_input_dim = block_out_channels[0]
263
+ self.time_embedding = TimestepEmbedding(
264
+ timestep_input_dim,
265
+ time_embed_dim,
266
+ act_fn=act_fn,
267
+ )
268
+
269
+ if encoder_hid_dim_type is None and encoder_hid_dim is not None:
270
+ encoder_hid_dim_type = "text_proj"
271
+ self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
272
+ logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.")
273
+
274
+ if encoder_hid_dim is None and encoder_hid_dim_type is not None:
275
+ raise ValueError(
276
+ f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
277
+ )
278
+
279
+ if encoder_hid_dim_type == "text_proj":
280
+ self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
281
+ elif encoder_hid_dim_type == "text_image_proj":
282
+ # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
283
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
284
+ # case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)`
285
+ self.encoder_hid_proj = TextImageProjection(
286
+ text_embed_dim=encoder_hid_dim,
287
+ image_embed_dim=cross_attention_dim,
288
+ cross_attention_dim=cross_attention_dim,
289
+ )
290
+
291
+ elif encoder_hid_dim_type is not None:
292
+ raise ValueError(
293
+ f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
294
+ )
295
+ else:
296
+ self.encoder_hid_proj = None
297
+
298
+ # class embedding
299
+ if class_embed_type is None and num_class_embeds is not None:
300
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
301
+ elif class_embed_type == "timestep":
302
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
303
+ elif class_embed_type == "identity":
304
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
305
+ elif class_embed_type == "projection":
306
+ if projection_class_embeddings_input_dim is None:
307
+ raise ValueError(
308
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
309
+ )
310
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
311
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
312
+ # 2. it projects from an arbitrary input dimension.
313
+ #
314
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
315
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
316
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
317
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
318
+ else:
319
+ self.class_embedding = None
320
+
321
+ if addition_embed_type == "text":
322
+ if encoder_hid_dim is not None:
323
+ text_time_embedding_from_dim = encoder_hid_dim
324
+ else:
325
+ text_time_embedding_from_dim = cross_attention_dim
326
+
327
+ self.add_embedding = TextTimeEmbedding(
328
+ text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
329
+ )
330
+ elif addition_embed_type == "text_image":
331
+ # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
332
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
333
+ # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)`
334
+ self.add_embedding = TextImageTimeEmbedding(
335
+ text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
336
+ )
337
+ elif addition_embed_type == "text_time":
338
+ self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
339
+ self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
340
+
341
+ elif addition_embed_type is not None:
342
+ raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.")
343
+
344
+ # control net conditioning embedding
345
+ self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
346
+ conditioning_embedding_channels=block_out_channels[0],
347
+ block_out_channels=conditioning_embedding_out_channels,
348
+ conditioning_channels=conditioning_channels,
349
+ )
350
+
351
+ self.down_blocks = nn.ModuleList([])
352
+ self.controlnet_down_blocks = nn.ModuleList([])
353
+
354
+ if isinstance(only_cross_attention, bool):
355
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
356
+
357
+ if isinstance(attention_head_dim, int):
358
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
359
+
360
+ if isinstance(num_attention_heads, int):
361
+ num_attention_heads = (num_attention_heads,) * len(down_block_types)
362
+
363
+ # down
364
+ output_channel = block_out_channels[0]
365
+
366
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
367
+ controlnet_block = zero_module(controlnet_block)
368
+ self.controlnet_down_blocks.append(controlnet_block)
369
+
370
+ for i, down_block_type in enumerate(down_block_types):
371
+ input_channel = output_channel
372
+ output_channel = block_out_channels[i]
373
+ is_final_block = i == len(block_out_channels) - 1
374
+
375
+ down_block = get_down_block(
376
+ down_block_type,
377
+ num_layers=layers_per_block,
378
+ transformer_layers_per_block=transformer_layers_per_block[i],
379
+ in_channels=input_channel,
380
+ out_channels=output_channel,
381
+ temb_channels=time_embed_dim,
382
+ add_downsample=not is_final_block,
383
+ resnet_eps=norm_eps,
384
+ resnet_act_fn=act_fn,
385
+ resnet_groups=norm_num_groups,
386
+ cross_attention_dim=cross_attention_dim,
387
+ num_attention_heads=num_attention_heads[i],
388
+ attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
389
+ downsample_padding=downsample_padding,
390
+ use_linear_projection=use_linear_projection,
391
+ only_cross_attention=only_cross_attention[i],
392
+ upcast_attention=upcast_attention,
393
+ resnet_time_scale_shift=resnet_time_scale_shift,
394
+ )
395
+ self.down_blocks.append(down_block)
396
+
397
+ for _ in range(layers_per_block):
398
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
399
+ controlnet_block = zero_module(controlnet_block)
400
+ self.controlnet_down_blocks.append(controlnet_block)
401
+
402
+ if not is_final_block:
403
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
404
+ controlnet_block = zero_module(controlnet_block)
405
+ self.controlnet_down_blocks.append(controlnet_block)
406
+
407
+ # mid
408
+ mid_block_channel = block_out_channels[-1]
409
+
410
+ controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)
411
+ controlnet_block = zero_module(controlnet_block)
412
+ self.controlnet_mid_block = controlnet_block
413
+
414
+ if mid_block_type == "UNetMidBlock2DCrossAttn":
415
+ self.mid_block = UNetMidBlock2DCrossAttn(
416
+ transformer_layers_per_block=transformer_layers_per_block[-1],
417
+ in_channels=mid_block_channel,
418
+ temb_channels=time_embed_dim,
419
+ resnet_eps=norm_eps,
420
+ resnet_act_fn=act_fn,
421
+ output_scale_factor=mid_block_scale_factor,
422
+ resnet_time_scale_shift=resnet_time_scale_shift,
423
+ cross_attention_dim=cross_attention_dim,
424
+ num_attention_heads=num_attention_heads[-1],
425
+ resnet_groups=norm_num_groups,
426
+ use_linear_projection=use_linear_projection,
427
+ upcast_attention=upcast_attention,
428
+ )
429
+ elif mid_block_type == "UNetMidBlock2D":
430
+ self.mid_block = UNetMidBlock2D(
431
+ in_channels=block_out_channels[-1],
432
+ temb_channels=time_embed_dim,
433
+ num_layers=0,
434
+ resnet_eps=norm_eps,
435
+ resnet_act_fn=act_fn,
436
+ output_scale_factor=mid_block_scale_factor,
437
+ resnet_groups=norm_num_groups,
438
+ resnet_time_scale_shift=resnet_time_scale_shift,
439
+ add_attention=False,
440
+ )
441
+ else:
442
+ raise ValueError(f"unknown mid_block_type : {mid_block_type}")
443
+
444
+ @classmethod
445
+ def from_unet(
446
+ cls,
447
+ unet: UNet2DConditionModel,
448
+ controlnet_conditioning_channel_order: str = "rgb",
449
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
450
+ load_weights_from_unet: bool = True,
451
+ conditioning_channels: int = 3,
452
+ ):
453
+ r"""
454
+ Instantiate a [`ControlNetModel`] from [`UNet2DConditionModel`].
455
+
456
+ Parameters:
457
+ unet (`UNet2DConditionModel`):
458
+ The UNet model weights to copy to the [`ControlNetModel`]. All configuration options are also copied
459
+ where applicable.
460
+ """
461
+ transformer_layers_per_block = (
462
+ unet.config.transformer_layers_per_block if "transformer_layers_per_block" in unet.config else 1
463
+ )
464
+ encoder_hid_dim = unet.config.encoder_hid_dim if "encoder_hid_dim" in unet.config else None
465
+ encoder_hid_dim_type = unet.config.encoder_hid_dim_type if "encoder_hid_dim_type" in unet.config else None
466
+ addition_embed_type = unet.config.addition_embed_type if "addition_embed_type" in unet.config else None
467
+ addition_time_embed_dim = (
468
+ unet.config.addition_time_embed_dim if "addition_time_embed_dim" in unet.config else None
469
+ )
470
+
471
+ controlnet = cls(
472
+ encoder_hid_dim=encoder_hid_dim,
473
+ encoder_hid_dim_type=encoder_hid_dim_type,
474
+ addition_embed_type=addition_embed_type,
475
+ addition_time_embed_dim=addition_time_embed_dim,
476
+ transformer_layers_per_block=transformer_layers_per_block,
477
+ in_channels=unet.config.in_channels,
478
+ flip_sin_to_cos=unet.config.flip_sin_to_cos,
479
+ freq_shift=unet.config.freq_shift,
480
+ down_block_types=unet.config.down_block_types,
481
+ only_cross_attention=unet.config.only_cross_attention,
482
+ block_out_channels=unet.config.block_out_channels,
483
+ layers_per_block=unet.config.layers_per_block,
484
+ downsample_padding=unet.config.downsample_padding,
485
+ mid_block_scale_factor=unet.config.mid_block_scale_factor,
486
+ act_fn=unet.config.act_fn,
487
+ norm_num_groups=unet.config.norm_num_groups,
488
+ norm_eps=unet.config.norm_eps,
489
+ cross_attention_dim=unet.config.cross_attention_dim,
490
+ attention_head_dim=unet.config.attention_head_dim,
491
+ num_attention_heads=unet.config.num_attention_heads,
492
+ use_linear_projection=unet.config.use_linear_projection,
493
+ class_embed_type=unet.config.class_embed_type,
494
+ num_class_embeds=unet.config.num_class_embeds,
495
+ upcast_attention=unet.config.upcast_attention,
496
+ resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
497
+ projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
498
+ mid_block_type=unet.config.mid_block_type,
499
+ controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
500
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
501
+ conditioning_channels=conditioning_channels,
502
+ )
503
+
504
+ if load_weights_from_unet:
505
+ controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())
506
+ controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())
507
+ controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
508
+
509
+ if controlnet.class_embedding:
510
+ controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())
511
+
512
+ controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())
513
+ controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())
514
+
515
+ return controlnet
516
+
517
+ @property
518
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
519
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
520
+ r"""
521
+ Returns:
522
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
523
+ indexed by its weight name.
524
+ """
525
+ # set recursively
526
+ processors = {}
527
+
528
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
529
+ if hasattr(module, "get_processor"):
530
+ processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
531
+
532
+ for sub_name, child in module.named_children():
533
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
534
+
535
+ return processors
536
+
537
+ for name, module in self.named_children():
538
+ fn_recursive_add_processors(name, module, processors)
539
+
540
+ return processors
541
+
542
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
543
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
544
+ r"""
545
+ Sets the attention processor to use to compute attention.
546
+
547
+ Parameters:
548
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
549
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
550
+ for **all** `Attention` layers.
551
+
552
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
553
+ processor. This is strongly recommended when setting trainable attention processors.
554
+
555
+ """
556
+ count = len(self.attn_processors.keys())
557
+
558
+ if isinstance(processor, dict) and len(processor) != count:
559
+ raise ValueError(
560
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
561
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
562
+ )
563
+
564
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
565
+ if hasattr(module, "set_processor"):
566
+ if not isinstance(processor, dict):
567
+ module.set_processor(processor)
568
+ else:
569
+ module.set_processor(processor.pop(f"{name}.processor"))
570
+
571
+ for sub_name, child in module.named_children():
572
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
573
+
574
+ for name, module in self.named_children():
575
+ fn_recursive_attn_processor(name, module, processor)
576
+
577
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
578
+ def set_default_attn_processor(self):
579
+ """
580
+ Disables custom attention processors and sets the default attention implementation.
581
+ """
582
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
583
+ processor = AttnAddedKVProcessor()
584
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
585
+ processor = AttnProcessor()
586
+ else:
587
+ raise ValueError(
588
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
589
+ )
590
+
591
+ self.set_attn_processor(processor)
592
+
593
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attention_slice
594
+ def set_attention_slice(self, slice_size: Union[str, int, List[int]]) -> None:
595
+ r"""
596
+ Enable sliced attention computation.
597
+
598
+ When this option is enabled, the attention module splits the input tensor in slices to compute attention in
599
+ several steps. This is useful for saving some memory in exchange for a small decrease in speed.
600
+
601
+ Args:
602
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
603
+ When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
604
+ `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
605
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
606
+ must be a multiple of `slice_size`.
607
+ """
608
+ sliceable_head_dims = []
609
+
610
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
611
+ if hasattr(module, "set_attention_slice"):
612
+ sliceable_head_dims.append(module.sliceable_head_dim)
613
+
614
+ for child in module.children():
615
+ fn_recursive_retrieve_sliceable_dims(child)
616
+
617
+ # retrieve number of attention layers
618
+ for module in self.children():
619
+ fn_recursive_retrieve_sliceable_dims(module)
620
+
621
+ num_sliceable_layers = len(sliceable_head_dims)
622
+
623
+ if slice_size == "auto":
624
+ # half the attention head size is usually a good trade-off between
625
+ # speed and memory
626
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
627
+ elif slice_size == "max":
628
+ # make smallest slice possible
629
+ slice_size = num_sliceable_layers * [1]
630
+
631
+ slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
632
+
633
+ if len(slice_size) != len(sliceable_head_dims):
634
+ raise ValueError(
635
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
636
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
637
+ )
638
+
639
+ for i in range(len(slice_size)):
640
+ size = slice_size[i]
641
+ dim = sliceable_head_dims[i]
642
+ if size is not None and size > dim:
643
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
644
+
645
+ # Recursively walk through all the children.
646
+ # Any children which exposes the set_attention_slice method
647
+ # gets the message
648
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
649
+ if hasattr(module, "set_attention_slice"):
650
+ module.set_attention_slice(slice_size.pop())
651
+
652
+ for child in module.children():
653
+ fn_recursive_set_attention_slice(child, slice_size)
654
+
655
+ reversed_slice_size = list(reversed(slice_size))
656
+ for module in self.children():
657
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
658
+
659
+ def _set_gradient_checkpointing(self, module, value: bool = False) -> None:
660
+ if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):
661
+ module.gradient_checkpointing = value
662
+
663
+ def forward(
664
+ self,
665
+ sample: torch.FloatTensor,
666
+ timestep: Union[torch.Tensor, float, int],
667
+ encoder_hidden_states: torch.Tensor,
668
+ controlnet_cond: torch.FloatTensor,
669
+ conditioning_scale: float = 1.0,
670
+ class_labels: Optional[torch.Tensor] = None,
671
+ timestep_cond: Optional[torch.Tensor] = None,
672
+ attention_mask: Optional[torch.Tensor] = None,
673
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
674
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
675
+ guess_mode: bool = False,
676
+ return_dict: bool = True,
677
+ ) -> Union[ControlNetOutput, Tuple[Tuple[torch.FloatTensor, ...], torch.FloatTensor]]:
678
+ """
679
+ The [`ControlNetModel`] forward method.
680
+
681
+ Args:
682
+ sample (`torch.FloatTensor`):
683
+ The noisy input tensor.
684
+ timestep (`Union[torch.Tensor, float, int]`):
685
+ The number of timesteps to denoise an input.
686
+ encoder_hidden_states (`torch.Tensor`):
687
+ The encoder hidden states.
688
+ controlnet_cond (`torch.FloatTensor`):
689
+ The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
690
+ conditioning_scale (`float`, defaults to `1.0`):
691
+ The scale factor for ControlNet outputs.
692
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
693
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
694
+ timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
695
+ Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
696
+ timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
697
+ embeddings.
698
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
699
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
700
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
701
+ negative values to the attention scores corresponding to "discard" tokens.
702
+ added_cond_kwargs (`dict`):
703
+ Additional conditions for the Stable Diffusion XL UNet.
704
+ cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
705
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
706
+ guess_mode (`bool`, defaults to `False`):
707
+ In this mode, the ControlNet encoder tries its best to recognize the input content of the input even if
708
+ you remove all prompts. A `guidance_scale` between 3.0 and 5.0 is recommended.
709
+ return_dict (`bool`, defaults to `True`):
710
+ Whether or not to return a [`~models.controlnet.ControlNetOutput`] instead of a plain tuple.
711
+
712
+ Returns:
713
+ [`~models.controlnet.ControlNetOutput`] **or** `tuple`:
714
+ If `return_dict` is `True`, a [`~models.controlnet.ControlNetOutput`] is returned, otherwise a tuple is
715
+ returned where the first element is the sample tensor.
716
+ """
717
+ # check channel order
718
+ channel_order = self.config.controlnet_conditioning_channel_order
719
+
720
+ if channel_order == "rgb":
721
+ # in rgb order by default
722
+ ...
723
+ elif channel_order == "bgr":
724
+ controlnet_cond = torch.flip(controlnet_cond, dims=[1])
725
+ else:
726
+ raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
727
+
728
+ # prepare attention_mask
729
+ if attention_mask is not None:
730
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
731
+ attention_mask = attention_mask.unsqueeze(1)
732
+
733
+ # 1. time
734
+ timesteps = timestep
735
+ if not torch.is_tensor(timesteps):
736
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
737
+ # This would be a good case for the `match` statement (Python 3.10+)
738
+ is_mps = sample.device.type == "mps"
739
+ if isinstance(timestep, float):
740
+ dtype = torch.float32 if is_mps else torch.float64
741
+ else:
742
+ dtype = torch.int32 if is_mps else torch.int64
743
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
744
+ elif len(timesteps.shape) == 0:
745
+ timesteps = timesteps[None].to(sample.device)
746
+
747
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
748
+ timesteps = timesteps.expand(sample.shape[0])
749
+
750
+ t_emb = self.time_proj(timesteps)
751
+
752
+ # timesteps does not contain any weights and will always return f32 tensors
753
+ # but time_embedding might actually be running in fp16. so we need to cast here.
754
+ # there might be better ways to encapsulate this.
755
+ t_emb = t_emb.to(dtype=sample.dtype)
756
+
757
+ emb = self.time_embedding(t_emb, timestep_cond)
758
+ aug_emb = None
759
+
760
+ if self.class_embedding is not None:
761
+ if class_labels is None:
762
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
763
+
764
+ if self.config.class_embed_type == "timestep":
765
+ class_labels = self.time_proj(class_labels)
766
+
767
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
768
+ emb = emb + class_emb
769
+
770
+ if self.config.addition_embed_type is not None:
771
+ if self.config.addition_embed_type == "text":
772
+ aug_emb = self.add_embedding(encoder_hidden_states)
773
+
774
+ elif self.config.addition_embed_type == "text_time":
775
+ if "text_embeds" not in added_cond_kwargs:
776
+ raise ValueError(
777
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`"
778
+ )
779
+ text_embeds = added_cond_kwargs.get("text_embeds")
780
+ if "time_ids" not in added_cond_kwargs:
781
+ raise ValueError(
782
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`"
783
+ )
784
+ time_ids = added_cond_kwargs.get("time_ids")
785
+ time_embeds = self.add_time_proj(time_ids.flatten())
786
+ time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
787
+
788
+ add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
789
+ add_embeds = add_embeds.to(emb.dtype)
790
+ aug_emb = self.add_embedding(add_embeds)
791
+
792
+ emb = emb + aug_emb if aug_emb is not None else emb
793
+
794
+ # 2. pre-process
795
+ sample = self.conv_in(sample)
796
+
797
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
798
+ sample = sample + controlnet_cond
799
+
800
+ # 3. down
801
+ down_block_res_samples = (sample,)
802
+ for downsample_block in self.down_blocks:
803
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
804
+ sample, res_samples = downsample_block(
805
+ hidden_states=sample,
806
+ temb=emb,
807
+ encoder_hidden_states=encoder_hidden_states,
808
+ attention_mask=attention_mask,
809
+ cross_attention_kwargs=cross_attention_kwargs,
810
+ )
811
+ else:
812
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
813
+
814
+ down_block_res_samples += res_samples
815
+
816
+ # 4. mid
817
+ if self.mid_block is not None:
818
+ if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
819
+ sample = self.mid_block(
820
+ sample,
821
+ emb,
822
+ encoder_hidden_states=encoder_hidden_states,
823
+ attention_mask=attention_mask,
824
+ cross_attention_kwargs=cross_attention_kwargs,
825
+ )
826
+ else:
827
+ sample = self.mid_block(sample, emb)
828
+
829
+ # 5. Control net blocks
830
+
831
+ controlnet_down_block_res_samples = ()
832
+
833
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
834
+ down_block_res_sample = controlnet_block(down_block_res_sample)
835
+ controlnet_down_block_res_samples = controlnet_down_block_res_samples + (down_block_res_sample,)
836
+
837
+ down_block_res_samples = controlnet_down_block_res_samples
838
+
839
+ mid_block_res_sample = self.controlnet_mid_block(sample)
840
+
841
+ # 6. scaling
842
+ if guess_mode and not self.config.global_pool_conditions:
843
+ scales = torch.logspace(-1, 0, len(down_block_res_samples) + 1, device=sample.device) # 0.1 to 1.0
844
+ scales = scales * conditioning_scale
845
+ down_block_res_samples = [sample * scale for sample, scale in zip(down_block_res_samples, scales)]
846
+ mid_block_res_sample = mid_block_res_sample * scales[-1] # last one
847
+ else:
848
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
849
+ mid_block_res_sample = mid_block_res_sample * conditioning_scale
850
+
851
+ if self.config.global_pool_conditions:
852
+ down_block_res_samples = [
853
+ torch.mean(sample, dim=(2, 3), keepdim=True) for sample in down_block_res_samples
854
+ ]
855
+ mid_block_res_sample = torch.mean(mid_block_res_sample, dim=(2, 3), keepdim=True)
856
+
857
+ if not return_dict:
858
+ return (down_block_res_samples, mid_block_res_sample)
859
+
860
+ return ControlNetOutput(
861
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
862
+ )
863
+
864
+
865
+ def zero_module(module):
866
+ for p in module.parameters():
867
+ nn.init.zeros_(p)
868
+ return module
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/controlnet_flax.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Optional, Tuple, Union
15
+
16
+ import flax
17
+ import flax.linen as nn
18
+ import jax
19
+ import jax.numpy as jnp
20
+ from flax.core.frozen_dict import FrozenDict
21
+
22
+ from ..configuration_utils import ConfigMixin, flax_register_to_config
23
+ from ..utils import BaseOutput
24
+ from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps
25
+ from .modeling_flax_utils import FlaxModelMixin
26
+ from .unets.unet_2d_blocks_flax import (
27
+ FlaxCrossAttnDownBlock2D,
28
+ FlaxDownBlock2D,
29
+ FlaxUNetMidBlock2DCrossAttn,
30
+ )
31
+
32
+
33
+ @flax.struct.dataclass
34
+ class FlaxControlNetOutput(BaseOutput):
35
+ """
36
+ The output of [`FlaxControlNetModel`].
37
+
38
+ Args:
39
+ down_block_res_samples (`jnp.ndarray`):
40
+ mid_block_res_sample (`jnp.ndarray`):
41
+ """
42
+
43
+ down_block_res_samples: jnp.ndarray
44
+ mid_block_res_sample: jnp.ndarray
45
+
46
+
47
+ class FlaxControlNetConditioningEmbedding(nn.Module):
48
+ conditioning_embedding_channels: int
49
+ block_out_channels: Tuple[int, ...] = (16, 32, 96, 256)
50
+ dtype: jnp.dtype = jnp.float32
51
+
52
+ def setup(self) -> None:
53
+ self.conv_in = nn.Conv(
54
+ self.block_out_channels[0],
55
+ kernel_size=(3, 3),
56
+ padding=((1, 1), (1, 1)),
57
+ dtype=self.dtype,
58
+ )
59
+
60
+ blocks = []
61
+ for i in range(len(self.block_out_channels) - 1):
62
+ channel_in = self.block_out_channels[i]
63
+ channel_out = self.block_out_channels[i + 1]
64
+ conv1 = nn.Conv(
65
+ channel_in,
66
+ kernel_size=(3, 3),
67
+ padding=((1, 1), (1, 1)),
68
+ dtype=self.dtype,
69
+ )
70
+ blocks.append(conv1)
71
+ conv2 = nn.Conv(
72
+ channel_out,
73
+ kernel_size=(3, 3),
74
+ strides=(2, 2),
75
+ padding=((1, 1), (1, 1)),
76
+ dtype=self.dtype,
77
+ )
78
+ blocks.append(conv2)
79
+ self.blocks = blocks
80
+
81
+ self.conv_out = nn.Conv(
82
+ self.conditioning_embedding_channels,
83
+ kernel_size=(3, 3),
84
+ padding=((1, 1), (1, 1)),
85
+ kernel_init=nn.initializers.zeros_init(),
86
+ bias_init=nn.initializers.zeros_init(),
87
+ dtype=self.dtype,
88
+ )
89
+
90
+ def __call__(self, conditioning: jnp.ndarray) -> jnp.ndarray:
91
+ embedding = self.conv_in(conditioning)
92
+ embedding = nn.silu(embedding)
93
+
94
+ for block in self.blocks:
95
+ embedding = block(embedding)
96
+ embedding = nn.silu(embedding)
97
+
98
+ embedding = self.conv_out(embedding)
99
+
100
+ return embedding
101
+
102
+
103
+ @flax_register_to_config
104
+ class FlaxControlNetModel(nn.Module, FlaxModelMixin, ConfigMixin):
105
+ r"""
106
+ A ControlNet model.
107
+
108
+ This model inherits from [`FlaxModelMixin`]. Check the superclass documentation for it’s generic methods
109
+ implemented for all models (such as downloading or saving).
110
+
111
+ This model is also a Flax Linen [`flax.linen.Module`](https://flax.readthedocs.io/en/latest/flax.linen.html#module)
112
+ subclass. Use it as a regular Flax Linen module and refer to the Flax documentation for all matters related to its
113
+ general usage and behavior.
114
+
115
+ Inherent JAX features such as the following are supported:
116
+
117
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
118
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
119
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
120
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
121
+
122
+ Parameters:
123
+ sample_size (`int`, *optional*):
124
+ The size of the input sample.
125
+ in_channels (`int`, *optional*, defaults to 4):
126
+ The number of channels in the input sample.
127
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("FlaxCrossAttnDownBlock2D", "FlaxCrossAttnDownBlock2D", "FlaxCrossAttnDownBlock2D", "FlaxDownBlock2D")`):
128
+ The tuple of downsample blocks to use.
129
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
130
+ The tuple of output channels for each block.
131
+ layers_per_block (`int`, *optional*, defaults to 2):
132
+ The number of layers per block.
133
+ attention_head_dim (`int` or `Tuple[int]`, *optional*, defaults to 8):
134
+ The dimension of the attention heads.
135
+ num_attention_heads (`int` or `Tuple[int]`, *optional*):
136
+ The number of attention heads.
137
+ cross_attention_dim (`int`, *optional*, defaults to 768):
138
+ The dimension of the cross attention features.
139
+ dropout (`float`, *optional*, defaults to 0):
140
+ Dropout probability for down, up and bottleneck blocks.
141
+ flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
142
+ Whether to flip the sin to cos in the time embedding.
143
+ freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
144
+ controlnet_conditioning_channel_order (`str`, *optional*, defaults to `rgb`):
145
+ The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
146
+ conditioning_embedding_out_channels (`tuple`, *optional*, defaults to `(16, 32, 96, 256)`):
147
+ The tuple of output channel for each block in the `conditioning_embedding` layer.
148
+ """
149
+
150
+ sample_size: int = 32
151
+ in_channels: int = 4
152
+ down_block_types: Tuple[str, ...] = (
153
+ "CrossAttnDownBlock2D",
154
+ "CrossAttnDownBlock2D",
155
+ "CrossAttnDownBlock2D",
156
+ "DownBlock2D",
157
+ )
158
+ only_cross_attention: Union[bool, Tuple[bool, ...]] = False
159
+ block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280)
160
+ layers_per_block: int = 2
161
+ attention_head_dim: Union[int, Tuple[int, ...]] = 8
162
+ num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None
163
+ cross_attention_dim: int = 1280
164
+ dropout: float = 0.0
165
+ use_linear_projection: bool = False
166
+ dtype: jnp.dtype = jnp.float32
167
+ flip_sin_to_cos: bool = True
168
+ freq_shift: int = 0
169
+ controlnet_conditioning_channel_order: str = "rgb"
170
+ conditioning_embedding_out_channels: Tuple[int, ...] = (16, 32, 96, 256)
171
+
172
+ def init_weights(self, rng: jax.Array) -> FrozenDict:
173
+ # init input tensors
174
+ sample_shape = (1, self.in_channels, self.sample_size, self.sample_size)
175
+ sample = jnp.zeros(sample_shape, dtype=jnp.float32)
176
+ timesteps = jnp.ones((1,), dtype=jnp.int32)
177
+ encoder_hidden_states = jnp.zeros((1, 1, self.cross_attention_dim), dtype=jnp.float32)
178
+ controlnet_cond_shape = (1, 3, self.sample_size * 8, self.sample_size * 8)
179
+ controlnet_cond = jnp.zeros(controlnet_cond_shape, dtype=jnp.float32)
180
+
181
+ params_rng, dropout_rng = jax.random.split(rng)
182
+ rngs = {"params": params_rng, "dropout": dropout_rng}
183
+
184
+ return self.init(rngs, sample, timesteps, encoder_hidden_states, controlnet_cond)["params"]
185
+
186
+ def setup(self) -> None:
187
+ block_out_channels = self.block_out_channels
188
+ time_embed_dim = block_out_channels[0] * 4
189
+
190
+ # If `num_attention_heads` is not defined (which is the case for most models)
191
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
192
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
193
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
194
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
195
+ # which is why we correct for the naming here.
196
+ num_attention_heads = self.num_attention_heads or self.attention_head_dim
197
+
198
+ # input
199
+ self.conv_in = nn.Conv(
200
+ block_out_channels[0],
201
+ kernel_size=(3, 3),
202
+ strides=(1, 1),
203
+ padding=((1, 1), (1, 1)),
204
+ dtype=self.dtype,
205
+ )
206
+
207
+ # time
208
+ self.time_proj = FlaxTimesteps(
209
+ block_out_channels[0], flip_sin_to_cos=self.flip_sin_to_cos, freq_shift=self.config.freq_shift
210
+ )
211
+ self.time_embedding = FlaxTimestepEmbedding(time_embed_dim, dtype=self.dtype)
212
+
213
+ self.controlnet_cond_embedding = FlaxControlNetConditioningEmbedding(
214
+ conditioning_embedding_channels=block_out_channels[0],
215
+ block_out_channels=self.conditioning_embedding_out_channels,
216
+ )
217
+
218
+ only_cross_attention = self.only_cross_attention
219
+ if isinstance(only_cross_attention, bool):
220
+ only_cross_attention = (only_cross_attention,) * len(self.down_block_types)
221
+
222
+ if isinstance(num_attention_heads, int):
223
+ num_attention_heads = (num_attention_heads,) * len(self.down_block_types)
224
+
225
+ # down
226
+ down_blocks = []
227
+ controlnet_down_blocks = []
228
+
229
+ output_channel = block_out_channels[0]
230
+
231
+ controlnet_block = nn.Conv(
232
+ output_channel,
233
+ kernel_size=(1, 1),
234
+ padding="VALID",
235
+ kernel_init=nn.initializers.zeros_init(),
236
+ bias_init=nn.initializers.zeros_init(),
237
+ dtype=self.dtype,
238
+ )
239
+ controlnet_down_blocks.append(controlnet_block)
240
+
241
+ for i, down_block_type in enumerate(self.down_block_types):
242
+ input_channel = output_channel
243
+ output_channel = block_out_channels[i]
244
+ is_final_block = i == len(block_out_channels) - 1
245
+
246
+ if down_block_type == "CrossAttnDownBlock2D":
247
+ down_block = FlaxCrossAttnDownBlock2D(
248
+ in_channels=input_channel,
249
+ out_channels=output_channel,
250
+ dropout=self.dropout,
251
+ num_layers=self.layers_per_block,
252
+ num_attention_heads=num_attention_heads[i],
253
+ add_downsample=not is_final_block,
254
+ use_linear_projection=self.use_linear_projection,
255
+ only_cross_attention=only_cross_attention[i],
256
+ dtype=self.dtype,
257
+ )
258
+ else:
259
+ down_block = FlaxDownBlock2D(
260
+ in_channels=input_channel,
261
+ out_channels=output_channel,
262
+ dropout=self.dropout,
263
+ num_layers=self.layers_per_block,
264
+ add_downsample=not is_final_block,
265
+ dtype=self.dtype,
266
+ )
267
+
268
+ down_blocks.append(down_block)
269
+
270
+ for _ in range(self.layers_per_block):
271
+ controlnet_block = nn.Conv(
272
+ output_channel,
273
+ kernel_size=(1, 1),
274
+ padding="VALID",
275
+ kernel_init=nn.initializers.zeros_init(),
276
+ bias_init=nn.initializers.zeros_init(),
277
+ dtype=self.dtype,
278
+ )
279
+ controlnet_down_blocks.append(controlnet_block)
280
+
281
+ if not is_final_block:
282
+ controlnet_block = nn.Conv(
283
+ output_channel,
284
+ kernel_size=(1, 1),
285
+ padding="VALID",
286
+ kernel_init=nn.initializers.zeros_init(),
287
+ bias_init=nn.initializers.zeros_init(),
288
+ dtype=self.dtype,
289
+ )
290
+ controlnet_down_blocks.append(controlnet_block)
291
+
292
+ self.down_blocks = down_blocks
293
+ self.controlnet_down_blocks = controlnet_down_blocks
294
+
295
+ # mid
296
+ mid_block_channel = block_out_channels[-1]
297
+ self.mid_block = FlaxUNetMidBlock2DCrossAttn(
298
+ in_channels=mid_block_channel,
299
+ dropout=self.dropout,
300
+ num_attention_heads=num_attention_heads[-1],
301
+ use_linear_projection=self.use_linear_projection,
302
+ dtype=self.dtype,
303
+ )
304
+
305
+ self.controlnet_mid_block = nn.Conv(
306
+ mid_block_channel,
307
+ kernel_size=(1, 1),
308
+ padding="VALID",
309
+ kernel_init=nn.initializers.zeros_init(),
310
+ bias_init=nn.initializers.zeros_init(),
311
+ dtype=self.dtype,
312
+ )
313
+
314
+ def __call__(
315
+ self,
316
+ sample: jnp.ndarray,
317
+ timesteps: Union[jnp.ndarray, float, int],
318
+ encoder_hidden_states: jnp.ndarray,
319
+ controlnet_cond: jnp.ndarray,
320
+ conditioning_scale: float = 1.0,
321
+ return_dict: bool = True,
322
+ train: bool = False,
323
+ ) -> Union[FlaxControlNetOutput, Tuple[Tuple[jnp.ndarray, ...], jnp.ndarray]]:
324
+ r"""
325
+ Args:
326
+ sample (`jnp.ndarray`): (batch, channel, height, width) noisy inputs tensor
327
+ timestep (`jnp.ndarray` or `float` or `int`): timesteps
328
+ encoder_hidden_states (`jnp.ndarray`): (batch_size, sequence_length, hidden_size) encoder hidden states
329
+ controlnet_cond (`jnp.ndarray`): (batch, channel, height, width) the conditional input tensor
330
+ conditioning_scale (`float`, *optional*, defaults to `1.0`): the scale factor for controlnet outputs
331
+ return_dict (`bool`, *optional*, defaults to `True`):
332
+ Whether or not to return a [`models.unets.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] instead of a
333
+ plain tuple.
334
+ train (`bool`, *optional*, defaults to `False`):
335
+ Use deterministic functions and disable dropout when not training.
336
+
337
+ Returns:
338
+ [`~models.unets.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] or `tuple`:
339
+ [`~models.unets.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] if `return_dict` is True, otherwise a
340
+ `tuple`. When returning a tuple, the first element is the sample tensor.
341
+ """
342
+ channel_order = self.controlnet_conditioning_channel_order
343
+ if channel_order == "bgr":
344
+ controlnet_cond = jnp.flip(controlnet_cond, axis=1)
345
+
346
+ # 1. time
347
+ if not isinstance(timesteps, jnp.ndarray):
348
+ timesteps = jnp.array([timesteps], dtype=jnp.int32)
349
+ elif isinstance(timesteps, jnp.ndarray) and len(timesteps.shape) == 0:
350
+ timesteps = timesteps.astype(dtype=jnp.float32)
351
+ timesteps = jnp.expand_dims(timesteps, 0)
352
+
353
+ t_emb = self.time_proj(timesteps)
354
+ t_emb = self.time_embedding(t_emb)
355
+
356
+ # 2. pre-process
357
+ sample = jnp.transpose(sample, (0, 2, 3, 1))
358
+ sample = self.conv_in(sample)
359
+
360
+ controlnet_cond = jnp.transpose(controlnet_cond, (0, 2, 3, 1))
361
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
362
+ sample += controlnet_cond
363
+
364
+ # 3. down
365
+ down_block_res_samples = (sample,)
366
+ for down_block in self.down_blocks:
367
+ if isinstance(down_block, FlaxCrossAttnDownBlock2D):
368
+ sample, res_samples = down_block(sample, t_emb, encoder_hidden_states, deterministic=not train)
369
+ else:
370
+ sample, res_samples = down_block(sample, t_emb, deterministic=not train)
371
+ down_block_res_samples += res_samples
372
+
373
+ # 4. mid
374
+ sample = self.mid_block(sample, t_emb, encoder_hidden_states, deterministic=not train)
375
+
376
+ # 5. contronet blocks
377
+ controlnet_down_block_res_samples = ()
378
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
379
+ down_block_res_sample = controlnet_block(down_block_res_sample)
380
+ controlnet_down_block_res_samples += (down_block_res_sample,)
381
+
382
+ down_block_res_samples = controlnet_down_block_res_samples
383
+
384
+ mid_block_res_sample = self.controlnet_mid_block(sample)
385
+
386
+ # 6. scaling
387
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
388
+ mid_block_res_sample *= conditioning_scale
389
+
390
+ if not return_dict:
391
+ return (down_block_res_samples, mid_block_res_sample)
392
+
393
+ return FlaxControlNetOutput(
394
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
395
+ )
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/downsampling.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Optional, Tuple
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+
21
+ from ..utils import deprecate
22
+ from .normalization import RMSNorm
23
+ from .upsampling import upfirdn2d_native
24
+
25
+
26
+ class Downsample1D(nn.Module):
27
+ """A 1D downsampling layer with an optional convolution.
28
+
29
+ Parameters:
30
+ channels (`int`):
31
+ number of channels in the inputs and outputs.
32
+ use_conv (`bool`, default `False`):
33
+ option to use a convolution.
34
+ out_channels (`int`, optional):
35
+ number of output channels. Defaults to `channels`.
36
+ padding (`int`, default `1`):
37
+ padding for the convolution.
38
+ name (`str`, default `conv`):
39
+ name of the downsampling 1D layer.
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ channels: int,
45
+ use_conv: bool = False,
46
+ out_channels: Optional[int] = None,
47
+ padding: int = 1,
48
+ name: str = "conv",
49
+ ):
50
+ super().__init__()
51
+ self.channels = channels
52
+ self.out_channels = out_channels or channels
53
+ self.use_conv = use_conv
54
+ self.padding = padding
55
+ stride = 2
56
+ self.name = name
57
+
58
+ if use_conv:
59
+ self.conv = nn.Conv1d(self.channels, self.out_channels, 3, stride=stride, padding=padding)
60
+ else:
61
+ assert self.channels == self.out_channels
62
+ self.conv = nn.AvgPool1d(kernel_size=stride, stride=stride)
63
+
64
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
65
+ assert inputs.shape[1] == self.channels
66
+ return self.conv(inputs)
67
+
68
+
69
+ class Downsample2D(nn.Module):
70
+ """A 2D downsampling layer with an optional convolution.
71
+
72
+ Parameters:
73
+ channels (`int`):
74
+ number of channels in the inputs and outputs.
75
+ use_conv (`bool`, default `False`):
76
+ option to use a convolution.
77
+ out_channels (`int`, optional):
78
+ number of output channels. Defaults to `channels`.
79
+ padding (`int`, default `1`):
80
+ padding for the convolution.
81
+ name (`str`, default `conv`):
82
+ name of the downsampling 2D layer.
83
+ """
84
+
85
+ def __init__(
86
+ self,
87
+ channels: int,
88
+ use_conv: bool = False,
89
+ out_channels: Optional[int] = None,
90
+ padding: int = 1,
91
+ name: str = "conv",
92
+ kernel_size=3,
93
+ norm_type=None,
94
+ eps=None,
95
+ elementwise_affine=None,
96
+ bias=True,
97
+ ):
98
+ super().__init__()
99
+ self.channels = channels
100
+ self.out_channels = out_channels or channels
101
+ self.use_conv = use_conv
102
+ self.padding = padding
103
+ stride = 2
104
+ self.name = name
105
+ conv_cls = nn.Conv2d
106
+
107
+ if norm_type == "ln_norm":
108
+ self.norm = nn.LayerNorm(channels, eps, elementwise_affine)
109
+ elif norm_type == "rms_norm":
110
+ self.norm = RMSNorm(channels, eps, elementwise_affine)
111
+ elif norm_type is None:
112
+ self.norm = None
113
+ else:
114
+ raise ValueError(f"unknown norm_type: {norm_type}")
115
+
116
+ if use_conv:
117
+ conv = conv_cls(
118
+ self.channels, self.out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias
119
+ )
120
+ else:
121
+ assert self.channels == self.out_channels
122
+ conv = nn.AvgPool2d(kernel_size=stride, stride=stride)
123
+
124
+ # TODO(Suraj, Patrick) - clean up after weight dicts are correctly renamed
125
+ if name == "conv":
126
+ self.Conv2d_0 = conv
127
+ self.conv = conv
128
+ elif name == "Conv2d_0":
129
+ self.conv = conv
130
+ else:
131
+ self.conv = conv
132
+
133
+ def forward(self, hidden_states: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
134
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
135
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
136
+ deprecate("scale", "1.0.0", deprecation_message)
137
+ assert hidden_states.shape[1] == self.channels
138
+
139
+ if self.norm is not None:
140
+ hidden_states = self.norm(hidden_states.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
141
+
142
+ if self.use_conv and self.padding == 0:
143
+ pad = (0, 1, 0, 1)
144
+ hidden_states = F.pad(hidden_states, pad, mode="constant", value=0)
145
+
146
+ assert hidden_states.shape[1] == self.channels
147
+
148
+ hidden_states = self.conv(hidden_states)
149
+
150
+ return hidden_states
151
+
152
+
153
+ class FirDownsample2D(nn.Module):
154
+ """A 2D FIR downsampling layer with an optional convolution.
155
+
156
+ Parameters:
157
+ channels (`int`):
158
+ number of channels in the inputs and outputs.
159
+ use_conv (`bool`, default `False`):
160
+ option to use a convolution.
161
+ out_channels (`int`, optional):
162
+ number of output channels. Defaults to `channels`.
163
+ fir_kernel (`tuple`, default `(1, 3, 3, 1)`):
164
+ kernel for the FIR filter.
165
+ """
166
+
167
+ def __init__(
168
+ self,
169
+ channels: Optional[int] = None,
170
+ out_channels: Optional[int] = None,
171
+ use_conv: bool = False,
172
+ fir_kernel: Tuple[int, int, int, int] = (1, 3, 3, 1),
173
+ ):
174
+ super().__init__()
175
+ out_channels = out_channels if out_channels else channels
176
+ if use_conv:
177
+ self.Conv2d_0 = nn.Conv2d(channels, out_channels, kernel_size=3, stride=1, padding=1)
178
+ self.fir_kernel = fir_kernel
179
+ self.use_conv = use_conv
180
+ self.out_channels = out_channels
181
+
182
+ def _downsample_2d(
183
+ self,
184
+ hidden_states: torch.FloatTensor,
185
+ weight: Optional[torch.FloatTensor] = None,
186
+ kernel: Optional[torch.FloatTensor] = None,
187
+ factor: int = 2,
188
+ gain: float = 1,
189
+ ) -> torch.FloatTensor:
190
+ """Fused `Conv2d()` followed by `downsample_2d()`.
191
+ Padding is performed only once at the beginning, not between the operations. The fused op is considerably more
192
+ efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of
193
+ arbitrary order.
194
+
195
+ Args:
196
+ hidden_states (`torch.FloatTensor`):
197
+ Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
198
+ weight (`torch.FloatTensor`, *optional*):
199
+ Weight tensor of the shape `[filterH, filterW, inChannels, outChannels]`. Grouped convolution can be
200
+ performed by `inChannels = x.shape[0] // numGroups`.
201
+ kernel (`torch.FloatTensor`, *optional*):
202
+ FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
203
+ corresponds to average pooling.
204
+ factor (`int`, *optional*, default to `2`):
205
+ Integer downsampling factor.
206
+ gain (`float`, *optional*, default to `1.0`):
207
+ Scaling factor for signal magnitude.
208
+
209
+ Returns:
210
+ output (`torch.FloatTensor`):
211
+ Tensor of the shape `[N, C, H // factor, W // factor]` or `[N, H // factor, W // factor, C]`, and same
212
+ datatype as `x`.
213
+ """
214
+
215
+ assert isinstance(factor, int) and factor >= 1
216
+ if kernel is None:
217
+ kernel = [1] * factor
218
+
219
+ # setup kernel
220
+ kernel = torch.tensor(kernel, dtype=torch.float32)
221
+ if kernel.ndim == 1:
222
+ kernel = torch.outer(kernel, kernel)
223
+ kernel /= torch.sum(kernel)
224
+
225
+ kernel = kernel * gain
226
+
227
+ if self.use_conv:
228
+ _, _, convH, convW = weight.shape
229
+ pad_value = (kernel.shape[0] - factor) + (convW - 1)
230
+ stride_value = [factor, factor]
231
+ upfirdn_input = upfirdn2d_native(
232
+ hidden_states,
233
+ torch.tensor(kernel, device=hidden_states.device),
234
+ pad=((pad_value + 1) // 2, pad_value // 2),
235
+ )
236
+ output = F.conv2d(upfirdn_input, weight, stride=stride_value, padding=0)
237
+ else:
238
+ pad_value = kernel.shape[0] - factor
239
+ output = upfirdn2d_native(
240
+ hidden_states,
241
+ torch.tensor(kernel, device=hidden_states.device),
242
+ down=factor,
243
+ pad=((pad_value + 1) // 2, pad_value // 2),
244
+ )
245
+
246
+ return output
247
+
248
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
249
+ if self.use_conv:
250
+ downsample_input = self._downsample_2d(hidden_states, weight=self.Conv2d_0.weight, kernel=self.fir_kernel)
251
+ hidden_states = downsample_input + self.Conv2d_0.bias.reshape(1, -1, 1, 1)
252
+ else:
253
+ hidden_states = self._downsample_2d(hidden_states, kernel=self.fir_kernel, factor=2)
254
+
255
+ return hidden_states
256
+
257
+
258
+ # downsample/upsample layer used in k-upscaler, might be able to use FirDownsample2D/DirUpsample2D instead
259
+ class KDownsample2D(nn.Module):
260
+ r"""A 2D K-downsampling layer.
261
+
262
+ Parameters:
263
+ pad_mode (`str`, *optional*, default to `"reflect"`): the padding mode to use.
264
+ """
265
+
266
+ def __init__(self, pad_mode: str = "reflect"):
267
+ super().__init__()
268
+ self.pad_mode = pad_mode
269
+ kernel_1d = torch.tensor([[1 / 8, 3 / 8, 3 / 8, 1 / 8]])
270
+ self.pad = kernel_1d.shape[1] // 2 - 1
271
+ self.register_buffer("kernel", kernel_1d.T @ kernel_1d, persistent=False)
272
+
273
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
274
+ inputs = F.pad(inputs, (self.pad,) * 4, self.pad_mode)
275
+ weight = inputs.new_zeros(
276
+ [
277
+ inputs.shape[1],
278
+ inputs.shape[1],
279
+ self.kernel.shape[0],
280
+ self.kernel.shape[1],
281
+ ]
282
+ )
283
+ indices = torch.arange(inputs.shape[1], device=inputs.device)
284
+ kernel = self.kernel.to(weight)[None, :].expand(inputs.shape[1], -1, -1)
285
+ weight[indices, indices] = kernel
286
+ return F.conv2d(inputs, weight, stride=2)
287
+
288
+
289
+ def downsample_2d(
290
+ hidden_states: torch.FloatTensor,
291
+ kernel: Optional[torch.FloatTensor] = None,
292
+ factor: int = 2,
293
+ gain: float = 1,
294
+ ) -> torch.FloatTensor:
295
+ r"""Downsample2D a batch of 2D images with the given filter.
296
+ Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]` and downsamples each image with the
297
+ given filter. The filter is normalized so that if the input pixels are constant, they will be scaled by the
298
+ specified `gain`. Pixels outside the image are assumed to be zero, and the filter is padded with zeros so that its
299
+ shape is a multiple of the downsampling factor.
300
+
301
+ Args:
302
+ hidden_states (`torch.FloatTensor`)
303
+ Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
304
+ kernel (`torch.FloatTensor`, *optional*):
305
+ FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
306
+ corresponds to average pooling.
307
+ factor (`int`, *optional*, default to `2`):
308
+ Integer downsampling factor.
309
+ gain (`float`, *optional*, default to `1.0`):
310
+ Scaling factor for signal magnitude.
311
+
312
+ Returns:
313
+ output (`torch.FloatTensor`):
314
+ Tensor of the shape `[N, C, H // factor, W // factor]`
315
+ """
316
+
317
+ assert isinstance(factor, int) and factor >= 1
318
+ if kernel is None:
319
+ kernel = [1] * factor
320
+
321
+ kernel = torch.tensor(kernel, dtype=torch.float32)
322
+ if kernel.ndim == 1:
323
+ kernel = torch.outer(kernel, kernel)
324
+ kernel /= torch.sum(kernel)
325
+
326
+ kernel = kernel * gain
327
+ pad_value = kernel.shape[0] - factor
328
+ output = upfirdn2d_native(
329
+ hidden_states,
330
+ kernel.to(device=hidden_states.device),
331
+ down=factor,
332
+ pad=((pad_value + 1) // 2, pad_value // 2),
333
+ )
334
+ return output
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/dual_transformer_2d.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from ..utils import deprecate
15
+ from .transformers.dual_transformer_2d import DualTransformer2DModel
16
+
17
+
18
+ class DualTransformer2DModel(DualTransformer2DModel):
19
+ deprecation_message = "Importing `DualTransformer2DModel` from `diffusers.models.dual_transformer_2d` is deprecated and this will be removed in a future version. Please use `from diffusers.models.transformers.dual_transformer_2d import DualTransformer2DModel`, instead."
20
+ deprecate("DualTransformer2DModel", "0.29", deprecation_message)
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/embeddings.py ADDED
@@ -0,0 +1,914 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import math
15
+ from typing import List, Optional, Tuple, Union
16
+
17
+ import numpy as np
18
+ import torch
19
+ from torch import nn
20
+
21
+ from ..utils import deprecate
22
+ from .activations import get_activation
23
+ from .attention_processor import Attention
24
+
25
+
26
+ def get_timestep_embedding(
27
+ timesteps: torch.Tensor,
28
+ embedding_dim: int,
29
+ flip_sin_to_cos: bool = False,
30
+ downscale_freq_shift: float = 1,
31
+ scale: float = 1,
32
+ max_period: int = 10000,
33
+ ):
34
+ """
35
+ This matches the implementation in Denoising Diffusion Probabilistic Models: Create sinusoidal timestep embeddings.
36
+
37
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
38
+ These may be fractional.
39
+ :param embedding_dim: the dimension of the output. :param max_period: controls the minimum frequency of the
40
+ embeddings. :return: an [N x dim] Tensor of positional embeddings.
41
+ """
42
+ assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array"
43
+
44
+ half_dim = embedding_dim // 2
45
+ exponent = -math.log(max_period) * torch.arange(
46
+ start=0, end=half_dim, dtype=torch.float32, device=timesteps.device
47
+ )
48
+ exponent = exponent / (half_dim - downscale_freq_shift)
49
+
50
+ emb = torch.exp(exponent)
51
+ emb = timesteps[:, None].float() * emb[None, :]
52
+
53
+ # scale embeddings
54
+ emb = scale * emb
55
+
56
+ # concat sine and cosine embeddings
57
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)
58
+
59
+ # flip sine and cosine embeddings
60
+ if flip_sin_to_cos:
61
+ emb = torch.cat([emb[:, half_dim:], emb[:, :half_dim]], dim=-1)
62
+
63
+ # zero pad
64
+ if embedding_dim % 2 == 1:
65
+ emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
66
+ return emb
67
+
68
+
69
+ def get_2d_sincos_pos_embed(
70
+ embed_dim, grid_size, cls_token=False, extra_tokens=0, interpolation_scale=1.0, base_size=16
71
+ ):
72
+ """
73
+ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or
74
+ [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
75
+ """
76
+ if isinstance(grid_size, int):
77
+ grid_size = (grid_size, grid_size)
78
+
79
+ grid_h = np.arange(grid_size[0], dtype=np.float32) / (grid_size[0] / base_size) / interpolation_scale
80
+ grid_w = np.arange(grid_size[1], dtype=np.float32) / (grid_size[1] / base_size) / interpolation_scale
81
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
82
+ grid = np.stack(grid, axis=0)
83
+
84
+ grid = grid.reshape([2, 1, grid_size[1], grid_size[0]])
85
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
86
+ if cls_token and extra_tokens > 0:
87
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
88
+ return pos_embed
89
+
90
+
91
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
92
+ if embed_dim % 2 != 0:
93
+ raise ValueError("embed_dim must be divisible by 2")
94
+
95
+ # use half of dimensions to encode grid_h
96
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
97
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
98
+
99
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
100
+ return emb
101
+
102
+
103
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
104
+ """
105
+ embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)
106
+ """
107
+ if embed_dim % 2 != 0:
108
+ raise ValueError("embed_dim must be divisible by 2")
109
+
110
+ omega = np.arange(embed_dim // 2, dtype=np.float64)
111
+ omega /= embed_dim / 2.0
112
+ omega = 1.0 / 10000**omega # (D/2,)
113
+
114
+ pos = pos.reshape(-1) # (M,)
115
+ out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
116
+
117
+ emb_sin = np.sin(out) # (M, D/2)
118
+ emb_cos = np.cos(out) # (M, D/2)
119
+
120
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
121
+ return emb
122
+
123
+
124
+ class PatchEmbed(nn.Module):
125
+ """2D Image to Patch Embedding"""
126
+
127
+ def __init__(
128
+ self,
129
+ height=224,
130
+ width=224,
131
+ patch_size=16,
132
+ in_channels=3,
133
+ embed_dim=768,
134
+ layer_norm=False,
135
+ flatten=True,
136
+ bias=True,
137
+ interpolation_scale=1,
138
+ ):
139
+ super().__init__()
140
+
141
+ num_patches = (height // patch_size) * (width // patch_size)
142
+ self.flatten = flatten
143
+ self.layer_norm = layer_norm
144
+
145
+ self.proj = nn.Conv2d(
146
+ in_channels, embed_dim, kernel_size=(patch_size, patch_size), stride=patch_size, bias=bias
147
+ )
148
+ if layer_norm:
149
+ self.norm = nn.LayerNorm(embed_dim, elementwise_affine=False, eps=1e-6)
150
+ else:
151
+ self.norm = None
152
+
153
+ self.patch_size = patch_size
154
+ # See:
155
+ # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L161
156
+ self.height, self.width = height // patch_size, width // patch_size
157
+ self.base_size = height // patch_size
158
+ self.interpolation_scale = interpolation_scale
159
+ pos_embed = get_2d_sincos_pos_embed(
160
+ embed_dim, int(num_patches**0.5), base_size=self.base_size, interpolation_scale=self.interpolation_scale
161
+ )
162
+ self.register_buffer("pos_embed", torch.from_numpy(pos_embed).float().unsqueeze(0), persistent=False)
163
+
164
+ def forward(self, latent):
165
+ height, width = latent.shape[-2] // self.patch_size, latent.shape[-1] // self.patch_size
166
+
167
+ latent = self.proj(latent)
168
+ if self.flatten:
169
+ latent = latent.flatten(2).transpose(1, 2) # BCHW -> BNC
170
+ if self.layer_norm:
171
+ latent = self.norm(latent)
172
+
173
+ # Interpolate positional embeddings if needed.
174
+ # (For PixArt-Alpha: https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L162C151-L162C160)
175
+ if self.height != height or self.width != width:
176
+ pos_embed = get_2d_sincos_pos_embed(
177
+ embed_dim=self.pos_embed.shape[-1],
178
+ grid_size=(height, width),
179
+ base_size=self.base_size,
180
+ interpolation_scale=self.interpolation_scale,
181
+ )
182
+ pos_embed = torch.from_numpy(pos_embed)
183
+ pos_embed = pos_embed.float().unsqueeze(0).to(latent.device)
184
+ else:
185
+ pos_embed = self.pos_embed
186
+
187
+ return (latent + pos_embed).to(latent.dtype)
188
+
189
+
190
+ class TimestepEmbedding(nn.Module):
191
+ def __init__(
192
+ self,
193
+ in_channels: int,
194
+ time_embed_dim: int,
195
+ act_fn: str = "silu",
196
+ out_dim: int = None,
197
+ post_act_fn: Optional[str] = None,
198
+ cond_proj_dim=None,
199
+ sample_proj_bias=True,
200
+ ):
201
+ super().__init__()
202
+ linear_cls = nn.Linear
203
+
204
+ self.linear_1 = linear_cls(in_channels, time_embed_dim, sample_proj_bias)
205
+
206
+ if cond_proj_dim is not None:
207
+ self.cond_proj = nn.Linear(cond_proj_dim, in_channels, bias=False)
208
+ else:
209
+ self.cond_proj = None
210
+
211
+ self.act = get_activation(act_fn)
212
+
213
+ if out_dim is not None:
214
+ time_embed_dim_out = out_dim
215
+ else:
216
+ time_embed_dim_out = time_embed_dim
217
+ self.linear_2 = linear_cls(time_embed_dim, time_embed_dim_out, sample_proj_bias)
218
+
219
+ if post_act_fn is None:
220
+ self.post_act = None
221
+ else:
222
+ self.post_act = get_activation(post_act_fn)
223
+
224
+ def forward(self, sample, condition=None):
225
+ if condition is not None:
226
+ sample = sample + self.cond_proj(condition)
227
+ sample = self.linear_1(sample)
228
+
229
+ if self.act is not None:
230
+ sample = self.act(sample)
231
+
232
+ sample = self.linear_2(sample)
233
+
234
+ if self.post_act is not None:
235
+ sample = self.post_act(sample)
236
+ return sample
237
+
238
+
239
+ class Timesteps(nn.Module):
240
+ def __init__(self, num_channels: int, flip_sin_to_cos: bool, downscale_freq_shift: float):
241
+ super().__init__()
242
+ self.num_channels = num_channels
243
+ self.flip_sin_to_cos = flip_sin_to_cos
244
+ self.downscale_freq_shift = downscale_freq_shift
245
+
246
+ def forward(self, timesteps):
247
+ t_emb = get_timestep_embedding(
248
+ timesteps,
249
+ self.num_channels,
250
+ flip_sin_to_cos=self.flip_sin_to_cos,
251
+ downscale_freq_shift=self.downscale_freq_shift,
252
+ )
253
+ return t_emb
254
+
255
+
256
+ class GaussianFourierProjection(nn.Module):
257
+ """Gaussian Fourier embeddings for noise levels."""
258
+
259
+ def __init__(
260
+ self, embedding_size: int = 256, scale: float = 1.0, set_W_to_weight=True, log=True, flip_sin_to_cos=False
261
+ ):
262
+ super().__init__()
263
+ self.weight = nn.Parameter(torch.randn(embedding_size) * scale, requires_grad=False)
264
+ self.log = log
265
+ self.flip_sin_to_cos = flip_sin_to_cos
266
+
267
+ if set_W_to_weight:
268
+ # to delete later
269
+ self.W = nn.Parameter(torch.randn(embedding_size) * scale, requires_grad=False)
270
+
271
+ self.weight = self.W
272
+
273
+ def forward(self, x):
274
+ if self.log:
275
+ x = torch.log(x)
276
+
277
+ x_proj = x[:, None] * self.weight[None, :] * 2 * np.pi
278
+
279
+ if self.flip_sin_to_cos:
280
+ out = torch.cat([torch.cos(x_proj), torch.sin(x_proj)], dim=-1)
281
+ else:
282
+ out = torch.cat([torch.sin(x_proj), torch.cos(x_proj)], dim=-1)
283
+ return out
284
+
285
+
286
+ class SinusoidalPositionalEmbedding(nn.Module):
287
+ """Apply positional information to a sequence of embeddings.
288
+
289
+ Takes in a sequence of embeddings with shape (batch_size, seq_length, embed_dim) and adds positional embeddings to
290
+ them
291
+
292
+ Args:
293
+ embed_dim: (int): Dimension of the positional embedding.
294
+ max_seq_length: Maximum sequence length to apply positional embeddings
295
+
296
+ """
297
+
298
+ def __init__(self, embed_dim: int, max_seq_length: int = 32):
299
+ super().__init__()
300
+ position = torch.arange(max_seq_length).unsqueeze(1)
301
+ div_term = torch.exp(torch.arange(0, embed_dim, 2) * (-math.log(10000.0) / embed_dim))
302
+ pe = torch.zeros(1, max_seq_length, embed_dim)
303
+ pe[0, :, 0::2] = torch.sin(position * div_term)
304
+ pe[0, :, 1::2] = torch.cos(position * div_term)
305
+ self.register_buffer("pe", pe)
306
+
307
+ def forward(self, x):
308
+ _, seq_length, _ = x.shape
309
+ x = x + self.pe[:, :seq_length]
310
+ return x
311
+
312
+
313
+ class ImagePositionalEmbeddings(nn.Module):
314
+ """
315
+ Converts latent image classes into vector embeddings. Sums the vector embeddings with positional embeddings for the
316
+ height and width of the latent space.
317
+
318
+ For more details, see figure 10 of the dall-e paper: https://arxiv.org/abs/2102.12092
319
+
320
+ For VQ-diffusion:
321
+
322
+ Output vector embeddings are used as input for the transformer.
323
+
324
+ Note that the vector embeddings for the transformer are different than the vector embeddings from the VQVAE.
325
+
326
+ Args:
327
+ num_embed (`int`):
328
+ Number of embeddings for the latent pixels embeddings.
329
+ height (`int`):
330
+ Height of the latent image i.e. the number of height embeddings.
331
+ width (`int`):
332
+ Width of the latent image i.e. the number of width embeddings.
333
+ embed_dim (`int`):
334
+ Dimension of the produced vector embeddings. Used for the latent pixel, height, and width embeddings.
335
+ """
336
+
337
+ def __init__(
338
+ self,
339
+ num_embed: int,
340
+ height: int,
341
+ width: int,
342
+ embed_dim: int,
343
+ ):
344
+ super().__init__()
345
+
346
+ self.height = height
347
+ self.width = width
348
+ self.num_embed = num_embed
349
+ self.embed_dim = embed_dim
350
+
351
+ self.emb = nn.Embedding(self.num_embed, embed_dim)
352
+ self.height_emb = nn.Embedding(self.height, embed_dim)
353
+ self.width_emb = nn.Embedding(self.width, embed_dim)
354
+
355
+ def forward(self, index):
356
+ emb = self.emb(index)
357
+
358
+ height_emb = self.height_emb(torch.arange(self.height, device=index.device).view(1, self.height))
359
+
360
+ # 1 x H x D -> 1 x H x 1 x D
361
+ height_emb = height_emb.unsqueeze(2)
362
+
363
+ width_emb = self.width_emb(torch.arange(self.width, device=index.device).view(1, self.width))
364
+
365
+ # 1 x W x D -> 1 x 1 x W x D
366
+ width_emb = width_emb.unsqueeze(1)
367
+
368
+ pos_emb = height_emb + width_emb
369
+
370
+ # 1 x H x W x D -> 1 x L xD
371
+ pos_emb = pos_emb.view(1, self.height * self.width, -1)
372
+
373
+ emb = emb + pos_emb[:, : emb.shape[1], :]
374
+
375
+ return emb
376
+
377
+
378
+ class LabelEmbedding(nn.Module):
379
+ """
380
+ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
381
+
382
+ Args:
383
+ num_classes (`int`): The number of classes.
384
+ hidden_size (`int`): The size of the vector embeddings.
385
+ dropout_prob (`float`): The probability of dropping a label.
386
+ """
387
+
388
+ def __init__(self, num_classes, hidden_size, dropout_prob):
389
+ super().__init__()
390
+ use_cfg_embedding = dropout_prob > 0
391
+ self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)
392
+ self.num_classes = num_classes
393
+ self.dropout_prob = dropout_prob
394
+
395
+ def token_drop(self, labels, force_drop_ids=None):
396
+ """
397
+ Drops labels to enable classifier-free guidance.
398
+ """
399
+ if force_drop_ids is None:
400
+ drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob
401
+ else:
402
+ drop_ids = torch.tensor(force_drop_ids == 1)
403
+ labels = torch.where(drop_ids, self.num_classes, labels)
404
+ return labels
405
+
406
+ def forward(self, labels: torch.LongTensor, force_drop_ids=None):
407
+ use_dropout = self.dropout_prob > 0
408
+ if (self.training and use_dropout) or (force_drop_ids is not None):
409
+ labels = self.token_drop(labels, force_drop_ids)
410
+ embeddings = self.embedding_table(labels)
411
+ return embeddings
412
+
413
+
414
+ class TextImageProjection(nn.Module):
415
+ def __init__(
416
+ self,
417
+ text_embed_dim: int = 1024,
418
+ image_embed_dim: int = 768,
419
+ cross_attention_dim: int = 768,
420
+ num_image_text_embeds: int = 10,
421
+ ):
422
+ super().__init__()
423
+
424
+ self.num_image_text_embeds = num_image_text_embeds
425
+ self.image_embeds = nn.Linear(image_embed_dim, self.num_image_text_embeds * cross_attention_dim)
426
+ self.text_proj = nn.Linear(text_embed_dim, cross_attention_dim)
427
+
428
+ def forward(self, text_embeds: torch.FloatTensor, image_embeds: torch.FloatTensor):
429
+ batch_size = text_embeds.shape[0]
430
+
431
+ # image
432
+ image_text_embeds = self.image_embeds(image_embeds)
433
+ image_text_embeds = image_text_embeds.reshape(batch_size, self.num_image_text_embeds, -1)
434
+
435
+ # text
436
+ text_embeds = self.text_proj(text_embeds)
437
+
438
+ return torch.cat([image_text_embeds, text_embeds], dim=1)
439
+
440
+
441
+ class ImageProjection(nn.Module):
442
+ def __init__(
443
+ self,
444
+ image_embed_dim: int = 768,
445
+ cross_attention_dim: int = 768,
446
+ num_image_text_embeds: int = 32,
447
+ ):
448
+ super().__init__()
449
+
450
+ self.num_image_text_embeds = num_image_text_embeds
451
+ self.image_embeds = nn.Linear(image_embed_dim, self.num_image_text_embeds * cross_attention_dim)
452
+ self.norm = nn.LayerNorm(cross_attention_dim)
453
+
454
+ def forward(self, image_embeds: torch.FloatTensor):
455
+ batch_size = image_embeds.shape[0]
456
+
457
+ # image
458
+ image_embeds = self.image_embeds(image_embeds)
459
+ image_embeds = image_embeds.reshape(batch_size, self.num_image_text_embeds, -1)
460
+ image_embeds = self.norm(image_embeds)
461
+ return image_embeds
462
+
463
+
464
+ class IPAdapterFullImageProjection(nn.Module):
465
+ def __init__(self, image_embed_dim=1024, cross_attention_dim=1024):
466
+ super().__init__()
467
+ from .attention import FeedForward
468
+
469
+ self.ff = FeedForward(image_embed_dim, cross_attention_dim, mult=1, activation_fn="gelu")
470
+ self.norm = nn.LayerNorm(cross_attention_dim)
471
+
472
+ def forward(self, image_embeds: torch.FloatTensor):
473
+ return self.norm(self.ff(image_embeds))
474
+
475
+
476
+ class CombinedTimestepLabelEmbeddings(nn.Module):
477
+ def __init__(self, num_classes, embedding_dim, class_dropout_prob=0.1):
478
+ super().__init__()
479
+
480
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=1)
481
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
482
+ self.class_embedder = LabelEmbedding(num_classes, embedding_dim, class_dropout_prob)
483
+
484
+ def forward(self, timestep, class_labels, hidden_dtype=None):
485
+ timesteps_proj = self.time_proj(timestep)
486
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype)) # (N, D)
487
+
488
+ class_labels = self.class_embedder(class_labels) # (N, D)
489
+
490
+ conditioning = timesteps_emb + class_labels # (N, D)
491
+
492
+ return conditioning
493
+
494
+
495
+ class TextTimeEmbedding(nn.Module):
496
+ def __init__(self, encoder_dim: int, time_embed_dim: int, num_heads: int = 64):
497
+ super().__init__()
498
+ self.norm1 = nn.LayerNorm(encoder_dim)
499
+ self.pool = AttentionPooling(num_heads, encoder_dim)
500
+ self.proj = nn.Linear(encoder_dim, time_embed_dim)
501
+ self.norm2 = nn.LayerNorm(time_embed_dim)
502
+
503
+ def forward(self, hidden_states):
504
+ hidden_states = self.norm1(hidden_states)
505
+ hidden_states = self.pool(hidden_states)
506
+ hidden_states = self.proj(hidden_states)
507
+ hidden_states = self.norm2(hidden_states)
508
+ return hidden_states
509
+
510
+
511
+ class TextImageTimeEmbedding(nn.Module):
512
+ def __init__(self, text_embed_dim: int = 768, image_embed_dim: int = 768, time_embed_dim: int = 1536):
513
+ super().__init__()
514
+ self.text_proj = nn.Linear(text_embed_dim, time_embed_dim)
515
+ self.text_norm = nn.LayerNorm(time_embed_dim)
516
+ self.image_proj = nn.Linear(image_embed_dim, time_embed_dim)
517
+
518
+ def forward(self, text_embeds: torch.FloatTensor, image_embeds: torch.FloatTensor):
519
+ # text
520
+ time_text_embeds = self.text_proj(text_embeds)
521
+ time_text_embeds = self.text_norm(time_text_embeds)
522
+
523
+ # image
524
+ time_image_embeds = self.image_proj(image_embeds)
525
+
526
+ return time_image_embeds + time_text_embeds
527
+
528
+
529
+ class ImageTimeEmbedding(nn.Module):
530
+ def __init__(self, image_embed_dim: int = 768, time_embed_dim: int = 1536):
531
+ super().__init__()
532
+ self.image_proj = nn.Linear(image_embed_dim, time_embed_dim)
533
+ self.image_norm = nn.LayerNorm(time_embed_dim)
534
+
535
+ def forward(self, image_embeds: torch.FloatTensor):
536
+ # image
537
+ time_image_embeds = self.image_proj(image_embeds)
538
+ time_image_embeds = self.image_norm(time_image_embeds)
539
+ return time_image_embeds
540
+
541
+
542
+ class ImageHintTimeEmbedding(nn.Module):
543
+ def __init__(self, image_embed_dim: int = 768, time_embed_dim: int = 1536):
544
+ super().__init__()
545
+ self.image_proj = nn.Linear(image_embed_dim, time_embed_dim)
546
+ self.image_norm = nn.LayerNorm(time_embed_dim)
547
+ self.input_hint_block = nn.Sequential(
548
+ nn.Conv2d(3, 16, 3, padding=1),
549
+ nn.SiLU(),
550
+ nn.Conv2d(16, 16, 3, padding=1),
551
+ nn.SiLU(),
552
+ nn.Conv2d(16, 32, 3, padding=1, stride=2),
553
+ nn.SiLU(),
554
+ nn.Conv2d(32, 32, 3, padding=1),
555
+ nn.SiLU(),
556
+ nn.Conv2d(32, 96, 3, padding=1, stride=2),
557
+ nn.SiLU(),
558
+ nn.Conv2d(96, 96, 3, padding=1),
559
+ nn.SiLU(),
560
+ nn.Conv2d(96, 256, 3, padding=1, stride=2),
561
+ nn.SiLU(),
562
+ nn.Conv2d(256, 4, 3, padding=1),
563
+ )
564
+
565
+ def forward(self, image_embeds: torch.FloatTensor, hint: torch.FloatTensor):
566
+ # image
567
+ time_image_embeds = self.image_proj(image_embeds)
568
+ time_image_embeds = self.image_norm(time_image_embeds)
569
+ hint = self.input_hint_block(hint)
570
+ return time_image_embeds, hint
571
+
572
+
573
+ class AttentionPooling(nn.Module):
574
+ # Copied from https://github.com/deep-floyd/IF/blob/2f91391f27dd3c468bf174be5805b4cc92980c0b/deepfloyd_if/model/nn.py#L54
575
+
576
+ def __init__(self, num_heads, embed_dim, dtype=None):
577
+ super().__init__()
578
+ self.dtype = dtype
579
+ self.positional_embedding = nn.Parameter(torch.randn(1, embed_dim) / embed_dim**0.5)
580
+ self.k_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype)
581
+ self.q_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype)
582
+ self.v_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype)
583
+ self.num_heads = num_heads
584
+ self.dim_per_head = embed_dim // self.num_heads
585
+
586
+ def forward(self, x):
587
+ bs, length, width = x.size()
588
+
589
+ def shape(x):
590
+ # (bs, length, width) --> (bs, length, n_heads, dim_per_head)
591
+ x = x.view(bs, -1, self.num_heads, self.dim_per_head)
592
+ # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
593
+ x = x.transpose(1, 2)
594
+ # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
595
+ x = x.reshape(bs * self.num_heads, -1, self.dim_per_head)
596
+ # (bs*n_heads, length, dim_per_head) --> (bs*n_heads, dim_per_head, length)
597
+ x = x.transpose(1, 2)
598
+ return x
599
+
600
+ class_token = x.mean(dim=1, keepdim=True) + self.positional_embedding.to(x.dtype)
601
+ x = torch.cat([class_token, x], dim=1) # (bs, length+1, width)
602
+
603
+ # (bs*n_heads, class_token_length, dim_per_head)
604
+ q = shape(self.q_proj(class_token))
605
+ # (bs*n_heads, length+class_token_length, dim_per_head)
606
+ k = shape(self.k_proj(x))
607
+ v = shape(self.v_proj(x))
608
+
609
+ # (bs*n_heads, class_token_length, length+class_token_length):
610
+ scale = 1 / math.sqrt(math.sqrt(self.dim_per_head))
611
+ weight = torch.einsum("bct,bcs->bts", q * scale, k * scale) # More stable with f16 than dividing afterwards
612
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
613
+
614
+ # (bs*n_heads, dim_per_head, class_token_length)
615
+ a = torch.einsum("bts,bcs->bct", weight, v)
616
+
617
+ # (bs, length+1, width)
618
+ a = a.reshape(bs, -1, 1).transpose(1, 2)
619
+
620
+ return a[:, 0, :] # cls_token
621
+
622
+
623
+ def get_fourier_embeds_from_boundingbox(embed_dim, box):
624
+ """
625
+ Args:
626
+ embed_dim: int
627
+ box: a 3-D tensor [B x N x 4] representing the bounding boxes for GLIGEN pipeline
628
+ Returns:
629
+ [B x N x embed_dim] tensor of positional embeddings
630
+ """
631
+
632
+ batch_size, num_boxes = box.shape[:2]
633
+
634
+ emb = 100 ** (torch.arange(embed_dim) / embed_dim)
635
+ emb = emb[None, None, None].to(device=box.device, dtype=box.dtype)
636
+ emb = emb * box.unsqueeze(-1)
637
+
638
+ emb = torch.stack((emb.sin(), emb.cos()), dim=-1)
639
+ emb = emb.permute(0, 1, 3, 4, 2).reshape(batch_size, num_boxes, embed_dim * 2 * 4)
640
+
641
+ return emb
642
+
643
+
644
+ class GLIGENTextBoundingboxProjection(nn.Module):
645
+ def __init__(self, positive_len, out_dim, feature_type="text-only", fourier_freqs=8):
646
+ super().__init__()
647
+ self.positive_len = positive_len
648
+ self.out_dim = out_dim
649
+
650
+ self.fourier_embedder_dim = fourier_freqs
651
+ self.position_dim = fourier_freqs * 2 * 4 # 2: sin/cos, 4: xyxy
652
+
653
+ if isinstance(out_dim, tuple):
654
+ out_dim = out_dim[0]
655
+
656
+ if feature_type == "text-only":
657
+ self.linears = nn.Sequential(
658
+ nn.Linear(self.positive_len + self.position_dim, 512),
659
+ nn.SiLU(),
660
+ nn.Linear(512, 512),
661
+ nn.SiLU(),
662
+ nn.Linear(512, out_dim),
663
+ )
664
+ self.null_positive_feature = torch.nn.Parameter(torch.zeros([self.positive_len]))
665
+
666
+ elif feature_type == "text-image":
667
+ self.linears_text = nn.Sequential(
668
+ nn.Linear(self.positive_len + self.position_dim, 512),
669
+ nn.SiLU(),
670
+ nn.Linear(512, 512),
671
+ nn.SiLU(),
672
+ nn.Linear(512, out_dim),
673
+ )
674
+ self.linears_image = nn.Sequential(
675
+ nn.Linear(self.positive_len + self.position_dim, 512),
676
+ nn.SiLU(),
677
+ nn.Linear(512, 512),
678
+ nn.SiLU(),
679
+ nn.Linear(512, out_dim),
680
+ )
681
+ self.null_text_feature = torch.nn.Parameter(torch.zeros([self.positive_len]))
682
+ self.null_image_feature = torch.nn.Parameter(torch.zeros([self.positive_len]))
683
+
684
+ self.null_position_feature = torch.nn.Parameter(torch.zeros([self.position_dim]))
685
+
686
+ def forward(
687
+ self,
688
+ boxes,
689
+ masks,
690
+ positive_embeddings=None,
691
+ phrases_masks=None,
692
+ image_masks=None,
693
+ phrases_embeddings=None,
694
+ image_embeddings=None,
695
+ ):
696
+ masks = masks.unsqueeze(-1)
697
+
698
+ # embedding position (it may includes padding as placeholder)
699
+ xyxy_embedding = get_fourier_embeds_from_boundingbox(self.fourier_embedder_dim, boxes) # B*N*4 -> B*N*C
700
+
701
+ # learnable null embedding
702
+ xyxy_null = self.null_position_feature.view(1, 1, -1)
703
+
704
+ # replace padding with learnable null embedding
705
+ xyxy_embedding = xyxy_embedding * masks + (1 - masks) * xyxy_null
706
+
707
+ # positionet with text only information
708
+ if positive_embeddings is not None:
709
+ # learnable null embedding
710
+ positive_null = self.null_positive_feature.view(1, 1, -1)
711
+
712
+ # replace padding with learnable null embedding
713
+ positive_embeddings = positive_embeddings * masks + (1 - masks) * positive_null
714
+
715
+ objs = self.linears(torch.cat([positive_embeddings, xyxy_embedding], dim=-1))
716
+
717
+ # positionet with text and image infomation
718
+ else:
719
+ phrases_masks = phrases_masks.unsqueeze(-1)
720
+ image_masks = image_masks.unsqueeze(-1)
721
+
722
+ # learnable null embedding
723
+ text_null = self.null_text_feature.view(1, 1, -1)
724
+ image_null = self.null_image_feature.view(1, 1, -1)
725
+
726
+ # replace padding with learnable null embedding
727
+ phrases_embeddings = phrases_embeddings * phrases_masks + (1 - phrases_masks) * text_null
728
+ image_embeddings = image_embeddings * image_masks + (1 - image_masks) * image_null
729
+
730
+ objs_text = self.linears_text(torch.cat([phrases_embeddings, xyxy_embedding], dim=-1))
731
+ objs_image = self.linears_image(torch.cat([image_embeddings, xyxy_embedding], dim=-1))
732
+ objs = torch.cat([objs_text, objs_image], dim=1)
733
+
734
+ return objs
735
+
736
+
737
+ class PixArtAlphaCombinedTimestepSizeEmbeddings(nn.Module):
738
+ """
739
+ For PixArt-Alpha.
740
+
741
+ Reference:
742
+ https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L164C9-L168C29
743
+ """
744
+
745
+ def __init__(self, embedding_dim, size_emb_dim, use_additional_conditions: bool = False):
746
+ super().__init__()
747
+
748
+ self.outdim = size_emb_dim
749
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
750
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
751
+
752
+ self.use_additional_conditions = use_additional_conditions
753
+ if use_additional_conditions:
754
+ self.additional_condition_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
755
+ self.resolution_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=size_emb_dim)
756
+ self.aspect_ratio_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=size_emb_dim)
757
+
758
+ def forward(self, timestep, resolution, aspect_ratio, batch_size, hidden_dtype):
759
+ timesteps_proj = self.time_proj(timestep)
760
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype)) # (N, D)
761
+
762
+ if self.use_additional_conditions:
763
+ resolution_emb = self.additional_condition_proj(resolution.flatten()).to(hidden_dtype)
764
+ resolution_emb = self.resolution_embedder(resolution_emb).reshape(batch_size, -1)
765
+ aspect_ratio_emb = self.additional_condition_proj(aspect_ratio.flatten()).to(hidden_dtype)
766
+ aspect_ratio_emb = self.aspect_ratio_embedder(aspect_ratio_emb).reshape(batch_size, -1)
767
+ conditioning = timesteps_emb + torch.cat([resolution_emb, aspect_ratio_emb], dim=1)
768
+ else:
769
+ conditioning = timesteps_emb
770
+
771
+ return conditioning
772
+
773
+
774
+ class PixArtAlphaTextProjection(nn.Module):
775
+ """
776
+ Projects caption embeddings. Also handles dropout for classifier-free guidance.
777
+
778
+ Adapted from https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/nets/PixArt_blocks.py
779
+ """
780
+
781
+ def __init__(self, in_features, hidden_size, num_tokens=120):
782
+ super().__init__()
783
+ self.linear_1 = nn.Linear(in_features=in_features, out_features=hidden_size, bias=True)
784
+ self.act_1 = nn.GELU(approximate="tanh")
785
+ self.linear_2 = nn.Linear(in_features=hidden_size, out_features=hidden_size, bias=True)
786
+
787
+ def forward(self, caption):
788
+ hidden_states = self.linear_1(caption)
789
+ hidden_states = self.act_1(hidden_states)
790
+ hidden_states = self.linear_2(hidden_states)
791
+ return hidden_states
792
+
793
+
794
+ class IPAdapterPlusImageProjection(nn.Module):
795
+ """Resampler of IP-Adapter Plus.
796
+
797
+ Args:
798
+ ----
799
+ embed_dims (int): The feature dimension. Defaults to 768.
800
+ output_dims (int): The number of output channels, that is the same
801
+ number of the channels in the
802
+ `unet.config.cross_attention_dim`. Defaults to 1024.
803
+ hidden_dims (int): The number of hidden channels. Defaults to 1280.
804
+ depth (int): The number of blocks. Defaults to 8.
805
+ dim_head (int): The number of head channels. Defaults to 64.
806
+ heads (int): Parallel attention heads. Defaults to 16.
807
+ num_queries (int): The number of queries. Defaults to 8.
808
+ ffn_ratio (float): The expansion ratio of feedforward network hidden
809
+ layer channels. Defaults to 4.
810
+ """
811
+
812
+ def __init__(
813
+ self,
814
+ embed_dims: int = 768,
815
+ output_dims: int = 1024,
816
+ hidden_dims: int = 1280,
817
+ depth: int = 4,
818
+ dim_head: int = 64,
819
+ heads: int = 16,
820
+ num_queries: int = 8,
821
+ ffn_ratio: float = 4,
822
+ ) -> None:
823
+ super().__init__()
824
+ from .attention import FeedForward # Lazy import to avoid circular import
825
+
826
+ self.latents = nn.Parameter(torch.randn(1, num_queries, hidden_dims) / hidden_dims**0.5)
827
+
828
+ self.proj_in = nn.Linear(embed_dims, hidden_dims)
829
+
830
+ self.proj_out = nn.Linear(hidden_dims, output_dims)
831
+ self.norm_out = nn.LayerNorm(output_dims)
832
+
833
+ self.layers = nn.ModuleList([])
834
+ for _ in range(depth):
835
+ self.layers.append(
836
+ nn.ModuleList(
837
+ [
838
+ nn.LayerNorm(hidden_dims),
839
+ nn.LayerNorm(hidden_dims),
840
+ Attention(
841
+ query_dim=hidden_dims,
842
+ dim_head=dim_head,
843
+ heads=heads,
844
+ out_bias=False,
845
+ ),
846
+ nn.Sequential(
847
+ nn.LayerNorm(hidden_dims),
848
+ FeedForward(hidden_dims, hidden_dims, activation_fn="gelu", mult=ffn_ratio, bias=False),
849
+ ),
850
+ ]
851
+ )
852
+ )
853
+
854
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
855
+ """Forward pass.
856
+
857
+ Args:
858
+ ----
859
+ x (torch.Tensor): Input Tensor.
860
+
861
+ Returns:
862
+ -------
863
+ torch.Tensor: Output Tensor.
864
+ """
865
+ latents = self.latents.repeat(x.size(0), 1, 1)
866
+
867
+ x = self.proj_in(x)
868
+
869
+ for ln0, ln1, attn, ff in self.layers:
870
+ residual = latents
871
+
872
+ encoder_hidden_states = ln0(x)
873
+ latents = ln1(latents)
874
+ encoder_hidden_states = torch.cat([encoder_hidden_states, latents], dim=-2)
875
+ latents = attn(latents, encoder_hidden_states) + residual
876
+ latents = ff(latents) + latents
877
+
878
+ latents = self.proj_out(latents)
879
+ return self.norm_out(latents)
880
+
881
+
882
+ class MultiIPAdapterImageProjection(nn.Module):
883
+ def __init__(self, IPAdapterImageProjectionLayers: Union[List[nn.Module], Tuple[nn.Module]]):
884
+ super().__init__()
885
+ self.image_projection_layers = nn.ModuleList(IPAdapterImageProjectionLayers)
886
+
887
+ def forward(self, image_embeds: List[torch.FloatTensor]):
888
+ projected_image_embeds = []
889
+
890
+ # currently, we accept `image_embeds` as
891
+ # 1. a tensor (deprecated) with shape [batch_size, embed_dim] or [batch_size, sequence_length, embed_dim]
892
+ # 2. list of `n` tensors where `n` is number of ip-adapters, each tensor can hae shape [batch_size, num_images, embed_dim] or [batch_size, num_images, sequence_length, embed_dim]
893
+ if not isinstance(image_embeds, list):
894
+ deprecation_message = (
895
+ "You have passed a tensor as `image_embeds`.This is deprecated and will be removed in a future release."
896
+ " Please make sure to update your script to pass `image_embeds` as a list of tensors to supress this warning."
897
+ )
898
+ deprecate("image_embeds not a list", "1.0.0", deprecation_message, standard_warn=False)
899
+ image_embeds = [image_embeds.unsqueeze(1)]
900
+
901
+ if len(image_embeds) != len(self.image_projection_layers):
902
+ raise ValueError(
903
+ f"image_embeds must have the same length as image_projection_layers, got {len(image_embeds)} and {len(self.image_projection_layers)}"
904
+ )
905
+
906
+ for image_embed, image_projection_layer in zip(image_embeds, self.image_projection_layers):
907
+ batch_size, num_images = image_embed.shape[0], image_embed.shape[1]
908
+ image_embed = image_embed.reshape((batch_size * num_images,) + image_embed.shape[2:])
909
+ image_embed = image_projection_layer(image_embed)
910
+ image_embed = image_embed.reshape((batch_size, num_images) + image_embed.shape[1:])
911
+
912
+ projected_image_embeds.append(image_embed)
913
+
914
+ return projected_image_embeds
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/embeddings_flax.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import math
15
+
16
+ import flax.linen as nn
17
+ import jax.numpy as jnp
18
+
19
+
20
+ def get_sinusoidal_embeddings(
21
+ timesteps: jnp.ndarray,
22
+ embedding_dim: int,
23
+ freq_shift: float = 1,
24
+ min_timescale: float = 1,
25
+ max_timescale: float = 1.0e4,
26
+ flip_sin_to_cos: bool = False,
27
+ scale: float = 1.0,
28
+ ) -> jnp.ndarray:
29
+ """Returns the positional encoding (same as Tensor2Tensor).
30
+
31
+ Args:
32
+ timesteps: a 1-D Tensor of N indices, one per batch element.
33
+ These may be fractional.
34
+ embedding_dim: The number of output channels.
35
+ min_timescale: The smallest time unit (should probably be 0.0).
36
+ max_timescale: The largest time unit.
37
+ Returns:
38
+ a Tensor of timing signals [N, num_channels]
39
+ """
40
+ assert timesteps.ndim == 1, "Timesteps should be a 1d-array"
41
+ assert embedding_dim % 2 == 0, f"Embedding dimension {embedding_dim} should be even"
42
+ num_timescales = float(embedding_dim // 2)
43
+ log_timescale_increment = math.log(max_timescale / min_timescale) / (num_timescales - freq_shift)
44
+ inv_timescales = min_timescale * jnp.exp(jnp.arange(num_timescales, dtype=jnp.float32) * -log_timescale_increment)
45
+ emb = jnp.expand_dims(timesteps, 1) * jnp.expand_dims(inv_timescales, 0)
46
+
47
+ # scale embeddings
48
+ scaled_time = scale * emb
49
+
50
+ if flip_sin_to_cos:
51
+ signal = jnp.concatenate([jnp.cos(scaled_time), jnp.sin(scaled_time)], axis=1)
52
+ else:
53
+ signal = jnp.concatenate([jnp.sin(scaled_time), jnp.cos(scaled_time)], axis=1)
54
+ signal = jnp.reshape(signal, [jnp.shape(timesteps)[0], embedding_dim])
55
+ return signal
56
+
57
+
58
+ class FlaxTimestepEmbedding(nn.Module):
59
+ r"""
60
+ Time step Embedding Module. Learns embeddings for input time steps.
61
+
62
+ Args:
63
+ time_embed_dim (`int`, *optional*, defaults to `32`):
64
+ Time step embedding dimension
65
+ dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
66
+ Parameters `dtype`
67
+ """
68
+
69
+ time_embed_dim: int = 32
70
+ dtype: jnp.dtype = jnp.float32
71
+
72
+ @nn.compact
73
+ def __call__(self, temb):
74
+ temb = nn.Dense(self.time_embed_dim, dtype=self.dtype, name="linear_1")(temb)
75
+ temb = nn.silu(temb)
76
+ temb = nn.Dense(self.time_embed_dim, dtype=self.dtype, name="linear_2")(temb)
77
+ return temb
78
+
79
+
80
+ class FlaxTimesteps(nn.Module):
81
+ r"""
82
+ Wrapper Module for sinusoidal Time step Embeddings as described in https://arxiv.org/abs/2006.11239
83
+
84
+ Args:
85
+ dim (`int`, *optional*, defaults to `32`):
86
+ Time step embedding dimension
87
+ """
88
+
89
+ dim: int = 32
90
+ flip_sin_to_cos: bool = False
91
+ freq_shift: float = 1
92
+
93
+ @nn.compact
94
+ def __call__(self, timesteps):
95
+ return get_sinusoidal_embeddings(
96
+ timesteps, embedding_dim=self.dim, flip_sin_to_cos=self.flip_sin_to_cos, freq_shift=self.freq_shift
97
+ )
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/lora.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ # IMPORTANT: #
17
+ ###################################################################
18
+ # ----------------------------------------------------------------#
19
+ # This file is deprecated and will be removed soon #
20
+ # (as soon as PEFT will become a required dependency for LoRA) #
21
+ # ----------------------------------------------------------------#
22
+ ###################################################################
23
+
24
+ from typing import Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ from torch import nn
29
+
30
+ from ..utils import deprecate, logging
31
+ from ..utils.import_utils import is_transformers_available
32
+
33
+
34
+ if is_transformers_available():
35
+ from transformers import CLIPTextModel, CLIPTextModelWithProjection
36
+
37
+
38
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
39
+
40
+
41
+ def text_encoder_attn_modules(text_encoder):
42
+ attn_modules = []
43
+
44
+ if isinstance(text_encoder, (CLIPTextModel, CLIPTextModelWithProjection)):
45
+ for i, layer in enumerate(text_encoder.text_model.encoder.layers):
46
+ name = f"text_model.encoder.layers.{i}.self_attn"
47
+ mod = layer.self_attn
48
+ attn_modules.append((name, mod))
49
+ else:
50
+ raise ValueError(f"do not know how to get attention modules for: {text_encoder.__class__.__name__}")
51
+
52
+ return attn_modules
53
+
54
+
55
+ def text_encoder_mlp_modules(text_encoder):
56
+ mlp_modules = []
57
+
58
+ if isinstance(text_encoder, (CLIPTextModel, CLIPTextModelWithProjection)):
59
+ for i, layer in enumerate(text_encoder.text_model.encoder.layers):
60
+ mlp_mod = layer.mlp
61
+ name = f"text_model.encoder.layers.{i}.mlp"
62
+ mlp_modules.append((name, mlp_mod))
63
+ else:
64
+ raise ValueError(f"do not know how to get mlp modules for: {text_encoder.__class__.__name__}")
65
+
66
+ return mlp_modules
67
+
68
+
69
+ def adjust_lora_scale_text_encoder(text_encoder, lora_scale: float = 1.0):
70
+ for _, attn_module in text_encoder_attn_modules(text_encoder):
71
+ if isinstance(attn_module.q_proj, PatchedLoraProjection):
72
+ attn_module.q_proj.lora_scale = lora_scale
73
+ attn_module.k_proj.lora_scale = lora_scale
74
+ attn_module.v_proj.lora_scale = lora_scale
75
+ attn_module.out_proj.lora_scale = lora_scale
76
+
77
+ for _, mlp_module in text_encoder_mlp_modules(text_encoder):
78
+ if isinstance(mlp_module.fc1, PatchedLoraProjection):
79
+ mlp_module.fc1.lora_scale = lora_scale
80
+ mlp_module.fc2.lora_scale = lora_scale
81
+
82
+
83
+ class PatchedLoraProjection(torch.nn.Module):
84
+ def __init__(self, regular_linear_layer, lora_scale=1, network_alpha=None, rank=4, dtype=None):
85
+ deprecation_message = "Use of `PatchedLoraProjection` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
86
+ deprecate("PatchedLoraProjection", "1.0.0", deprecation_message)
87
+
88
+ super().__init__()
89
+ from ..models.lora import LoRALinearLayer
90
+
91
+ self.regular_linear_layer = regular_linear_layer
92
+
93
+ device = self.regular_linear_layer.weight.device
94
+
95
+ if dtype is None:
96
+ dtype = self.regular_linear_layer.weight.dtype
97
+
98
+ self.lora_linear_layer = LoRALinearLayer(
99
+ self.regular_linear_layer.in_features,
100
+ self.regular_linear_layer.out_features,
101
+ network_alpha=network_alpha,
102
+ device=device,
103
+ dtype=dtype,
104
+ rank=rank,
105
+ )
106
+
107
+ self.lora_scale = lora_scale
108
+
109
+ # overwrite PyTorch's `state_dict` to be sure that only the 'regular_linear_layer' weights are saved
110
+ # when saving the whole text encoder model and when LoRA is unloaded or fused
111
+ def state_dict(self, *args, destination=None, prefix="", keep_vars=False):
112
+ if self.lora_linear_layer is None:
113
+ return self.regular_linear_layer.state_dict(
114
+ *args, destination=destination, prefix=prefix, keep_vars=keep_vars
115
+ )
116
+
117
+ return super().state_dict(*args, destination=destination, prefix=prefix, keep_vars=keep_vars)
118
+
119
+ def _fuse_lora(self, lora_scale=1.0, safe_fusing=False):
120
+ if self.lora_linear_layer is None:
121
+ return
122
+
123
+ dtype, device = self.regular_linear_layer.weight.data.dtype, self.regular_linear_layer.weight.data.device
124
+
125
+ w_orig = self.regular_linear_layer.weight.data.float()
126
+ w_up = self.lora_linear_layer.up.weight.data.float()
127
+ w_down = self.lora_linear_layer.down.weight.data.float()
128
+
129
+ if self.lora_linear_layer.network_alpha is not None:
130
+ w_up = w_up * self.lora_linear_layer.network_alpha / self.lora_linear_layer.rank
131
+
132
+ fused_weight = w_orig + (lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
133
+
134
+ if safe_fusing and torch.isnan(fused_weight).any().item():
135
+ raise ValueError(
136
+ "This LoRA weight seems to be broken. "
137
+ f"Encountered NaN values when trying to fuse LoRA weights for {self}."
138
+ "LoRA weights will not be fused."
139
+ )
140
+
141
+ self.regular_linear_layer.weight.data = fused_weight.to(device=device, dtype=dtype)
142
+
143
+ # we can drop the lora layer now
144
+ self.lora_linear_layer = None
145
+
146
+ # offload the up and down matrices to CPU to not blow the memory
147
+ self.w_up = w_up.cpu()
148
+ self.w_down = w_down.cpu()
149
+ self.lora_scale = lora_scale
150
+
151
+ def _unfuse_lora(self):
152
+ if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None):
153
+ return
154
+
155
+ fused_weight = self.regular_linear_layer.weight.data
156
+ dtype, device = fused_weight.dtype, fused_weight.device
157
+
158
+ w_up = self.w_up.to(device=device).float()
159
+ w_down = self.w_down.to(device).float()
160
+
161
+ unfused_weight = fused_weight.float() - (self.lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
162
+ self.regular_linear_layer.weight.data = unfused_weight.to(device=device, dtype=dtype)
163
+
164
+ self.w_up = None
165
+ self.w_down = None
166
+
167
+ def forward(self, input):
168
+ if self.lora_scale is None:
169
+ self.lora_scale = 1.0
170
+ if self.lora_linear_layer is None:
171
+ return self.regular_linear_layer(input)
172
+ return self.regular_linear_layer(input) + (self.lora_scale * self.lora_linear_layer(input))
173
+
174
+
175
+ class LoRALinearLayer(nn.Module):
176
+ r"""
177
+ A linear layer that is used with LoRA.
178
+
179
+ Parameters:
180
+ in_features (`int`):
181
+ Number of input features.
182
+ out_features (`int`):
183
+ Number of output features.
184
+ rank (`int`, `optional`, defaults to 4):
185
+ The rank of the LoRA layer.
186
+ network_alpha (`float`, `optional`, defaults to `None`):
187
+ The value of the network alpha used for stable learning and preventing underflow. This value has the same
188
+ meaning as the `--network_alpha` option in the kohya-ss trainer script. See
189
+ https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
190
+ device (`torch.device`, `optional`, defaults to `None`):
191
+ The device to use for the layer's weights.
192
+ dtype (`torch.dtype`, `optional`, defaults to `None`):
193
+ The dtype to use for the layer's weights.
194
+ """
195
+
196
+ def __init__(
197
+ self,
198
+ in_features: int,
199
+ out_features: int,
200
+ rank: int = 4,
201
+ network_alpha: Optional[float] = None,
202
+ device: Optional[Union[torch.device, str]] = None,
203
+ dtype: Optional[torch.dtype] = None,
204
+ ):
205
+ super().__init__()
206
+
207
+ deprecation_message = "Use of `LoRALinearLayer` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
208
+ deprecate("LoRALinearLayer", "1.0.0", deprecation_message)
209
+
210
+ self.down = nn.Linear(in_features, rank, bias=False, device=device, dtype=dtype)
211
+ self.up = nn.Linear(rank, out_features, bias=False, device=device, dtype=dtype)
212
+ # This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script.
213
+ # See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
214
+ self.network_alpha = network_alpha
215
+ self.rank = rank
216
+ self.out_features = out_features
217
+ self.in_features = in_features
218
+
219
+ nn.init.normal_(self.down.weight, std=1 / rank)
220
+ nn.init.zeros_(self.up.weight)
221
+
222
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
223
+ orig_dtype = hidden_states.dtype
224
+ dtype = self.down.weight.dtype
225
+
226
+ down_hidden_states = self.down(hidden_states.to(dtype))
227
+ up_hidden_states = self.up(down_hidden_states)
228
+
229
+ if self.network_alpha is not None:
230
+ up_hidden_states *= self.network_alpha / self.rank
231
+
232
+ return up_hidden_states.to(orig_dtype)
233
+
234
+
235
+ class LoRAConv2dLayer(nn.Module):
236
+ r"""
237
+ A convolutional layer that is used with LoRA.
238
+
239
+ Parameters:
240
+ in_features (`int`):
241
+ Number of input features.
242
+ out_features (`int`):
243
+ Number of output features.
244
+ rank (`int`, `optional`, defaults to 4):
245
+ The rank of the LoRA layer.
246
+ kernel_size (`int` or `tuple` of two `int`, `optional`, defaults to 1):
247
+ The kernel size of the convolution.
248
+ stride (`int` or `tuple` of two `int`, `optional`, defaults to 1):
249
+ The stride of the convolution.
250
+ padding (`int` or `tuple` of two `int` or `str`, `optional`, defaults to 0):
251
+ The padding of the convolution.
252
+ network_alpha (`float`, `optional`, defaults to `None`):
253
+ The value of the network alpha used for stable learning and preventing underflow. This value has the same
254
+ meaning as the `--network_alpha` option in the kohya-ss trainer script. See
255
+ https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
256
+ """
257
+
258
+ def __init__(
259
+ self,
260
+ in_features: int,
261
+ out_features: int,
262
+ rank: int = 4,
263
+ kernel_size: Union[int, Tuple[int, int]] = (1, 1),
264
+ stride: Union[int, Tuple[int, int]] = (1, 1),
265
+ padding: Union[int, Tuple[int, int], str] = 0,
266
+ network_alpha: Optional[float] = None,
267
+ ):
268
+ super().__init__()
269
+
270
+ deprecation_message = "Use of `LoRAConv2dLayer` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
271
+ deprecate("LoRAConv2dLayer", "1.0.0", deprecation_message)
272
+
273
+ self.down = nn.Conv2d(in_features, rank, kernel_size=kernel_size, stride=stride, padding=padding, bias=False)
274
+ # according to the official kohya_ss trainer kernel_size are always fixed for the up layer
275
+ # # see: https://github.com/bmaltais/kohya_ss/blob/2accb1305979ba62f5077a23aabac23b4c37e935/networks/lora_diffusers.py#L129
276
+ self.up = nn.Conv2d(rank, out_features, kernel_size=(1, 1), stride=(1, 1), bias=False)
277
+
278
+ # This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script.
279
+ # See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
280
+ self.network_alpha = network_alpha
281
+ self.rank = rank
282
+
283
+ nn.init.normal_(self.down.weight, std=1 / rank)
284
+ nn.init.zeros_(self.up.weight)
285
+
286
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
287
+ orig_dtype = hidden_states.dtype
288
+ dtype = self.down.weight.dtype
289
+
290
+ down_hidden_states = self.down(hidden_states.to(dtype))
291
+ up_hidden_states = self.up(down_hidden_states)
292
+
293
+ if self.network_alpha is not None:
294
+ up_hidden_states *= self.network_alpha / self.rank
295
+
296
+ return up_hidden_states.to(orig_dtype)
297
+
298
+
299
+ class LoRACompatibleConv(nn.Conv2d):
300
+ """
301
+ A convolutional layer that can be used with LoRA.
302
+ """
303
+
304
+ def __init__(self, *args, lora_layer: Optional[LoRAConv2dLayer] = None, **kwargs):
305
+ deprecation_message = "Use of `LoRACompatibleConv` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
306
+ deprecate("LoRACompatibleConv", "1.0.0", deprecation_message)
307
+
308
+ super().__init__(*args, **kwargs)
309
+ self.lora_layer = lora_layer
310
+
311
+ def set_lora_layer(self, lora_layer: Optional[LoRAConv2dLayer]):
312
+ deprecation_message = "Use of `set_lora_layer()` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
313
+ deprecate("set_lora_layer", "1.0.0", deprecation_message)
314
+
315
+ self.lora_layer = lora_layer
316
+
317
+ def _fuse_lora(self, lora_scale: float = 1.0, safe_fusing: bool = False):
318
+ if self.lora_layer is None:
319
+ return
320
+
321
+ dtype, device = self.weight.data.dtype, self.weight.data.device
322
+
323
+ w_orig = self.weight.data.float()
324
+ w_up = self.lora_layer.up.weight.data.float()
325
+ w_down = self.lora_layer.down.weight.data.float()
326
+
327
+ if self.lora_layer.network_alpha is not None:
328
+ w_up = w_up * self.lora_layer.network_alpha / self.lora_layer.rank
329
+
330
+ fusion = torch.mm(w_up.flatten(start_dim=1), w_down.flatten(start_dim=1))
331
+ fusion = fusion.reshape((w_orig.shape))
332
+ fused_weight = w_orig + (lora_scale * fusion)
333
+
334
+ if safe_fusing and torch.isnan(fused_weight).any().item():
335
+ raise ValueError(
336
+ "This LoRA weight seems to be broken. "
337
+ f"Encountered NaN values when trying to fuse LoRA weights for {self}."
338
+ "LoRA weights will not be fused."
339
+ )
340
+
341
+ self.weight.data = fused_weight.to(device=device, dtype=dtype)
342
+
343
+ # we can drop the lora layer now
344
+ self.lora_layer = None
345
+
346
+ # offload the up and down matrices to CPU to not blow the memory
347
+ self.w_up = w_up.cpu()
348
+ self.w_down = w_down.cpu()
349
+ self._lora_scale = lora_scale
350
+
351
+ def _unfuse_lora(self):
352
+ if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None):
353
+ return
354
+
355
+ fused_weight = self.weight.data
356
+ dtype, device = fused_weight.data.dtype, fused_weight.data.device
357
+
358
+ self.w_up = self.w_up.to(device=device).float()
359
+ self.w_down = self.w_down.to(device).float()
360
+
361
+ fusion = torch.mm(self.w_up.flatten(start_dim=1), self.w_down.flatten(start_dim=1))
362
+ fusion = fusion.reshape((fused_weight.shape))
363
+ unfused_weight = fused_weight.float() - (self._lora_scale * fusion)
364
+ self.weight.data = unfused_weight.to(device=device, dtype=dtype)
365
+
366
+ self.w_up = None
367
+ self.w_down = None
368
+
369
+ def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
370
+ if self.padding_mode != "zeros":
371
+ hidden_states = F.pad(hidden_states, self._reversed_padding_repeated_twice, mode=self.padding_mode)
372
+ padding = (0, 0)
373
+ else:
374
+ padding = self.padding
375
+
376
+ original_outputs = F.conv2d(
377
+ hidden_states, self.weight, self.bias, self.stride, padding, self.dilation, self.groups
378
+ )
379
+
380
+ if self.lora_layer is None:
381
+ return original_outputs
382
+ else:
383
+ return original_outputs + (scale * self.lora_layer(hidden_states))
384
+
385
+
386
+ class LoRACompatibleLinear(nn.Linear):
387
+ """
388
+ A Linear layer that can be used with LoRA.
389
+ """
390
+
391
+ def __init__(self, *args, lora_layer: Optional[LoRALinearLayer] = None, **kwargs):
392
+ deprecation_message = "Use of `LoRACompatibleLinear` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
393
+ deprecate("LoRACompatibleLinear", "1.0.0", deprecation_message)
394
+
395
+ super().__init__(*args, **kwargs)
396
+ self.lora_layer = lora_layer
397
+
398
+ def set_lora_layer(self, lora_layer: Optional[LoRALinearLayer]):
399
+ deprecation_message = "Use of `set_lora_layer()` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
400
+ deprecate("set_lora_layer", "1.0.0", deprecation_message)
401
+ self.lora_layer = lora_layer
402
+
403
+ def _fuse_lora(self, lora_scale: float = 1.0, safe_fusing: bool = False):
404
+ if self.lora_layer is None:
405
+ return
406
+
407
+ dtype, device = self.weight.data.dtype, self.weight.data.device
408
+
409
+ w_orig = self.weight.data.float()
410
+ w_up = self.lora_layer.up.weight.data.float()
411
+ w_down = self.lora_layer.down.weight.data.float()
412
+
413
+ if self.lora_layer.network_alpha is not None:
414
+ w_up = w_up * self.lora_layer.network_alpha / self.lora_layer.rank
415
+
416
+ fused_weight = w_orig + (lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
417
+
418
+ if safe_fusing and torch.isnan(fused_weight).any().item():
419
+ raise ValueError(
420
+ "This LoRA weight seems to be broken. "
421
+ f"Encountered NaN values when trying to fuse LoRA weights for {self}."
422
+ "LoRA weights will not be fused."
423
+ )
424
+
425
+ self.weight.data = fused_weight.to(device=device, dtype=dtype)
426
+
427
+ # we can drop the lora layer now
428
+ self.lora_layer = None
429
+
430
+ # offload the up and down matrices to CPU to not blow the memory
431
+ self.w_up = w_up.cpu()
432
+ self.w_down = w_down.cpu()
433
+ self._lora_scale = lora_scale
434
+
435
+ def _unfuse_lora(self):
436
+ if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None):
437
+ return
438
+
439
+ fused_weight = self.weight.data
440
+ dtype, device = fused_weight.dtype, fused_weight.device
441
+
442
+ w_up = self.w_up.to(device=device).float()
443
+ w_down = self.w_down.to(device).float()
444
+
445
+ unfused_weight = fused_weight.float() - (self._lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
446
+ self.weight.data = unfused_weight.to(device=device, dtype=dtype)
447
+
448
+ self.w_up = None
449
+ self.w_down = None
450
+
451
+ def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
452
+ if self.lora_layer is None:
453
+ out = super().forward(hidden_states)
454
+ return out
455
+ else:
456
+ out = super().forward(hidden_states) + (scale * self.lora_layer(hidden_states))
457
+ return out
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/modeling_flax_utils.py ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import os
17
+ from pickle import UnpicklingError
18
+ from typing import Any, Dict, Union
19
+
20
+ import jax
21
+ import jax.numpy as jnp
22
+ import msgpack.exceptions
23
+ from flax.core.frozen_dict import FrozenDict, unfreeze
24
+ from flax.serialization import from_bytes, to_bytes
25
+ from flax.traverse_util import flatten_dict, unflatten_dict
26
+ from huggingface_hub import create_repo, hf_hub_download
27
+ from huggingface_hub.utils import (
28
+ EntryNotFoundError,
29
+ RepositoryNotFoundError,
30
+ RevisionNotFoundError,
31
+ validate_hf_hub_args,
32
+ )
33
+ from requests import HTTPError
34
+
35
+ from .. import __version__, is_torch_available
36
+ from ..utils import (
37
+ CONFIG_NAME,
38
+ FLAX_WEIGHTS_NAME,
39
+ HUGGINGFACE_CO_RESOLVE_ENDPOINT,
40
+ WEIGHTS_NAME,
41
+ PushToHubMixin,
42
+ logging,
43
+ )
44
+ from .modeling_flax_pytorch_utils import convert_pytorch_state_dict_to_flax
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+
50
+ class FlaxModelMixin(PushToHubMixin):
51
+ r"""
52
+ Base class for all Flax models.
53
+
54
+ [`FlaxModelMixin`] takes care of storing the model configuration and provides methods for loading, downloading and
55
+ saving models.
56
+
57
+ - **config_name** ([`str`]) -- Filename to save a model to when calling [`~FlaxModelMixin.save_pretrained`].
58
+ """
59
+
60
+ config_name = CONFIG_NAME
61
+ _automatically_saved_args = ["_diffusers_version", "_class_name", "_name_or_path"]
62
+ _flax_internal_args = ["name", "parent", "dtype"]
63
+
64
+ @classmethod
65
+ def _from_config(cls, config, **kwargs):
66
+ """
67
+ All context managers that the model should be initialized under go here.
68
+ """
69
+ return cls(config, **kwargs)
70
+
71
+ def _cast_floating_to(self, params: Union[Dict, FrozenDict], dtype: jnp.dtype, mask: Any = None) -> Any:
72
+ """
73
+ Helper method to cast floating-point values of given parameter `PyTree` to given `dtype`.
74
+ """
75
+
76
+ # taken from https://github.com/deepmind/jmp/blob/3a8318abc3292be38582794dbf7b094e6583b192/jmp/_src/policy.py#L27
77
+ def conditional_cast(param):
78
+ if isinstance(param, jnp.ndarray) and jnp.issubdtype(param.dtype, jnp.floating):
79
+ param = param.astype(dtype)
80
+ return param
81
+
82
+ if mask is None:
83
+ return jax.tree_map(conditional_cast, params)
84
+
85
+ flat_params = flatten_dict(params)
86
+ flat_mask, _ = jax.tree_flatten(mask)
87
+
88
+ for masked, key in zip(flat_mask, flat_params.keys()):
89
+ if masked:
90
+ param = flat_params[key]
91
+ flat_params[key] = conditional_cast(param)
92
+
93
+ return unflatten_dict(flat_params)
94
+
95
+ def to_bf16(self, params: Union[Dict, FrozenDict], mask: Any = None):
96
+ r"""
97
+ Cast the floating-point `params` to `jax.numpy.bfloat16`. This returns a new `params` tree and does not cast
98
+ the `params` in place.
99
+
100
+ This method can be used on a TPU to explicitly convert the model parameters to bfloat16 precision to do full
101
+ half-precision training or to save weights in bfloat16 for inference in order to save memory and improve speed.
102
+
103
+ Arguments:
104
+ params (`Union[Dict, FrozenDict]`):
105
+ A `PyTree` of model parameters.
106
+ mask (`Union[Dict, FrozenDict]`):
107
+ A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`
108
+ for params you want to cast, and `False` for those you want to skip.
109
+
110
+ Examples:
111
+
112
+ ```python
113
+ >>> from diffusers import FlaxUNet2DConditionModel
114
+
115
+ >>> # load model
116
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
117
+ >>> # By default, the model parameters will be in fp32 precision, to cast these to bfloat16 precision
118
+ >>> params = model.to_bf16(params)
119
+ >>> # If you don't want to cast certain parameters (for example layer norm bias and scale)
120
+ >>> # then pass the mask as follows
121
+ >>> from flax import traverse_util
122
+
123
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
124
+ >>> flat_params = traverse_util.flatten_dict(params)
125
+ >>> mask = {
126
+ ... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale"))
127
+ ... for path in flat_params
128
+ ... }
129
+ >>> mask = traverse_util.unflatten_dict(mask)
130
+ >>> params = model.to_bf16(params, mask)
131
+ ```"""
132
+ return self._cast_floating_to(params, jnp.bfloat16, mask)
133
+
134
+ def to_fp32(self, params: Union[Dict, FrozenDict], mask: Any = None):
135
+ r"""
136
+ Cast the floating-point `params` to `jax.numpy.float32`. This method can be used to explicitly convert the
137
+ model parameters to fp32 precision. This returns a new `params` tree and does not cast the `params` in place.
138
+
139
+ Arguments:
140
+ params (`Union[Dict, FrozenDict]`):
141
+ A `PyTree` of model parameters.
142
+ mask (`Union[Dict, FrozenDict]`):
143
+ A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`
144
+ for params you want to cast, and `False` for those you want to skip.
145
+
146
+ Examples:
147
+
148
+ ```python
149
+ >>> from diffusers import FlaxUNet2DConditionModel
150
+
151
+ >>> # Download model and configuration from huggingface.co
152
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
153
+ >>> # By default, the model params will be in fp32, to illustrate the use of this method,
154
+ >>> # we'll first cast to fp16 and back to fp32
155
+ >>> params = model.to_f16(params)
156
+ >>> # now cast back to fp32
157
+ >>> params = model.to_fp32(params)
158
+ ```"""
159
+ return self._cast_floating_to(params, jnp.float32, mask)
160
+
161
+ def to_fp16(self, params: Union[Dict, FrozenDict], mask: Any = None):
162
+ r"""
163
+ Cast the floating-point `params` to `jax.numpy.float16`. This returns a new `params` tree and does not cast the
164
+ `params` in place.
165
+
166
+ This method can be used on a GPU to explicitly convert the model parameters to float16 precision to do full
167
+ half-precision training or to save weights in float16 for inference in order to save memory and improve speed.
168
+
169
+ Arguments:
170
+ params (`Union[Dict, FrozenDict]`):
171
+ A `PyTree` of model parameters.
172
+ mask (`Union[Dict, FrozenDict]`):
173
+ A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`
174
+ for params you want to cast, and `False` for those you want to skip.
175
+
176
+ Examples:
177
+
178
+ ```python
179
+ >>> from diffusers import FlaxUNet2DConditionModel
180
+
181
+ >>> # load model
182
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
183
+ >>> # By default, the model params will be in fp32, to cast these to float16
184
+ >>> params = model.to_fp16(params)
185
+ >>> # If you want don't want to cast certain parameters (for example layer norm bias and scale)
186
+ >>> # then pass the mask as follows
187
+ >>> from flax import traverse_util
188
+
189
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
190
+ >>> flat_params = traverse_util.flatten_dict(params)
191
+ >>> mask = {
192
+ ... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale"))
193
+ ... for path in flat_params
194
+ ... }
195
+ >>> mask = traverse_util.unflatten_dict(mask)
196
+ >>> params = model.to_fp16(params, mask)
197
+ ```"""
198
+ return self._cast_floating_to(params, jnp.float16, mask)
199
+
200
+ def init_weights(self, rng: jax.Array) -> Dict:
201
+ raise NotImplementedError(f"init_weights method has to be implemented for {self}")
202
+
203
+ @classmethod
204
+ @validate_hf_hub_args
205
+ def from_pretrained(
206
+ cls,
207
+ pretrained_model_name_or_path: Union[str, os.PathLike],
208
+ dtype: jnp.dtype = jnp.float32,
209
+ *model_args,
210
+ **kwargs,
211
+ ):
212
+ r"""
213
+ Instantiate a pretrained Flax model from a pretrained model configuration.
214
+
215
+ Parameters:
216
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
217
+ Can be either:
218
+
219
+ - A string, the *model id* (for example `runwayml/stable-diffusion-v1-5`) of a pretrained model
220
+ hosted on the Hub.
221
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
222
+ using [`~FlaxModelMixin.save_pretrained`].
223
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
224
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
225
+ `jax.numpy.bfloat16` (on TPUs).
226
+
227
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
228
+ specified, all the computation will be performed with the given `dtype`.
229
+
230
+ <Tip>
231
+
232
+ This only specifies the dtype of the *computation* and does not influence the dtype of model
233
+ parameters.
234
+
235
+ If you wish to change the dtype of the model parameters, see [`~FlaxModelMixin.to_fp16`] and
236
+ [`~FlaxModelMixin.to_bf16`].
237
+
238
+ </Tip>
239
+
240
+ model_args (sequence of positional arguments, *optional*):
241
+ All remaining positional arguments are passed to the underlying model's `__init__` method.
242
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
243
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
244
+ is not used.
245
+ force_download (`bool`, *optional*, defaults to `False`):
246
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
247
+ cached versions if they exist.
248
+ resume_download (`bool`, *optional*, defaults to `False`):
249
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
250
+ incompletely downloaded files are deleted.
251
+ proxies (`Dict[str, str]`, *optional*):
252
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
253
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
254
+ local_files_only(`bool`, *optional*, defaults to `False`):
255
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
256
+ won't be downloaded from the Hub.
257
+ revision (`str`, *optional*, defaults to `"main"`):
258
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
259
+ allowed by Git.
260
+ from_pt (`bool`, *optional*, defaults to `False`):
261
+ Load the model weights from a PyTorch checkpoint save file.
262
+ kwargs (remaining dictionary of keyword arguments, *optional*):
263
+ Can be used to update the configuration object (after it is loaded) and initiate the model (for
264
+ example, `output_attentions=True`). Behaves differently depending on whether a `config` is provided or
265
+ automatically loaded:
266
+
267
+ - If a configuration is provided with `config`, `kwargs` are directly passed to the underlying
268
+ model's `__init__` method (we assume all relevant updates to the configuration have already been
269
+ done).
270
+ - If a configuration is not provided, `kwargs` are first passed to the configuration class
271
+ initialization function [`~ConfigMixin.from_config`]. Each key of the `kwargs` that corresponds
272
+ to a configuration attribute is used to override said attribute with the supplied `kwargs` value.
273
+ Remaining keys that do not correspond to any configuration attribute are passed to the underlying
274
+ model's `__init__` function.
275
+
276
+ Examples:
277
+
278
+ ```python
279
+ >>> from diffusers import FlaxUNet2DConditionModel
280
+
281
+ >>> # Download model and configuration from huggingface.co and cache.
282
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
283
+ >>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable).
284
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("./test/saved_model/")
285
+ ```
286
+
287
+ If you get the error message below, you need to finetune the weights for your downstream task:
288
+
289
+ ```bash
290
+ Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
291
+ - conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
292
+ You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
293
+ ```
294
+ """
295
+ config = kwargs.pop("config", None)
296
+ cache_dir = kwargs.pop("cache_dir", None)
297
+ force_download = kwargs.pop("force_download", False)
298
+ from_pt = kwargs.pop("from_pt", False)
299
+ resume_download = kwargs.pop("resume_download", False)
300
+ proxies = kwargs.pop("proxies", None)
301
+ local_files_only = kwargs.pop("local_files_only", False)
302
+ token = kwargs.pop("token", None)
303
+ revision = kwargs.pop("revision", None)
304
+ subfolder = kwargs.pop("subfolder", None)
305
+
306
+ user_agent = {
307
+ "diffusers": __version__,
308
+ "file_type": "model",
309
+ "framework": "flax",
310
+ }
311
+
312
+ # Load config if we don't provide one
313
+ if config is None:
314
+ config, unused_kwargs = cls.load_config(
315
+ pretrained_model_name_or_path,
316
+ cache_dir=cache_dir,
317
+ return_unused_kwargs=True,
318
+ force_download=force_download,
319
+ resume_download=resume_download,
320
+ proxies=proxies,
321
+ local_files_only=local_files_only,
322
+ token=token,
323
+ revision=revision,
324
+ subfolder=subfolder,
325
+ **kwargs,
326
+ )
327
+
328
+ model, model_kwargs = cls.from_config(config, dtype=dtype, return_unused_kwargs=True, **unused_kwargs)
329
+
330
+ # Load model
331
+ pretrained_path_with_subfolder = (
332
+ pretrained_model_name_or_path
333
+ if subfolder is None
334
+ else os.path.join(pretrained_model_name_or_path, subfolder)
335
+ )
336
+ if os.path.isdir(pretrained_path_with_subfolder):
337
+ if from_pt:
338
+ if not os.path.isfile(os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)):
339
+ raise EnvironmentError(
340
+ f"Error no file named {WEIGHTS_NAME} found in directory {pretrained_path_with_subfolder} "
341
+ )
342
+ model_file = os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)
343
+ elif os.path.isfile(os.path.join(pretrained_path_with_subfolder, FLAX_WEIGHTS_NAME)):
344
+ # Load from a Flax checkpoint
345
+ model_file = os.path.join(pretrained_path_with_subfolder, FLAX_WEIGHTS_NAME)
346
+ # Check if pytorch weights exist instead
347
+ elif os.path.isfile(os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)):
348
+ raise EnvironmentError(
349
+ f"{WEIGHTS_NAME} file found in directory {pretrained_path_with_subfolder}. Please load the model"
350
+ " using `from_pt=True`."
351
+ )
352
+ else:
353
+ raise EnvironmentError(
354
+ f"Error no file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME} found in directory "
355
+ f"{pretrained_path_with_subfolder}."
356
+ )
357
+ else:
358
+ try:
359
+ model_file = hf_hub_download(
360
+ pretrained_model_name_or_path,
361
+ filename=FLAX_WEIGHTS_NAME if not from_pt else WEIGHTS_NAME,
362
+ cache_dir=cache_dir,
363
+ force_download=force_download,
364
+ proxies=proxies,
365
+ resume_download=resume_download,
366
+ local_files_only=local_files_only,
367
+ token=token,
368
+ user_agent=user_agent,
369
+ subfolder=subfolder,
370
+ revision=revision,
371
+ )
372
+
373
+ except RepositoryNotFoundError:
374
+ raise EnvironmentError(
375
+ f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier "
376
+ "listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a "
377
+ "token having permission to this repo with `token` or log in with `huggingface-cli "
378
+ "login`."
379
+ )
380
+ except RevisionNotFoundError:
381
+ raise EnvironmentError(
382
+ f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for "
383
+ "this model name. Check the model page at "
384
+ f"'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
385
+ )
386
+ except EntryNotFoundError:
387
+ raise EnvironmentError(
388
+ f"{pretrained_model_name_or_path} does not appear to have a file named {FLAX_WEIGHTS_NAME}."
389
+ )
390
+ except HTTPError as err:
391
+ raise EnvironmentError(
392
+ f"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n"
393
+ f"{err}"
394
+ )
395
+ except ValueError:
396
+ raise EnvironmentError(
397
+ f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
398
+ f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
399
+ f" directory containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}.\nCheckout your"
400
+ " internet connection or see how to run the library in offline mode at"
401
+ " 'https://huggingface.co/docs/transformers/installation#offline-mode'."
402
+ )
403
+ except EnvironmentError:
404
+ raise EnvironmentError(
405
+ f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from "
406
+ "'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
407
+ f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
408
+ f"containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}."
409
+ )
410
+
411
+ if from_pt:
412
+ if is_torch_available():
413
+ from .modeling_utils import load_state_dict
414
+ else:
415
+ raise EnvironmentError(
416
+ "Can't load the model in PyTorch format because PyTorch is not installed. "
417
+ "Please, install PyTorch or use native Flax weights."
418
+ )
419
+
420
+ # Step 1: Get the pytorch file
421
+ pytorch_model_file = load_state_dict(model_file)
422
+
423
+ # Step 2: Convert the weights
424
+ state = convert_pytorch_state_dict_to_flax(pytorch_model_file, model)
425
+ else:
426
+ try:
427
+ with open(model_file, "rb") as state_f:
428
+ state = from_bytes(cls, state_f.read())
429
+ except (UnpicklingError, msgpack.exceptions.ExtraData) as e:
430
+ try:
431
+ with open(model_file) as f:
432
+ if f.read().startswith("version"):
433
+ raise OSError(
434
+ "You seem to have cloned a repository without having git-lfs installed. Please"
435
+ " install git-lfs and run `git lfs install` followed by `git lfs pull` in the"
436
+ " folder you cloned."
437
+ )
438
+ else:
439
+ raise ValueError from e
440
+ except (UnicodeDecodeError, ValueError):
441
+ raise EnvironmentError(f"Unable to convert {model_file} to Flax deserializable object. ")
442
+ # make sure all arrays are stored as jnp.ndarray
443
+ # NOTE: This is to prevent a bug this will be fixed in Flax >= v0.3.4:
444
+ # https://github.com/google/flax/issues/1261
445
+ state = jax.tree_util.tree_map(lambda x: jax.device_put(x, jax.local_devices(backend="cpu")[0]), state)
446
+
447
+ # flatten dicts
448
+ state = flatten_dict(state)
449
+
450
+ params_shape_tree = jax.eval_shape(model.init_weights, rng=jax.random.PRNGKey(0))
451
+ required_params = set(flatten_dict(unfreeze(params_shape_tree)).keys())
452
+
453
+ shape_state = flatten_dict(unfreeze(params_shape_tree))
454
+
455
+ missing_keys = required_params - set(state.keys())
456
+ unexpected_keys = set(state.keys()) - required_params
457
+
458
+ if missing_keys:
459
+ logger.warning(
460
+ f"The checkpoint {pretrained_model_name_or_path} is missing required keys: {missing_keys}. "
461
+ "Make sure to call model.init_weights to initialize the missing weights."
462
+ )
463
+ cls._missing_keys = missing_keys
464
+
465
+ for key in state.keys():
466
+ if key in shape_state and state[key].shape != shape_state[key].shape:
467
+ raise ValueError(
468
+ f"Trying to load the pretrained weight for {key} failed: checkpoint has shape "
469
+ f"{state[key].shape} which is incompatible with the model shape {shape_state[key].shape}. "
470
+ )
471
+
472
+ # remove unexpected keys to not be saved again
473
+ for unexpected_key in unexpected_keys:
474
+ del state[unexpected_key]
475
+
476
+ if len(unexpected_keys) > 0:
477
+ logger.warning(
478
+ f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when"
479
+ f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are"
480
+ f" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task or"
481
+ " with another architecture."
482
+ )
483
+ else:
484
+ logger.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n")
485
+
486
+ if len(missing_keys) > 0:
487
+ logger.warning(
488
+ f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
489
+ f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably"
490
+ " TRAIN this model on a down-stream task to be able to use it for predictions and inference."
491
+ )
492
+ else:
493
+ logger.info(
494
+ f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at"
495
+ f" {pretrained_model_name_or_path}.\nIf your task is similar to the task the model of the checkpoint"
496
+ f" was trained on, you can already use {model.__class__.__name__} for predictions without further"
497
+ " training."
498
+ )
499
+
500
+ return model, unflatten_dict(state)
501
+
502
+ def save_pretrained(
503
+ self,
504
+ save_directory: Union[str, os.PathLike],
505
+ params: Union[Dict, FrozenDict],
506
+ is_main_process: bool = True,
507
+ push_to_hub: bool = False,
508
+ **kwargs,
509
+ ):
510
+ """
511
+ Save a model and its configuration file to a directory so that it can be reloaded using the
512
+ [`~FlaxModelMixin.from_pretrained`] class method.
513
+
514
+ Arguments:
515
+ save_directory (`str` or `os.PathLike`):
516
+ Directory to save a model and its configuration file to. Will be created if it doesn't exist.
517
+ params (`Union[Dict, FrozenDict]`):
518
+ A `PyTree` of model parameters.
519
+ is_main_process (`bool`, *optional*, defaults to `True`):
520
+ Whether the process calling this is the main process or not. Useful during distributed training and you
521
+ need to call this function on all processes. In this case, set `is_main_process=True` only on the main
522
+ process to avoid race conditions.
523
+ push_to_hub (`bool`, *optional*, defaults to `False`):
524
+ Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
525
+ repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
526
+ namespace).
527
+ kwargs (`Dict[str, Any]`, *optional*):
528
+ Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
529
+ """
530
+ if os.path.isfile(save_directory):
531
+ logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
532
+ return
533
+
534
+ os.makedirs(save_directory, exist_ok=True)
535
+
536
+ if push_to_hub:
537
+ commit_message = kwargs.pop("commit_message", None)
538
+ private = kwargs.pop("private", False)
539
+ create_pr = kwargs.pop("create_pr", False)
540
+ token = kwargs.pop("token", None)
541
+ repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
542
+ repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id
543
+
544
+ model_to_save = self
545
+
546
+ # Attach architecture to the config
547
+ # Save the config
548
+ if is_main_process:
549
+ model_to_save.save_config(save_directory)
550
+
551
+ # save model
552
+ output_model_file = os.path.join(save_directory, FLAX_WEIGHTS_NAME)
553
+ with open(output_model_file, "wb") as f:
554
+ model_bytes = to_bytes(params)
555
+ f.write(model_bytes)
556
+
557
+ logger.info(f"Model weights saved in {output_model_file}")
558
+
559
+ if push_to_hub:
560
+ self._upload_folder(
561
+ save_directory,
562
+ repo_id,
563
+ token=token,
564
+ commit_message=commit_message,
565
+ create_pr=create_pr,
566
+ )
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/modeling_outputs.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ from ..utils import BaseOutput
4
+
5
+
6
+ @dataclass
7
+ class AutoencoderKLOutput(BaseOutput):
8
+ """
9
+ Output of AutoencoderKL encoding method.
10
+
11
+ Args:
12
+ latent_dist (`DiagonalGaussianDistribution`):
13
+ Encoded outputs of `Encoder` represented as the mean and logvar of `DiagonalGaussianDistribution`.
14
+ `DiagonalGaussianDistribution` allows for sampling latents from the distribution.
15
+ """
16
+
17
+ latent_dist: "DiagonalGaussianDistribution" # noqa: F821
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/modeling_utils.py ADDED
@@ -0,0 +1,1021 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
3
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import inspect
18
+ import itertools
19
+ import os
20
+ import re
21
+ from collections import OrderedDict
22
+ from functools import partial
23
+ from typing import Any, Callable, List, Optional, Tuple, Union
24
+
25
+ import safetensors
26
+ import torch
27
+ from huggingface_hub import create_repo
28
+ from huggingface_hub.utils import validate_hf_hub_args
29
+ from torch import Tensor, nn
30
+
31
+ from .. import __version__
32
+ from ..utils import (
33
+ CONFIG_NAME,
34
+ FLAX_WEIGHTS_NAME,
35
+ SAFETENSORS_FILE_EXTENSION,
36
+ SAFETENSORS_WEIGHTS_NAME,
37
+ WEIGHTS_NAME,
38
+ _add_variant,
39
+ _get_model_file,
40
+ deprecate,
41
+ is_accelerate_available,
42
+ is_torch_version,
43
+ logging,
44
+ )
45
+ from ..utils.hub_utils import PushToHubMixin, load_or_create_model_card, populate_model_card
46
+
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+
51
+ if is_torch_version(">=", "1.9.0"):
52
+ _LOW_CPU_MEM_USAGE_DEFAULT = True
53
+ else:
54
+ _LOW_CPU_MEM_USAGE_DEFAULT = False
55
+
56
+
57
+ if is_accelerate_available():
58
+ import accelerate
59
+ from accelerate.utils import set_module_tensor_to_device
60
+ from accelerate.utils.versions import is_torch_version
61
+
62
+
63
+ def get_parameter_device(parameter: torch.nn.Module) -> torch.device:
64
+ try:
65
+ parameters_and_buffers = itertools.chain(parameter.parameters(), parameter.buffers())
66
+ return next(parameters_and_buffers).device
67
+ except StopIteration:
68
+ # For torch.nn.DataParallel compatibility in PyTorch 1.5
69
+
70
+ def find_tensor_attributes(module: torch.nn.Module) -> List[Tuple[str, Tensor]]:
71
+ tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)]
72
+ return tuples
73
+
74
+ gen = parameter._named_members(get_members_fn=find_tensor_attributes)
75
+ first_tuple = next(gen)
76
+ return first_tuple[1].device
77
+
78
+
79
+ def get_parameter_dtype(parameter: torch.nn.Module) -> torch.dtype:
80
+ try:
81
+ params = tuple(parameter.parameters())
82
+ if len(params) > 0:
83
+ return params[0].dtype
84
+
85
+ buffers = tuple(parameter.buffers())
86
+ if len(buffers) > 0:
87
+ return buffers[0].dtype
88
+
89
+ except StopIteration:
90
+ # For torch.nn.DataParallel compatibility in PyTorch 1.5
91
+
92
+ def find_tensor_attributes(module: torch.nn.Module) -> List[Tuple[str, Tensor]]:
93
+ tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)]
94
+ return tuples
95
+
96
+ gen = parameter._named_members(get_members_fn=find_tensor_attributes)
97
+ first_tuple = next(gen)
98
+ return first_tuple[1].dtype
99
+
100
+
101
+ def load_state_dict(checkpoint_file: Union[str, os.PathLike], variant: Optional[str] = None):
102
+ """
103
+ Reads a checkpoint file, returning properly formatted errors if they arise.
104
+ """
105
+ try:
106
+ file_extension = os.path.basename(checkpoint_file).split(".")[-1]
107
+ if file_extension == SAFETENSORS_FILE_EXTENSION:
108
+ return safetensors.torch.load_file(checkpoint_file, device="cpu")
109
+ else:
110
+ return torch.load(checkpoint_file, map_location="cpu")
111
+ except Exception as e:
112
+ try:
113
+ with open(checkpoint_file) as f:
114
+ if f.read().startswith("version"):
115
+ raise OSError(
116
+ "You seem to have cloned a repository without having git-lfs installed. Please install "
117
+ "git-lfs and run `git lfs install` followed by `git lfs pull` in the folder "
118
+ "you cloned."
119
+ )
120
+ else:
121
+ raise ValueError(
122
+ f"Unable to locate the file {checkpoint_file} which is necessary to load this pretrained "
123
+ "model. Make sure you have saved the model properly."
124
+ ) from e
125
+ except (UnicodeDecodeError, ValueError):
126
+ raise OSError(
127
+ f"Unable to load weights from checkpoint file for '{checkpoint_file}' " f"at '{checkpoint_file}'. "
128
+ )
129
+
130
+
131
+ def load_model_dict_into_meta(
132
+ model,
133
+ state_dict: OrderedDict,
134
+ device: Optional[Union[str, torch.device]] = None,
135
+ dtype: Optional[Union[str, torch.dtype]] = None,
136
+ model_name_or_path: Optional[str] = None,
137
+ ) -> List[str]:
138
+ device = device or torch.device("cpu")
139
+ dtype = dtype or torch.float32
140
+
141
+ accepts_dtype = "dtype" in set(inspect.signature(set_module_tensor_to_device).parameters.keys())
142
+
143
+ unexpected_keys = []
144
+ empty_state_dict = model.state_dict()
145
+ for param_name, param in state_dict.items():
146
+ if param_name not in empty_state_dict:
147
+ unexpected_keys.append(param_name)
148
+ continue
149
+
150
+ if empty_state_dict[param_name].shape != param.shape:
151
+ model_name_or_path_str = f"{model_name_or_path} " if model_name_or_path is not None else ""
152
+ raise ValueError(
153
+ f"Cannot load {model_name_or_path_str}because {param_name} expected shape {empty_state_dict[param_name]}, but got {param.shape}. If you want to instead overwrite randomly initialized weights, please make sure to pass both `low_cpu_mem_usage=False` and `ignore_mismatched_sizes=True`. For more information, see also: https://github.com/huggingface/diffusers/issues/1619#issuecomment-1345604389 as an example."
154
+ )
155
+
156
+ if accepts_dtype:
157
+ set_module_tensor_to_device(model, param_name, device, value=param, dtype=dtype)
158
+ else:
159
+ set_module_tensor_to_device(model, param_name, device, value=param)
160
+ return unexpected_keys
161
+
162
+
163
+ def _load_state_dict_into_model(model_to_load, state_dict: OrderedDict) -> List[str]:
164
+ # Convert old format to new format if needed from a PyTorch state_dict
165
+ # copy state_dict so _load_from_state_dict can modify it
166
+ state_dict = state_dict.copy()
167
+ error_msgs = []
168
+
169
+ # PyTorch's `_load_from_state_dict` does not copy parameters in a module's descendants
170
+ # so we need to apply the function recursively.
171
+ def load(module: torch.nn.Module, prefix: str = ""):
172
+ args = (state_dict, prefix, {}, True, [], [], error_msgs)
173
+ module._load_from_state_dict(*args)
174
+
175
+ for name, child in module._modules.items():
176
+ if child is not None:
177
+ load(child, prefix + name + ".")
178
+
179
+ load(model_to_load)
180
+
181
+ return error_msgs
182
+
183
+
184
+ class ModelMixin(torch.nn.Module, PushToHubMixin):
185
+ r"""
186
+ Base class for all models.
187
+
188
+ [`ModelMixin`] takes care of storing the model configuration and provides methods for loading, downloading and
189
+ saving models.
190
+
191
+ - **config_name** ([`str`]) -- Filename to save a model to when calling [`~models.ModelMixin.save_pretrained`].
192
+ """
193
+
194
+ config_name = CONFIG_NAME
195
+ _automatically_saved_args = ["_diffusers_version", "_class_name", "_name_or_path"]
196
+ _supports_gradient_checkpointing = False
197
+ _keys_to_ignore_on_load_unexpected = None
198
+
199
+ def __init__(self):
200
+ super().__init__()
201
+
202
+ def __getattr__(self, name: str) -> Any:
203
+ """The only reason we overwrite `getattr` here is to gracefully deprecate accessing
204
+ config attributes directly. See https://github.com/huggingface/diffusers/pull/3129 We need to overwrite
205
+ __getattr__ here in addition so that we don't trigger `torch.nn.Module`'s __getattr__':
206
+ https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
207
+ """
208
+
209
+ is_in_config = "_internal_dict" in self.__dict__ and hasattr(self.__dict__["_internal_dict"], name)
210
+ is_attribute = name in self.__dict__
211
+
212
+ if is_in_config and not is_attribute:
213
+ deprecation_message = f"Accessing config attribute `{name}` directly via '{type(self).__name__}' object attribute is deprecated. Please access '{name}' over '{type(self).__name__}'s config object instead, e.g. 'unet.config.{name}'."
214
+ deprecate("direct config name access", "1.0.0", deprecation_message, standard_warn=False, stacklevel=3)
215
+ return self._internal_dict[name]
216
+
217
+ # call PyTorch's https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
218
+ return super().__getattr__(name)
219
+
220
+ @property
221
+ def is_gradient_checkpointing(self) -> bool:
222
+ """
223
+ Whether gradient checkpointing is activated for this model or not.
224
+ """
225
+ return any(hasattr(m, "gradient_checkpointing") and m.gradient_checkpointing for m in self.modules())
226
+
227
+ def enable_gradient_checkpointing(self) -> None:
228
+ """
229
+ Activates gradient checkpointing for the current model (may be referred to as *activation checkpointing* or
230
+ *checkpoint activations* in other frameworks).
231
+ """
232
+ if not self._supports_gradient_checkpointing:
233
+ raise ValueError(f"{self.__class__.__name__} does not support gradient checkpointing.")
234
+ self.apply(partial(self._set_gradient_checkpointing, value=True))
235
+
236
+ def disable_gradient_checkpointing(self) -> None:
237
+ """
238
+ Deactivates gradient checkpointing for the current model (may be referred to as *activation checkpointing* or
239
+ *checkpoint activations* in other frameworks).
240
+ """
241
+ if self._supports_gradient_checkpointing:
242
+ self.apply(partial(self._set_gradient_checkpointing, value=False))
243
+
244
+ def set_use_memory_efficient_attention_xformers(
245
+ self, valid: bool, attention_op: Optional[Callable] = None
246
+ ) -> None:
247
+ # Recursively walk through all the children.
248
+ # Any children which exposes the set_use_memory_efficient_attention_xformers method
249
+ # gets the message
250
+ def fn_recursive_set_mem_eff(module: torch.nn.Module):
251
+ if hasattr(module, "set_use_memory_efficient_attention_xformers"):
252
+ module.set_use_memory_efficient_attention_xformers(valid, attention_op)
253
+
254
+ for child in module.children():
255
+ fn_recursive_set_mem_eff(child)
256
+
257
+ for module in self.children():
258
+ if isinstance(module, torch.nn.Module):
259
+ fn_recursive_set_mem_eff(module)
260
+
261
+ def enable_xformers_memory_efficient_attention(self, attention_op: Optional[Callable] = None) -> None:
262
+ r"""
263
+ Enable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).
264
+
265
+ When this option is enabled, you should observe lower GPU memory usage and a potential speed up during
266
+ inference. Speed up during training is not guaranteed.
267
+
268
+ <Tip warning={true}>
269
+
270
+ ⚠️ When memory efficient attention and sliced attention are both enabled, memory efficient attention takes
271
+ precedent.
272
+
273
+ </Tip>
274
+
275
+ Parameters:
276
+ attention_op (`Callable`, *optional*):
277
+ Override the default `None` operator for use as `op` argument to the
278
+ [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention)
279
+ function of xFormers.
280
+
281
+ Examples:
282
+
283
+ ```py
284
+ >>> import torch
285
+ >>> from diffusers import UNet2DConditionModel
286
+ >>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp
287
+
288
+ >>> model = UNet2DConditionModel.from_pretrained(
289
+ ... "stabilityai/stable-diffusion-2-1", subfolder="unet", torch_dtype=torch.float16
290
+ ... )
291
+ >>> model = model.to("cuda")
292
+ >>> model.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
293
+ ```
294
+ """
295
+ self.set_use_memory_efficient_attention_xformers(True, attention_op)
296
+
297
+ def disable_xformers_memory_efficient_attention(self) -> None:
298
+ r"""
299
+ Disable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).
300
+ """
301
+ self.set_use_memory_efficient_attention_xformers(False)
302
+
303
+ def save_pretrained(
304
+ self,
305
+ save_directory: Union[str, os.PathLike],
306
+ is_main_process: bool = True,
307
+ save_function: Optional[Callable] = None,
308
+ safe_serialization: bool = True,
309
+ variant: Optional[str] = None,
310
+ push_to_hub: bool = False,
311
+ **kwargs,
312
+ ):
313
+ """
314
+ Save a model and its configuration file to a directory so that it can be reloaded using the
315
+ [`~models.ModelMixin.from_pretrained`] class method.
316
+
317
+ Arguments:
318
+ save_directory (`str` or `os.PathLike`):
319
+ Directory to save a model and its configuration file to. Will be created if it doesn't exist.
320
+ is_main_process (`bool`, *optional*, defaults to `True`):
321
+ Whether the process calling this is the main process or not. Useful during distributed training and you
322
+ need to call this function on all processes. In this case, set `is_main_process=True` only on the main
323
+ process to avoid race conditions.
324
+ save_function (`Callable`):
325
+ The function to use to save the state dictionary. Useful during distributed training when you need to
326
+ replace `torch.save` with another method. Can be configured with the environment variable
327
+ `DIFFUSERS_SAVE_MODE`.
328
+ safe_serialization (`bool`, *optional*, defaults to `True`):
329
+ Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
330
+ variant (`str`, *optional*):
331
+ If specified, weights are saved in the format `pytorch_model.<variant>.bin`.
332
+ push_to_hub (`bool`, *optional*, defaults to `False`):
333
+ Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
334
+ repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
335
+ namespace).
336
+ kwargs (`Dict[str, Any]`, *optional*):
337
+ Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
338
+ """
339
+ if os.path.isfile(save_directory):
340
+ logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
341
+ return
342
+
343
+ os.makedirs(save_directory, exist_ok=True)
344
+
345
+ if push_to_hub:
346
+ commit_message = kwargs.pop("commit_message", None)
347
+ private = kwargs.pop("private", False)
348
+ create_pr = kwargs.pop("create_pr", False)
349
+ token = kwargs.pop("token", None)
350
+ repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
351
+ repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id
352
+
353
+ # Only save the model itself if we are using distributed training
354
+ model_to_save = self
355
+
356
+ # Attach architecture to the config
357
+ # Save the config
358
+ if is_main_process:
359
+ model_to_save.save_config(save_directory)
360
+
361
+ # Save the model
362
+ state_dict = model_to_save.state_dict()
363
+
364
+ weights_name = SAFETENSORS_WEIGHTS_NAME if safe_serialization else WEIGHTS_NAME
365
+ weights_name = _add_variant(weights_name, variant)
366
+
367
+ # Save the model
368
+ if safe_serialization:
369
+ safetensors.torch.save_file(
370
+ state_dict, os.path.join(save_directory, weights_name), metadata={"format": "pt"}
371
+ )
372
+ else:
373
+ torch.save(state_dict, os.path.join(save_directory, weights_name))
374
+
375
+ logger.info(f"Model weights saved in {os.path.join(save_directory, weights_name)}")
376
+
377
+ if push_to_hub:
378
+ # Create a new empty model card and eventually tag it
379
+ model_card = load_or_create_model_card(repo_id, token=token)
380
+ model_card = populate_model_card(model_card)
381
+ model_card.save(os.path.join(save_directory, "README.md"))
382
+
383
+ self._upload_folder(
384
+ save_directory,
385
+ repo_id,
386
+ token=token,
387
+ commit_message=commit_message,
388
+ create_pr=create_pr,
389
+ )
390
+
391
+ @classmethod
392
+ @validate_hf_hub_args
393
+ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
394
+ r"""
395
+ Instantiate a pretrained PyTorch model from a pretrained model configuration.
396
+
397
+ The model is set in evaluation mode - `model.eval()` - by default, and dropout modules are deactivated. To
398
+ train the model, set it back in training mode with `model.train()`.
399
+
400
+ Parameters:
401
+ pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
402
+ Can be either:
403
+
404
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
405
+ the Hub.
406
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
407
+ with [`~ModelMixin.save_pretrained`].
408
+
409
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
410
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
411
+ is not used.
412
+ torch_dtype (`str` or `torch.dtype`, *optional*):
413
+ Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
414
+ dtype is automatically derived from the model's weights.
415
+ force_download (`bool`, *optional*, defaults to `False`):
416
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
417
+ cached versions if they exist.
418
+ resume_download (`bool`, *optional*, defaults to `False`):
419
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
420
+ incompletely downloaded files are deleted.
421
+ proxies (`Dict[str, str]`, *optional*):
422
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
423
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
424
+ output_loading_info (`bool`, *optional*, defaults to `False`):
425
+ Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
426
+ local_files_only(`bool`, *optional*, defaults to `False`):
427
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
428
+ won't be downloaded from the Hub.
429
+ token (`str` or *bool*, *optional*):
430
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
431
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
432
+ revision (`str`, *optional*, defaults to `"main"`):
433
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
434
+ allowed by Git.
435
+ from_flax (`bool`, *optional*, defaults to `False`):
436
+ Load the model weights from a Flax checkpoint save file.
437
+ subfolder (`str`, *optional*, defaults to `""`):
438
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
439
+ mirror (`str`, *optional*):
440
+ Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
441
+ guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
442
+ information.
443
+ device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
444
+ A map that specifies where each submodule should go. It doesn't need to be defined for each
445
+ parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
446
+ same device.
447
+
448
+ Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
449
+ more information about each option see [designing a device
450
+ map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
451
+ max_memory (`Dict`, *optional*):
452
+ A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
453
+ each GPU and the available CPU RAM if unset.
454
+ offload_folder (`str` or `os.PathLike`, *optional*):
455
+ The path to offload weights if `device_map` contains the value `"disk"`.
456
+ offload_state_dict (`bool`, *optional*):
457
+ If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if
458
+ the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True`
459
+ when there is some disk offload.
460
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
461
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
462
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
463
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
464
+ argument to `True` will raise an error.
465
+ variant (`str`, *optional*):
466
+ Load weights from a specified `variant` filename such as `"fp16"` or `"ema"`. This is ignored when
467
+ loading `from_flax`.
468
+ use_safetensors (`bool`, *optional*, defaults to `None`):
469
+ If set to `None`, the `safetensors` weights are downloaded if they're available **and** if the
470
+ `safetensors` library is installed. If set to `True`, the model is forcibly loaded from `safetensors`
471
+ weights. If set to `False`, `safetensors` weights are not loaded.
472
+
473
+ <Tip>
474
+
475
+ To use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models), log-in with
476
+ `huggingface-cli login`. You can also activate the special
477
+ ["offline-mode"](https://huggingface.co/diffusers/installation.html#offline-mode) to use this method in a
478
+ firewalled environment.
479
+
480
+ </Tip>
481
+
482
+ Example:
483
+
484
+ ```py
485
+ from diffusers import UNet2DConditionModel
486
+
487
+ unet = UNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5", subfolder="unet")
488
+ ```
489
+
490
+ If you get the error message below, you need to finetune the weights for your downstream task:
491
+
492
+ ```bash
493
+ Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
494
+ - conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
495
+ You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
496
+ ```
497
+ """
498
+ cache_dir = kwargs.pop("cache_dir", None)
499
+ ignore_mismatched_sizes = kwargs.pop("ignore_mismatched_sizes", False)
500
+ force_download = kwargs.pop("force_download", False)
501
+ from_flax = kwargs.pop("from_flax", False)
502
+ resume_download = kwargs.pop("resume_download", False)
503
+ proxies = kwargs.pop("proxies", None)
504
+ output_loading_info = kwargs.pop("output_loading_info", False)
505
+ local_files_only = kwargs.pop("local_files_only", None)
506
+ token = kwargs.pop("token", None)
507
+ revision = kwargs.pop("revision", None)
508
+ torch_dtype = kwargs.pop("torch_dtype", None)
509
+ subfolder = kwargs.pop("subfolder", None)
510
+ device_map = kwargs.pop("device_map", None)
511
+ max_memory = kwargs.pop("max_memory", None)
512
+ offload_folder = kwargs.pop("offload_folder", None)
513
+ offload_state_dict = kwargs.pop("offload_state_dict", False)
514
+ low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
515
+ variant = kwargs.pop("variant", None)
516
+ use_safetensors = kwargs.pop("use_safetensors", None)
517
+
518
+ allow_pickle = False
519
+ if use_safetensors is None:
520
+ use_safetensors = True
521
+ allow_pickle = True
522
+
523
+ if low_cpu_mem_usage and not is_accelerate_available():
524
+ low_cpu_mem_usage = False
525
+ logger.warning(
526
+ "Cannot initialize model with low cpu memory usage because `accelerate` was not found in the"
527
+ " environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install"
528
+ " `accelerate` for faster and less memory-intense model loading. You can do so with: \n```\npip"
529
+ " install accelerate\n```\n."
530
+ )
531
+
532
+ if device_map is not None and not is_accelerate_available():
533
+ raise NotImplementedError(
534
+ "Loading and dispatching requires `accelerate`. Please make sure to install accelerate or set"
535
+ " `device_map=None`. You can install accelerate with `pip install accelerate`."
536
+ )
537
+
538
+ # Check if we can handle device_map and dispatching the weights
539
+ if device_map is not None and not is_torch_version(">=", "1.9.0"):
540
+ raise NotImplementedError(
541
+ "Loading and dispatching requires torch >= 1.9.0. Please either update your PyTorch version or set"
542
+ " `device_map=None`."
543
+ )
544
+
545
+ if low_cpu_mem_usage is True and not is_torch_version(">=", "1.9.0"):
546
+ raise NotImplementedError(
547
+ "Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set"
548
+ " `low_cpu_mem_usage=False`."
549
+ )
550
+
551
+ if low_cpu_mem_usage is False and device_map is not None:
552
+ raise ValueError(
553
+ f"You cannot set `low_cpu_mem_usage` to `False` while using device_map={device_map} for loading and"
554
+ " dispatching. Please make sure to set `low_cpu_mem_usage=True`."
555
+ )
556
+
557
+ # Load config if we don't provide a configuration
558
+ config_path = pretrained_model_name_or_path
559
+
560
+ user_agent = {
561
+ "diffusers": __version__,
562
+ "file_type": "model",
563
+ "framework": "pytorch",
564
+ }
565
+
566
+ # load config
567
+ config, unused_kwargs, commit_hash = cls.load_config(
568
+ config_path,
569
+ cache_dir=cache_dir,
570
+ return_unused_kwargs=True,
571
+ return_commit_hash=True,
572
+ force_download=force_download,
573
+ resume_download=resume_download,
574
+ proxies=proxies,
575
+ local_files_only=local_files_only,
576
+ token=token,
577
+ revision=revision,
578
+ subfolder=subfolder,
579
+ device_map=device_map,
580
+ max_memory=max_memory,
581
+ offload_folder=offload_folder,
582
+ offload_state_dict=offload_state_dict,
583
+ user_agent=user_agent,
584
+ **kwargs,
585
+ )
586
+
587
+ # load model
588
+ model_file = None
589
+ if from_flax:
590
+ model_file = _get_model_file(
591
+ pretrained_model_name_or_path,
592
+ weights_name=FLAX_WEIGHTS_NAME,
593
+ cache_dir=cache_dir,
594
+ force_download=force_download,
595
+ resume_download=resume_download,
596
+ proxies=proxies,
597
+ local_files_only=local_files_only,
598
+ token=token,
599
+ revision=revision,
600
+ subfolder=subfolder,
601
+ user_agent=user_agent,
602
+ commit_hash=commit_hash,
603
+ )
604
+ model = cls.from_config(config, **unused_kwargs)
605
+
606
+ # Convert the weights
607
+ from .modeling_pytorch_flax_utils import load_flax_checkpoint_in_pytorch_model
608
+
609
+ model = load_flax_checkpoint_in_pytorch_model(model, model_file)
610
+ else:
611
+ if use_safetensors:
612
+ try:
613
+ model_file = _get_model_file(
614
+ pretrained_model_name_or_path,
615
+ weights_name=_add_variant(SAFETENSORS_WEIGHTS_NAME, variant),
616
+ cache_dir=cache_dir,
617
+ force_download=force_download,
618
+ resume_download=resume_download,
619
+ proxies=proxies,
620
+ local_files_only=local_files_only,
621
+ token=token,
622
+ revision=revision,
623
+ subfolder=subfolder,
624
+ user_agent=user_agent,
625
+ commit_hash=commit_hash,
626
+ )
627
+ except IOError as e:
628
+ if not allow_pickle:
629
+ raise e
630
+ pass
631
+ if model_file is None:
632
+ model_file = _get_model_file(
633
+ pretrained_model_name_or_path,
634
+ weights_name=_add_variant(WEIGHTS_NAME, variant),
635
+ cache_dir=cache_dir,
636
+ force_download=force_download,
637
+ resume_download=resume_download,
638
+ proxies=proxies,
639
+ local_files_only=local_files_only,
640
+ token=token,
641
+ revision=revision,
642
+ subfolder=subfolder,
643
+ user_agent=user_agent,
644
+ commit_hash=commit_hash,
645
+ )
646
+
647
+ if low_cpu_mem_usage:
648
+ # Instantiate model with empty weights
649
+ with accelerate.init_empty_weights():
650
+ model = cls.from_config(config, **unused_kwargs)
651
+
652
+ # if device_map is None, load the state dict and move the params from meta device to the cpu
653
+ if device_map is None:
654
+ param_device = "cpu"
655
+ state_dict = load_state_dict(model_file, variant=variant)
656
+ model._convert_deprecated_attention_blocks(state_dict)
657
+ # move the params from meta device to cpu
658
+ missing_keys = set(model.state_dict().keys()) - set(state_dict.keys())
659
+ if len(missing_keys) > 0:
660
+ raise ValueError(
661
+ f"Cannot load {cls} from {pretrained_model_name_or_path} because the following keys are"
662
+ f" missing: \n {', '.join(missing_keys)}. \n Please make sure to pass"
663
+ " `low_cpu_mem_usage=False` and `device_map=None` if you want to randomly initialize"
664
+ " those weights or else make sure your checkpoint file is correct."
665
+ )
666
+
667
+ unexpected_keys = load_model_dict_into_meta(
668
+ model,
669
+ state_dict,
670
+ device=param_device,
671
+ dtype=torch_dtype,
672
+ model_name_or_path=pretrained_model_name_or_path,
673
+ )
674
+
675
+ if cls._keys_to_ignore_on_load_unexpected is not None:
676
+ for pat in cls._keys_to_ignore_on_load_unexpected:
677
+ unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
678
+
679
+ if len(unexpected_keys) > 0:
680
+ logger.warning(
681
+ f"Some weights of the model checkpoint were not used when initializing {cls.__name__}: \n {[', '.join(unexpected_keys)]}"
682
+ )
683
+
684
+ else: # else let accelerate handle loading and dispatching.
685
+ # Load weights and dispatch according to the device_map
686
+ # by default the device_map is None and the weights are loaded on the CPU
687
+ try:
688
+ accelerate.load_checkpoint_and_dispatch(
689
+ model,
690
+ model_file,
691
+ device_map,
692
+ max_memory=max_memory,
693
+ offload_folder=offload_folder,
694
+ offload_state_dict=offload_state_dict,
695
+ dtype=torch_dtype,
696
+ )
697
+ except AttributeError as e:
698
+ # When using accelerate loading, we do not have the ability to load the state
699
+ # dict and rename the weight names manually. Additionally, accelerate skips
700
+ # torch loading conventions and directly writes into `module.{_buffers, _parameters}`
701
+ # (which look like they should be private variables?), so we can't use the standard hooks
702
+ # to rename parameters on load. We need to mimic the original weight names so the correct
703
+ # attributes are available. After we have loaded the weights, we convert the deprecated
704
+ # names to the new non-deprecated names. Then we _greatly encourage_ the user to convert
705
+ # the weights so we don't have to do this again.
706
+
707
+ if "'Attention' object has no attribute" in str(e):
708
+ logger.warning(
709
+ f"Taking `{str(e)}` while using `accelerate.load_checkpoint_and_dispatch` to mean {pretrained_model_name_or_path}"
710
+ " was saved with deprecated attention block weight names. We will load it with the deprecated attention block"
711
+ " names and convert them on the fly to the new attention block format. Please re-save the model after this conversion,"
712
+ " so we don't have to do the on the fly renaming in the future. If the model is from a hub checkpoint,"
713
+ " please also re-upload it or open a PR on the original repository."
714
+ )
715
+ model._temp_convert_self_to_deprecated_attention_blocks()
716
+ accelerate.load_checkpoint_and_dispatch(
717
+ model,
718
+ model_file,
719
+ device_map,
720
+ max_memory=max_memory,
721
+ offload_folder=offload_folder,
722
+ offload_state_dict=offload_state_dict,
723
+ dtype=torch_dtype,
724
+ )
725
+ model._undo_temp_convert_self_to_deprecated_attention_blocks()
726
+ else:
727
+ raise e
728
+
729
+ loading_info = {
730
+ "missing_keys": [],
731
+ "unexpected_keys": [],
732
+ "mismatched_keys": [],
733
+ "error_msgs": [],
734
+ }
735
+ else:
736
+ model = cls.from_config(config, **unused_kwargs)
737
+
738
+ state_dict = load_state_dict(model_file, variant=variant)
739
+ model._convert_deprecated_attention_blocks(state_dict)
740
+
741
+ model, missing_keys, unexpected_keys, mismatched_keys, error_msgs = cls._load_pretrained_model(
742
+ model,
743
+ state_dict,
744
+ model_file,
745
+ pretrained_model_name_or_path,
746
+ ignore_mismatched_sizes=ignore_mismatched_sizes,
747
+ )
748
+
749
+ loading_info = {
750
+ "missing_keys": missing_keys,
751
+ "unexpected_keys": unexpected_keys,
752
+ "mismatched_keys": mismatched_keys,
753
+ "error_msgs": error_msgs,
754
+ }
755
+
756
+ if torch_dtype is not None and not isinstance(torch_dtype, torch.dtype):
757
+ raise ValueError(
758
+ f"{torch_dtype} needs to be of type `torch.dtype`, e.g. `torch.float16`, but is {type(torch_dtype)}."
759
+ )
760
+ elif torch_dtype is not None:
761
+ model = model.to(torch_dtype)
762
+
763
+ model.register_to_config(_name_or_path=pretrained_model_name_or_path)
764
+
765
+ # Set model in evaluation mode to deactivate DropOut modules by default
766
+ model.eval()
767
+ if output_loading_info:
768
+ return model, loading_info
769
+
770
+ return model
771
+
772
+ @classmethod
773
+ def _load_pretrained_model(
774
+ cls,
775
+ model,
776
+ state_dict: OrderedDict,
777
+ resolved_archive_file,
778
+ pretrained_model_name_or_path: Union[str, os.PathLike],
779
+ ignore_mismatched_sizes: bool = False,
780
+ ):
781
+ # Retrieve missing & unexpected_keys
782
+ model_state_dict = model.state_dict()
783
+ loaded_keys = list(state_dict.keys())
784
+
785
+ expected_keys = list(model_state_dict.keys())
786
+
787
+ original_loaded_keys = loaded_keys
788
+
789
+ missing_keys = list(set(expected_keys) - set(loaded_keys))
790
+ unexpected_keys = list(set(loaded_keys) - set(expected_keys))
791
+
792
+ # Make sure we are able to load base models as well as derived models (with heads)
793
+ model_to_load = model
794
+
795
+ def _find_mismatched_keys(
796
+ state_dict,
797
+ model_state_dict,
798
+ loaded_keys,
799
+ ignore_mismatched_sizes,
800
+ ):
801
+ mismatched_keys = []
802
+ if ignore_mismatched_sizes:
803
+ for checkpoint_key in loaded_keys:
804
+ model_key = checkpoint_key
805
+
806
+ if (
807
+ model_key in model_state_dict
808
+ and state_dict[checkpoint_key].shape != model_state_dict[model_key].shape
809
+ ):
810
+ mismatched_keys.append(
811
+ (checkpoint_key, state_dict[checkpoint_key].shape, model_state_dict[model_key].shape)
812
+ )
813
+ del state_dict[checkpoint_key]
814
+ return mismatched_keys
815
+
816
+ if state_dict is not None:
817
+ # Whole checkpoint
818
+ mismatched_keys = _find_mismatched_keys(
819
+ state_dict,
820
+ model_state_dict,
821
+ original_loaded_keys,
822
+ ignore_mismatched_sizes,
823
+ )
824
+ error_msgs = _load_state_dict_into_model(model_to_load, state_dict)
825
+
826
+ if len(error_msgs) > 0:
827
+ error_msg = "\n\t".join(error_msgs)
828
+ if "size mismatch" in error_msg:
829
+ error_msg += (
830
+ "\n\tYou may consider adding `ignore_mismatched_sizes=True` in the model `from_pretrained` method."
831
+ )
832
+ raise RuntimeError(f"Error(s) in loading state_dict for {model.__class__.__name__}:\n\t{error_msg}")
833
+
834
+ if len(unexpected_keys) > 0:
835
+ logger.warning(
836
+ f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when"
837
+ f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are"
838
+ f" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task"
839
+ " or with another architecture (e.g. initializing a BertForSequenceClassification model from a"
840
+ " BertForPreTraining model).\n- This IS NOT expected if you are initializing"
841
+ f" {model.__class__.__name__} from the checkpoint of a model that you expect to be exactly"
842
+ " identical (initializing a BertForSequenceClassification model from a"
843
+ " BertForSequenceClassification model)."
844
+ )
845
+ else:
846
+ logger.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n")
847
+ if len(missing_keys) > 0:
848
+ logger.warning(
849
+ f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
850
+ f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably"
851
+ " TRAIN this model on a down-stream task to be able to use it for predictions and inference."
852
+ )
853
+ elif len(mismatched_keys) == 0:
854
+ logger.info(
855
+ f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at"
856
+ f" {pretrained_model_name_or_path}.\nIf your task is similar to the task the model of the"
857
+ f" checkpoint was trained on, you can already use {model.__class__.__name__} for predictions"
858
+ " without further training."
859
+ )
860
+ if len(mismatched_keys) > 0:
861
+ mismatched_warning = "\n".join(
862
+ [
863
+ f"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated"
864
+ for key, shape1, shape2 in mismatched_keys
865
+ ]
866
+ )
867
+ logger.warning(
868
+ f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
869
+ f" {pretrained_model_name_or_path} and are newly initialized because the shapes did not"
870
+ f" match:\n{mismatched_warning}\nYou should probably TRAIN this model on a down-stream task to be"
871
+ " able to use it for predictions and inference."
872
+ )
873
+
874
+ return model, missing_keys, unexpected_keys, mismatched_keys, error_msgs
875
+
876
+ @property
877
+ def device(self) -> torch.device:
878
+ """
879
+ `torch.device`: The device on which the module is (assuming that all the module parameters are on the same
880
+ device).
881
+ """
882
+ return get_parameter_device(self)
883
+
884
+ @property
885
+ def dtype(self) -> torch.dtype:
886
+ """
887
+ `torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype).
888
+ """
889
+ return get_parameter_dtype(self)
890
+
891
+ def num_parameters(self, only_trainable: bool = False, exclude_embeddings: bool = False) -> int:
892
+ """
893
+ Get number of (trainable or non-embedding) parameters in the module.
894
+
895
+ Args:
896
+ only_trainable (`bool`, *optional*, defaults to `False`):
897
+ Whether or not to return only the number of trainable parameters.
898
+ exclude_embeddings (`bool`, *optional*, defaults to `False`):
899
+ Whether or not to return only the number of non-embedding parameters.
900
+
901
+ Returns:
902
+ `int`: The number of parameters.
903
+
904
+ Example:
905
+
906
+ ```py
907
+ from diffusers import UNet2DConditionModel
908
+
909
+ model_id = "runwayml/stable-diffusion-v1-5"
910
+ unet = UNet2DConditionModel.from_pretrained(model_id, subfolder="unet")
911
+ unet.num_parameters(only_trainable=True)
912
+ 859520964
913
+ ```
914
+ """
915
+
916
+ if exclude_embeddings:
917
+ embedding_param_names = [
918
+ f"{name}.weight"
919
+ for name, module_type in self.named_modules()
920
+ if isinstance(module_type, torch.nn.Embedding)
921
+ ]
922
+ non_embedding_parameters = [
923
+ parameter for name, parameter in self.named_parameters() if name not in embedding_param_names
924
+ ]
925
+ return sum(p.numel() for p in non_embedding_parameters if p.requires_grad or not only_trainable)
926
+ else:
927
+ return sum(p.numel() for p in self.parameters() if p.requires_grad or not only_trainable)
928
+
929
+ def _convert_deprecated_attention_blocks(self, state_dict: OrderedDict) -> None:
930
+ deprecated_attention_block_paths = []
931
+
932
+ def recursive_find_attn_block(name, module):
933
+ if hasattr(module, "_from_deprecated_attn_block") and module._from_deprecated_attn_block:
934
+ deprecated_attention_block_paths.append(name)
935
+
936
+ for sub_name, sub_module in module.named_children():
937
+ sub_name = sub_name if name == "" else f"{name}.{sub_name}"
938
+ recursive_find_attn_block(sub_name, sub_module)
939
+
940
+ recursive_find_attn_block("", self)
941
+
942
+ # NOTE: we have to check if the deprecated parameters are in the state dict
943
+ # because it is possible we are loading from a state dict that was already
944
+ # converted
945
+
946
+ for path in deprecated_attention_block_paths:
947
+ # group_norm path stays the same
948
+
949
+ # query -> to_q
950
+ if f"{path}.query.weight" in state_dict:
951
+ state_dict[f"{path}.to_q.weight"] = state_dict.pop(f"{path}.query.weight")
952
+ if f"{path}.query.bias" in state_dict:
953
+ state_dict[f"{path}.to_q.bias"] = state_dict.pop(f"{path}.query.bias")
954
+
955
+ # key -> to_k
956
+ if f"{path}.key.weight" in state_dict:
957
+ state_dict[f"{path}.to_k.weight"] = state_dict.pop(f"{path}.key.weight")
958
+ if f"{path}.key.bias" in state_dict:
959
+ state_dict[f"{path}.to_k.bias"] = state_dict.pop(f"{path}.key.bias")
960
+
961
+ # value -> to_v
962
+ if f"{path}.value.weight" in state_dict:
963
+ state_dict[f"{path}.to_v.weight"] = state_dict.pop(f"{path}.value.weight")
964
+ if f"{path}.value.bias" in state_dict:
965
+ state_dict[f"{path}.to_v.bias"] = state_dict.pop(f"{path}.value.bias")
966
+
967
+ # proj_attn -> to_out.0
968
+ if f"{path}.proj_attn.weight" in state_dict:
969
+ state_dict[f"{path}.to_out.0.weight"] = state_dict.pop(f"{path}.proj_attn.weight")
970
+ if f"{path}.proj_attn.bias" in state_dict:
971
+ state_dict[f"{path}.to_out.0.bias"] = state_dict.pop(f"{path}.proj_attn.bias")
972
+
973
+ def _temp_convert_self_to_deprecated_attention_blocks(self) -> None:
974
+ deprecated_attention_block_modules = []
975
+
976
+ def recursive_find_attn_block(module):
977
+ if hasattr(module, "_from_deprecated_attn_block") and module._from_deprecated_attn_block:
978
+ deprecated_attention_block_modules.append(module)
979
+
980
+ for sub_module in module.children():
981
+ recursive_find_attn_block(sub_module)
982
+
983
+ recursive_find_attn_block(self)
984
+
985
+ for module in deprecated_attention_block_modules:
986
+ module.query = module.to_q
987
+ module.key = module.to_k
988
+ module.value = module.to_v
989
+ module.proj_attn = module.to_out[0]
990
+
991
+ # We don't _have_ to delete the old attributes, but it's helpful to ensure
992
+ # that _all_ the weights are loaded into the new attributes and we're not
993
+ # making an incorrect assumption that this model should be converted when
994
+ # it really shouldn't be.
995
+ del module.to_q
996
+ del module.to_k
997
+ del module.to_v
998
+ del module.to_out
999
+
1000
+ def _undo_temp_convert_self_to_deprecated_attention_blocks(self) -> None:
1001
+ deprecated_attention_block_modules = []
1002
+
1003
+ def recursive_find_attn_block(module) -> None:
1004
+ if hasattr(module, "_from_deprecated_attn_block") and module._from_deprecated_attn_block:
1005
+ deprecated_attention_block_modules.append(module)
1006
+
1007
+ for sub_module in module.children():
1008
+ recursive_find_attn_block(sub_module)
1009
+
1010
+ recursive_find_attn_block(self)
1011
+
1012
+ for module in deprecated_attention_block_modules:
1013
+ module.to_q = module.query
1014
+ module.to_k = module.key
1015
+ module.to_v = module.value
1016
+ module.to_out = nn.ModuleList([module.proj_attn, nn.Dropout(module.dropout)])
1017
+
1018
+ del module.query
1019
+ del module.key
1020
+ del module.value
1021
+ del module.proj_attn
evalkit_tf437/lib/python3.10/site-packages/diffusers/models/prior_transformer.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..utils import deprecate
2
+ from .transformers.prior_transformer import PriorTransformer, PriorTransformerOutput
3
+
4
+
5
+ class PriorTransformerOutput(PriorTransformerOutput):
6
+ deprecation_message = "Importing `PriorTransformerOutput` from `diffusers.models.prior_transformer` is deprecated and this will be removed in a future version. Please use `from diffusers.models.transformers.prior_transformer import PriorTransformerOutput`, instead."
7
+ deprecate("PriorTransformerOutput", "0.29", deprecation_message)
8
+
9
+
10
+ class PriorTransformer(PriorTransformer):
11
+ deprecation_message = "Importing `PriorTransformer` from `diffusers.models.prior_transformer` is deprecated and this will be removed in a future version. Please use `from diffusers.models.transformers.prior_transformer import PriorTransformer`, instead."
12
+ deprecate("PriorTransformer", "0.29", deprecation_message)