nexaai 1.0.16rc10__cp310-cp310-macosx_14_0_universal2.whl → 1.0.16rc11__cp310-cp310-macosx_14_0_universal2.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of nexaai might be problematic. Click here for more details.
- nexaai/_stub.cpython-310-darwin.so +0 -0
- nexaai/_version.py +1 -1
- nexaai/binds/libnexa_bridge.dylib +0 -0
- nexaai/binds/nexa_mlx/libnexa_plugin.dylib +0 -0
- nexaai/binds/nexa_mlx/py-lib/ml.py +60 -14
- nexaai/mlx_backend/image_gen/__init__.py +1 -0
- nexaai/mlx_backend/image_gen/generate_sd.py +244 -0
- nexaai/mlx_backend/image_gen/interface.py +82 -0
- nexaai/mlx_backend/image_gen/main.py +281 -0
- nexaai/mlx_backend/image_gen/stable_diffusion/__init__.py +306 -0
- nexaai/mlx_backend/image_gen/stable_diffusion/clip.py +116 -0
- nexaai/mlx_backend/image_gen/stable_diffusion/config.py +65 -0
- nexaai/mlx_backend/image_gen/stable_diffusion/model_io.py +386 -0
- nexaai/mlx_backend/image_gen/stable_diffusion/sampler.py +105 -0
- nexaai/mlx_backend/image_gen/stable_diffusion/tokenizer.py +100 -0
- nexaai/mlx_backend/image_gen/stable_diffusion/unet.py +460 -0
- nexaai/mlx_backend/image_gen/stable_diffusion/vae.py +274 -0
- nexaai/mlx_backend/ml.py +60 -14
- nexaai/mlx_backend/sd/modeling/model_io.py +72 -17
- {nexaai-1.0.16rc10.dist-info → nexaai-1.0.16rc11.dist-info}/METADATA +1 -1
- {nexaai-1.0.16rc10.dist-info → nexaai-1.0.16rc11.dist-info}/RECORD +23 -11
- {nexaai-1.0.16rc10.dist-info → nexaai-1.0.16rc11.dist-info}/WHEEL +0 -0
- {nexaai-1.0.16rc10.dist-info → nexaai-1.0.16rc11.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Command line interface for text-to-image generation using MLX backend.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import sys
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
# Add the parent directory to the path to import the interface
|
|
13
|
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
14
|
+
|
|
15
|
+
from interface import ImageGen, ImageSamplerConfig
|
|
16
|
+
from ml import (
|
|
17
|
+
ImageGenCreateInput,
|
|
18
|
+
ImageGenTxt2ImgInput,
|
|
19
|
+
ImageGenerationConfig,
|
|
20
|
+
ImageSamplerConfig as MLImageSamplerConfig,
|
|
21
|
+
SchedulerConfig,
|
|
22
|
+
ModelConfig
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def create_default_config() -> ImageGenerationConfig:
|
|
27
|
+
"""Create a default image generation configuration."""
|
|
28
|
+
sampler_config = MLImageSamplerConfig(
|
|
29
|
+
method="ddim",
|
|
30
|
+
steps=4, # SDXL Turbo optimized
|
|
31
|
+
guidance_scale=0.0, # SDXL Turbo works well with no guidance
|
|
32
|
+
eta=0.0,
|
|
33
|
+
seed=-1
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
scheduler_config = SchedulerConfig(
|
|
37
|
+
type="ddim",
|
|
38
|
+
num_train_timesteps=1000,
|
|
39
|
+
steps_offset=0,
|
|
40
|
+
beta_start=0.00085,
|
|
41
|
+
beta_end=0.012,
|
|
42
|
+
beta_schedule="scaled_linear",
|
|
43
|
+
prediction_type="epsilon",
|
|
44
|
+
timestep_type="discrete",
|
|
45
|
+
timestep_spacing="linspace",
|
|
46
|
+
interpolation_type="linear"
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
return ImageGenerationConfig(
|
|
50
|
+
prompts=[""], # Will be set by user input
|
|
51
|
+
sampler_config=sampler_config,
|
|
52
|
+
scheduler_config=scheduler_config,
|
|
53
|
+
strength=1.0,
|
|
54
|
+
negative_prompts=None,
|
|
55
|
+
height=512,
|
|
56
|
+
width=512
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def parse_arguments():
|
|
61
|
+
"""Parse command line arguments."""
|
|
62
|
+
parser = argparse.ArgumentParser(
|
|
63
|
+
description="Generate images from text prompts using MLX backend",
|
|
64
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
65
|
+
epilog="""
|
|
66
|
+
Examples:
|
|
67
|
+
python main.py "a beautiful sunset over mountains"
|
|
68
|
+
python main.py "a cat sitting on a chair" --output output.png --width 1024 --height 1024
|
|
69
|
+
python main.py "a futuristic city" --model-path ./models/sdxl-turbo --steps 8 --seed 42
|
|
70
|
+
"""
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
# Required arguments
|
|
74
|
+
parser.add_argument(
|
|
75
|
+
"prompt",
|
|
76
|
+
help="Text prompt for image generation"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
# Optional arguments
|
|
80
|
+
parser.add_argument(
|
|
81
|
+
"--output", "-o",
|
|
82
|
+
type=str,
|
|
83
|
+
help="Output image path (default: generated_image.png)"
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
parser.add_argument(
|
|
87
|
+
"--model-path", "-m",
|
|
88
|
+
type=str,
|
|
89
|
+
default="stabilityai/sdxl-turbo",
|
|
90
|
+
help="Path to the model or HuggingFace model name (default: stabilityai/sdxl-turbo)"
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
parser.add_argument(
|
|
94
|
+
"--width", "-w",
|
|
95
|
+
type=int,
|
|
96
|
+
default=512,
|
|
97
|
+
help="Image width (must be divisible by 16, default: 512)"
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
parser.add_argument(
|
|
101
|
+
"--height", "-h",
|
|
102
|
+
type=int,
|
|
103
|
+
default=512,
|
|
104
|
+
help="Image height (must be divisible by 16, default: 512)"
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
parser.add_argument(
|
|
108
|
+
"--steps", "-s",
|
|
109
|
+
type=int,
|
|
110
|
+
default=4,
|
|
111
|
+
help="Number of denoising steps (default: 4 for SDXL Turbo)"
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
parser.add_argument(
|
|
115
|
+
"--guidance-scale", "-g",
|
|
116
|
+
type=float,
|
|
117
|
+
default=0.0,
|
|
118
|
+
help="Guidance scale (default: 0.0 for SDXL Turbo)"
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
parser.add_argument(
|
|
122
|
+
"--seed",
|
|
123
|
+
type=int,
|
|
124
|
+
default=-1,
|
|
125
|
+
help="Random seed (-1 for random, default: -1)"
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
parser.add_argument(
|
|
129
|
+
"--negative-prompt", "-n",
|
|
130
|
+
type=str,
|
|
131
|
+
help="Negative prompt to avoid certain elements"
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
parser.add_argument(
|
|
135
|
+
"--device-id",
|
|
136
|
+
type=str,
|
|
137
|
+
help="Device ID to use (default: auto-detect)"
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
parser.add_argument(
|
|
141
|
+
"--verbose", "-v",
|
|
142
|
+
action="store_true",
|
|
143
|
+
help="Enable verbose logging"
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
return parser.parse_args()
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def validate_arguments(args):
|
|
150
|
+
"""Validate command line arguments."""
|
|
151
|
+
# Check dimensions are divisible by 16
|
|
152
|
+
if args.width % 16 != 0:
|
|
153
|
+
raise ValueError(f"Width must be divisible by 16, got {args.width}")
|
|
154
|
+
if args.height % 16 != 0:
|
|
155
|
+
raise ValueError(f"Height must be divisible by 16, got {args.height}")
|
|
156
|
+
|
|
157
|
+
# Check steps is positive
|
|
158
|
+
if args.steps <= 0:
|
|
159
|
+
raise ValueError(f"Steps must be positive, got {args.steps}")
|
|
160
|
+
|
|
161
|
+
# Check guidance scale is non-negative
|
|
162
|
+
if args.guidance_scale < 0:
|
|
163
|
+
raise ValueError(f"Guidance scale must be non-negative, got {args.guidance_scale}")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def main():
|
|
167
|
+
"""Main function for command line interface."""
|
|
168
|
+
try:
|
|
169
|
+
# Parse arguments
|
|
170
|
+
args = parse_arguments()
|
|
171
|
+
|
|
172
|
+
# Validate arguments
|
|
173
|
+
validate_arguments(args)
|
|
174
|
+
|
|
175
|
+
# Set up output path
|
|
176
|
+
if args.output:
|
|
177
|
+
output_path = Path(args.output)
|
|
178
|
+
else:
|
|
179
|
+
output_path = Path("generated_image.png")
|
|
180
|
+
|
|
181
|
+
# Ensure output directory exists
|
|
182
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
183
|
+
|
|
184
|
+
if args.verbose:
|
|
185
|
+
print(f"Initializing image generation...")
|
|
186
|
+
print(f"Model: {args.model_path}")
|
|
187
|
+
print(f"Prompt: {args.prompt}")
|
|
188
|
+
print(f"Output: {output_path}")
|
|
189
|
+
print(f"Dimensions: {args.width}x{args.height}")
|
|
190
|
+
print(f"Steps: {args.steps}")
|
|
191
|
+
print(f"Guidance scale: {args.guidance_scale}")
|
|
192
|
+
print(f"Seed: {args.seed}")
|
|
193
|
+
if args.negative_prompt:
|
|
194
|
+
print(f"Negative prompt: {args.negative_prompt}")
|
|
195
|
+
|
|
196
|
+
# Create model configuration
|
|
197
|
+
model_config = ModelConfig(
|
|
198
|
+
name="sdxl-turbo",
|
|
199
|
+
version="1.0",
|
|
200
|
+
description="SDXL Turbo model for fast image generation"
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
# Create image generator
|
|
204
|
+
create_input = ImageGenCreateInput(
|
|
205
|
+
model_name="sdxl-turbo",
|
|
206
|
+
model_path=args.model_path,
|
|
207
|
+
config=model_config,
|
|
208
|
+
scheduler_config_path="", # Not used for SDXL Turbo
|
|
209
|
+
plugin_id="mlx",
|
|
210
|
+
device_id=args.device_id
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
image_gen = ImageGen(create_input)
|
|
214
|
+
|
|
215
|
+
# Create generation configuration
|
|
216
|
+
sampler_config = MLImageSamplerConfig(
|
|
217
|
+
method="ddim",
|
|
218
|
+
steps=args.steps,
|
|
219
|
+
guidance_scale=args.guidance_scale,
|
|
220
|
+
eta=0.0,
|
|
221
|
+
seed=args.seed
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
scheduler_config = SchedulerConfig(
|
|
225
|
+
type="ddim",
|
|
226
|
+
num_train_timesteps=1000,
|
|
227
|
+
steps_offset=0,
|
|
228
|
+
beta_start=0.00085,
|
|
229
|
+
beta_end=0.012,
|
|
230
|
+
beta_schedule="scaled_linear",
|
|
231
|
+
prediction_type="epsilon",
|
|
232
|
+
timestep_type="discrete",
|
|
233
|
+
timestep_spacing="linspace",
|
|
234
|
+
interpolation_type="linear"
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
generation_config = ImageGenerationConfig(
|
|
238
|
+
prompts=[args.prompt],
|
|
239
|
+
sampler_config=sampler_config,
|
|
240
|
+
scheduler_config=scheduler_config,
|
|
241
|
+
strength=1.0,
|
|
242
|
+
negative_prompts=[args.negative_prompt] if args.negative_prompt else None,
|
|
243
|
+
height=args.height,
|
|
244
|
+
width=args.width
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
# Create text-to-image input
|
|
248
|
+
txt2img_input = ImageGenTxt2ImgInput(
|
|
249
|
+
prompt=args.prompt,
|
|
250
|
+
config=generation_config,
|
|
251
|
+
output_path=str(output_path)
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
if args.verbose:
|
|
255
|
+
print("Generating image...")
|
|
256
|
+
|
|
257
|
+
# Generate image
|
|
258
|
+
result = image_gen.txt2img(txt2img_input)
|
|
259
|
+
|
|
260
|
+
if args.verbose:
|
|
261
|
+
print(f"Image generated successfully!")
|
|
262
|
+
print(f"Saved to: {result.output_image_path}")
|
|
263
|
+
else:
|
|
264
|
+
print(f"Image saved to: {result.output_image_path}")
|
|
265
|
+
|
|
266
|
+
# Clean up
|
|
267
|
+
image_gen.close()
|
|
268
|
+
|
|
269
|
+
except KeyboardInterrupt:
|
|
270
|
+
print("\nGeneration cancelled by user.")
|
|
271
|
+
sys.exit(1)
|
|
272
|
+
except Exception as e:
|
|
273
|
+
print(f"Error: {e}", file=sys.stderr)
|
|
274
|
+
if args.verbose:
|
|
275
|
+
import traceback
|
|
276
|
+
traceback.print_exc()
|
|
277
|
+
sys.exit(1)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
if __name__ == "__main__":
|
|
281
|
+
main()
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
# Copyright © 2023-2024 Apple Inc.
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from typing import Optional, Tuple
|
|
5
|
+
|
|
6
|
+
import mlx.core as mx
|
|
7
|
+
|
|
8
|
+
from .model_io import (
|
|
9
|
+
_DEFAULT_MODEL,
|
|
10
|
+
load_autoencoder,
|
|
11
|
+
load_diffusion_config,
|
|
12
|
+
load_text_encoder,
|
|
13
|
+
load_tokenizer,
|
|
14
|
+
load_unet,
|
|
15
|
+
)
|
|
16
|
+
from .sampler import SimpleEulerAncestralSampler, SimpleEulerSampler
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class StableDiffusion:
|
|
20
|
+
def __init__(self, model: str = _DEFAULT_MODEL, float16: bool = False):
|
|
21
|
+
self.dtype = mx.float16 if float16 else mx.float32
|
|
22
|
+
self.diffusion_config = load_diffusion_config(model)
|
|
23
|
+
self.unet = load_unet(model, float16)
|
|
24
|
+
self.text_encoder = load_text_encoder(model, float16)
|
|
25
|
+
self.autoencoder = load_autoencoder(model, False)
|
|
26
|
+
self.sampler = SimpleEulerSampler(self.diffusion_config)
|
|
27
|
+
self.tokenizer = load_tokenizer(model)
|
|
28
|
+
|
|
29
|
+
def ensure_models_are_loaded(self):
|
|
30
|
+
mx.eval(self.unet.parameters())
|
|
31
|
+
mx.eval(self.text_encoder.parameters())
|
|
32
|
+
mx.eval(self.autoencoder.parameters())
|
|
33
|
+
|
|
34
|
+
def _tokenize(self, tokenizer, text: str, negative_text: Optional[str] = None):
|
|
35
|
+
# Tokenize the text
|
|
36
|
+
tokens = [tokenizer.tokenize(text)]
|
|
37
|
+
if negative_text is not None:
|
|
38
|
+
tokens += [tokenizer.tokenize(negative_text)]
|
|
39
|
+
lengths = [len(t) for t in tokens]
|
|
40
|
+
N = max(lengths)
|
|
41
|
+
tokens = [t + [0] * (N - len(t)) for t in tokens]
|
|
42
|
+
tokens = mx.array(tokens)
|
|
43
|
+
|
|
44
|
+
return tokens
|
|
45
|
+
|
|
46
|
+
def _get_text_conditioning(
|
|
47
|
+
self,
|
|
48
|
+
text: str,
|
|
49
|
+
n_images: int = 1,
|
|
50
|
+
cfg_weight: float = 7.5,
|
|
51
|
+
negative_text: str = "",
|
|
52
|
+
):
|
|
53
|
+
# Tokenize the text
|
|
54
|
+
tokens = self._tokenize(
|
|
55
|
+
self.tokenizer, text, (negative_text if cfg_weight > 1 else None)
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
# Compute the features
|
|
59
|
+
conditioning = self.text_encoder(tokens).last_hidden_state
|
|
60
|
+
|
|
61
|
+
# Repeat the conditioning for each of the generated images
|
|
62
|
+
if n_images > 1:
|
|
63
|
+
conditioning = mx.repeat(conditioning, n_images, axis=0)
|
|
64
|
+
|
|
65
|
+
return conditioning
|
|
66
|
+
|
|
67
|
+
def _denoising_step(
|
|
68
|
+
self, x_t, t, t_prev, conditioning, cfg_weight: float = 7.5, text_time=None
|
|
69
|
+
):
|
|
70
|
+
x_t_unet = mx.concatenate([x_t] * 2, axis=0) if cfg_weight > 1 else x_t
|
|
71
|
+
t_unet = mx.broadcast_to(t, [len(x_t_unet)])
|
|
72
|
+
eps_pred = self.unet(
|
|
73
|
+
x_t_unet, t_unet, encoder_x=conditioning, text_time=text_time
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
if cfg_weight > 1:
|
|
77
|
+
eps_text, eps_neg = eps_pred.split(2)
|
|
78
|
+
eps_pred = eps_neg + cfg_weight * (eps_text - eps_neg)
|
|
79
|
+
|
|
80
|
+
x_t_prev = self.sampler.step(eps_pred, x_t, t, t_prev)
|
|
81
|
+
|
|
82
|
+
return x_t_prev
|
|
83
|
+
|
|
84
|
+
def _denoising_loop(
|
|
85
|
+
self,
|
|
86
|
+
x_T,
|
|
87
|
+
T,
|
|
88
|
+
conditioning,
|
|
89
|
+
num_steps: int = 50,
|
|
90
|
+
cfg_weight: float = 7.5,
|
|
91
|
+
text_time=None,
|
|
92
|
+
):
|
|
93
|
+
x_t = x_T
|
|
94
|
+
for t, t_prev in self.sampler.timesteps(
|
|
95
|
+
num_steps, start_time=T, dtype=self.dtype
|
|
96
|
+
):
|
|
97
|
+
x_t = self._denoising_step(
|
|
98
|
+
x_t, t, t_prev, conditioning, cfg_weight, text_time
|
|
99
|
+
)
|
|
100
|
+
yield x_t
|
|
101
|
+
|
|
102
|
+
def generate_latents(
|
|
103
|
+
self,
|
|
104
|
+
text: str,
|
|
105
|
+
n_images: int = 1,
|
|
106
|
+
num_steps: int = 50,
|
|
107
|
+
cfg_weight: float = 7.5,
|
|
108
|
+
negative_text: str = "",
|
|
109
|
+
latent_size: Tuple[int] = (64, 64),
|
|
110
|
+
seed=None,
|
|
111
|
+
):
|
|
112
|
+
# Set the PRNG state
|
|
113
|
+
seed = int(time.time()) if seed is None else seed
|
|
114
|
+
mx.random.seed(seed)
|
|
115
|
+
|
|
116
|
+
# Get the text conditioning
|
|
117
|
+
conditioning = self._get_text_conditioning(
|
|
118
|
+
text, n_images, cfg_weight, negative_text
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
# Create the latent variables
|
|
122
|
+
x_T = self.sampler.sample_prior(
|
|
123
|
+
(n_images, *latent_size, self.autoencoder.latent_channels), dtype=self.dtype
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
# Perform the denoising loop
|
|
127
|
+
yield from self._denoising_loop(
|
|
128
|
+
x_T, self.sampler.max_time, conditioning, num_steps, cfg_weight
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
def generate_latents_from_image(
|
|
132
|
+
self,
|
|
133
|
+
image,
|
|
134
|
+
text: str,
|
|
135
|
+
n_images: int = 1,
|
|
136
|
+
strength: float = 0.8,
|
|
137
|
+
num_steps: int = 50,
|
|
138
|
+
cfg_weight: float = 7.5,
|
|
139
|
+
negative_text: str = "",
|
|
140
|
+
seed=None,
|
|
141
|
+
):
|
|
142
|
+
# Set the PRNG state
|
|
143
|
+
seed = int(time.time()) if seed is None else seed
|
|
144
|
+
mx.random.seed(seed)
|
|
145
|
+
|
|
146
|
+
# Define the num steps and start step
|
|
147
|
+
start_step = self.sampler.max_time * strength
|
|
148
|
+
num_steps = int(num_steps * strength)
|
|
149
|
+
|
|
150
|
+
# Get the text conditioning
|
|
151
|
+
conditioning = self._get_text_conditioning(
|
|
152
|
+
text, n_images, cfg_weight, negative_text
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
# Get the latents from the input image and add noise according to the
|
|
156
|
+
# start time.
|
|
157
|
+
x_0, _ = self.autoencoder.encode(image[None])
|
|
158
|
+
x_0 = mx.broadcast_to(x_0, (n_images,) + x_0.shape[1:])
|
|
159
|
+
x_T = self.sampler.add_noise(x_0, mx.array(start_step))
|
|
160
|
+
|
|
161
|
+
# Perform the denoising loop
|
|
162
|
+
yield from self._denoising_loop(
|
|
163
|
+
x_T, start_step, conditioning, num_steps, cfg_weight
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
def decode(self, x_t):
|
|
167
|
+
x = self.autoencoder.decode(x_t)
|
|
168
|
+
x = mx.clip(x / 2 + 0.5, 0, 1)
|
|
169
|
+
return x
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class StableDiffusionXL(StableDiffusion):
|
|
173
|
+
def __init__(self, model: str = _DEFAULT_MODEL, float16: bool = False):
|
|
174
|
+
super().__init__(model, float16)
|
|
175
|
+
|
|
176
|
+
self.sampler = SimpleEulerAncestralSampler(self.diffusion_config)
|
|
177
|
+
|
|
178
|
+
self.text_encoder_1 = self.text_encoder
|
|
179
|
+
self.tokenizer_1 = self.tokenizer
|
|
180
|
+
del self.tokenizer, self.text_encoder
|
|
181
|
+
|
|
182
|
+
self.text_encoder_2 = load_text_encoder(
|
|
183
|
+
model,
|
|
184
|
+
float16,
|
|
185
|
+
model_key="text_encoder_2",
|
|
186
|
+
)
|
|
187
|
+
self.tokenizer_2 = load_tokenizer(
|
|
188
|
+
model,
|
|
189
|
+
merges_key="tokenizer_2_merges",
|
|
190
|
+
vocab_key="tokenizer_2_vocab",
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
def ensure_models_are_loaded(self):
|
|
194
|
+
mx.eval(self.unet.parameters())
|
|
195
|
+
mx.eval(self.text_encoder_1.parameters())
|
|
196
|
+
mx.eval(self.text_encoder_2.parameters())
|
|
197
|
+
mx.eval(self.autoencoder.parameters())
|
|
198
|
+
|
|
199
|
+
def _get_text_conditioning(
|
|
200
|
+
self,
|
|
201
|
+
text: str,
|
|
202
|
+
n_images: int = 1,
|
|
203
|
+
cfg_weight: float = 7.5,
|
|
204
|
+
negative_text: str = "",
|
|
205
|
+
):
|
|
206
|
+
tokens_1 = self._tokenize(
|
|
207
|
+
self.tokenizer_1,
|
|
208
|
+
text,
|
|
209
|
+
(negative_text if cfg_weight > 1 else None),
|
|
210
|
+
)
|
|
211
|
+
tokens_2 = self._tokenize(
|
|
212
|
+
self.tokenizer_2,
|
|
213
|
+
text,
|
|
214
|
+
(negative_text if cfg_weight > 1 else None),
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
conditioning_1 = self.text_encoder_1(tokens_1)
|
|
218
|
+
conditioning_2 = self.text_encoder_2(tokens_2)
|
|
219
|
+
conditioning = mx.concatenate(
|
|
220
|
+
[conditioning_1.hidden_states[-2], conditioning_2.hidden_states[-2]],
|
|
221
|
+
axis=-1,
|
|
222
|
+
)
|
|
223
|
+
pooled_conditioning = conditioning_2.pooled_output
|
|
224
|
+
|
|
225
|
+
if n_images > 1:
|
|
226
|
+
conditioning = mx.repeat(conditioning, n_images, axis=0)
|
|
227
|
+
pooled_conditioning = mx.repeat(pooled_conditioning, n_images, axis=0)
|
|
228
|
+
|
|
229
|
+
return conditioning, pooled_conditioning
|
|
230
|
+
|
|
231
|
+
def generate_latents(
|
|
232
|
+
self,
|
|
233
|
+
text: str,
|
|
234
|
+
n_images: int = 1,
|
|
235
|
+
num_steps: int = 2,
|
|
236
|
+
cfg_weight: float = 0.0,
|
|
237
|
+
negative_text: str = "",
|
|
238
|
+
latent_size: Tuple[int] = (64, 64),
|
|
239
|
+
seed=None,
|
|
240
|
+
):
|
|
241
|
+
# Set the PRNG state
|
|
242
|
+
seed = int(time.time()) if seed is None else seed
|
|
243
|
+
mx.random.seed(seed)
|
|
244
|
+
|
|
245
|
+
# Get the text conditioning
|
|
246
|
+
conditioning, pooled_conditioning = self._get_text_conditioning(
|
|
247
|
+
text, n_images, cfg_weight, negative_text
|
|
248
|
+
)
|
|
249
|
+
text_time = (
|
|
250
|
+
pooled_conditioning,
|
|
251
|
+
mx.array([[512, 512, 0, 0, 512, 512.0]] * len(pooled_conditioning)),
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
# Create the latent variables
|
|
255
|
+
x_T = self.sampler.sample_prior(
|
|
256
|
+
(n_images, *latent_size, self.autoencoder.latent_channels), dtype=self.dtype
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
# Perform the denoising loop
|
|
260
|
+
yield from self._denoising_loop(
|
|
261
|
+
x_T,
|
|
262
|
+
self.sampler.max_time,
|
|
263
|
+
conditioning,
|
|
264
|
+
num_steps,
|
|
265
|
+
cfg_weight,
|
|
266
|
+
text_time=text_time,
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
def generate_latents_from_image(
|
|
270
|
+
self,
|
|
271
|
+
image,
|
|
272
|
+
text: str,
|
|
273
|
+
n_images: int = 1,
|
|
274
|
+
strength: float = 0.8,
|
|
275
|
+
num_steps: int = 2,
|
|
276
|
+
cfg_weight: float = 0.0,
|
|
277
|
+
negative_text: str = "",
|
|
278
|
+
seed=None,
|
|
279
|
+
):
|
|
280
|
+
# Set the PRNG state
|
|
281
|
+
seed = seed or int(time.time())
|
|
282
|
+
mx.random.seed(seed)
|
|
283
|
+
|
|
284
|
+
# Define the num steps and start step
|
|
285
|
+
start_step = self.sampler.max_time * strength
|
|
286
|
+
num_steps = int(num_steps * strength)
|
|
287
|
+
|
|
288
|
+
# Get the text conditioning
|
|
289
|
+
conditioning, pooled_conditioning = self._get_text_conditioning(
|
|
290
|
+
text, n_images, cfg_weight, negative_text
|
|
291
|
+
)
|
|
292
|
+
text_time = (
|
|
293
|
+
pooled_conditioning,
|
|
294
|
+
mx.array([[512, 512, 0, 0, 512, 512.0]] * len(pooled_conditioning)),
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
# Get the latents from the input image and add noise according to the
|
|
298
|
+
# start time.
|
|
299
|
+
x_0, _ = self.autoencoder.encode(image[None])
|
|
300
|
+
x_0 = mx.broadcast_to(x_0, (n_images,) + x_0.shape[1:])
|
|
301
|
+
x_T = self.sampler.add_noise(x_0, mx.array(start_step))
|
|
302
|
+
|
|
303
|
+
# Perform the denoising loop
|
|
304
|
+
yield from self._denoising_loop(
|
|
305
|
+
x_T, start_step, conditioning, num_steps, cfg_weight, text_time=text_time
|
|
306
|
+
)
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# Copyright © 2023-2024 Apple Inc.
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import List, Optional
|
|
5
|
+
|
|
6
|
+
import mlx.core as mx
|
|
7
|
+
import mlx.nn as nn
|
|
8
|
+
|
|
9
|
+
from .config import CLIPTextModelConfig
|
|
10
|
+
|
|
11
|
+
_ACTIVATIONS = {"quick_gelu": nn.gelu_fast_approx, "gelu": nn.gelu}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class CLIPOutput:
|
|
16
|
+
# The last_hidden_state indexed at the EOS token and possibly projected if
|
|
17
|
+
# the model has a projection layer
|
|
18
|
+
pooled_output: Optional[mx.array] = None
|
|
19
|
+
|
|
20
|
+
# The full sequence output of the transformer after the final layernorm
|
|
21
|
+
last_hidden_state: Optional[mx.array] = None
|
|
22
|
+
|
|
23
|
+
# A list of hidden states corresponding to the outputs of the transformer layers
|
|
24
|
+
hidden_states: Optional[List[mx.array]] = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class CLIPEncoderLayer(nn.Module):
|
|
28
|
+
"""The transformer encoder layer from CLIP."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, model_dims: int, num_heads: int, activation: str):
|
|
31
|
+
super().__init__()
|
|
32
|
+
|
|
33
|
+
self.layer_norm1 = nn.LayerNorm(model_dims)
|
|
34
|
+
self.layer_norm2 = nn.LayerNorm(model_dims)
|
|
35
|
+
|
|
36
|
+
self.attention = nn.MultiHeadAttention(model_dims, num_heads)
|
|
37
|
+
# Add biases to the attention projections to match CLIP
|
|
38
|
+
self.attention.query_proj.bias = mx.zeros(model_dims)
|
|
39
|
+
self.attention.key_proj.bias = mx.zeros(model_dims)
|
|
40
|
+
self.attention.value_proj.bias = mx.zeros(model_dims)
|
|
41
|
+
self.attention.out_proj.bias = mx.zeros(model_dims)
|
|
42
|
+
|
|
43
|
+
self.linear1 = nn.Linear(model_dims, 4 * model_dims)
|
|
44
|
+
self.linear2 = nn.Linear(4 * model_dims, model_dims)
|
|
45
|
+
|
|
46
|
+
self.act = _ACTIVATIONS[activation]
|
|
47
|
+
|
|
48
|
+
def __call__(self, x, attn_mask=None):
|
|
49
|
+
y = self.layer_norm1(x)
|
|
50
|
+
y = self.attention(y, y, y, attn_mask)
|
|
51
|
+
x = y + x
|
|
52
|
+
|
|
53
|
+
y = self.layer_norm2(x)
|
|
54
|
+
y = self.linear1(y)
|
|
55
|
+
y = self.act(y)
|
|
56
|
+
y = self.linear2(y)
|
|
57
|
+
x = y + x
|
|
58
|
+
|
|
59
|
+
return x
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class CLIPTextModel(nn.Module):
|
|
63
|
+
"""Implements the text encoder transformer from CLIP."""
|
|
64
|
+
|
|
65
|
+
def __init__(self, config: CLIPTextModelConfig):
|
|
66
|
+
super().__init__()
|
|
67
|
+
|
|
68
|
+
self.token_embedding = nn.Embedding(config.vocab_size, config.model_dims)
|
|
69
|
+
self.position_embedding = nn.Embedding(config.max_length, config.model_dims)
|
|
70
|
+
self.layers = [
|
|
71
|
+
CLIPEncoderLayer(config.model_dims, config.num_heads, config.hidden_act)
|
|
72
|
+
for i in range(config.num_layers)
|
|
73
|
+
]
|
|
74
|
+
self.final_layer_norm = nn.LayerNorm(config.model_dims)
|
|
75
|
+
|
|
76
|
+
if config.projection_dim is not None:
|
|
77
|
+
self.text_projection = nn.Linear(
|
|
78
|
+
config.model_dims, config.projection_dim, bias=False
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
def _get_mask(self, N, dtype):
|
|
82
|
+
indices = mx.arange(N)
|
|
83
|
+
mask = indices[:, None] < indices[None]
|
|
84
|
+
mask = mask.astype(dtype) * (-6e4 if dtype == mx.float16 else -1e9)
|
|
85
|
+
return mask
|
|
86
|
+
|
|
87
|
+
def __call__(self, x):
|
|
88
|
+
# Extract some shapes
|
|
89
|
+
B, N = x.shape
|
|
90
|
+
eos_tokens = x.argmax(-1)
|
|
91
|
+
|
|
92
|
+
# Compute the embeddings
|
|
93
|
+
x = self.token_embedding(x)
|
|
94
|
+
x = x + self.position_embedding.weight[:N]
|
|
95
|
+
|
|
96
|
+
# Compute the features from the transformer
|
|
97
|
+
mask = self._get_mask(N, x.dtype)
|
|
98
|
+
hidden_states = []
|
|
99
|
+
for l in self.layers:
|
|
100
|
+
x = l(x, mask)
|
|
101
|
+
hidden_states.append(x)
|
|
102
|
+
|
|
103
|
+
# Apply the final layernorm and return
|
|
104
|
+
x = self.final_layer_norm(x)
|
|
105
|
+
last_hidden_state = x
|
|
106
|
+
|
|
107
|
+
# Select the EOS token
|
|
108
|
+
pooled_output = x[mx.arange(len(x)), eos_tokens]
|
|
109
|
+
if "text_projection" in self:
|
|
110
|
+
pooled_output = self.text_projection(pooled_output)
|
|
111
|
+
|
|
112
|
+
return CLIPOutput(
|
|
113
|
+
pooled_output=pooled_output,
|
|
114
|
+
last_hidden_state=last_hidden_state,
|
|
115
|
+
hidden_states=hidden_states,
|
|
116
|
+
)
|