keras-hub-nightly 0.16.1.dev202410080341__py3-none-any.whl → 0.16.1.dev202410100339__py3-none-any.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.
- keras_hub/api/layers/__init__.py +3 -0
- keras_hub/api/models/__init__.py +11 -0
- keras_hub/src/layers/preprocessing/image_converter.py +2 -1
- keras_hub/src/models/image_to_image.py +411 -0
- keras_hub/src/models/inpaint.py +513 -0
- keras_hub/src/models/mix_transformer/__init__.py +12 -0
- keras_hub/src/models/mix_transformer/mix_transformer_classifier.py +4 -0
- keras_hub/src/models/mix_transformer/mix_transformer_classifier_preprocessor.py +16 -0
- keras_hub/src/models/mix_transformer/mix_transformer_image_converter.py +8 -0
- keras_hub/src/models/mix_transformer/mix_transformer_layers.py +9 -5
- keras_hub/src/models/mix_transformer/mix_transformer_presets.py +151 -0
- keras_hub/src/models/preprocessor.py +4 -4
- keras_hub/src/models/stable_diffusion_3/mmdit.py +308 -177
- keras_hub/src/models/stable_diffusion_3/stable_diffusion_3_backbone.py +87 -55
- keras_hub/src/models/stable_diffusion_3/stable_diffusion_3_image_to_image.py +171 -0
- keras_hub/src/models/stable_diffusion_3/stable_diffusion_3_inpaint.py +194 -0
- keras_hub/src/models/stable_diffusion_3/stable_diffusion_3_presets.py +1 -1
- keras_hub/src/models/stable_diffusion_3/stable_diffusion_3_text_to_image.py +13 -8
- keras_hub/src/models/task.py +1 -1
- keras_hub/src/models/text_to_image.py +89 -36
- keras_hub/src/tests/test_case.py +3 -1
- keras_hub/src/tokenizers/tokenizer.py +7 -7
- keras_hub/src/utils/preset_utils.py +7 -7
- keras_hub/src/utils/timm/preset_loader.py +1 -3
- keras_hub/src/version_utils.py +1 -1
- {keras_hub_nightly-0.16.1.dev202410080341.dist-info → keras_hub_nightly-0.16.1.dev202410100339.dist-info}/METADATA +1 -1
- {keras_hub_nightly-0.16.1.dev202410080341.dist-info → keras_hub_nightly-0.16.1.dev202410100339.dist-info}/RECORD +29 -22
- {keras_hub_nightly-0.16.1.dev202410080341.dist-info → keras_hub_nightly-0.16.1.dev202410100339.dist-info}/WHEEL +0 -0
- {keras_hub_nightly-0.16.1.dev202410080341.dist-info → keras_hub_nightly-0.16.1.dev202410100339.dist-info}/top_level.txt +0 -0
keras_hub/api/layers/__init__.py
CHANGED
@@ -40,6 +40,9 @@ from keras_hub.src.models.deeplab_v3.deeplab_v3_image_converter import (
|
|
40
40
|
from keras_hub.src.models.densenet.densenet_image_converter import (
|
41
41
|
DenseNetImageConverter,
|
42
42
|
)
|
43
|
+
from keras_hub.src.models.mix_transformer.mix_transformer_image_converter import (
|
44
|
+
MiTImageConverter,
|
45
|
+
)
|
43
46
|
from keras_hub.src.models.pali_gemma.pali_gemma_image_converter import (
|
44
47
|
PaliGemmaImageConverter,
|
45
48
|
)
|
keras_hub/api/models/__init__.py
CHANGED
@@ -180,6 +180,8 @@ from keras_hub.src.models.image_segmenter import ImageSegmenter
|
|
180
180
|
from keras_hub.src.models.image_segmenter_preprocessor import (
|
181
181
|
ImageSegmenterPreprocessor,
|
182
182
|
)
|
183
|
+
from keras_hub.src.models.image_to_image import ImageToImage
|
184
|
+
from keras_hub.src.models.inpaint import Inpaint
|
183
185
|
from keras_hub.src.models.llama3.llama3_backbone import Llama3Backbone
|
184
186
|
from keras_hub.src.models.llama3.llama3_causal_lm import Llama3CausalLM
|
185
187
|
from keras_hub.src.models.llama3.llama3_causal_lm_preprocessor import (
|
@@ -206,6 +208,9 @@ from keras_hub.src.models.mix_transformer.mix_transformer_backbone import (
|
|
206
208
|
from keras_hub.src.models.mix_transformer.mix_transformer_classifier import (
|
207
209
|
MiTImageClassifier,
|
208
210
|
)
|
211
|
+
from keras_hub.src.models.mix_transformer.mix_transformer_classifier_preprocessor import (
|
212
|
+
MiTImageClassifierPreprocessor,
|
213
|
+
)
|
209
214
|
from keras_hub.src.models.mobilenet.mobilenet_backbone import MobileNetBackbone
|
210
215
|
from keras_hub.src.models.mobilenet.mobilenet_image_classifier import (
|
211
216
|
MobileNetImageClassifier,
|
@@ -270,6 +275,12 @@ from keras_hub.src.models.seq_2_seq_lm_preprocessor import Seq2SeqLMPreprocessor
|
|
270
275
|
from keras_hub.src.models.stable_diffusion_3.stable_diffusion_3_backbone import (
|
271
276
|
StableDiffusion3Backbone,
|
272
277
|
)
|
278
|
+
from keras_hub.src.models.stable_diffusion_3.stable_diffusion_3_image_to_image import (
|
279
|
+
StableDiffusion3ImageToImage,
|
280
|
+
)
|
281
|
+
from keras_hub.src.models.stable_diffusion_3.stable_diffusion_3_inpaint import (
|
282
|
+
StableDiffusion3Inpaint,
|
283
|
+
)
|
273
284
|
from keras_hub.src.models.stable_diffusion_3.stable_diffusion_3_text_to_image import (
|
274
285
|
StableDiffusion3TextToImage,
|
275
286
|
)
|
@@ -145,8 +145,9 @@ class ImageConverter(PreprocessingLayer):
|
|
145
145
|
|
146
146
|
@preprocessing_function
|
147
147
|
def call(self, inputs):
|
148
|
+
x = inputs
|
148
149
|
if self.image_size is not None:
|
149
|
-
x = self.resizing(
|
150
|
+
x = self.resizing(x)
|
150
151
|
if self.scale is not None:
|
151
152
|
x = x * self._expand_non_channel_dims(self.scale, x)
|
152
153
|
if self.offset is not None:
|
@@ -0,0 +1,411 @@
|
|
1
|
+
import itertools
|
2
|
+
from functools import partial
|
3
|
+
|
4
|
+
import keras
|
5
|
+
from keras import ops
|
6
|
+
from keras import random
|
7
|
+
|
8
|
+
from keras_hub.src.api_export import keras_hub_export
|
9
|
+
from keras_hub.src.models.task import Task
|
10
|
+
from keras_hub.src.utils.keras_utils import standardize_data_format
|
11
|
+
|
12
|
+
try:
|
13
|
+
import tensorflow as tf
|
14
|
+
except ImportError:
|
15
|
+
tf = None
|
16
|
+
|
17
|
+
|
18
|
+
@keras_hub_export("keras_hub.models.ImageToImage")
|
19
|
+
class ImageToImage(Task):
|
20
|
+
"""Base class for image-to-image tasks.
|
21
|
+
|
22
|
+
`ImageToImage` tasks wrap a `keras_hub.models.Backbone` and
|
23
|
+
a `keras_hub.models.Preprocessor` to create a model that can be used for
|
24
|
+
generation and generative fine-tuning.
|
25
|
+
|
26
|
+
`ImageToImage` tasks provide an additional, high-level `generate()` function
|
27
|
+
which can be used to generate image by token with a (image, string) in,
|
28
|
+
image out signature.
|
29
|
+
|
30
|
+
All `ImageToImage` tasks include a `from_preset()` constructor which can be
|
31
|
+
used to load a pre-trained config and weights.
|
32
|
+
|
33
|
+
Example:
|
34
|
+
|
35
|
+
```python
|
36
|
+
# Load a Stable Diffusion 3 backbone with pre-trained weights.
|
37
|
+
reference_image = np.ones((1024, 1024, 3), dtype="float32")
|
38
|
+
image_to_image = keras_hub.models.ImageToImage.from_preset(
|
39
|
+
"stable_diffusion_3_medium",
|
40
|
+
)
|
41
|
+
image_to_image.generate(
|
42
|
+
reference_image,
|
43
|
+
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
44
|
+
)
|
45
|
+
|
46
|
+
# Load a Stable Diffusion 3 backbone at bfloat16 precision.
|
47
|
+
image_to_image = keras_hub.models.ImageToImage.from_preset(
|
48
|
+
"stable_diffusion_3_medium",
|
49
|
+
dtype="bfloat16",
|
50
|
+
)
|
51
|
+
image_to_image.generate(
|
52
|
+
reference_image,
|
53
|
+
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
54
|
+
)
|
55
|
+
```
|
56
|
+
"""
|
57
|
+
|
58
|
+
def __init__(self, *args, **kwargs):
|
59
|
+
super().__init__(*args, **kwargs)
|
60
|
+
# Default compilation.
|
61
|
+
self.compile()
|
62
|
+
|
63
|
+
@property
|
64
|
+
def support_negative_prompts(self):
|
65
|
+
"""Whether the model supports `negative_prompts` key in `generate()`."""
|
66
|
+
return bool(True)
|
67
|
+
|
68
|
+
@property
|
69
|
+
def image_shape(self):
|
70
|
+
return tuple(self.backbone.image_shape)
|
71
|
+
|
72
|
+
@property
|
73
|
+
def latent_shape(self):
|
74
|
+
return tuple(self.backbone.latent_shape)
|
75
|
+
|
76
|
+
def compile(
|
77
|
+
self,
|
78
|
+
optimizer="auto",
|
79
|
+
loss="auto",
|
80
|
+
*,
|
81
|
+
metrics="auto",
|
82
|
+
**kwargs,
|
83
|
+
):
|
84
|
+
"""Configures the `ImageToImage` task for training.
|
85
|
+
|
86
|
+
The `ImageToImage` task extends the default compilation signature of
|
87
|
+
`keras.Model.compile` with defaults for `optimizer`, `loss`, and
|
88
|
+
`metrics`. To override these defaults, pass any value
|
89
|
+
to these arguments during compilation.
|
90
|
+
|
91
|
+
Args:
|
92
|
+
optimizer: `"auto"`, an optimizer name, or a `keras.Optimizer`
|
93
|
+
instance. Defaults to `"auto"`, which uses the default optimizer
|
94
|
+
for the given model and task. See `keras.Model.compile` and
|
95
|
+
`keras.optimizers` for more info on possible `optimizer` values.
|
96
|
+
loss: `"auto"`, a loss name, or a `keras.losses.Loss` instance.
|
97
|
+
Defaults to `"auto"`, where a
|
98
|
+
`keras.losses.MeanSquaredError` loss will be applied. See
|
99
|
+
`keras.Model.compile` and `keras.losses` for more info on
|
100
|
+
possible `loss` values.
|
101
|
+
metrics: `"auto"`, or a list of metrics to be evaluated by
|
102
|
+
the model during training and testing. Defaults to `"auto"`,
|
103
|
+
where a `keras.metrics.MeanSquaredError` will be applied to
|
104
|
+
track the loss of the model during training. See
|
105
|
+
`keras.Model.compile` and `keras.metrics` for more info on
|
106
|
+
possible `metrics` values.
|
107
|
+
**kwargs: See `keras.Model.compile` for a full list of arguments
|
108
|
+
supported by the compile method.
|
109
|
+
"""
|
110
|
+
# Ref: https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image.py#L410-L414
|
111
|
+
if optimizer == "auto":
|
112
|
+
optimizer = keras.optimizers.AdamW(
|
113
|
+
1e-4, weight_decay=1e-2, epsilon=1e-8, clipnorm=1.0
|
114
|
+
)
|
115
|
+
if loss == "auto":
|
116
|
+
loss = keras.losses.MeanSquaredError()
|
117
|
+
if metrics == "auto":
|
118
|
+
metrics = [keras.metrics.MeanSquaredError()]
|
119
|
+
super().compile(
|
120
|
+
optimizer=optimizer,
|
121
|
+
loss=loss,
|
122
|
+
metrics=metrics,
|
123
|
+
**kwargs,
|
124
|
+
)
|
125
|
+
self.generate_function = None
|
126
|
+
|
127
|
+
def generate_step(self, *args, **kwargs):
|
128
|
+
"""Run generation on batches of input."""
|
129
|
+
raise NotImplementedError
|
130
|
+
|
131
|
+
def make_generate_function(self):
|
132
|
+
"""Create or return the compiled generation function."""
|
133
|
+
if self.generate_function is not None:
|
134
|
+
return self.generate_function
|
135
|
+
|
136
|
+
self.generate_function = self.generate_step
|
137
|
+
if keras.config.backend() == "torch":
|
138
|
+
import torch
|
139
|
+
|
140
|
+
def wrapped_function(*args, **kwargs):
|
141
|
+
with torch.no_grad():
|
142
|
+
return self.generate_step(*args, **kwargs)
|
143
|
+
|
144
|
+
self.generate_function = wrapped_function
|
145
|
+
elif keras.config.backend() == "tensorflow" and not self.run_eagerly:
|
146
|
+
self.generate_function = tf.function(
|
147
|
+
self.generate_step, jit_compile=self.jit_compile
|
148
|
+
)
|
149
|
+
elif keras.config.backend() == "jax" and not self.run_eagerly:
|
150
|
+
import jax
|
151
|
+
|
152
|
+
@partial(jax.jit)
|
153
|
+
def compiled_function(state, *args, **kwargs):
|
154
|
+
(
|
155
|
+
trainable_variables,
|
156
|
+
non_trainable_variables,
|
157
|
+
) = state
|
158
|
+
mapping = itertools.chain(
|
159
|
+
zip(self.trainable_variables, trainable_variables),
|
160
|
+
zip(self.non_trainable_variables, non_trainable_variables),
|
161
|
+
)
|
162
|
+
|
163
|
+
with keras.StatelessScope(state_mapping=mapping):
|
164
|
+
outputs = self.generate_step(*args, **kwargs)
|
165
|
+
return outputs
|
166
|
+
|
167
|
+
def wrapped_function(*args, **kwargs):
|
168
|
+
# Create an explicit tuple of all variable state.
|
169
|
+
state = (
|
170
|
+
# Use the explicit variable.value to preserve the
|
171
|
+
# sharding spec of distribution.
|
172
|
+
[v.value for v in self.trainable_variables],
|
173
|
+
[v.value for v in self.non_trainable_variables],
|
174
|
+
)
|
175
|
+
outputs = compiled_function(state, *args, **kwargs)
|
176
|
+
return outputs
|
177
|
+
|
178
|
+
self.generate_function = wrapped_function
|
179
|
+
return self.generate_function
|
180
|
+
|
181
|
+
def _normalize_generate_inputs(self, inputs):
|
182
|
+
"""Normalize user input to the generate function.
|
183
|
+
|
184
|
+
This function converts all inputs to tensors, adds a batch dimension if
|
185
|
+
necessary, and returns a iterable "dataset like" object (either an
|
186
|
+
actual `tf.data.Dataset` or a list with a single batch element).
|
187
|
+
|
188
|
+
The input format must be one of the following:
|
189
|
+
- A dict with "images", "prompts" and/or "negative_prompts" keys
|
190
|
+
- A tf.data.Dataset with "images", "prompts" and/or "negative_prompts"
|
191
|
+
keys
|
192
|
+
|
193
|
+
The output will be a dict with "images", "prompts" and/or
|
194
|
+
"negative_prompts" keys.
|
195
|
+
"""
|
196
|
+
if tf and isinstance(inputs, tf.data.Dataset):
|
197
|
+
_inputs = {
|
198
|
+
"images": inputs.map(lambda x: x["images"]).as_numpy_iterator(),
|
199
|
+
"prompts": inputs.map(
|
200
|
+
lambda x: x["prompts"]
|
201
|
+
).as_numpy_iterator(),
|
202
|
+
}
|
203
|
+
if self.support_negative_prompts:
|
204
|
+
_inputs["negative_prompts"] = inputs.map(
|
205
|
+
lambda x: x["negative_prompts"]
|
206
|
+
).as_numpy_iterator()
|
207
|
+
return _inputs, False
|
208
|
+
|
209
|
+
if (
|
210
|
+
not isinstance(inputs, dict)
|
211
|
+
or "images" not in inputs
|
212
|
+
or "prompts" not in inputs
|
213
|
+
):
|
214
|
+
raise ValueError(
|
215
|
+
'`inputs` must be a dict with "images" and "prompts" keys or a'
|
216
|
+
f"tf.data.Dataset. Received: inputs={inputs}"
|
217
|
+
)
|
218
|
+
|
219
|
+
def normalize(x):
|
220
|
+
if isinstance(x, str):
|
221
|
+
return [x], True
|
222
|
+
if tf and isinstance(x, tf.Tensor) and x.shape.rank == 0:
|
223
|
+
return x[tf.newaxis], True
|
224
|
+
return x, False
|
225
|
+
|
226
|
+
def normalize_images(x):
|
227
|
+
data_format = getattr(
|
228
|
+
self.backbone, "data_format", standardize_data_format(None)
|
229
|
+
)
|
230
|
+
input_is_scalar = False
|
231
|
+
x = ops.convert_to_tensor(x)
|
232
|
+
if len(ops.shape(x)) < 4:
|
233
|
+
x = ops.expand_dims(x, axis=0)
|
234
|
+
input_is_scalar = True
|
235
|
+
x = ops.image.resize(
|
236
|
+
x,
|
237
|
+
(self.backbone.height, self.backbone.width),
|
238
|
+
interpolation="nearest",
|
239
|
+
data_format=data_format,
|
240
|
+
)
|
241
|
+
return x, input_is_scalar
|
242
|
+
|
243
|
+
def get_dummy_prompts(x):
|
244
|
+
dummy_prompts = [""] * len(x)
|
245
|
+
if tf and isinstance(x, tf.Tensor):
|
246
|
+
return tf.convert_to_tensor(dummy_prompts)
|
247
|
+
else:
|
248
|
+
return dummy_prompts
|
249
|
+
|
250
|
+
for key in inputs:
|
251
|
+
if key == "images":
|
252
|
+
inputs[key], input_is_scalar = normalize_images(inputs[key])
|
253
|
+
else:
|
254
|
+
inputs[key], input_is_scalar = normalize(inputs[key])
|
255
|
+
|
256
|
+
if self.support_negative_prompts and "negative_prompts" not in inputs:
|
257
|
+
inputs["negative_prompts"] = get_dummy_prompts(inputs["prompts"])
|
258
|
+
|
259
|
+
return [inputs], input_is_scalar
|
260
|
+
|
261
|
+
def _normalize_generate_outputs(self, outputs, input_is_scalar):
|
262
|
+
"""Normalize user output from the generate function.
|
263
|
+
|
264
|
+
This function converts all output to numpy with a value range of
|
265
|
+
`[0, 255]`. If a batch dimension was added to the input, it is removed
|
266
|
+
from the output.
|
267
|
+
"""
|
268
|
+
|
269
|
+
def normalize(x):
|
270
|
+
outputs = ops.concatenate(x, axis=0)
|
271
|
+
outputs = ops.clip(ops.divide(ops.add(outputs, 1.0), 2.0), 0.0, 1.0)
|
272
|
+
outputs = ops.cast(ops.round(ops.multiply(outputs, 255.0)), "uint8")
|
273
|
+
outputs = ops.squeeze(outputs, 0) if input_is_scalar else outputs
|
274
|
+
return ops.convert_to_numpy(outputs)
|
275
|
+
|
276
|
+
if isinstance(outputs[0], dict):
|
277
|
+
normalized = {}
|
278
|
+
for key in outputs[0]:
|
279
|
+
normalized[key] = normalize([x[key] for x in outputs])
|
280
|
+
return normalized
|
281
|
+
return normalize([x for x in outputs])
|
282
|
+
|
283
|
+
def generate(
|
284
|
+
self,
|
285
|
+
inputs,
|
286
|
+
num_steps,
|
287
|
+
guidance_scale,
|
288
|
+
strength,
|
289
|
+
seed=None,
|
290
|
+
):
|
291
|
+
"""Generate image based on the provided `inputs`.
|
292
|
+
|
293
|
+
Typically, `inputs` is a dict with `"images"` and `"prompts"` keys.
|
294
|
+
`"images"` are reference images within a value range of
|
295
|
+
`[-1.0, 1.0]`, which will be resized to `self.backbone.height` and
|
296
|
+
`self.backbone.width`, then encoded into latent space by the VAE
|
297
|
+
encoder. `"prompts"` are strings that will be tokenized and encoded by
|
298
|
+
the text encoder.
|
299
|
+
|
300
|
+
Some models support a `"negative_prompts"` key, which helps steer the
|
301
|
+
model away from generating certain styles and elements. To enable this,
|
302
|
+
add `"negative_prompts"` to the input dict.
|
303
|
+
|
304
|
+
If `inputs` are a `tf.data.Dataset`, outputs will be generated
|
305
|
+
"batch-by-batch" and concatenated. Otherwise, all inputs will be
|
306
|
+
processed as batches.
|
307
|
+
|
308
|
+
Args:
|
309
|
+
inputs: python data, tensor data, or a `tf.data.Dataset`. The format
|
310
|
+
must be one of the following:
|
311
|
+
- A dict with `"images"`, `"prompts"` and/or
|
312
|
+
`"negative_prompts"` keys.
|
313
|
+
- A `tf.data.Dataset` with `"images"`, `"prompts"` and/or
|
314
|
+
`"negative_prompts"` keys.
|
315
|
+
num_steps: int. The number of diffusion steps to take.
|
316
|
+
guidance_scale: float. The classifier free guidance scale defined in
|
317
|
+
[Classifier-Free Diffusion Guidance](
|
318
|
+
https://arxiv.org/abs/2207.12598). A higher scale encourages
|
319
|
+
generating images more closely related to the prompts, typically
|
320
|
+
at the cost of lower image quality.
|
321
|
+
strength: float. Indicates the extent to which the reference
|
322
|
+
`images` are transformed. Must be between `0.0` and `1.0`. When
|
323
|
+
`strength=1.0`, `images` is essentially ignore and added noise
|
324
|
+
is maximum and the denoising process runs for the full number of
|
325
|
+
iterations specified in `num_steps`.
|
326
|
+
seed: optional int. Used as a random seed.
|
327
|
+
"""
|
328
|
+
num_steps = int(num_steps)
|
329
|
+
guidance_scale = float(guidance_scale)
|
330
|
+
strength = float(strength)
|
331
|
+
if strength < 0.0 or strength > 1.0:
|
332
|
+
raise ValueError(
|
333
|
+
"`strength` must be between `0.0` and `1.0`. "
|
334
|
+
f"Received strength={strength}."
|
335
|
+
)
|
336
|
+
starting_step = int(num_steps * (1.0 - strength))
|
337
|
+
starting_step = ops.convert_to_tensor(starting_step, "int32")
|
338
|
+
num_steps = ops.convert_to_tensor(num_steps, "int32")
|
339
|
+
guidance_scale = ops.convert_to_tensor(guidance_scale)
|
340
|
+
|
341
|
+
# Check `inputs` format.
|
342
|
+
required_keys = ["images", "prompts"]
|
343
|
+
if tf and isinstance(inputs, tf.data.Dataset):
|
344
|
+
spec = inputs.element_spec
|
345
|
+
if not all(key in spec for key in required_keys):
|
346
|
+
raise ValueError(
|
347
|
+
"Expected a `tf.data.Dataset` with the following keys:"
|
348
|
+
f"{required_keys}. Received: inputs.element_spec={spec}"
|
349
|
+
)
|
350
|
+
else:
|
351
|
+
if not isinstance(inputs, dict):
|
352
|
+
raise ValueError(
|
353
|
+
"Expected a `dict` or `tf.data.Dataset`. "
|
354
|
+
f"Received: inputs={inputs} of type {type(inputs)}."
|
355
|
+
)
|
356
|
+
if not all(key in inputs for key in required_keys):
|
357
|
+
raise ValueError(
|
358
|
+
"Expected a `dict` with the following keys:"
|
359
|
+
f"{required_keys}. "
|
360
|
+
f"Received: inputs.keys={list(inputs.keys())}"
|
361
|
+
)
|
362
|
+
|
363
|
+
# Setup our three main passes.
|
364
|
+
# 1. Preprocessing strings to dense integer tensors.
|
365
|
+
# 2. Generate outputs via a compiled function on dense tensors.
|
366
|
+
# 3. Postprocess dense tensors to a value range of `[0, 255]`.
|
367
|
+
generate_function = self.make_generate_function()
|
368
|
+
|
369
|
+
def preprocess(x):
|
370
|
+
if self.preprocessor is not None:
|
371
|
+
return self.preprocessor.generate_preprocess(x)
|
372
|
+
else:
|
373
|
+
return x
|
374
|
+
|
375
|
+
def generate(images, x):
|
376
|
+
token_ids = x[0] if self.support_negative_prompts else x
|
377
|
+
|
378
|
+
# Initialize noises.
|
379
|
+
if isinstance(token_ids, dict):
|
380
|
+
arbitrary_key = list(token_ids.keys())[0]
|
381
|
+
batch_size = ops.shape(token_ids[arbitrary_key])[0]
|
382
|
+
else:
|
383
|
+
batch_size = ops.shape(token_ids)[0]
|
384
|
+
noise_shape = (batch_size,) + self.latent_shape[1:]
|
385
|
+
noises = random.normal(noise_shape, dtype="float32", seed=seed)
|
386
|
+
|
387
|
+
return generate_function(
|
388
|
+
images, noises, x, starting_step, num_steps, guidance_scale
|
389
|
+
)
|
390
|
+
|
391
|
+
# Normalize and preprocess inputs.
|
392
|
+
inputs, input_is_scalar = self._normalize_generate_inputs(inputs)
|
393
|
+
if self.support_negative_prompts:
|
394
|
+
images = [x["images"] for x in inputs]
|
395
|
+
token_ids = [preprocess(x["prompts"]) for x in inputs]
|
396
|
+
negative_token_ids = [
|
397
|
+
preprocess(x["negative_prompts"]) for x in inputs
|
398
|
+
]
|
399
|
+
# Tuple format: (images, (token_ids, negative_token_ids)).
|
400
|
+
inputs = [
|
401
|
+
x for x in zip(images, zip(token_ids, negative_token_ids))
|
402
|
+
]
|
403
|
+
else:
|
404
|
+
images = [x["images"] for x in inputs]
|
405
|
+
token_ids = [preprocess(x["prompts"]) for x in inputs]
|
406
|
+
# Tuple format: (images, token_ids).
|
407
|
+
inputs = [x for x in zip(images, token_ids)]
|
408
|
+
|
409
|
+
# Image-to-image.
|
410
|
+
outputs = [generate(*x) for x in inputs]
|
411
|
+
return self._normalize_generate_outputs(outputs, input_is_scalar)
|