xiaoanyu123 commited on
Commit
d4e4ceb
·
verified ·
1 Parent(s): 0bbcd57

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. pythonProject/.venv/Lib/site-packages/accelerate/__pycache__/big_modeling.cpython-310.pyc +0 -0
  2. pythonProject/.venv/Lib/site-packages/accelerate/__pycache__/checkpointing.cpython-310.pyc +0 -0
  3. pythonProject/.venv/Lib/site-packages/certifi-2025.8.3.dist-info/INSTALLER +1 -0
  4. pythonProject/.venv/Lib/site-packages/certifi-2025.8.3.dist-info/METADATA +77 -0
  5. pythonProject/.venv/Lib/site-packages/certifi-2025.8.3.dist-info/RECORD +14 -0
  6. pythonProject/.venv/Lib/site-packages/certifi/__pycache__/__main__.cpython-310.pyc +0 -0
  7. pythonProject/.venv/Lib/site-packages/diffusers/pipelines/latent_consistency_models/__init__.py +50 -0
  8. pythonProject/.venv/Lib/site-packages/diffusers/pipelines/latent_consistency_models/__pycache__/__init__.cpython-310.pyc +0 -0
  9. pythonProject/.venv/Lib/site-packages/diffusers/pipelines/latent_consistency_models/__pycache__/pipeline_latent_consistency_img2img.cpython-310.pyc +0 -0
  10. pythonProject/.venv/Lib/site-packages/diffusers/pipelines/latent_consistency_models/__pycache__/pipeline_latent_consistency_text2img.cpython-310.pyc +0 -0
  11. pythonProject/.venv/Lib/site-packages/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +747 -0
  12. pythonProject/.venv/Lib/site-packages/numpy/f2py/_backends/_backend.py +46 -0
  13. pythonProject/.venv/Lib/site-packages/numpy/f2py/_backends/_distutils.py +75 -0
  14. pythonProject/.venv/Lib/site-packages/numpy/f2py/_backends/meson.build.template +55 -0
  15. pythonProject/.venv/Lib/site-packages/numpy/f2py/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  16. pythonProject/.venv/Lib/site-packages/numpy/f2py/tests/__pycache__/test_size.cpython-310.pyc +0 -0
  17. pythonProject/.venv/Lib/site-packages/numpy/f2py/tests/__pycache__/test_string.cpython-310.pyc +0 -0
  18. pythonProject/.venv/Lib/site-packages/numpy/f2py/tests/__pycache__/test_symbolic.cpython-310.pyc +0 -0
  19. pythonProject/.venv/Lib/site-packages/numpy/f2py/tests/__pycache__/test_value_attrspec.cpython-310.pyc +0 -0
  20. pythonProject/.venv/Lib/site-packages/numpy/f2py/tests/__pycache__/util.cpython-310.pyc +0 -0
pythonProject/.venv/Lib/site-packages/accelerate/__pycache__/big_modeling.cpython-310.pyc ADDED
Binary file (29.1 kB). View file
 
pythonProject/.venv/Lib/site-packages/accelerate/__pycache__/checkpointing.cpython-310.pyc ADDED
Binary file (9.7 kB). View file
 
pythonProject/.venv/Lib/site-packages/certifi-2025.8.3.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
pythonProject/.venv/Lib/site-packages/certifi-2025.8.3.dist-info/METADATA ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: certifi
3
+ Version: 2025.8.3
4
+ Summary: Python package for providing Mozilla's CA Bundle.
5
+ Home-page: https://github.com/certifi/python-certifi
6
+ Author: Kenneth Reitz
7
+ Author-email: me@kennethreitz.com
8
+ License: MPL-2.0
9
+ Project-URL: Source, https://github.com/certifi/python-certifi
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
13
+ Classifier: Natural Language :: English
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.7
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Requires-Python: >=3.7
25
+ License-File: LICENSE
26
+ Dynamic: author
27
+ Dynamic: author-email
28
+ Dynamic: classifier
29
+ Dynamic: description
30
+ Dynamic: home-page
31
+ Dynamic: license
32
+ Dynamic: license-file
33
+ Dynamic: project-url
34
+ Dynamic: requires-python
35
+ Dynamic: summary
36
+
37
+ Certifi: Python SSL Certificates
38
+ ================================
39
+
40
+ Certifi provides Mozilla's carefully curated collection of Root Certificates for
41
+ validating the trustworthiness of SSL certificates while verifying the identity
42
+ of TLS hosts. It has been extracted from the `Requests`_ project.
43
+
44
+ Installation
45
+ ------------
46
+
47
+ ``certifi`` is available on PyPI. Simply install it with ``pip``::
48
+
49
+ $ pip install certifi
50
+
51
+ Usage
52
+ -----
53
+
54
+ To reference the installed certificate authority (CA) bundle, you can use the
55
+ built-in function::
56
+
57
+ >>> import certifi
58
+
59
+ >>> certifi.where()
60
+ '/usr/local/lib/python3.7/site-packages/certifi/cacert.pem'
61
+
62
+ Or from the command line::
63
+
64
+ $ python -m certifi
65
+ /usr/local/lib/python3.7/site-packages/certifi/cacert.pem
66
+
67
+ Enjoy!
68
+
69
+ .. _`Requests`: https://requests.readthedocs.io/en/master/
70
+
71
+ Addition/Removal of Certificates
72
+ --------------------------------
73
+
74
+ Certifi does not support any addition/removal or other modification of the
75
+ CA trust store content. This project is intended to provide a reliable and
76
+ highly portable root of trust to python deployments. Look to upstream projects
77
+ for methods to use alternate trust.
pythonProject/.venv/Lib/site-packages/certifi-2025.8.3.dist-info/RECORD ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ certifi-2025.8.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ certifi-2025.8.3.dist-info/METADATA,sha256=z4sG3fosbP3nviub_TUpSb71z0bPmsp3Xa6ZIatGUe4,2422
3
+ certifi-2025.8.3.dist-info/RECORD,,
4
+ certifi-2025.8.3.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
5
+ certifi-2025.8.3.dist-info/licenses/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989
6
+ certifi-2025.8.3.dist-info/top_level.txt,sha256=KMu4vUCfsjLrkPbSNdgdekS-pVJzBAJFO__nI8NF6-U,8
7
+ certifi/__init__.py,sha256=0a5ro4KTYep37Oo0Z8TycCPXaDlOEtvuj2pNWZ_1t8Y,94
8
+ certifi/__main__.py,sha256=xBBoj905TUWBLRGANOcf7oi6e-3dMP4cEoG9OyMs11g,243
9
+ certifi/__pycache__/__init__.cpython-310.pyc,,
10
+ certifi/__pycache__/__main__.cpython-310.pyc,,
11
+ certifi/__pycache__/core.cpython-310.pyc,,
12
+ certifi/cacert.pem,sha256=kQLmo2RKBxumzb1KU2mPKRxKZLGEUKCLwEZUi221zIs,287634
13
+ certifi/core.py,sha256=XFXycndG5pf37ayeF8N32HUuDafsyhkVMbO4BAPWHa0,3394
14
+ certifi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
pythonProject/.venv/Lib/site-packages/certifi/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (415 Bytes). View file
 
