ai-edge-torch-nightly 0.3.0.dev20250114__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (213) hide show
  1. ai_edge_torch/__init__.py +32 -0
  2. ai_edge_torch/_config.py +69 -0
  3. ai_edge_torch/_convert/__init__.py +14 -0
  4. ai_edge_torch/_convert/conversion.py +153 -0
  5. ai_edge_torch/_convert/conversion_utils.py +64 -0
  6. ai_edge_torch/_convert/converter.py +270 -0
  7. ai_edge_torch/_convert/fx_passes/__init__.py +23 -0
  8. ai_edge_torch/_convert/fx_passes/build_aten_composite_pass.py +288 -0
  9. ai_edge_torch/_convert/fx_passes/build_interpolate_composite_pass.py +131 -0
  10. ai_edge_torch/_convert/fx_passes/inject_mlir_debuginfo_pass.py +73 -0
  11. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/__init__.py +16 -0
  12. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_check.py +258 -0
  13. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_mark.py +50 -0
  14. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/__init__.py +18 -0
  15. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/greedy.py +68 -0
  16. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_partitioners/min_cut.py +216 -0
  17. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/layout_rewrite.py +449 -0
  18. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/op_func_registry.py +30 -0
  19. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/pass_body.py +303 -0
  20. ai_edge_torch/_convert/fx_passes/optimize_layout_transposes_pass/utils.py +64 -0
  21. ai_edge_torch/_convert/fx_passes/remove_non_user_outputs_pass.py +52 -0
  22. ai_edge_torch/_convert/signature.py +66 -0
  23. ai_edge_torch/_convert/test/__init__.py +14 -0
  24. ai_edge_torch/_convert/test/test_convert.py +558 -0
  25. ai_edge_torch/_convert/test/test_convert_composites.py +234 -0
  26. ai_edge_torch/_convert/test/test_convert_multisig.py +189 -0
  27. ai_edge_torch/_convert/test/test_to_channel_last_io.py +96 -0
  28. ai_edge_torch/_convert/to_channel_last_io.py +92 -0
  29. ai_edge_torch/conftest.py +20 -0
  30. ai_edge_torch/debug/__init__.py +17 -0
  31. ai_edge_torch/debug/culprit.py +496 -0
  32. ai_edge_torch/debug/test/__init__.py +14 -0
  33. ai_edge_torch/debug/test/test_culprit.py +140 -0
  34. ai_edge_torch/debug/test/test_search_model.py +51 -0
  35. ai_edge_torch/debug/utils.py +59 -0
  36. ai_edge_torch/experimental/__init__.py +14 -0
  37. ai_edge_torch/fx_pass_base.py +110 -0
  38. ai_edge_torch/generative/__init__.py +14 -0
  39. ai_edge_torch/generative/examples/__init__.py +14 -0
  40. ai_edge_torch/generative/examples/amd_llama_135m/__init__.py +14 -0
  41. ai_edge_torch/generative/examples/amd_llama_135m/amd_llama_135m.py +87 -0
  42. ai_edge_torch/generative/examples/amd_llama_135m/convert_to_tflite.py +70 -0
  43. ai_edge_torch/generative/examples/amd_llama_135m/verify.py +72 -0
  44. ai_edge_torch/generative/examples/gemma/__init__.py +14 -0
  45. ai_edge_torch/generative/examples/gemma/convert_gemma1_to_tflite.py +80 -0
  46. ai_edge_torch/generative/examples/gemma/convert_gemma2_to_tflite.py +80 -0
  47. ai_edge_torch/generative/examples/gemma/gemma1.py +107 -0
  48. ai_edge_torch/generative/examples/gemma/gemma2.py +295 -0
  49. ai_edge_torch/generative/examples/gemma/verify_gemma1.py +56 -0
  50. ai_edge_torch/generative/examples/gemma/verify_gemma2.py +43 -0
  51. ai_edge_torch/generative/examples/gemma/verify_util.py +157 -0
  52. ai_edge_torch/generative/examples/llama/__init__.py +14 -0
  53. ai_edge_torch/generative/examples/llama/convert_to_tflite.py +91 -0
  54. ai_edge_torch/generative/examples/llama/llama.py +196 -0
  55. ai_edge_torch/generative/examples/llama/verify.py +88 -0
  56. ai_edge_torch/generative/examples/moonshine/__init__.py +14 -0
  57. ai_edge_torch/generative/examples/moonshine/convert_moonshine_to_tflite.py +50 -0
  58. ai_edge_torch/generative/examples/moonshine/moonshine.py +103 -0
  59. ai_edge_torch/generative/examples/openelm/__init__.py +14 -0
  60. ai_edge_torch/generative/examples/openelm/convert_to_tflite.py +80 -0
  61. ai_edge_torch/generative/examples/openelm/openelm.py +127 -0
  62. ai_edge_torch/generative/examples/openelm/verify.py +71 -0
  63. ai_edge_torch/generative/examples/paligemma/__init__.py +14 -0
  64. ai_edge_torch/generative/examples/paligemma/convert_to_tflite.py +95 -0
  65. ai_edge_torch/generative/examples/paligemma/decoder.py +151 -0
  66. ai_edge_torch/generative/examples/paligemma/decoder2.py +177 -0
  67. ai_edge_torch/generative/examples/paligemma/image_encoder.py +160 -0
  68. ai_edge_torch/generative/examples/paligemma/paligemma.py +179 -0
  69. ai_edge_torch/generative/examples/paligemma/verify.py +161 -0
  70. ai_edge_torch/generative/examples/paligemma/verify_decoder.py +75 -0
  71. ai_edge_torch/generative/examples/paligemma/verify_decoder2.py +72 -0
  72. ai_edge_torch/generative/examples/paligemma/verify_image_encoder.py +99 -0
  73. ai_edge_torch/generative/examples/phi/__init__.py +14 -0
  74. ai_edge_torch/generative/examples/phi/convert_phi3_to_tflite.py +80 -0
  75. ai_edge_torch/generative/examples/phi/convert_to_tflite.py +80 -0
  76. ai_edge_torch/generative/examples/phi/phi2.py +107 -0
  77. ai_edge_torch/generative/examples/phi/phi3.py +219 -0
  78. ai_edge_torch/generative/examples/phi/verify.py +64 -0
  79. ai_edge_torch/generative/examples/phi/verify_phi3.py +69 -0
  80. ai_edge_torch/generative/examples/qwen/__init__.py +14 -0
  81. ai_edge_torch/generative/examples/qwen/convert_to_tflite.py +93 -0
  82. ai_edge_torch/generative/examples/qwen/qwen.py +134 -0
  83. ai_edge_torch/generative/examples/qwen/verify.py +88 -0
  84. ai_edge_torch/generative/examples/smollm/__init__.py +14 -0
  85. ai_edge_torch/generative/examples/smollm/convert_to_tflite.py +80 -0
  86. ai_edge_torch/generative/examples/smollm/convert_v2_to_tflite.py +71 -0
  87. ai_edge_torch/generative/examples/smollm/smollm.py +125 -0
  88. ai_edge_torch/generative/examples/smollm/verify.py +86 -0
  89. ai_edge_torch/generative/examples/stable_diffusion/__init__.py +14 -0
  90. ai_edge_torch/generative/examples/stable_diffusion/attention.py +108 -0
  91. ai_edge_torch/generative/examples/stable_diffusion/clip.py +185 -0
  92. ai_edge_torch/generative/examples/stable_diffusion/convert_to_tflite.py +173 -0
  93. ai_edge_torch/generative/examples/stable_diffusion/decoder.py +398 -0
  94. ai_edge_torch/generative/examples/stable_diffusion/diffusion.py +749 -0
  95. ai_edge_torch/generative/examples/stable_diffusion/encoder.py +119 -0
  96. ai_edge_torch/generative/examples/stable_diffusion/pipeline.py +254 -0
  97. ai_edge_torch/generative/examples/stable_diffusion/samplers/__init__.py +19 -0
  98. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler.py +62 -0
  99. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler_ancestral.py +66 -0
  100. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_lms.py +74 -0
  101. ai_edge_torch/generative/examples/stable_diffusion/samplers/sampler.py +39 -0
  102. ai_edge_torch/generative/examples/stable_diffusion/tokenizer.py +111 -0
  103. ai_edge_torch/generative/examples/stable_diffusion/util.py +77 -0
  104. ai_edge_torch/generative/examples/t5/__init__.py +14 -0
  105. ai_edge_torch/generative/examples/t5/convert_to_tflite.py +138 -0
  106. ai_edge_torch/generative/examples/t5/t5.py +655 -0
  107. ai_edge_torch/generative/examples/t5/t5_attention.py +246 -0
  108. ai_edge_torch/generative/examples/test_models/__init__.py +14 -0
  109. ai_edge_torch/generative/examples/test_models/convert_toy_model.py +105 -0
  110. ai_edge_torch/generative/examples/test_models/toy_model.py +156 -0
  111. ai_edge_torch/generative/examples/test_models/toy_model_with_kv_cache.py +138 -0
  112. ai_edge_torch/generative/examples/tiny_llama/__init__.py +14 -0
  113. ai_edge_torch/generative/examples/tiny_llama/convert_to_tflite.py +80 -0
  114. ai_edge_torch/generative/examples/tiny_llama/tiny_llama.py +88 -0
  115. ai_edge_torch/generative/examples/tiny_llama/verify.py +72 -0
  116. ai_edge_torch/generative/fx_passes/__init__.py +30 -0
  117. ai_edge_torch/generative/fx_passes/remove_sdpa_zero_mask_pass.py +50 -0
  118. ai_edge_torch/generative/layers/__init__.py +14 -0
  119. ai_edge_torch/generative/layers/attention.py +399 -0
  120. ai_edge_torch/generative/layers/attention_utils.py +210 -0
  121. ai_edge_torch/generative/layers/builder.py +160 -0
  122. ai_edge_torch/generative/layers/feed_forward.py +120 -0
  123. ai_edge_torch/generative/layers/kv_cache.py +204 -0
  124. ai_edge_torch/generative/layers/lora.py +557 -0
  125. ai_edge_torch/generative/layers/model_config.py +238 -0
  126. ai_edge_torch/generative/layers/normalization.py +222 -0
  127. ai_edge_torch/generative/layers/rotary_position_embedding.py +94 -0
  128. ai_edge_torch/generative/layers/scaled_dot_product_attention.py +144 -0
  129. ai_edge_torch/generative/layers/unet/__init__.py +14 -0
  130. ai_edge_torch/generative/layers/unet/blocks_2d.py +806 -0
  131. ai_edge_torch/generative/layers/unet/builder.py +50 -0
  132. ai_edge_torch/generative/layers/unet/model_config.py +282 -0
  133. ai_edge_torch/generative/quantize/__init__.py +14 -0
  134. ai_edge_torch/generative/quantize/example.py +47 -0
  135. ai_edge_torch/generative/quantize/quant_attrs.py +68 -0
  136. ai_edge_torch/generative/quantize/quant_recipe.py +154 -0
  137. ai_edge_torch/generative/quantize/quant_recipe_utils.py +62 -0
  138. ai_edge_torch/generative/quantize/quant_recipes.py +56 -0
  139. ai_edge_torch/generative/quantize/supported_schemes.py +32 -0
  140. ai_edge_torch/generative/test/__init__.py +14 -0
  141. ai_edge_torch/generative/test/test_custom_dus.py +107 -0
  142. ai_edge_torch/generative/test/test_kv_cache.py +120 -0
  143. ai_edge_torch/generative/test/test_loader.py +83 -0
  144. ai_edge_torch/generative/test/test_lora.py +147 -0
  145. ai_edge_torch/generative/test/test_model_conversion.py +191 -0
  146. ai_edge_torch/generative/test/test_model_conversion_large.py +362 -0
  147. ai_edge_torch/generative/test/test_quantize.py +183 -0
  148. ai_edge_torch/generative/test/utils.py +82 -0
  149. ai_edge_torch/generative/utilities/__init__.py +15 -0
  150. ai_edge_torch/generative/utilities/converter.py +215 -0
  151. ai_edge_torch/generative/utilities/dynamic_update_slice.py +56 -0
  152. ai_edge_torch/generative/utilities/loader.py +398 -0
  153. ai_edge_torch/generative/utilities/model_builder.py +180 -0
  154. ai_edge_torch/generative/utilities/moonshine_loader.py +154 -0
  155. ai_edge_torch/generative/utilities/stable_diffusion_loader.py +1032 -0
  156. ai_edge_torch/generative/utilities/t5_loader.py +512 -0
  157. ai_edge_torch/generative/utilities/transformers_verifier.py +42 -0
  158. ai_edge_torch/generative/utilities/verifier.py +335 -0
  159. ai_edge_torch/hlfb/__init__.py +16 -0
  160. ai_edge_torch/hlfb/mark_pattern/__init__.py +153 -0
  161. ai_edge_torch/hlfb/mark_pattern/fx_utils.py +69 -0
  162. ai_edge_torch/hlfb/mark_pattern/pattern.py +288 -0
  163. ai_edge_torch/hlfb/test/__init__.py +14 -0
  164. ai_edge_torch/hlfb/test/test_mark_pattern.py +185 -0
  165. ai_edge_torch/lowertools/__init__.py +18 -0
  166. ai_edge_torch/lowertools/_shim.py +86 -0
  167. ai_edge_torch/lowertools/common_utils.py +142 -0
  168. ai_edge_torch/lowertools/odml_torch_utils.py +260 -0
  169. ai_edge_torch/lowertools/test_utils.py +62 -0
  170. ai_edge_torch/lowertools/torch_xla_utils.py +301 -0
  171. ai_edge_torch/lowertools/translate_recipe.py +163 -0
  172. ai_edge_torch/model.py +177 -0
  173. ai_edge_torch/odml_torch/__init__.py +20 -0
  174. ai_edge_torch/odml_torch/_torch_future.py +88 -0
  175. ai_edge_torch/odml_torch/_torch_library.py +19 -0
  176. ai_edge_torch/odml_torch/composite/__init__.py +16 -0
  177. ai_edge_torch/odml_torch/composite/mark_tensor.py +120 -0
  178. ai_edge_torch/odml_torch/composite/stablehlo_composite_builder.py +106 -0
  179. ai_edge_torch/odml_torch/debuginfo/__init__.py +16 -0
  180. ai_edge_torch/odml_torch/debuginfo/_build.py +43 -0
  181. ai_edge_torch/odml_torch/debuginfo/_op_polyfill.py +55 -0
  182. ai_edge_torch/odml_torch/export.py +403 -0
  183. ai_edge_torch/odml_torch/export_utils.py +157 -0
  184. ai_edge_torch/odml_torch/jax_bridge/__init__.py +18 -0
  185. ai_edge_torch/odml_torch/jax_bridge/_wrap.py +180 -0
  186. ai_edge_torch/odml_torch/jax_bridge/utils.py +75 -0
  187. ai_edge_torch/odml_torch/lowerings/__init__.py +27 -0
  188. ai_edge_torch/odml_torch/lowerings/_basic.py +294 -0
  189. ai_edge_torch/odml_torch/lowerings/_batch_norm.py +65 -0
  190. ai_edge_torch/odml_torch/lowerings/_convolution.py +243 -0
  191. ai_edge_torch/odml_torch/lowerings/_jax_lowerings.py +285 -0
  192. ai_edge_torch/odml_torch/lowerings/_layer_norm.py +87 -0
  193. ai_edge_torch/odml_torch/lowerings/_quantized_decomposed.py +177 -0
  194. ai_edge_torch/odml_torch/lowerings/_rand.py +142 -0
  195. ai_edge_torch/odml_torch/lowerings/context.py +42 -0
  196. ai_edge_torch/odml_torch/lowerings/decomp.py +69 -0
  197. ai_edge_torch/odml_torch/lowerings/registry.py +65 -0
  198. ai_edge_torch/odml_torch/lowerings/utils.py +201 -0
  199. ai_edge_torch/odml_torch/passes/__init__.py +38 -0
  200. ai_edge_torch/odml_torch/tf_integration.py +156 -0
  201. ai_edge_torch/quantize/__init__.py +16 -0
  202. ai_edge_torch/quantize/pt2e_quantizer.py +466 -0
  203. ai_edge_torch/quantize/pt2e_quantizer_utils.py +1061 -0
  204. ai_edge_torch/quantize/quant_config.py +85 -0
  205. ai_edge_torch/testing/__init__.py +14 -0
  206. ai_edge_torch/testing/model_coverage/__init__.py +16 -0
  207. ai_edge_torch/testing/model_coverage/model_coverage.py +145 -0
  208. ai_edge_torch/version.py +16 -0
  209. ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/LICENSE +202 -0
  210. ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/METADATA +44 -0
  211. ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/RECORD +213 -0
  212. ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/WHEEL +5 -0
  213. ai_edge_torch_nightly-0.3.0.dev20250114.dist-info/top_level.txt +1 -0
