ai-edge-torch-nightly 0.1.dev202405131930__py3-none-any.whl → 0.2.0.dev20240601__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.

Potentially problematic release.


This version of ai-edge-torch-nightly might be problematic. Click here for more details.

Files changed (24) hide show
  1. ai_edge_torch/convert/fx_passes/build_aten_composite_pass.py +5 -2
  2. ai_edge_torch/convert/test/test_convert_composites.py +3 -0
  3. ai_edge_torch/generative/examples/stable_diffusion/__init__.py +14 -0
  4. ai_edge_torch/generative/examples/stable_diffusion/attention.py +106 -0
  5. ai_edge_torch/generative/examples/stable_diffusion/clip.py +79 -0
  6. ai_edge_torch/generative/examples/stable_diffusion/convert_to_tflite.py +107 -0
  7. ai_edge_torch/generative/examples/stable_diffusion/decoder.py +113 -0
  8. ai_edge_torch/generative/examples/stable_diffusion/diffusion.py +499 -0
  9. ai_edge_torch/generative/examples/stable_diffusion/encoder.py +67 -0
  10. ai_edge_torch/generative/examples/stable_diffusion/pipeline.py +222 -0
  11. ai_edge_torch/generative/examples/stable_diffusion/samplers/__init__.py +19 -0
  12. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler.py +61 -0
  13. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_euler_ancestral.py +65 -0
  14. ai_edge_torch/generative/examples/stable_diffusion/samplers/k_lms.py +73 -0
  15. ai_edge_torch/generative/examples/stable_diffusion/samplers/sampler.py +38 -0
  16. ai_edge_torch/generative/examples/stable_diffusion/tokenizer.py +108 -0
  17. ai_edge_torch/generative/examples/stable_diffusion/util.py +71 -0
  18. ai_edge_torch/generative/test/loader_test.py +80 -0
  19. ai_edge_torch/generative/utilities/loader.py +8 -4
  20. {ai_edge_torch_nightly-0.1.dev202405131930.dist-info → ai_edge_torch_nightly-0.2.0.dev20240601.dist-info}/METADATA +2 -2
  21. {ai_edge_torch_nightly-0.1.dev202405131930.dist-info → ai_edge_torch_nightly-0.2.0.dev20240601.dist-info}/RECORD +24 -8
  22. {ai_edge_torch_nightly-0.1.dev202405131930.dist-info → ai_edge_torch_nightly-0.2.0.dev20240601.dist-info}/LICENSE +0 -0
  23. {ai_edge_torch_nightly-0.1.dev202405131930.dist-info → ai_edge_torch_nightly-0.2.0.dev20240601.dist-info}/WHEEL +0 -0
  24. {ai_edge_torch_nightly-0.1.dev202405131930.dist-info → ai_edge_torch_nightly-0.2.0.dev20240601.dist-info}/top_level.txt +0 -0
@@ -141,8 +141,11 @@ def _aten_avg_pool2d(gm: GraphModule, node: Node):
141
141
  # Only wrap in a composite when the underlying converter can handle it.
142
142
  # TODO We should be able to remove this if the converter can inline composites when it can not handle them.
143
143
 
144
- # We don't cover any cases where ceil_mode is True or divisor_override is set.
145
- if full_kwargs["ceil_mode"] or full_kwargs["divisor_override"] is not None:
144
+ # We don't cover any cases where the divisor_override is set.
145
+ if full_kwargs["divisor_override"] is not None:
146
+ return op(*args, **kwargs)
147
+
148
+ if full_kwargs["ceil_mode"] and not full_kwargs["count_include_pad"]:
146
149
  return op(*args, **kwargs)
147
150
 
148
151
  # We also can not cover a case where count_include_pad is False but the padding is custom.
@@ -51,6 +51,7 @@ class TestConvertComposites(unittest.TestCase):
51
51
 