pythonProject/.venv/Lib/site-packages/diffusers/pipelines/latent_consistency_models/__init__.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING
2
+
3
+ from ...utils import (
4
+ DIFFUSERS_SLOW_IMPORT,
5
+ OptionalDependencyNotAvailable,
6
+ _LazyModule,
7
+ get_objects_from_module,
8
+ is_torch_available,
9
+ is_transformers_available,
10
+ )
11
+
12
+
13
+ _dummy_objects = {}
14
+ _import_structure = {}
15
+
16
+
17
+ try:
18
+ if not (is_transformers_available() and is_torch_available()):
19
+ raise OptionalDependencyNotAvailable()
20
+ except OptionalDependencyNotAvailable:
21
+ from ...utils import dummy_torch_and_transformers_objects # noqa F403
22
+
23
+ _dummy_objects.update(get_objects_from_module(dummy_torch_and_transformers_objects))
24
+ else:
25
+ _import_structure["pipeline_latent_consistency_img2img"] = ["LatentConsistencyModelImg2ImgPipeline"]
26
+ _import_structure["pipeline_latent_consistency_text2img"] = ["LatentConsistencyModelPipeline"]
27
+
28
+ if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
29
+ try:
30
+ if not (is_transformers_available() and is_torch_available()):
31
+ raise OptionalDependencyNotAvailable()
32
+
33
+ except OptionalDependencyNotAvailable:
34
+ from ...utils.dummy_torch_and_transformers_objects import *
35
+ else:
36
+ from .pipeline_latent_consistency_img2img import LatentConsistencyModelImg2ImgPipeline
37
+ from .pipeline_latent_consistency_text2img import LatentConsistencyModelPipeline
38
+
39
+ else:
40
+ import sys
41
+
42
+ sys.modules[__name__] = _LazyModule(
43
+ __name__,
44
+ globals()["__file__"],
45
+ _import_structure,
46
+ module_spec=__spec__,
47
+ )
48
+
49
+ for name, value in _dummy_objects.items():
50
+ setattr(sys.modules[__name__], name, value)
pythonProject/.venv/Lib/site-packages/diffusers/pipelines/latent_consistency_models/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.2 kB). View file
 
pythonProject/.venv/Lib/site-packages/diffusers/pipelines/latent_consistency_models/__pycache__/pipeline_latent_consistency_img2img.cpython-310.pyc ADDED
Binary file (32.4 kB). View file
 
pythonProject/.venv/Lib/site-packages/diffusers/pipelines/latent_consistency_models/__pycache__/pipeline_latent_consistency_text2img.cpython-310.pyc ADDED
Binary file (30.2 kB). View file
 