@@ -0,0 +1,119 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ from ai_edge_torch.generative.examples.stable_diffusion.attention import SelfAttention # NOQA
17
+ import torch
18
+ from torch import nn
19
+ from torch.nn import functional as F
20
+
21
+
22
+ class AttentionBlock(nn.Module):
23
+
24
+ def __init__(self, channels):
25
+ super().__init__()
26
+ self.groupnorm = nn.GroupNorm(32, channels)
27
+ self.attention = SelfAttention(1, channels)
28
+
29
+ def forward(self, x):
30
+ residue = x
31
+ x = self.groupnorm(x)
32
+
33
+ n, c, h, w = x.shape
34
+ x = x.view((n, c, h * w))
35
+ x = x.transpose(-1, -2)
36
+ x = self.attention(x)
37
+ x = x.transpose(-1, -2)
38
+ x = x.view((n, c, h, w))
39
+
40
+ x += residue
41
+ return x
42
+
43
+
44
+ class ResidualBlock(nn.Module):
45
+
46
+ def __init__(self, in_channels, out_channels):
47
+ super().__init__()
48
+ self.groupnorm_1 = nn.GroupNorm(32, in_channels)
49
+ self.conv_1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)
50
+
51
+ self.groupnorm_2 = nn.GroupNorm(32, out_channels)
52
+ self.conv_2 = nn.Conv2d(
53
+ out_channels, out_channels, kernel_size=3, padding=1
54
+ )
55
+
56
+ if in_channels == out_channels:
57
+ self.residual_layer = nn.Identity()
58
+ else:
59
+ self.residual_layer = nn.Conv2d(
60
+ in_channels, out_channels, kernel_size=1, padding=0
61
+ )
62
+
63
+ def forward(self, x):
64
+ residue = x
65
+
66
+ x = self.groupnorm_1(x)
67
+ x = F.silu(x)
68
+ x = self.conv_1(x)
69
+
70
+ x = self.groupnorm_2(x)
71
+ x = F.silu(x)
72
+ x = self.conv_2(x)
73
+
74
+ return x + self.residual_layer(residue)
75
+
76
+
77
+ class Encoder(nn.Sequential):
78
+
79
+ def __init__(self):
80
+ super().__init__(
81
+ nn.Conv2d(3, 128, kernel_size=3, padding=1),
82
+ ResidualBlock(128, 128),
83
+ ResidualBlock(128, 128),
84
+ nn.Conv2d(128, 128, kernel_size=3, stride=2, padding=0),
85
+ ResidualBlock(128, 256),
86
+ ResidualBlock(256, 256),
87
+ nn.Conv2d(256, 256, kernel_size=3, stride=2, padding=0),
88
+ ResidualBlock(256, 512),
89
+ ResidualBlock(512, 512),
90
+ nn.Conv2d(512, 512, kernel_size=3, stride=2, padding=0),
91
+ ResidualBlock(512, 512),
92
+ ResidualBlock(512, 512),
93
+ ResidualBlock(512, 512),
94
+ AttentionBlock(512),
95
+ ResidualBlock(512, 512),
96
+ nn.GroupNorm(32, 512),
97
+ nn.SiLU(),
98
+ nn.Conv2d(512, 8, kernel_size=3, padding=1),
99
+ nn.Conv2d(8, 8, kernel_size=1, padding=0),
100
+ )
101
+
102
+ @torch.inference_mode
103
+ def forward(self, x, noise):
104
+ for module in self:
105
+ if getattr(module, 'stride', None) == (
106
+ 2,
107
+ 2,
108
+ ): # Padding at downsampling should be asymmetric (see #8)
109
+ x = F.pad(x, (0, 1, 0, 1))
110
+ x = module(x)
111
+
112
+ mean, log_variance = torch.chunk(x, 2, dim=1)
113
+ log_variance = torch.clamp(log_variance, -30, 20)
114
+ variance = log_variance.exp()
115
+ stdev = variance.sqrt()
116
+ x = mean + stdev * noise
117
+
118
+ x *= 0.18215
119
+ return x
@@ -0,0 +1,254 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ import argparse
17
+ import os
18
+ import pathlib
19
+ from typing import Optional
20
+
21
+ import ai_edge_torch
22
+ from ai_edge_torch.generative.examples.stable_diffusion import samplers
23
+ from ai_edge_torch.generative.examples.stable_diffusion import tokenizer
24
+ from ai_edge_torch.generative.examples.stable_diffusion import util
25
+ import numpy as np
26
+ from PIL import Image
27
+ import tqdm
28
+
29
+ arg_parser = argparse.ArgumentParser()
30
+ arg_parser.add_argument(
31
+ '--tokenizer_vocab_dir',
32
+ type=str,
33
+ help=(
34
+ 'Directory to the tokenizer vocabulary files, which include'
35
+ ' `merges.txt` and `vocab.json`'
36
+ ),
37
+ required=True,
38
+ )
39
+ arg_parser.add_argument(
40
+ '--clip_ckpt',
41
+ type=str,
42
+ help='Path to CLIP TFLite tflite file',
43
+ required=True,
44
+ )
45
+ arg_parser.add_argument(
46
+ '--diffusion_ckpt',
47
+ type=str,
48
+ help='Path to diffusion tflite file',
49
+ required=True,
50
+ )
51
+ arg_parser.add_argument(
52
+ '--decoder_ckpt',
53
+ type=str,
54
+ help='Path to decoder tflite file',
55
+ required=True,
56
+ )
57
+ arg_parser.add_argument(
58
+ '--output_path',
59
+ type=str,
60
+ help='Path to the output generated image file.',
61
+ required=True,
62
+ )
63
+ arg_parser.add_argument(
64
+ '--prompt',
65
+ default='a photograph of an astronaut riding a horse',
66
+ type=str,
67
+ help='The prompt to guide the image generation.',
68
+ )
69
+ arg_parser.add_argument(
70
+ '--n_inference_steps',
71
+ default=20,
72
+ type=int,
73
+ help='The number of denoising steps.',
74
+ )
75
+ arg_parser.add_argument(
76
+ '--sampler',
77
+ default='k_euler',
78
+ type=str,
79
+ choices=['k_euler', 'k_euler_ancestral', 'k_lms'],
80
+ help=(
81
+ 'A sampler to be used to denoise the encoded image latents. Can be one'
82
+ ' of `k_lms, `k_euler`, or `k_euler_ancestral`.'
83
+ ),
84
+ )
85
+ arg_parser.add_argument(
86
+ '--seed',
87
+ default=None,
88
+ type=int,
89
+ help=(
90
+ 'A seed to make generation deterministic. A random number is used if'
91
+ ' unspecified.'
92
+ ),
93
+ )
94
+
95
+
96
+ class StableDiffusion:
97
+
98
+ def __init__(
99
+ self,
100
+ *,
101
+ tokenizer_vocab_dir: str,
102
+ clip_ckpt: str,
103
+ encoder_ckpt: Optional[str] = None,
104
+ diffusion_ckpt: str,
105
+ decoder_ckpt: str
106
+ ):
107
+ self.tokenizer = tokenizer.Tokenizer(tokenizer_vocab_dir)
108
+ self.clip = ai_edge_torch.model.TfLiteModel.load(clip_ckpt)
109
+ self.decoder = ai_edge_torch.model.TfLiteModel.load(decoder_ckpt)
110
+ self.diffusion = ai_edge_torch.model.TfLiteModel.load(diffusion_ckpt)
111
+ if encoder_ckpt is not None:
112
+ self.encoder = ai_edge_torch.model.TfLiteModel.load(encoder_ckpt)
113
+
114
+
115
+ def run_tflite_pipeline(
116
+ model: StableDiffusion,
117
+ prompt: str,
118
+ output_path: str,
119
+ uncond_prompt: Optional[str] = None,
120
+ cfg_scale: float = 7.5,
121
+ height: int = 512,
122
+ width: int = 512,
123
+ sampler: str = 'k_euler',
124
+ n_inference_steps: int = 20,
125
+ seed: Optional[int] = None,
126
+ strength: float = 0.8,
127
+ input_image: Optional[Image.Image] = None,
128
+ ):
129
+ """Run stable diffusion pipeline with tflite model.
130
+
131
+ Args:
132
+ model: StableDiffsuion model.
133
+ prompt: The prompt to guide the image generation.
134
+ output_path: The path to the generated output image.
135
+ uncond_prompt: The prompt not to guide the image generation.
136
+ cfg_scale: Guidance scale of classifier-free guidance. Higher guidance scale
137
+ encourages to generate images that are closely linked to the text
138
+ `prompt`, usually at the expense of lower image quality.
139
+ height: The height in pixels of the generated image.
140
+ width: The width in pixels of the generated image.
141
+ sampler: A sampler to be used to denoise the encoded image latents. Can be
142
+ one of `k_lms, `k_euler`, or `k_euler_ancestral`.
143
+ n_inference_steps: The number of denoising steps. More denoising steps
144
+ usually lead to a higher quality image at the expense of slower inference.
145
+ This parameter will be modulated by `strength`.
146
+ seed: A seed to make generation deterministic.
147
+ strength: Conceptually, indicates how much to transform the reference
148
+ `input_image`. Must be between 0 and 1. `input_image` will be used as a
149
+ starting point, adding more noise to it the larger the `strength`. The
150
+ number of denoising steps depends on the amount of noise initially added.
151
+ When `strength` is 1, added noise will be maximum and the denoising
152
+ process will run for the full number of iterations specified in
153
+ `n_inference_steps`. A value of 1, therefore, essentially ignores
154
+ `input_image`.
155
+ input_image: Image which is served as the starting point for the image
156
+ generation.
157
+ """
158
+ if not 0 < strength < 1:
159
+ raise ValueError('strength must be between 0 and 1')
160
+ if height % 8 or width % 8:
161
+ raise ValueError('height and width must be a multiple of 8')
162
+ if seed is not None:
163
+ np.random.seed(seed)
164
+ if uncond_prompt is None:
165
+ uncond_prompt = ''
166
+
167
+ if sampler == 'k_lms':
168
+ sampler = samplers.KLMSSampler(n_inference_steps=n_inference_steps)
169
+ elif sampler == 'k_euler':
170
+ sampler = samplers.KEulerSampler(n_inference_steps=n_inference_steps)
171
+ elif sampler == 'k_euler_ancestral':
172
+ sampler = samplers.KEulerAncestralSampler(
173
+ n_inference_steps=n_inference_steps
174
+ )
175
+ else:
176
+ raise ValueError(
177
+ 'Unknown sampler value %s. '
178
+ 'Accepted values are {k_lms, k_euler, k_euler_ancestral}' % sampler
179
+ )
180
+
181
+ # Text embedding.
182
+ cond_tokens = model.tokenizer.encode(prompt)
183
+ cond_context = model.clip(
184
+ np.array(cond_tokens).astype(np.int32), signature_name='encode'
185
+ )
186
+ uncond_tokens = model.tokenizer.encode(uncond_prompt)
187
+ uncond_context = model.clip(
188
+ np.array(uncond_tokens).astype(np.int32), signature_name='encode'
189
+ )
190
+ context = np.concatenate([cond_context, uncond_context], axis=0)
191
+ noise_shape = (1, 4, height // 8, width // 8)
192
+
193
+ # Initialization starts from input_image if any, otherwise, starts from a
194
+ # random sampling.
195
+ if input_image:
196
+ if not hasattr(model, 'encoder'):
197
+ raise AttributeError(
198
+ 'Stable Diffusion must be initialized with encoder to accept'
199
+ ' input_image.'
200
+ )
201
+ input_image = input_image.resize((width, height))
202
+ input_image_np = util.rescale(input_image, (0, 255), (-1, 1))
203
+ input_image_np = util.move_channel(input_image_np, to='first')
204
+ encoder_noise = np.random.normal(size=noise_shape).astype(np.float32)
205
+ latents = model.encoder(input_image_np.astype(np.float32), encoder_noise)
206
+ latents_noise = np.random.normal(size=noise_shape).astype(np.float32)
207
+ sampler.set_strength(strength=strength)
208
+ latents += latents_noise * sampler.initial_scale
209
+ else:
210
+ latents = np.random.normal(size=noise_shape).astype(np.float32)
211
+ latents *= sampler.initial_scale
212
+
213
+ # Diffusion process.
214
+ timesteps = tqdm.tqdm(sampler.timesteps)
215
+ for _, timestep in enumerate(timesteps):
216
+ time_embedding = util.get_time_embedding(timestep)
217
+
218
+ input_latents = latents * sampler.get_input_scale()
219
+ input_latents = input_latents.repeat(2, axis=0)
220
+ output = model.diffusion(
221
+ input_latents.astype(np.float32),
222
+ context.astype(np.float32),
223
+ time_embedding,
224
+ signature_name='diffusion',
225
+ )
226
+ output_cond, output_uncond = np.split(output, 2, axis=0)
227
+ output = cfg_scale * (output_cond - output_uncond) + output_uncond
228
+
229
+ latents = sampler.step(latents, output)
230
+
231
+ # Image decoding.
232
+ images = model.decoder(latents.astype(np.float32), signature_name='decode')
233
+ images = util.rescale(images, (-1, 1), (0, 255), clamp=True)
234
+ images = util.move_channel(images, to='last')
235
+ if not os.path.exists(output_path):
236
+ pathlib.Path(output_path).parent.mkdir(parents=True, exist_ok=True)
237
+ Image.fromarray(images[0].astype(np.uint8)).save(output_path)
238
+
239
+
240
+ if __name__ == '__main__':
241
+ args = arg_parser.parse_args()
242
+ run_tflite_pipeline(
243
+ StableDiffusion(
244
+ tokenizer_vocab_dir=args.tokenizer_vocab_dir,
245
+ clip_ckpt=args.clip_ckpt,
246
+ diffusion_ckpt=args.diffusion_ckpt,
247
+ decoder_ckpt=args.decoder_ckpt,
248
+ ),
249
+ prompt=args.prompt,
250
+ output_path=args.output_path,
251
+ sampler=args.sampler,
252
+ n_inference_steps=args.n_inference_steps,
253
+ seed=args.seed,
254
+ )
@@ -0,0 +1,19 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ from .k_euler import KEulerSampler
17
+ from .k_euler_ancestral import KEulerAncestralSampler
18
+ from .k_lms import KLMSSampler
19
+ from .sampler import SamplerInterface
@@ -0,0 +1,62 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ from ai_edge_torch.generative.examples.stable_diffusion import util
17
+ from ai_edge_torch.generative.examples.stable_diffusion.samplers.sampler import SamplerInterface # NOQA
18
+ import numpy as np
19
+
20
+
21
+ class KEulerSampler(SamplerInterface):
22
+
23
+ def __init__(self, n_inference_steps=50, n_training_steps=1000):
24
+ timesteps = np.linspace(n_training_steps - 1, 0, n_inference_steps)
25
+
26
+ alphas_cumprod = util.get_alphas_cumprod(n_training_steps=n_training_steps)
27
+ sigmas = ((1 - alphas_cumprod) / alphas_cumprod) ** 0.5
28
+ log_sigmas = np.log(sigmas)
29
+ log_sigmas = np.interp(timesteps, range(n_training_steps), log_sigmas)
30
+ sigmas = np.exp(log_sigmas)
31
+ sigmas = np.append(sigmas, 0)
32
+
33
+ self.sigmas = sigmas
34
+ self.initial_scale = sigmas.max()
35
+ self.timesteps = timesteps
36
+ self.n_inference_steps = n_inference_steps
37
+ self.n_training_steps = n_training_steps
38
+ self.step_count = 0
39
+
40
+ def get_input_scale(self, step_count=None):
41
+ if step_count is None:
42
+ step_count = self.step_count
43
+ sigma = self.sigmas[step_count]
44
+ return 1 / (sigma**2 + 1) ** 0.5
45
+
46
+ def set_strength(self, strength=1):
47
+ start_step = self.n_inference_steps - int(self.n_inference_steps * strength)
48
+ self.timesteps = np.linspace(
49
+ self.n_training_steps - 1, 0, self.n_inference_steps
50
+ )
51
+ self.timesteps = self.timesteps[start_step:]
52
+ self.initial_scale = self.sigmas[start_step]
53
+ self.step_count = start_step
54
+
55
+ def step(self, latents, output):
56
+ t = self.step_count
57
+ self.step_count += 1
58
+
59
+ sigma_from = self.sigmas[t]
60
+ sigma_to = self.sigmas[t + 1]
61
+ latents += output * (sigma_to - sigma_from)
62
+ return latents
@@ -0,0 +1,66 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ from ai_edge_torch.generative.examples.stable_diffusion import util
17
+ from ai_edge_torch.generative.examples.stable_diffusion.samplers.sampler import SamplerInterface # NOQA
18
+ import numpy as np
19
+
20
+
21
+ class KEulerAncestralSampler(SamplerInterface):
22
+
23
+ def __init__(self, n_inference_steps=50, n_training_steps=1000):
24
+ timesteps = np.linspace(n_training_steps - 1, 0, n_inference_steps)
25
+
26
+ alphas_cumprod = util.get_alphas_cumprod(n_training_steps=n_training_steps)
27
+ sigmas = ((1 - alphas_cumprod) / alphas_cumprod) ** 0.5
28
+ log_sigmas = np.log(sigmas)
29
+ log_sigmas = np.interp(timesteps, range(n_training_steps), log_sigmas)
30
+ sigmas = np.exp(log_sigmas)
31
+ sigmas = np.append(sigmas, 0)
32
+
33
+ self.sigmas = sigmas
34
+ self.initial_scale = sigmas.max()
35
+ self.timesteps = timesteps
36
+ self.n_inference_steps = n_inference_steps
37
+ self.n_training_steps = n_training_steps
38
+ self.step_count = 0
39
+
40
+ def get_input_scale(self, step_count=None):
41
+ if step_count is None:
42
+ step_count = self.step_count
43
+ sigma = self.sigmas[step_count]
44
+ return 1 / (sigma**2 + 1) ** 0.5
45
+
46
+ def set_strength(self, strength=1):
47
+ start_step = self.n_inference_steps - int(self.n_inference_steps * strength)
48
+ self.timesteps = np.linspace(
49
+ self.n_training_steps - 1, 0, self.n_inference_steps
50
+ )
51
+ self.timesteps = self.timesteps[start_step:]
52
+ self.initial_scale = self.sigmas[start_step]
53
+ self.step_count = start_step
54
+
55
+ def step(self, latents, output):
56
+ t = self.step_count
57
+ self.step_count += 1
58
+
59
+ sigma_from = self.sigmas[t]
60
+ sigma_to = self.sigmas[t + 1]
61
+ sigma_up = sigma_to * (1 - (sigma_to**2 / sigma_from**2)) ** 0.5
62
+ sigma_down = sigma_to**2 / sigma_from
63
+ latents += output * (sigma_down - sigma_from)
64
+ noise = np.random.normal(size=latents.shape)
65
+ latents += noise * sigma_up
66
+ return latents
@@ -0,0 +1,74 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ from ai_edge_torch.generative.examples.stable_diffusion import util
17
+ from ai_edge_torch.generative.examples.stable_diffusion.samplers.sampler import SamplerInterface # NOQA
18
+ import numpy as np
19
+
20
+
21
+ class KLMSSampler(SamplerInterface):
22
+
23
+ def __init__(self, n_inference_steps=50, n_training_steps=1000, lms_order=4):
24
+ timesteps = np.linspace(n_training_steps - 1, 0, n_inference_steps)
25
+
26
+ alphas_cumprod = util.get_alphas_cumprod(n_training_steps=n_training_steps)
27
+ sigmas = ((1 - alphas_cumprod) / alphas_cumprod) ** 0.5
28
+ log_sigmas = np.log(sigmas)
29
+ log_sigmas = np.interp(timesteps, range(n_training_steps), log_sigmas)
30
+ sigmas = np.exp(log_sigmas)
31
+ sigmas = np.append(sigmas, 0)
32
+
33
+ self.sigmas = sigmas
34
+ self.initial_scale = sigmas.max()
35
+ self.timesteps = timesteps
36
+ self.n_inference_steps = n_inference_steps
37
+ self.n_training_steps = n_training_steps
38
+ self.lms_order = lms_order
39
+ self.step_count = 0
40
+ self.outputs = []
41
+
42
+ def get_input_scale(self, step_count=None):
43
+ if step_count is None:
44
+ step_count = self.step_count
45
+ sigma = self.sigmas[step_count]
46
+ return 1 / (sigma**2 + 1) ** 0.5
47
+
48
+ def set_strength(self, strength=1):
49
+ start_step = self.n_inference_steps - int(self.n_inference_steps * strength)
50
+ self.timesteps = np.linspace(
51
+ self.n_training_steps - 1, 0, self.n_inference_steps
52
+ )
53
+ self.timesteps = self.timesteps[start_step:]
54
+ self.initial_scale = self.sigmas[start_step]
55
+ self.step_count = start_step
56
+
57
+ def step(self, latents, output):
58
+ t = self.step_count
59
+ self.step_count += 1
60
+
61
+ self.outputs = [output] + self.outputs[: self.lms_order - 1]
62
+ order = len(self.outputs)
63
+ for i, output in enumerate(self.outputs):
64
+ # Integrate polynomial by trapezoidal approx. method for 81 points.
65
+ x = np.linspace(self.sigmas[t], self.sigmas[t + 1], 81)
66
+ y = np.ones(81)
67
+ for j in range(order):
68
+ if i == j:
69
+ continue
70
+ y *= x - self.sigmas[t - j]
71
+ y /= self.sigmas[t - i] - self.sigmas[t - j]
72
+ lms_coeff = np.trapz(y=y, x=x)
73
+ latents += lms_coeff * output
74
+ return latents
@@ -0,0 +1,39 @@
1
+ # Copyright 2024 The AI Edge Torch Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ import abc
17
+
18
+ import numpy as np
19
+
20
+
21
+ class SamplerInterface(abc.ABC):
22
+
23
+ @abc.abstractmethod
24
+ def get_input_scale(self, step_count: int = 1) -> float:
25
+ """Get the input scale of the random samples from sampled distribution"""
26
+ return NotImplemented
27
+
28
+ @abc.abstractmethod
29
+ def set_strength(self, strength: float = 1) -> None:
30
+ """Set the strength of initial step.
31
+
32
+ Conceptually, indicates how much to transform the reference `input_images`.
33
+ """
34
+ return NotImplemented
35
+
36
+ @abc.abstractmethod
37
+ def step(self, latents: np.ndarray, output: np.ndarray) -> np.ndarray:
38
+ """Update latents from the diffusion output by a step"""
39
+ return NotImplemented