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
@@ -0,0 +1,513 @@
|
|
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.Inpaint")
|
19
|
+
class Inpaint(Task):
|
20
|
+
"""Base class for image-to-image tasks.
|
21
|
+
|
22
|
+
`Inpaint` 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
|
+
`Inpaint` tasks provide an additional, high-level `generate()` function
|
27
|
+
which can be used to generate image by token with a (image, mask, string)
|
28
|
+
in, image out signature.
|
29
|
+
|
30
|
+
All `Inpaint` 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
|
+
reference_mask = np.ones((1024, 1024), dtype="float32")
|
39
|
+
inpaint = keras_hub.models.Inpaint.from_preset(
|
40
|
+
"stable_diffusion_3_medium",
|
41
|
+
)
|
42
|
+
inpaint.generate(
|
43
|
+
reference_image,
|
44
|
+
reference_mask,
|
45
|
+
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
46
|
+
)
|
47
|
+
|
48
|
+
# Load a Stable Diffusion 3 backbone at bfloat16 precision.
|
49
|
+
inpaint = keras_hub.models.Inpaint.from_preset(
|
50
|
+
"stable_diffusion_3_medium",
|
51
|
+
dtype="bfloat16",
|
52
|
+
)
|
53
|
+
inpaint.generate(
|
54
|
+
reference_image,
|
55
|
+
reference_mask,
|
56
|
+
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
57
|
+
)
|
58
|
+
```
|
59
|
+
"""
|
60
|
+
|
61
|
+
def __init__(self, *args, **kwargs):
|
62
|
+
super().__init__(*args, **kwargs)
|
63
|
+
# Default compilation.
|
64
|
+
self.compile()
|
65
|
+
|
66
|
+
@property
|
67
|
+
def support_negative_prompts(self):
|
68
|
+
"""Whether the model supports `negative_prompts` key in `generate()`."""
|
69
|
+
return bool(True)
|
70
|
+
|
71
|
+
@property
|
72
|
+
def image_shape(self):
|
73
|
+
return tuple(self.backbone.image_shape)
|
74
|
+
|
75
|
+
@property
|
76
|
+
def latent_shape(self):
|
77
|
+
return tuple(self.backbone.latent_shape)
|
78
|
+
|
79
|
+
def compile(
|
80
|
+
self,
|
81
|
+
optimizer="auto",
|
82
|
+
loss="auto",
|
83
|
+
*,
|
84
|
+
metrics="auto",
|
85
|
+
**kwargs,
|
86
|
+
):
|
87
|
+
"""Configures the `Inpaint` task for training.
|
88
|
+
|
89
|
+
The `Inpaint` task extends the default compilation signature of
|
90
|
+
`keras.Model.compile` with defaults for `optimizer`, `loss`, and
|
91
|
+
`metrics`. To override these defaults, pass any value
|
92
|
+
to these arguments during compilation.
|
93
|
+
|
94
|
+
Args:
|
95
|
+
optimizer: `"auto"`, an optimizer name, or a `keras.Optimizer`
|
96
|
+
instance. Defaults to `"auto"`, which uses the default optimizer
|
97
|
+
for the given model and task. See `keras.Model.compile` and
|
98
|
+
`keras.optimizers` for more info on possible `optimizer` values.
|
99
|
+
loss: `"auto"`, a loss name, or a `keras.losses.Loss` instance.
|
100
|
+
Defaults to `"auto"`, where a
|
101
|
+
`keras.losses.MeanSquaredError` loss will be applied. See
|
102
|
+
`keras.Model.compile` and `keras.losses` for more info on
|
103
|
+
possible `loss` values.
|
104
|
+
metrics: `"auto"`, or a list of metrics to be evaluated by
|
105
|
+
the model during training and testing. Defaults to `"auto"`,
|
106
|
+
where a `keras.metrics.MeanSquaredError` will be applied to
|
107
|
+
track the loss of the model during training. See
|
108
|
+
`keras.Model.compile` and `keras.metrics` for more info on
|
109
|
+
possible `metrics` values.
|
110
|
+
**kwargs: See `keras.Model.compile` for a full list of arguments
|
111
|
+
supported by the compile method.
|
112
|
+
"""
|
113
|
+
# Ref: https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image.py#L410-L414
|
114
|
+
if optimizer == "auto":
|
115
|
+
optimizer = keras.optimizers.AdamW(
|
116
|
+
1e-4, weight_decay=1e-2, epsilon=1e-8, clipnorm=1.0
|
117
|
+
)
|
118
|
+
if loss == "auto":
|
119
|
+
loss = keras.losses.MeanSquaredError()
|
120
|
+
if metrics == "auto":
|
121
|
+
metrics = [keras.metrics.MeanSquaredError()]
|
122
|
+
super().compile(
|
123
|
+
optimizer=optimizer,
|
124
|
+
loss=loss,
|
125
|
+
metrics=metrics,
|
126
|
+
**kwargs,
|
127
|
+
)
|
128
|
+
self.generate_function = None
|
129
|
+
|
130
|
+
def generate_step(self, *args, **kwargs):
|
131
|
+
"""Run generation on batches of input."""
|
132
|
+
raise NotImplementedError
|
133
|
+
|
134
|
+
def make_generate_function(self):
|
135
|
+
"""Create or return the compiled generation function."""
|
136
|
+
if self.generate_function is not None:
|
137
|
+
return self.generate_function
|
138
|
+
|
139
|
+
self.generate_function = self.generate_step
|
140
|
+
if keras.config.backend() == "torch":
|
141
|
+
import torch
|
142
|
+
|
143
|
+
def wrapped_function(*args, **kwargs):
|
144
|
+
with torch.no_grad():
|
145
|
+
return self.generate_step(*args, **kwargs)
|
146
|
+
|
147
|
+
self.generate_function = wrapped_function
|
148
|
+
elif keras.config.backend() == "tensorflow" and not self.run_eagerly:
|
149
|
+
self.generate_function = tf.function(
|
150
|
+
self.generate_step, jit_compile=self.jit_compile
|
151
|
+
)
|
152
|
+
elif keras.config.backend() == "jax" and not self.run_eagerly:
|
153
|
+
import jax
|
154
|
+
|
155
|
+
@partial(jax.jit)
|
156
|
+
def compiled_function(state, *args, **kwargs):
|
157
|
+
(
|
158
|
+
trainable_variables,
|
159
|
+
non_trainable_variables,
|
160
|
+
) = state
|
161
|
+
mapping = itertools.chain(
|
162
|
+
zip(self.trainable_variables, trainable_variables),
|
163
|
+
zip(self.non_trainable_variables, non_trainable_variables),
|
164
|
+
)
|
165
|
+
|
166
|
+
with keras.StatelessScope(state_mapping=mapping):
|
167
|
+
outputs = self.generate_step(*args, **kwargs)
|
168
|
+
return outputs
|
169
|
+
|
170
|
+
def wrapped_function(*args, **kwargs):
|
171
|
+
# Create an explicit tuple of all variable state.
|
172
|
+
state = (
|
173
|
+
# Use the explicit variable.value to preserve the
|
174
|
+
# sharding spec of distribution.
|
175
|
+
[v.value for v in self.trainable_variables],
|
176
|
+
[v.value for v in self.non_trainable_variables],
|
177
|
+
)
|
178
|
+
outputs = compiled_function(state, *args, **kwargs)
|
179
|
+
return outputs
|
180
|
+
|
181
|
+
self.generate_function = wrapped_function
|
182
|
+
return self.generate_function
|
183
|
+
|
184
|
+
def _normalize_generate_images(self, inputs):
|
185
|
+
"""Normalize user image to the generate function.
|
186
|
+
|
187
|
+
This function converts all inputs to tensors, adds a batch dimension if
|
188
|
+
necessary, and returns a iterable "dataset like" object (either an
|
189
|
+
actual `tf.data.Dataset` or a list with a single batch element).
|
190
|
+
"""
|
191
|
+
if tf and isinstance(inputs, tf.data.Dataset):
|
192
|
+
return inputs.as_numpy_iterator(), False
|
193
|
+
|
194
|
+
def normalize(x):
|
195
|
+
data_format = getattr(
|
196
|
+
self.backbone, "data_format", standardize_data_format(None)
|
197
|
+
)
|
198
|
+
input_is_scalar = False
|
199
|
+
x = ops.convert_to_tensor(x)
|
200
|
+
if len(ops.shape(x)) < 4:
|
201
|
+
x = ops.expand_dims(x, axis=0)
|
202
|
+
input_is_scalar = True
|
203
|
+
x = ops.image.resize(
|
204
|
+
x,
|
205
|
+
(self.backbone.height, self.backbone.width),
|
206
|
+
interpolation="nearest",
|
207
|
+
data_format=data_format,
|
208
|
+
)
|
209
|
+
return x, input_is_scalar
|
210
|
+
|
211
|
+
if isinstance(inputs, dict):
|
212
|
+
for key in inputs:
|
213
|
+
inputs[key], input_is_scalar = normalize(inputs[key])
|
214
|
+
else:
|
215
|
+
inputs, input_is_scalar = normalize(inputs)
|
216
|
+
|
217
|
+
return inputs, input_is_scalar
|
218
|
+
|
219
|
+
def _normalize_generate_masks(self, inputs):
|
220
|
+
"""Normalize user masks to the generate function.
|
221
|
+
|
222
|
+
This function converts all inputs to tensors, adds a batch dimension if
|
223
|
+
necessary, and returns a iterable "dataset like" object (either an
|
224
|
+
actual `tf.data.Dataset` or a list with a single batch element).
|
225
|
+
"""
|
226
|
+
if tf and isinstance(inputs, tf.data.Dataset):
|
227
|
+
return inputs.as_numpy_iterator(), False
|
228
|
+
|
229
|
+
def normalize(x):
|
230
|
+
data_format = getattr(
|
231
|
+
self.backbone, "data_format", standardize_data_format(None)
|
232
|
+
)
|
233
|
+
input_is_scalar = False
|
234
|
+
x = ops.convert_to_tensor(x)
|
235
|
+
if len(ops.shape(x)) < 3:
|
236
|
+
x = ops.expand_dims(x, axis=0)
|
237
|
+
input_is_scalar = True
|
238
|
+
x = ops.expand_dims(x, axis=-1)
|
239
|
+
if keras.backend.standardize_dtype(x.dtype) == "bool":
|
240
|
+
x = ops.cast(x, "float32")
|
241
|
+
x = ops.image.resize(
|
242
|
+
x,
|
243
|
+
(self.backbone.height, self.backbone.width),
|
244
|
+
interpolation="nearest",
|
245
|
+
data_format=data_format,
|
246
|
+
)
|
247
|
+
x = ops.squeeze(x, axis=-1)
|
248
|
+
return x, input_is_scalar
|
249
|
+
|
250
|
+
if isinstance(inputs, dict):
|
251
|
+
for key in inputs:
|
252
|
+
inputs[key], input_is_scalar = normalize(inputs[key])
|
253
|
+
else:
|
254
|
+
inputs, input_is_scalar = normalize(inputs)
|
255
|
+
|
256
|
+
return inputs, input_is_scalar
|
257
|
+
|
258
|
+
def _normalize_generate_inputs(self, inputs):
|
259
|
+
"""Normalize user input to the generate function.
|
260
|
+
|
261
|
+
This function converts all inputs to tensors, adds a batch dimension if
|
262
|
+
necessary, and returns a iterable "dataset like" object (either an
|
263
|
+
actual `tf.data.Dataset` or a list with a single batch element).
|
264
|
+
|
265
|
+
The input format must be one of the following:
|
266
|
+
- A dict with "images", "masks", "prompts" and/or "negative_prompts"
|
267
|
+
keys
|
268
|
+
- A tf.data.Dataset with "images", "masks", "prompts" and/or
|
269
|
+
"negative_prompts" keys
|
270
|
+
|
271
|
+
The output will be a dict with "images", "masks", "prompts" and/or
|
272
|
+
"negative_prompts" keys.
|
273
|
+
"""
|
274
|
+
if tf and isinstance(inputs, tf.data.Dataset):
|
275
|
+
_inputs = {
|
276
|
+
"images": inputs.map(lambda x: x["images"]).as_numpy_iterator(),
|
277
|
+
"masks": inputs.map(lambda x: x["masks"]).as_numpy_iterator(),
|
278
|
+
"prompts": inputs.map(
|
279
|
+
lambda x: x["prompts"]
|
280
|
+
).as_numpy_iterator(),
|
281
|
+
}
|
282
|
+
if self.support_negative_prompts:
|
283
|
+
_inputs["negative_prompts"] = inputs.map(
|
284
|
+
lambda x: x["negative_prompts"]
|
285
|
+
).as_numpy_iterator()
|
286
|
+
return _inputs, False
|
287
|
+
|
288
|
+
def normalize(x):
|
289
|
+
if isinstance(x, str):
|
290
|
+
return [x], True
|
291
|
+
if tf and isinstance(x, tf.Tensor) and x.shape.rank == 0:
|
292
|
+
return x[tf.newaxis], True
|
293
|
+
return x, False
|
294
|
+
|
295
|
+
def normalize_images(x):
|
296
|
+
data_format = getattr(
|
297
|
+
self.backbone, "data_format", standardize_data_format(None)
|
298
|
+
)
|
299
|
+
input_is_scalar = False
|
300
|
+
x = ops.convert_to_tensor(x)
|
301
|
+
if len(ops.shape(x)) < 4:
|
302
|
+
x = ops.expand_dims(x, axis=0)
|
303
|
+
input_is_scalar = True
|
304
|
+
x = ops.image.resize(
|
305
|
+
x,
|
306
|
+
(self.backbone.height, self.backbone.width),
|
307
|
+
interpolation="nearest",
|
308
|
+
data_format=data_format,
|
309
|
+
)
|
310
|
+
return x, input_is_scalar
|
311
|
+
|
312
|
+
def normalize_masks(x):
|
313
|
+
data_format = getattr(
|
314
|
+
self.backbone, "data_format", standardize_data_format(None)
|
315
|
+
)
|
316
|
+
input_is_scalar = False
|
317
|
+
x = ops.convert_to_tensor(x)
|
318
|
+
if len(ops.shape(x)) < 3:
|
319
|
+
x = ops.expand_dims(x, axis=0)
|
320
|
+
input_is_scalar = True
|
321
|
+
x = ops.expand_dims(x, axis=-1)
|
322
|
+
if keras.backend.standardize_dtype(x.dtype) == "bool":
|
323
|
+
x = ops.cast(x, "float32")
|
324
|
+
x = ops.image.resize(
|
325
|
+
x,
|
326
|
+
(self.backbone.height, self.backbone.width),
|
327
|
+
interpolation="nearest",
|
328
|
+
data_format=data_format,
|
329
|
+
)
|
330
|
+
x = ops.squeeze(x, axis=-1)
|
331
|
+
return x, input_is_scalar
|
332
|
+
|
333
|
+
def get_dummy_prompts(x):
|
334
|
+
dummy_prompts = [""] * len(x)
|
335
|
+
if tf and isinstance(x, tf.Tensor):
|
336
|
+
return tf.convert_to_tensor(dummy_prompts)
|
337
|
+
else:
|
338
|
+
return dummy_prompts
|
339
|
+
|
340
|
+
for key in inputs:
|
341
|
+
if key == "images":
|
342
|
+
inputs[key], input_is_scalar = normalize_images(inputs[key])
|
343
|
+
elif key == "masks":
|
344
|
+
inputs[key], input_is_scalar = normalize_masks(inputs[key])
|
345
|
+
else:
|
346
|
+
inputs[key], input_is_scalar = normalize(inputs[key])
|
347
|
+
|
348
|
+
if self.support_negative_prompts and "negative_prompts" not in inputs:
|
349
|
+
inputs["negative_prompts"] = get_dummy_prompts(inputs["prompts"])
|
350
|
+
|
351
|
+
return [inputs], input_is_scalar
|
352
|
+
|
353
|
+
def _normalize_generate_outputs(self, outputs, input_is_scalar):
|
354
|
+
"""Normalize user output from the generate function.
|
355
|
+
|
356
|
+
This function converts all output to numpy with a value range of
|
357
|
+
`[0, 255]`. If a batch dimension was added to the input, it is removed
|
358
|
+
from the output.
|
359
|
+
"""
|
360
|
+
|
361
|
+
def normalize(x):
|
362
|
+
outputs = ops.concatenate(x, axis=0)
|
363
|
+
outputs = ops.clip(ops.divide(ops.add(outputs, 1.0), 2.0), 0.0, 1.0)
|
364
|
+
outputs = ops.cast(ops.round(ops.multiply(outputs, 255.0)), "uint8")
|
365
|
+
outputs = ops.squeeze(outputs, 0) if input_is_scalar else outputs
|
366
|
+
return ops.convert_to_numpy(outputs)
|
367
|
+
|
368
|
+
if isinstance(outputs[0], dict):
|
369
|
+
normalized = {}
|
370
|
+
for key in outputs[0]:
|
371
|
+
normalized[key] = normalize([x[key] for x in outputs])
|
372
|
+
return normalized
|
373
|
+
return normalize([x for x in outputs])
|
374
|
+
|
375
|
+
def generate(
|
376
|
+
self,
|
377
|
+
inputs,
|
378
|
+
num_steps,
|
379
|
+
guidance_scale,
|
380
|
+
strength,
|
381
|
+
seed=None,
|
382
|
+
):
|
383
|
+
"""Generate image based on the provided `inputs`.
|
384
|
+
|
385
|
+
Typically, `inputs` is a dict with `"images"` `"masks"` and `"prompts"`
|
386
|
+
keys. `"images"` are reference images within a value range of
|
387
|
+
`[-1.0, 1.0]`, which will be resized to `self.backbone.height` and
|
388
|
+
`self.backbone.width`, then encoded into latent space by the VAE
|
389
|
+
encoder. `"masks"` are mask images with a boolean dtype, where white
|
390
|
+
pixels are repainted while black pixels are preserved. `"prompts"` are
|
391
|
+
strings that will be tokenized and encoded by the text encoder.
|
392
|
+
|
393
|
+
Some models support a `"negative_prompts"` key, which helps steer the
|
394
|
+
model away from generating certain styles and elements. To enable this,
|
395
|
+
add `"negative_prompts"` to the input dict.
|
396
|
+
|
397
|
+
If `inputs` are a `tf.data.Dataset`, outputs will be generated
|
398
|
+
"batch-by-batch" and concatenated. Otherwise, all inputs will be
|
399
|
+
processed as batches.
|
400
|
+
|
401
|
+
Args:
|
402
|
+
inputs: python data, tensor data, or a `tf.data.Dataset`. The format
|
403
|
+
must be one of the following:
|
404
|
+
- A dict with `"images"`, `"masks"`, `"prompts"` and/or
|
405
|
+
`"negative_prompts"` keys.
|
406
|
+
- A `tf.data.Dataset` with `"images"`, `"masks"`, `"prompts"`
|
407
|
+
and/or `"negative_prompts"` keys.
|
408
|
+
num_steps: int. The number of diffusion steps to take.
|
409
|
+
guidance_scale: float. The classifier free guidance scale defined in
|
410
|
+
[Classifier-Free Diffusion Guidance](
|
411
|
+
https://arxiv.org/abs/2207.12598). A higher scale encourages
|
412
|
+
generating images more closely related to the prompts, typically
|
413
|
+
at the cost of lower image quality.
|
414
|
+
strength: float. Indicates the extent to which the reference
|
415
|
+
`images` are transformed. Must be between `0.0` and `1.0`. When
|
416
|
+
`strength=1.0`, `images` is essentially ignore and added noise
|
417
|
+
is maximum and the denoising process runs for the full number of
|
418
|
+
iterations specified in `num_steps`.
|
419
|
+
seed: optional int. Used as a random seed.
|
420
|
+
"""
|
421
|
+
num_steps = int(num_steps)
|
422
|
+
guidance_scale = float(guidance_scale)
|
423
|
+
strength = float(strength)
|
424
|
+
if strength < 0.0 or strength > 1.0:
|
425
|
+
raise ValueError(
|
426
|
+
"`strength` must be between `0.0` and `1.0`. "
|
427
|
+
f"Received strength={strength}."
|
428
|
+
)
|
429
|
+
starting_step = int(num_steps * (1.0 - strength))
|
430
|
+
starting_step = ops.convert_to_tensor(starting_step, "int32")
|
431
|
+
num_steps = ops.convert_to_tensor(num_steps, "int32")
|
432
|
+
guidance_scale = ops.convert_to_tensor(guidance_scale)
|
433
|
+
|
434
|
+
# Check `inputs` format.
|
435
|
+
required_keys = ["images", "masks", "prompts"]
|
436
|
+
if tf and isinstance(inputs, tf.data.Dataset):
|
437
|
+
spec = inputs.element_spec
|
438
|
+
if not all(key in spec for key in required_keys):
|
439
|
+
raise ValueError(
|
440
|
+
"Expected a `tf.data.Dataset` with the following keys:"
|
441
|
+
f"{required_keys}. Received: inputs.element_spec={spec}"
|
442
|
+
)
|
443
|
+
else:
|
444
|
+
if not isinstance(inputs, dict):
|
445
|
+
raise ValueError(
|
446
|
+
"Expected a `dict` or `tf.data.Dataset`. "
|
447
|
+
f"Received: inputs={inputs} of type {type(inputs)}."
|
448
|
+
)
|
449
|
+
if not all(key in inputs for key in required_keys):
|
450
|
+
raise ValueError(
|
451
|
+
"Expected a `dict` with the following keys:"
|
452
|
+
f"{required_keys}. "
|
453
|
+
f"Received: inputs.keys={list(inputs.keys())}"
|
454
|
+
)
|
455
|
+
|
456
|
+
# Setup our three main passes.
|
457
|
+
# 1. Preprocessing strings to dense integer tensors.
|
458
|
+
# 2. Generate outputs via a compiled function on dense tensors.
|
459
|
+
# 3. Postprocess dense tensors to a value range of `[0, 255]`.
|
460
|
+
generate_function = self.make_generate_function()
|
461
|
+
|
462
|
+
def preprocess(x):
|
463
|
+
if self.preprocessor is not None:
|
464
|
+
return self.preprocessor.generate_preprocess(x)
|
465
|
+
else:
|
466
|
+
return x
|
467
|
+
|
468
|
+
def generate(images, masks, x):
|
469
|
+
token_ids = x[0] if self.support_negative_prompts else x
|
470
|
+
|
471
|
+
# Initialize noises.
|
472
|
+
if isinstance(token_ids, dict):
|
473
|
+
arbitrary_key = list(token_ids.keys())[0]
|
474
|
+
batch_size = ops.shape(token_ids[arbitrary_key])[0]
|
475
|
+
else:
|
476
|
+
batch_size = ops.shape(token_ids)[0]
|
477
|
+
noise_shape = (batch_size,) + self.latent_shape[1:]
|
478
|
+
noises = random.normal(noise_shape, dtype="float32", seed=seed)
|
479
|
+
|
480
|
+
return generate_function(
|
481
|
+
images,
|
482
|
+
masks,
|
483
|
+
noises,
|
484
|
+
x,
|
485
|
+
starting_step,
|
486
|
+
num_steps,
|
487
|
+
guidance_scale,
|
488
|
+
)
|
489
|
+
|
490
|
+
# Normalize and preprocess inputs.
|
491
|
+
inputs, input_is_scalar = self._normalize_generate_inputs(inputs)
|
492
|
+
if self.support_negative_prompts:
|
493
|
+
images = [x["images"] for x in inputs]
|
494
|
+
masks = [x["masks"] for x in inputs]
|
495
|
+
token_ids = [preprocess(x["prompts"]) for x in inputs]
|
496
|
+
negative_token_ids = [
|
497
|
+
preprocess(x["negative_prompts"]) for x in inputs
|
498
|
+
]
|
499
|
+
# Tuple format: (images, masks, (token_ids, negative_token_ids)).
|
500
|
+
inputs = [
|
501
|
+
x
|
502
|
+
for x in zip(images, masks, zip(token_ids, negative_token_ids))
|
503
|
+
]
|
504
|
+
else:
|
505
|
+
images = [x["images"] for x in inputs]
|
506
|
+
masks = [x["masks"] for x in inputs]
|
507
|
+
token_ids = [preprocess(x["prompts"]) for x in inputs]
|
508
|
+
# Tuple format: (images, masks, token_ids).
|
509
|
+
inputs = [x for x in zip(images, masks, token_ids)]
|
510
|
+
|
511
|
+
# Inpaint.
|
512
|
+
outputs = [generate(*x) for x in inputs]
|
513
|
+
return self._normalize_generate_outputs(outputs, input_is_scalar)
|
@@ -0,0 +1,12 @@
|
|
1
|
+
from keras_hub.src.models.mix_transformer.mix_transformer_backbone import (
|
2
|
+
MiTBackbone,
|
3
|
+
)
|
4
|
+
from keras_hub.src.models.mix_transformer.mix_transformer_classifier import (
|
5
|
+
MiTImageClassifier,
|
6
|
+
)
|
7
|
+
from keras_hub.src.models.mix_transformer.mix_transformer_presets import (
|
8
|
+
backbone_presets,
|
9
|
+
)
|
10
|
+
from keras_hub.src.utils.preset_utils import register_presets
|
11
|
+
|
12
|
+
register_presets(backbone_presets, MiTBackbone)
|
@@ -3,8 +3,12 @@ from keras_hub.src.models.image_classifier import ImageClassifier
|
|
3
3
|
from keras_hub.src.models.mix_transformer.mix_transformer_backbone import (
|
4
4
|
MiTBackbone,
|
5
5
|
)
|
6
|
+
from keras_hub.src.models.mix_transformer.mix_transformer_classifier_preprocessor import (
|
7
|
+
MiTImageClassifierPreprocessor,
|
8
|
+
)
|
6
9
|
|
7
10
|
|
8
11
|
@keras_hub_export("keras_hub.models.MiTImageClassifier")
|
9
12
|
class MiTImageClassifier(ImageClassifier):
|
10
13
|
backbone_cls = MiTBackbone
|
14
|
+
preprocessor_cls = MiTImageClassifierPreprocessor
|
@@ -0,0 +1,16 @@
|
|
1
|
+
from keras_hub.src.api_export import keras_hub_export
|
2
|
+
from keras_hub.src.models.image_classifier_preprocessor import (
|
3
|
+
ImageClassifierPreprocessor,
|
4
|
+
)
|
5
|
+
from keras_hub.src.models.mix_transformer.mix_transformer_backbone import (
|
6
|
+
MiTBackbone,
|
7
|
+
)
|
8
|
+
from keras_hub.src.models.mix_transformer.mix_transformer_image_converter import (
|
9
|
+
MiTImageConverter,
|
10
|
+
)
|
11
|
+
|
12
|
+
|
13
|
+
@keras_hub_export("keras_hub.models.MiTImageClassifierPreprocessor")
|
14
|
+
class MiTImageClassifierPreprocessor(ImageClassifierPreprocessor):
|
15
|
+
backbone_cls = MiTBackbone
|
16
|
+
image_converter_cls = MiTImageConverter
|
@@ -0,0 +1,8 @@
|
|
1
|
+
from keras_hub.src.api_export import keras_hub_export
|
2
|
+
from keras_hub.src.layers.preprocessing.image_converter import ImageConverter
|
3
|
+
from keras_hub.src.models.mix_transformer import MiTBackbone
|
4
|
+
|
5
|
+
|
6
|
+
@keras_hub_export("keras_hub.layers.MiTImageConverter")
|
7
|
+
class MiTImageConverter(ImageConverter):
|
8
|
+
backbone_cls = MiTBackbone
|
@@ -28,19 +28,23 @@ class OverlappingPatchingAndEmbedding(keras.layers.Layer):
|
|
28
28
|
self.patch_size = patch_size
|
29
29
|
self.stride = stride
|
30
30
|
|
31
|
+
padding_size = self.patch_size // 2
|
32
|
+
|
33
|
+
self.padding = keras.layers.ZeroPadding2D(
|
34
|
+
padding=(padding_size, padding_size)
|
35
|
+
)
|
31
36
|
self.proj = keras.layers.Conv2D(
|
32
37
|
filters=project_dim,
|
33
38
|
kernel_size=patch_size,
|
34
39
|
strides=stride,
|
35
|
-
padding="
|
40
|
+
padding="valid",
|
36
41
|
)
|
37
|
-
self.norm = keras.layers.LayerNormalization()
|
42
|
+
self.norm = keras.layers.LayerNormalization(epsilon=1e-5)
|
38
43
|
|
39
44
|
def call(self, x):
|
45
|
+
x = self.padding(x)
|
40
46
|
x = self.proj(x)
|
41
|
-
|
42
|
-
shape = x.shape
|
43
|
-
x = ops.reshape(x, (-1, shape[1] * shape[2], shape[3]))
|
47
|
+
x = ops.reshape(x, (-1, x.shape[1] * x.shape[2], x.shape[3]))
|
44
48
|
x = self.norm(x)
|
45
49
|
return x
|
46
50
|
|