pythonProject/.venv/Lib/site-packages/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py ADDED
@@ -0,0 +1,747 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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 inspect
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.utils.checkpoint
21
+ from transformers import PretrainedConfig, PreTrainedModel, PreTrainedTokenizer
22
+ from transformers.activations import ACT2FN
23
+ from transformers.modeling_outputs import BaseModelOutput
24
+ from transformers.utils import logging
25
+
26
+ from ...models import AutoencoderKL, UNet2DConditionModel, UNet2DModel, VQModel
27
+ from ...schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
28
+ from ...utils import is_torch_xla_available
29
+ from ...utils.torch_utils import randn_tensor
30
+ from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
31
+
32
+
33
+ if is_torch_xla_available():
34
+ import torch_xla.core.xla_model as xm
35
+
36
+ XLA_AVAILABLE = True
37
+ else:
38
+ XLA_AVAILABLE = False
39
+
40
+
41
+ class LDMTextToImagePipeline(DiffusionPipeline):
42
+ r"""
43
+ Pipeline for text-to-image generation using latent diffusion.
44
+
45
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
46
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
47
+
48
+ Parameters:
49
+ vqvae ([`VQModel`]):
50
+ Vector-quantized (VQ) model to encode and decode images to and from latent representations.
51
+ bert ([`LDMBertModel`]):
52
+ Text-encoder model based on [`~transformers.BERT`].
53
+ tokenizer ([`~transformers.BertTokenizer`]):
54
+ A `BertTokenizer` to tokenize text.
55
+ unet ([`UNet2DConditionModel`]):
56
+ A `UNet2DConditionModel` to denoise the encoded image latents.
57
+ scheduler ([`SchedulerMixin`]):
58
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
59
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
60
+ """
61
+
62
+ model_cpu_offload_seq = "bert->unet->vqvae"
63
+
64
+ def __init__(
65
+ self,
66
+ vqvae: Union[VQModel, AutoencoderKL],
67
+ bert: PreTrainedModel,
68
+ tokenizer: PreTrainedTokenizer,
69
+ unet: Union[UNet2DModel, UNet2DConditionModel],
70
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
71
+ ):
72
+ super().__init__()
73
+ self.register_modules(vqvae=vqvae, bert=bert, tokenizer=tokenizer, unet=unet, scheduler=scheduler)
74
+ self.vae_scale_factor = 2 ** (len(self.vqvae.config.block_out_channels) - 1)
75
+
76
+ @torch.no_grad()
77
+ def __call__(
78
+ self,
79
+ prompt: Union[str, List[str]],
80
+ height: Optional[int] = None,
81
+ width: Optional[int] = None,
82
+ num_inference_steps: Optional[int] = 50,
83
+ guidance_scale: Optional[float] = 1.0,
84
+ eta: Optional[float] = 0.0,
85
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
86
+ latents: Optional[torch.Tensor] = None,
87
+ output_type: Optional[str] = "pil",
88
+ return_dict: bool = True,
89
+ **kwargs,
90
+ ) -> Union[Tuple, ImagePipelineOutput]:
91
+ r"""
92
+ The call function to the pipeline for generation.
93
+
94
+ Args:
95
+ prompt (`str` or `List[str]`):
96
+ The prompt or prompts to guide the image generation.
97
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
98
+ The height in pixels of the generated image.
99
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
100
+ The width in pixels of the generated image.
101
+ num_inference_steps (`int`, *optional*, defaults to 50):
102
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
103
+ expense of slower inference.
104
+ guidance_scale (`float`, *optional*, defaults to 1.0):
105
+ A higher guidance scale value encourages the model to generate images closely linked to the text
106
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
107
+ generator (`torch.Generator`, *optional*):
108
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
109
+ generation deterministic.
110
+ latents (`torch.Tensor`, *optional*):
111
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
112
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
113
+ tensor is generated by sampling using the supplied random `generator`.
114
+ output_type (`str`, *optional*, defaults to `"pil"`):
115
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
116
+ return_dict (`bool`, *optional*, defaults to `True`):
117
+ Whether or not to return a [`ImagePipelineOutput`] instead of a plain tuple.
118
+
119
+ Example:
120
+
121
+ ```py
122
+ >>> from diffusers import DiffusionPipeline
123
+
124
+ >>> # load model and scheduler
125
+ >>> ldm = DiffusionPipeline.from_pretrained("CompVis/ldm-text2im-large-256")
126
+
127
+ >>> # run pipeline in inference (sample random noise and denoise)
128
+ >>> prompt = "A painting of a squirrel eating a burger"
129
+ >>> images = ldm([prompt], num_inference_steps=50, eta=0.3, guidance_scale=6).images
130
+
131
+ >>> # save images
132
+ >>> for idx, image in enumerate(images):
133
+ ... image.save(f"squirrel-{idx}.png")
134
+ ```
135
+
136
+ Returns:
137
+ [`~pipelines.ImagePipelineOutput`] or `tuple`:
138
+ If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
139
+ returned where the first element is a list with the generated images.
140
+ """
141
+ # 0. Default height and width to unet
142
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
143
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
144
+
145
+ if isinstance(prompt, str):
146
+ batch_size = 1
147
+ elif isinstance(prompt, list):
148
+ batch_size = len(prompt)
149
+ else:
150
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
151
+
152
+ if height % 8 != 0 or width % 8 != 0:
153
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
154
+
155
+ # get unconditional embeddings for classifier free guidance
156
+ if guidance_scale != 1.0:
157
+ uncond_input = self.tokenizer(
158
+ [""] * batch_size, padding="max_length", max_length=77, truncation=True, return_tensors="pt"
159
+ )
160
+ negative_prompt_embeds = self.bert(uncond_input.input_ids.to(self._execution_device))[0]
161
+
162
+ # get prompt text embeddings
163
+ text_input = self.tokenizer(prompt, padding="max_length", max_length=77, truncation=True, return_tensors="pt")
164
+ prompt_embeds = self.bert(text_input.input_ids.to(self._execution_device))[0]
165
+
166
+ # get the initial random noise unless the user supplied it
167
+ latents_shape = (batch_size, self.unet.config.in_channels, height // 8, width // 8)
168
+ if isinstance(generator, list) and len(generator) != batch_size:
169
+ raise ValueError(
170
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
171
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
172
+ )
173
+
174
+ if latents is None:
175
+ latents = randn_tensor(
176
+ latents_shape, generator=generator, device=self._execution_device, dtype=prompt_embeds.dtype
177
+ )
178
+ else:
179
+ if latents.shape != latents_shape:
180
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
181
+ latents = latents.to(self._execution_device)
182
+
183
+ self.scheduler.set_timesteps(num_inference_steps)
184
+
185
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
186
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
187
+
188
+ extra_kwargs = {}
189
+ if accepts_eta:
190
+ extra_kwargs["eta"] = eta
191
+
192
+ for t in self.progress_bar(self.scheduler.timesteps):
193
+ if guidance_scale == 1.0:
194
+ # guidance_scale of 1 means no guidance
195
+ latents_input = latents
196
+ context = prompt_embeds
197
+ else:
198
+ # For classifier free guidance, we need to do two forward passes.
199
+ # Here we concatenate the unconditional and text embeddings into a single batch
200
+ # to avoid doing two forward passes
201
+ latents_input = torch.cat([latents] * 2)
202
+ context = torch.cat([negative_prompt_embeds, prompt_embeds])
203
+
204
+ # predict the noise residual
205
+ noise_pred = self.unet(latents_input, t, encoder_hidden_states=context).sample
206
+ # perform guidance
207
+ if guidance_scale != 1.0:
208
+ noise_pred_uncond, noise_prediction_text = noise_pred.chunk(2)
209
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_prediction_text - noise_pred_uncond)
210
+
211
+ # compute the previous noisy sample x_t -> x_t-1
212
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_kwargs).prev_sample
213
+
214
+ if XLA_AVAILABLE:
215
+ xm.mark_step()
216
+
217
+ # scale and decode the image latents with vae
218
+ latents = 1 / self.vqvae.config.scaling_factor * latents
219
+ image = self.vqvae.decode(latents).sample
220
+
221
+ image = (image / 2 + 0.5).clamp(0, 1)
222
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
223
+ if output_type == "pil":
224
+ image = self.numpy_to_pil(image)
225
+
226
+ if not return_dict:
227
+ return (image,)
228
+
229
+ return ImagePipelineOutput(images=image)
230
+
231
+
232
+ ################################################################################
233
+ # Code for the text transformer model
234
+ ################################################################################
235
+ """ PyTorch LDMBERT model."""
236
+
237
+
238
+ logger = logging.get_logger(__name__)
239
+
240
+ LDMBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
241
+ "ldm-bert",
242
+ # See all LDMBert models at https://huggingface.co/models?filter=ldmbert
243
+ ]
244
+
245
+
246
+ LDMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
247
+ "ldm-bert": "https://huggingface.co/valhalla/ldm-bert/blob/main/config.json",
248
+ }
249
+
250
+
251
+ """ LDMBERT model configuration"""
252
+
253
+
254
+ class LDMBertConfig(PretrainedConfig):
255
+ model_type = "ldmbert"
256
+ keys_to_ignore_at_inference = ["past_key_values"]
257
+ attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
258
+
259
+ def __init__(
260
+ self,
261
+ vocab_size=30522,
262
+ max_position_embeddings=77,
263
+ encoder_layers=32,
264
+ encoder_ffn_dim=5120,
265
+ encoder_attention_heads=8,
266
+ head_dim=64,
267
+ encoder_layerdrop=0.0,
268
+ activation_function="gelu",
269
+ d_model=1280,
270
+ dropout=0.1,
271
+ attention_dropout=0.0,
272
+ activation_dropout=0.0,
273
+ init_std=0.02,
274
+ classifier_dropout=0.0,
275
+ scale_embedding=False,
276
+ use_cache=True,
277
+ pad_token_id=0,
278
+ **kwargs,
279
+ ):
280
+ self.vocab_size = vocab_size
281
+ self.max_position_embeddings = max_position_embeddings
282
+ self.d_model = d_model
283
+ self.encoder_ffn_dim = encoder_ffn_dim
284
+ self.encoder_layers = encoder_layers
285
+ self.encoder_attention_heads = encoder_attention_heads
286
+ self.head_dim = head_dim
287
+ self.dropout = dropout
288
+ self.attention_dropout = attention_dropout
289
+ self.activation_dropout = activation_dropout
290
+ self.activation_function = activation_function
291
+ self.init_std = init_std
292
+ self.encoder_layerdrop = encoder_layerdrop
293
+ self.classifier_dropout = classifier_dropout
294
+ self.use_cache = use_cache
295
+ self.num_hidden_layers = encoder_layers
296
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
297
+
298
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
299
+
300
+
301
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
302
+ """
303
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
304
+ """
305
+ bsz, src_len = mask.size()
306
+ tgt_len = tgt_len if tgt_len is not None else src_len
307
+
308
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
309
+
310
+ inverted_mask = 1.0 - expanded_mask
311
+
312
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
313
+
314
+
315
+ # Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->LDMBert
316
+ class LDMBertAttention(nn.Module):
317
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
318
+
319
+ def __init__(
320
+ self,
321
+ embed_dim: int,
322
+ num_heads: int,
323
+ head_dim: int,
324
+ dropout: float = 0.0,
325
+ is_decoder: bool = False,
326
+ bias: bool = False,
327
+ ):
328
+ super().__init__()
329
+ self.embed_dim = embed_dim
330
+ self.num_heads = num_heads
331
+ self.dropout = dropout
332
+ self.head_dim = head_dim
333
+ self.inner_dim = head_dim * num_heads
334
+
335
+ self.scaling = self.head_dim**-0.5
336
+ self.is_decoder = is_decoder
337
+
338
+ self.k_proj = nn.Linear(embed_dim, self.inner_dim, bias=bias)
339
+ self.v_proj = nn.Linear(embed_dim, self.inner_dim, bias=bias)
340
+ self.q_proj = nn.Linear(embed_dim, self.inner_dim, bias=bias)
341
+ self.out_proj = nn.Linear(self.inner_dim, embed_dim)
342
+
343
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
344
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
345
+
346
+ def forward(
347
+ self,
348
+ hidden_states: torch.Tensor,
349
+ key_value_states: Optional[torch.Tensor] = None,
350
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
351
+ attention_mask: Optional[torch.Tensor] = None,
352
+ layer_head_mask: Optional[torch.Tensor] = None,
353
+ output_attentions: bool = False,
354
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
355
+ """Input shape: Batch x Time x Channel"""
356
+
357
+ # if key_value_states are provided this layer is used as a cross-attention layer
358
+ # for the decoder
359
+ is_cross_attention = key_value_states is not None
360
+
361
+ bsz, tgt_len, _ = hidden_states.size()
362
+
363
+ # get query proj
364
+ query_states = self.q_proj(hidden_states) * self.scaling
365
+ # get key, value proj
366
+ if is_cross_attention and past_key_value is not None:
367
+ # reuse k,v, cross_attentions
368
+ key_states = past_key_value[0]
369
+ value_states = past_key_value[1]
370
+ elif is_cross_attention:
371
+ # cross_attentions
372
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
373
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
374
+ elif past_key_value is not None:
375
+ # reuse k, v, self_attention
376
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
377
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
378
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
379
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
380
+ else:
381
+ # self_attention
382
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
383
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
384
+
385
+ if self.is_decoder:
386
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
387
+ # Further calls to cross_attention layer can then reuse all cross-attention
388
+ # key/value_states (first "if" case)
389
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
390
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
391
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
392
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
393
+ past_key_value = (key_states, value_states)
394
+
395
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
396
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
397
+ key_states = key_states.view(*proj_shape)
398
+ value_states = value_states.view(*proj_shape)
399
+
400
+ src_len = key_states.size(1)
401
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
402
+
403
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
404
+ raise ValueError(
405
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
406
+ f" {attn_weights.size()}"
407
+ )
408
+
409
+ if attention_mask is not None:
410
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
411
+ raise ValueError(
412
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
413
+ )
414
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
415
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
416
+
417
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
418
+
419
+ if layer_head_mask is not None:
420
+ if layer_head_mask.size() != (self.num_heads,):
421
+ raise ValueError(
422
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
423
+ f" {layer_head_mask.size()}"
424
+ )
425
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
426
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
427
+
428
+ if output_attentions:
429
+ # this operation is a bit awkward, but it's required to
430
+ # make sure that attn_weights keeps its gradient.
431
+ # In order to do so, attn_weights have to be reshaped
432
+ # twice and have to be reused in the following
433
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
434
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
435
+ else:
436
+ attn_weights_reshaped = None
437
+
438
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
439
+
440
+ attn_output = torch.bmm(attn_probs, value_states)
441
+
442
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
443
+ raise ValueError(
444
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
445
+ f" {attn_output.size()}"
446
+ )
447
+
448
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
449
+ attn_output = attn_output.transpose(1, 2)
450
+
451
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
452
+ # partitioned across GPUs when using tensor-parallelism.
453
+ attn_output = attn_output.reshape(bsz, tgt_len, self.inner_dim)
454
+
455
+ attn_output = self.out_proj(attn_output)
456
+
457
+ return attn_output, attn_weights_reshaped, past_key_value
458
+
459
+
460
+ class LDMBertEncoderLayer(nn.Module):
461
+ def __init__(self, config: LDMBertConfig):
462
+ super().__init__()
463
+ self.embed_dim = config.d_model
464
+ self.self_attn = LDMBertAttention(
465
+ embed_dim=self.embed_dim,
466
+ num_heads=config.encoder_attention_heads,
467
+ head_dim=config.head_dim,
468
+ dropout=config.attention_dropout,
469
+ )
470
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
471
+ self.dropout = config.dropout
472
+ self.activation_fn = ACT2FN[config.activation_function]
473
+ self.activation_dropout = config.activation_dropout
474
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
475
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
476
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
477
+
478
+ def forward(
479
+ self,
480
+ hidden_states: torch.Tensor,
481
+ attention_mask: torch.Tensor,
482
+ layer_head_mask: torch.Tensor,
483
+ output_attentions: Optional[bool] = False,
484
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
485
+ """
486
+ Args:
487
+ hidden_states (`torch.Tensor`): input to the layer of shape `(seq_len, batch, embed_dim)`
488
+ attention_mask (`torch.Tensor`): attention mask of size
489
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
490
+ layer_head_mask (`torch.Tensor`): mask for attention heads in a given layer of size
491
+ `(encoder_attention_heads,)`.
492
+ output_attentions (`bool`, *optional*):
493
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
494
+ returned tensors for more detail.
495
+ """
496
+ residual = hidden_states
497
+ hidden_states = self.self_attn_layer_norm(hidden_states)
498
+ hidden_states, attn_weights, _ = self.self_attn(
499
+ hidden_states=hidden_states,
500
+ attention_mask=attention_mask,
501
+ layer_head_mask=layer_head_mask,
502
+ output_attentions=output_attentions,
503
+ )
504
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
505
+ hidden_states = residual + hidden_states
506
+
507
+ residual = hidden_states
508
+ hidden_states = self.final_layer_norm(hidden_states)
509
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
510
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
511
+ hidden_states = self.fc2(hidden_states)
512
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
513
+ hidden_states = residual + hidden_states
514
+
515
+ if hidden_states.dtype == torch.float16 and (
516
+ torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
517
+ ):
518
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
519
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
520
+
521
+ outputs = (hidden_states,)
522
+
523
+ if output_attentions:
524
+ outputs += (attn_weights,)
525
+
526
+ return outputs
527
+
528
+
529
+ # Copied from transformers.models.bart.modeling_bart.BartPretrainedModel with Bart->LDMBert
530
+ class LDMBertPreTrainedModel(PreTrainedModel):
531
+ config_class = LDMBertConfig
532
+ base_model_prefix = "model"
533
+ _supports_gradient_checkpointing = True
534
+ _keys_to_ignore_on_load_unexpected = [r"encoder\.version", r"decoder\.version"]
535
+
536
+ def _init_weights(self, module):
537
+ std = self.config.init_std
538
+ if isinstance(module, nn.Linear):
539
+ module.weight.data.normal_(mean=0.0, std=std)
540
+ if module.bias is not None:
541
+ module.bias.data.zero_()
542
+ elif isinstance(module, nn.Embedding):
543
+ module.weight.data.normal_(mean=0.0, std=std)
544
+ if module.padding_idx is not None:
545
+ module.weight.data[module.padding_idx].zero_()
546
+
547
+ @property
548
+ def dummy_inputs(self):
549
+ pad_token = self.config.pad_token_id
550
+ input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
551
+ dummy_inputs = {
552
+ "attention_mask": input_ids.ne(pad_token),
553
+ "input_ids": input_ids,
554
+ }
555
+ return dummy_inputs
556
+
557
+
558
+ class LDMBertEncoder(LDMBertPreTrainedModel):
559
+ """
560
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
561
+ [`LDMBertEncoderLayer`].
562
+
563
+ Args:
564
+ config: LDMBertConfig
565
+ embed_tokens (nn.Embedding): output embedding
566
+ """
567
+
568
+ def __init__(self, config: LDMBertConfig):
569
+ super().__init__(config)
570
+
571
+ self.dropout = config.dropout
572
+
573
+ embed_dim = config.d_model
574
+ self.padding_idx = config.pad_token_id
575
+ self.max_source_positions = config.max_position_embeddings
576
+
577
+ self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim)
578
+ self.embed_positions = nn.Embedding(config.max_position_embeddings, embed_dim)
579
+ self.layers = nn.ModuleList([LDMBertEncoderLayer(config) for _ in range(config.encoder_layers)])
580
+ self.layer_norm = nn.LayerNorm(embed_dim)
581
+
582
+ self.gradient_checkpointing = False
583
+ # Initialize weights and apply final processing
584
+ self.post_init()
585
+
586
+ def get_input_embeddings(self):
587
+ return self.embed_tokens
588
+
589
+ def set_input_embeddings(self, value):
590
+ self.embed_tokens = value
591
+
592
+ def forward(
593
+ self,
594
+ input_ids: torch.LongTensor = None,
595
+ attention_mask: Optional[torch.Tensor] = None,
596
+ position_ids: Optional[torch.LongTensor] = None,
597
+ head_mask: Optional[torch.Tensor] = None,
598
+ inputs_embeds: Optional[torch.Tensor] = None,
599
+ output_attentions: Optional[bool] = None,
600
+ output_hidden_states: Optional[bool] = None,
601
+ return_dict: Optional[bool] = None,
602
+ ) -> Union[Tuple, BaseModelOutput]:
603
+ r"""
604
+ Args:
605
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
606
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
607
+ provide it.
608
+
609
+ Indices can be obtained using [`BartTokenizer`]. See [`PreTrainedTokenizer.encode`] and
610
+ [`PreTrainedTokenizer.__call__`] for details.
611
+
612
+ [What are input IDs?](../glossary#input-ids)
613
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
614
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
615
+
616
+ - 1 for tokens that are **not masked**,
617
+ - 0 for tokens that are **masked**.
618
+
619
+ [What are attention masks?](../glossary#attention-mask)
620
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
621
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
622
+
623
+ - 1 indicates the head is **not masked**,
624
+ - 0 indicates the head is **masked**.
625
+
626
+ inputs_embeds (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
627
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
628
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
629
+ than the model's internal embedding lookup matrix.
630
+ output_attentions (`bool`, *optional*):
631
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
632
+ returned tensors for more detail.
633
+ output_hidden_states (`bool`, *optional*):
634
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
635
+ for more detail.
636
+ return_dict (`bool`, *optional*):
637
+ Whether or not to return a [`~utils.BaseModelOutput`] instead of a plain tuple.
638
+ """
639
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
640
+ output_hidden_states = (
641
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
642
+ )
643
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
644
+
645
+ # retrieve input_ids and inputs_embeds
646
+ if input_ids is not None and inputs_embeds is not None:
647
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
648
+ elif input_ids is not None:
649
+ input_shape = input_ids.size()
650
+ input_ids = input_ids.view(-1, input_shape[-1])
651
+ elif inputs_embeds is not None:
652
+ input_shape = inputs_embeds.size()[:-1]
653
+ else:
654
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
655
+
656
+ if inputs_embeds is None:
657
+ inputs_embeds = self.embed_tokens(input_ids)
658
+
659
+ seq_len = input_shape[1]
660
+ if position_ids is None:
661
+ position_ids = torch.arange(seq_len, dtype=torch.long, device=inputs_embeds.device).expand((1, -1))
662
+ embed_pos = self.embed_positions(position_ids)
663
+
664
+ hidden_states = inputs_embeds + embed_pos
665
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
666
+
667
+ # expand attention_mask
668
+ if attention_mask is not None:
669
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
670
+ attention_mask = _expand_mask(attention_mask, inputs_embeds.dtype)
671
+
672
+ encoder_states = () if output_hidden_states else None
673
+ all_attentions = () if output_attentions else None
674
+
675
+ # check if head_mask has a correct number of layers specified if desired
676
+ if head_mask is not None:
677
+ if head_mask.size()[0] != (len(self.layers)):
678
+ raise ValueError(
679
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
680
+ f" {head_mask.size()[0]}."
681
+ )
682
+
683
+ for idx, encoder_layer in enumerate(self.layers):
684
+ if output_hidden_states:
685
+ encoder_states = encoder_states + (hidden_states,)
686
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
687
+ layer_outputs = self._gradient_checkpointing_func(
688
+ encoder_layer,
689
+ hidden_states,
690
+ attention_mask,
691
+ (head_mask[idx] if head_mask is not None else None),
692
+ )
693
+ else:
694
+ layer_outputs = encoder_layer(
695
+ hidden_states,
696
+ attention_mask,
697
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
698
+ output_attentions=output_attentions,
699
+ )
700
+
701
+ hidden_states = layer_outputs[0]
702
+
703
+ if output_attentions:
704
+ all_attentions = all_attentions + (layer_outputs[1],)
705
+
706
+ hidden_states = self.layer_norm(hidden_states)
707
+
708
+ if output_hidden_states:
709
+ encoder_states = encoder_states + (hidden_states,)
710
+
711
+ if not return_dict:
712
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
713
+ return BaseModelOutput(
714
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
715
+ )
716
+
717
+
718
+ class LDMBertModel(LDMBertPreTrainedModel):
719
+ _no_split_modules = []
720
+
721
+ def __init__(self, config: LDMBertConfig):
722
+ super().__init__(config)
723
+ self.model = LDMBertEncoder(config)
724
+ self.to_logits = nn.Linear(config.hidden_size, config.vocab_size)
725
+
726
+ def forward(
727
+ self,
728
+ input_ids=None,
729
+ attention_mask=None,
730
+ position_ids=None,
731
+ head_mask=None,
732
+ inputs_embeds=None,
733
+ output_attentions=None,
734
+ output_hidden_states=None,
735
+ return_dict=None,
736
+ ):
737
+ outputs = self.model(
738
+ input_ids,
739
+ attention_mask=attention_mask,
740
+ position_ids=position_ids,
741
+ head_mask=head_mask,
742
+ inputs_embeds=inputs_embeds,
743
+ output_attentions=output_attentions,
744
+ output_hidden_states=output_hidden_states,
745
+ return_dict=return_dict,
746
+ )
747
+ return outputs
pythonProject/.venv/Lib/site-packages/numpy/f2py/_backends/_backend.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+
6
+ class Backend(ABC):
7
+ def __init__(
8
+ self,
9
+ modulename,
10
+ sources,
11
+ extra_objects,
12
+ build_dir,
13
+ include_dirs,
14
+ library_dirs,
15
+ libraries,
16
+ define_macros,
17
+ undef_macros,
18
+ f2py_flags,
19
+ sysinfo_flags,
20
+ fc_flags,
21
+ flib_flags,
22
+ setup_flags,
23
+ remove_build_dir,
24
+ extra_dat,
25
+ ):
26
+ self.modulename = modulename
27
+ self.sources = sources
28
+ self.extra_objects = extra_objects
29
+ self.build_dir = build_dir
30
+ self.include_dirs = include_dirs
31
+ self.library_dirs = library_dirs
32
+ self.libraries = libraries
33
+ self.define_macros = define_macros
34
+ self.undef_macros = undef_macros
35
+ self.f2py_flags = f2py_flags
36
+ self.sysinfo_flags = sysinfo_flags
37
+ self.fc_flags = fc_flags
38
+ self.flib_flags = flib_flags
39
+ self.setup_flags = setup_flags
40
+ self.remove_build_dir = remove_build_dir
41
+ self.extra_dat = extra_dat
42
+
43
+ @abstractmethod
44
+ def compile(self) -> None:
45
+ """Compile the wrapper."""
46
+ pass
pythonProject/.venv/Lib/site-packages/numpy/f2py/_backends/_distutils.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._backend import Backend
2
+
3
+ from numpy.distutils.core import setup, Extension
4
+ from numpy.distutils.system_info import get_info
5
+ from numpy.distutils.misc_util import dict_append
6
+ from numpy.exceptions import VisibleDeprecationWarning
7
+ import os
8
+ import sys
9
+ import shutil
10
+ import warnings
11
+
12
+
13
+ class DistutilsBackend(Backend):
14
+ def __init__(sef, *args, **kwargs):
15
+ warnings.warn(
16
+ "\ndistutils has been deprecated since NumPy 1.26.x\n"
17
+ "Use the Meson backend instead, or generate wrappers"
18
+ " without -c and use a custom build script",
19
+ VisibleDeprecationWarning,
20
+ stacklevel=2,
21
+ )
22
+ super().__init__(*args, **kwargs)
23
+
24
+ def compile(self):
25
+ num_info = {}
26
+ if num_info:
27
+ self.include_dirs.extend(num_info.get("include_dirs", []))
28
+ ext_args = {
29
+ "name": self.modulename,
30
+ "sources": self.sources,
31
+ "include_dirs": self.include_dirs,
32
+ "library_dirs": self.library_dirs,
33
+ "libraries": self.libraries,
34
+ "define_macros": self.define_macros,
35
+ "undef_macros": self.undef_macros,
36
+ "extra_objects": self.extra_objects,
37
+ "f2py_options": self.f2py_flags,
38
+ }
39
+
40
+ if self.sysinfo_flags:
41
+ for n in self.sysinfo_flags:
42
+ i = get_info(n)
43
+ if not i:
44
+ print(
45
+ f"No {n!r} resources found"
46
+ "in system (try `f2py --help-link`)"
47
+ )
48
+ dict_append(ext_args, **i)
49
+
50
+ ext = Extension(**ext_args)
51
+
52
+ sys.argv = [sys.argv[0]] + self.setup_flags
53
+ sys.argv.extend(
54
+ [
55
+ "build",
56
+ "--build-temp",
57
+ self.build_dir,
58
+ "--build-base",
59
+ self.build_dir,
60
+ "--build-platlib",
61
+ ".",
62
+ "--disable-optimization",
63
+ ]
64
+ )
65
+
66
+ if self.fc_flags:
67
+ sys.argv.extend(["config_fc"] + self.fc_flags)
68
+ if self.flib_flags:
69
+ sys.argv.extend(["build_ext"] + self.flib_flags)
70
+
71
+ setup(ext_modules=[ext])
72
+
73
+ if self.remove_build_dir and os.path.exists(self.build_dir):
74
+ print(f"Removing build directory {self.build_dir}")
75
+ shutil.rmtree(self.build_dir)
pythonProject/.venv/Lib/site-packages/numpy/f2py/_backends/meson.build.template ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ project('${modulename}',
2
+ ['c', 'fortran'],
3
+ version : '0.1',
4
+ meson_version: '>= 1.1.0',
5
+ default_options : [
6
+ 'warning_level=1',
7
+ 'buildtype=${buildtype}'
8
+ ])
9
+ fc = meson.get_compiler('fortran')
10
+
11
+ py = import('python').find_installation('''${python}''', pure: false)
12
+ py_dep = py.dependency()
13
+
14
+ incdir_numpy = run_command(py,
15
+ ['-c', 'import os; os.chdir(".."); import numpy; print(numpy.get_include())'],
16
+ check : true
17
+ ).stdout().strip()
18
+
19
+ incdir_f2py = run_command(py,
20
+ ['-c', 'import os; os.chdir(".."); import numpy.f2py; print(numpy.f2py.get_include())'],
21
+ check : true
22
+ ).stdout().strip()
23
+
24
+ inc_np = include_directories(incdir_numpy)
25
+ np_dep = declare_dependency(include_directories: inc_np)
26
+
27
+ incdir_f2py = incdir_numpy / '..' / '..' / 'f2py' / 'src'
28
+ inc_f2py = include_directories(incdir_f2py)
29
+ fortranobject_c = incdir_f2py / 'fortranobject.c'
30
+
31
+ inc_np = include_directories(incdir_numpy, incdir_f2py)
32
+ # gh-25000
33
+ quadmath_dep = fc.find_library('quadmath', required: false)
34
+
35
+ ${lib_declarations}
36
+ ${lib_dir_declarations}
37
+
38
+ py.extension_module('${modulename}',
39
+ [
40
+ ${source_list},
41
+ fortranobject_c
42
+ ],
43
+ include_directories: [
44
+ inc_np,
45
+ ${inc_list}
46
+ ],
47
+ dependencies : [
48
+ py_dep,
49
+ quadmath_dep,
50
+ ${dep_list}
51
+ ${lib_list}
52
+ ${lib_dir_list}
53
+ ],
54
+ ${fortran_args}
55
+ install : true)
pythonProject/.venv/Lib/site-packages/numpy/f2py/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (455 Bytes). View file
 
pythonProject/.venv/Lib/site-packages/numpy/f2py/tests/__pycache__/test_size.cpython-310.pyc ADDED
Binary file (1.66 kB). View file
 
pythonProject/.venv/Lib/site-packages/numpy/f2py/tests/__pycache__/test_string.cpython-310.pyc ADDED
Binary file (3.31 kB). View file
 
pythonProject/.venv/Lib/site-packages/numpy/f2py/tests/__pycache__/test_symbolic.cpython-310.pyc ADDED
Binary file (14.6 kB). View file
 
pythonProject/.venv/Lib/site-packages/numpy/f2py/tests/__pycache__/test_value_attrspec.cpython-310.pyc ADDED
Binary file (747 Bytes). View file
 
pythonProject/.venv/Lib/site-packages/numpy/f2py/tests/__pycache__/util.cpython-310.pyc ADDED
Binary file (10.6 kB). View file