52
52
  @parameterized.parameterized.expand(
53
53
  [
54
+ # input_size, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override
54
55
  # no padding, stride = 1
55
56
  ([1, 3, 6, 6], [3, 3], [1, 1], [0, 0], False, True, None),
56
57
  # add stride
@@ -67,6 +68,8 @@ class TestConvertComposites(unittest.TestCase):
67
68
  ([1, 3, 6, 6], [3, 3], [1, 1], [1, 1], False, False, None),
68
69
  # ceil_mode = True
69
70
  ([1, 3, 6, 6], [3, 3], [1, 1], [1, 1], True, True, None),
71
+ # ceil_mode = True, stride=[3, 3]
72
+ ([1, 3, 6, 6], [3, 3], [3, 3], [1, 1], True, True, None),
70
73
  # set divisor_override
71
74
  ([1, 3, 6, 6], [3, 3], [1, 1], 0, False, True, 6),
72
75
  # padding set to one number
@@ -0,0 +1,14 @@
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
+ # ==============================================================================
@@ -0,0 +1,106 @@
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 math
17
+
18
+ import torch
19
+ from torch import _decomp
20
+ from torch import nn
21
+ from torch._prims_common import mask_tensor
22
+ from torch._prims_common.wrappers import out_wrapper
23
+ from torch.nn import functional as F
24
+
25
+
26
+ def triu(a):
27
+ h, w = a.shape[-2:]
28
+ mask = (
29
+ torch.arange(w, device=a.device).unsqueeze(-2)
30
+ - torch.arange(h, device=a.device).unsqueeze(-1)
31
+ ) >= 1
32
+ mask = torch.broadcast_to(mask, a.shape)
33
+ return torch.ops.aten.logical_and(a, mask).contiguous()
34
+
35
+
36
+ # _decomp.decomposition_table[torch.ops.aten.triu.default] = triu
37
+
38
+
39
+ class SelfAttention(nn.Module):
40
+
41
+ def __init__(self, n_heads, d_embed, in_proj_bias=True, out_proj_bias=True):
42
+ super().__init__()
43
+ self.in_proj = nn.Linear(d_embed, 3 * d_embed, bias=in_proj_bias)
44
+ self.out_proj = nn.Linear(d_embed, d_embed, bias=out_proj_bias)
45
+ self.n_heads = n_heads
46
+ self.d_head = d_embed // n_heads
47
+
48
+ def forward(self, x, causal_mask=False):
49
+ input_shape = x.shape
50
+ batch_size, sequence_length, d_embed = input_shape
51
+ interim_shape = (batch_size, sequence_length, self.n_heads, self.d_head)
52
+
53
+ q, k, v = self.in_proj(x).chunk(3, dim=-1)
54
+
55
+ q = q.view(interim_shape).transpose(1, 2)
56
+ k = k.view(interim_shape).transpose(1, 2)
57
+ v = v.view(interim_shape).transpose(1, 2)
58
+
59
+ weight = q @ k.transpose(-1, -2)
60
+ if causal_mask:
61
+ # mask = torch.ones_like(weight, dtype=torch.bool).triu(1)
62
+ mask = triu(torch.ones_like(weight, dtype=torch.bool))
63
+ weight.masked_fill_(mask, -torch.inf)
64
+ weight /= math.sqrt(self.d_head)
65
+ weight = F.softmax(weight, dim=-1)
66
+
67
+ output = weight @ v
68
+ output = output.transpose(1, 2)
69
+ output = output.reshape(input_shape)
70
+ output = self.out_proj(output)
71
+ return output
72
+
73
+
74
+ class CrossAttention(nn.Module):
75
+
76
+ def __init__(self, n_heads, d_embed, d_cross, in_proj_bias=True, out_proj_bias=True):
77
+ super().__init__()
78
+ self.q_proj = nn.Linear(d_embed, d_embed, bias=in_proj_bias)
79
+ self.k_proj = nn.Linear(d_cross, d_embed, bias=in_proj_bias)
80
+ self.v_proj = nn.Linear(d_cross, d_embed, bias=in_proj_bias)
81
+ self.out_proj = nn.Linear(d_embed, d_embed, bias=out_proj_bias)
82
+ self.n_heads = n_heads
83
+ self.d_head = d_embed // n_heads
84
+
85
+ def forward(self, x, y):
86
+ input_shape = x.shape
87
+ batch_size, sequence_length, d_embed = input_shape
88
+ interim_shape = (batch_size, -1, self.n_heads, self.d_head)
89
+
90
+ q = self.q_proj(x)
91
+ k = self.k_proj(y)
92
+ v = self.v_proj(y)
93
+
94
+ q = q.view(interim_shape).transpose(1, 2)
95
+ k = k.view(interim_shape).transpose(1, 2)
96
+ v = v.view(interim_shape).transpose(1, 2)
97
+
98
+ weight = q @ k.transpose(-1, -2)
99
+ weight /= math.sqrt(self.d_head)
100
+ weight = F.softmax(weight, dim=-1)
101
+
102
+ output = weight @ v
103
+ output = output.transpose(1, 2).contiguous()
104
+ output = output.view(input_shape)
105
+ output = self.out_proj(output)
106
+ return output
@@ -0,0 +1,79 @@
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 torch
17
+ from torch import nn
18
+ from torch._prims_common import mask_tensor
19
+ from torch._prims_common.wrappers import out_wrapper
20
+
21
+ from ai_edge_torch.generative.examples.stable_diffusion.attention import SelfAttention # NOQA
22
+
23
+
24
+ class CLIPEmbedding(nn.Module):
25
+
26
+ def __init__(self, n_vocab: int, n_embd: int, n_token: int):
27
+ super().__init__()
28
+ self.token_embedding = nn.Embedding(n_vocab, n_embd)
29
+ self.position_value = nn.Parameter(torch.zeros((n_token, n_embd)))
30
+
31
+ def forward(self, tokens):
32
+ x = self.token_embedding(tokens)
33
+ x += self.position_value
34
+ return x
35
+
36
+
37
+ class CLIPLayer(nn.Module):
38
+
39
+ def __init__(self, n_head: int, n_embd: int):
40
+ super().__init__()
41
+ self.layernorm_1 = nn.LayerNorm(n_embd)
42
+ self.attention = SelfAttention(n_head, n_embd)
43
+ self.layernorm_2 = nn.LayerNorm(n_embd)
44
+ self.linear_1 = nn.Linear(n_embd, 4 * n_embd)
45
+ self.linear_2 = nn.Linear(4 * n_embd, n_embd)
46
+
47
+ def forward(self, x):
48
+ residue = x
49
+ x = self.layernorm_1(x)
50
+ x = self.attention(x, causal_mask=True)
51
+ x += residue
52
+
53
+ residue = x
54
+ x = self.layernorm_2(x)
55
+ x = self.linear_1(x)
56
+ x = x * torch.sigmoid(1.702 * x) # QuickGELU activation function
57
+ x = self.linear_2(x)
58
+ x += residue
59
+
60
+ return x
61
+
62
+
63
+ class CLIP(nn.Module):
64
+
65
+ def __init__(self):
66
+ super().__init__()
67
+ self.embedding = CLIPEmbedding(49408, 768, 77)
68
+ self.layers = nn.ModuleList([CLIPLayer(12, 768) for i in range(12)])
69
+ self.layernorm = nn.LayerNorm(768)
70
+
71
+ @torch.inference_mode
72
+ def forward(self, tokens: torch.LongTensor) -> torch.FloatTensor:
73
+ tokens = tokens.type(torch.long)
74
+
75
+ state = self.embedding(tokens)
76
+ for layer in self.layers:
77
+ state = layer(state)
78
+ output = self.layernorm(state)
79
+ return output
@@ -0,0 +1,107 @@
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 os
17
+ from pathlib import Path
18
+
19
+ import torch
20
+
21
+ import ai_edge_torch
22
+ from ai_edge_torch.generative.examples.stable_diffusion.clip import CLIP
23
+ from ai_edge_torch.generative.examples.stable_diffusion.decoder import Decoder
24
+ from ai_edge_torch.generative.examples.stable_diffusion.diffusion import Diffusion # NOQA
25
+ from ai_edge_torch.generative.examples.stable_diffusion.encoder import Encoder
26
+ import ai_edge_torch.generative.examples.stable_diffusion.util as util
27
+
28
+
29
+ @torch.inference_mode
30
+ def convert_stable_diffusion_to_tflite(
31
+ clip_ckpt_path: str,
32
+ encoder_ckpt_path: str,
33
+ diffusion_ckpt_path: str,
34
+ decoder_ckpt_path: str,
35
+ image_height: int = 512,
36
+ image_width: int = 512,
37
+ ):
38
+
39
+ clip = CLIP()
40
+ clip.load_state_dict(torch.load(clip_ckpt_path))
41
+
42
+ encoder = Encoder()
43
+ encoder.load_state_dict(torch.load(encoder_ckpt_path))
44
+
45
+ diffusion = Diffusion()
46
+ diffusion.load_state_dict(torch.load(diffusion_ckpt_path))
47
+
48
+ decoder = Decoder()
49
+ decoder.load_state_dict(torch.load(decoder_ckpt_path))
50
+
51
+ # Tensors used to trace the model graph during conversion.
52
+ n_tokens = 77
53
+ timestamp = 0
54
+ len_prompt = 1
55
+ prompt_tokens = torch.full((1, n_tokens), 0, dtype=torch.long)
56
+ input_image = torch.full((1, 3, image_height, image_width), 0, dtype=torch.float32)
57
+ noise = torch.full(
58
+ (len_prompt, 4, image_height // 8, image_width // 8), 0, dtype=torch.float32
59
+ )
60
+
61
+ input_latents = encoder(input_image, noise)
62
+ context_cond = clip(prompt_tokens)
63
+ context_uncond = torch.zeros_like(context_cond)
64
+ context = torch.cat([context_cond, context_uncond], axis=0)
65
+ time_embedding = util.get_time_embedding(timestamp)
66
+
67
+ # CLIP text encoder
68
+ ai_edge_torch.signature('encode', clip, (prompt_tokens,)).convert().export(
69
+ '/tmp/stable_diffusion/clip.tflite'
70
+ )
71
+
72
+ # TODO(yichunk): convert to multi signature tflite model.
73
+ # Image encoder
74
+ ai_edge_torch.signature('encode', encoder, (input_image, noise)).convert().export(
75
+ '/tmp/stable_diffusion/encoder.tflite'
76
+ )
77
+
78
+ # Diffusion
79
+ ai_edge_torch.signature(
80
+ 'diffusion',
81
+ diffusion,
82
+ (torch.repeat_interleave(input_latents, 2, 0), context, time_embedding),
83
+ ).convert().export('/tmp/stable_diffusion/diffusion.tflite')
84
+
85
+ # Image decoder
86
+ ai_edge_torch.signature('decode', decoder, (input_latents,)).convert().export(
87
+ '/tmp/stable_diffusion/decoder.tflite'
88
+ )
89
+
90
+
91
+ if __name__ == '__main__':
92
+ convert_stable_diffusion_to_tflite(
93
+ clip_ckpt_path=os.path.join(
94
+ Path.home(), 'Downloads/stable_diffusion_data/ckpt/clip.pt'
95
+ ),
96
+ encoder_ckpt_path=os.path.join(
97
+ Path.home(), 'Downloads/stable_diffusion_data/ckpt/encoder.pt'
98
+ ),
99
+ diffusion_ckpt_path=os.path.join(
100
+ Path.home(), 'Downloads/stable_diffusion_data/ckpt/diffusion.pt'
101
+ ),
102
+ decoder_ckpt_path=os.path.join(
103
+ Path.home(), 'Downloads/stable_diffusion_data/ckpt/decoder.pt'
104
+ ),
105
+ image_height=512,
106
+ image_width=512,
107
+ )
@@ -0,0 +1,113 @@
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 torch
17
+ from torch import nn
18
+ from torch.nn import functional as F
19
+
20
+ from ai_edge_torch.generative.examples.stable_diffusion.attention import SelfAttention # NOQA
21
+
22
+
23
+ class AttentionBlock(nn.Module):
24
+
25
+ def __init__(self, channels):
26
+ super().__init__()
27
+ self.groupnorm = nn.GroupNorm(32, channels)
28
+ self.attention = SelfAttention(1, channels)
29
+
30
+ def forward(self, x):
31
+ residue = x
32
+ x = self.groupnorm(x)
33
+
34
+ n, c, h, w = x.shape
35
+ x = x.view((n, c, h * w))
36
+ x = x.transpose(-1, -2)
37
+ x = self.attention(x)
38
+ x = x.transpose(-1, -2)
39
+ x = x.view((n, c, h, w))
40
+
41
+ x += residue
42
+ return x
43
+
44
+
45
+ class ResidualBlock(nn.Module):
46
+
47
+ def __init__(self, in_channels, out_channels):
48
+ super().__init__()
49
+ self.groupnorm_1 = nn.GroupNorm(32, in_channels)
50
+ self.conv_1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)
51
+
52
+ self.groupnorm_2 = nn.GroupNorm(32, out_channels)
53
+ self.conv_2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1)
54
+
55
+ if in_channels == out_channels:
56
+ self.residual_layer = nn.Identity()
57
+ else:
58
+ self.residual_layer = nn.Conv2d(
59
+ in_channels, out_channels, kernel_size=1, padding=0
60
+ )
61
+
62
+ def forward(self, x):
63
+ residue = x
64
+
65
+ x = self.groupnorm_1(x)
66
+ x = F.silu(x)
67
+ x = self.conv_1(x)
68
+
69
+ x = self.groupnorm_2(x)
70
+ x = F.silu(x)
71
+ x = self.conv_2(x)
72
+
73
+ return x + self.residual_layer(residue)
74
+
75
+
76
+ class Decoder(nn.Sequential):
77
+
78
+ def __init__(self):
79
+ super().__init__(
80
+ nn.Conv2d(4, 4, kernel_size=1, padding=0),
81
+ nn.Conv2d(4, 512, kernel_size=3, padding=1),
82
+ ResidualBlock(512, 512),
83
+ AttentionBlock(512),
84
+ ResidualBlock(512, 512),
85
+ ResidualBlock(512, 512),
86
+ ResidualBlock(512, 512),
87
+ ResidualBlock(512, 512),
88
+ nn.Upsample(scale_factor=2),
89
+ nn.Conv2d(512, 512, kernel_size=3, padding=1),
90
+ ResidualBlock(512, 512),
91
+ ResidualBlock(512, 512),
92
+ ResidualBlock(512, 512),
93
+ nn.Upsample(scale_factor=2),
94
+ nn.Conv2d(512, 512, kernel_size=3, padding=1),
95
+ ResidualBlock(512, 256),
96
+ ResidualBlock(256, 256),
97
+ ResidualBlock(256, 256),
98
+ nn.Upsample(scale_factor=2),
99
+ nn.Conv2d(256, 256, kernel_size=3, padding=1),
100
+ ResidualBlock(256, 128),
101
+ ResidualBlock(128, 128),
102
+ ResidualBlock(128, 128),
103
+ nn.GroupNorm(32, 128),
104
+ nn.SiLU(),
105
+ nn.Conv2d(128, 3, kernel_size=3, padding=1),
106
+ )
107
+
108
+ @torch.inference_mode
109
+ def forward(self, x):
110
+ x = x / 0.18215
111
+ for module in self:
112
+ x = module(x)
113
+ return x