dusinan commited on
Commit
63df3cf
·
1 Parent(s): d615b3f
models/condition-----.py DELETED
@@ -1,169 +0,0 @@
1
- import torch
2
- from torch import Tensor
3
- from typing import Optional, Union, List, Tuple
4
- from PIL import Image, ImageFilter
5
- import numpy as np
6
- import cv2
7
-
8
-
9
- subject_dict = {
10
- f"<img{i}>": i for i in range(1, 11)
11
- }
12
- scene_dict = {
13
- "<scene>" : 11,
14
- }
15
- style_dict = {
16
- "<style>" : 12
17
- }
18
- human_dict = {
19
- f"<human{i-12}>": i for i in range(13, 21)
20
- }
21
-
22
- condition_dict = {
23
- **subject_dict,
24
- **scene_dict,
25
- **style_dict,
26
- **human_dict,
27
- }
28
-
29
-
30
- # def get_condition_type_list(condition_ids_parts: tuple):
31
- # condition_type_list = []
32
- # for condition_ids in condition_ids_parts:
33
- # cond_idx = int(torch.mean(condition_ids[:, :, 0]).item())
34
- # if cond_idx in subject_dict.values():
35
- # condition_type_list.append("subject")
36
- # elif cond_idx in scene_dict.values():
37
- # condition_type_list.append("scene")
38
- # elif cond_idx in style_dict.values():
39
- # condition_type_list.append("style")
40
- # else:
41
- # condition_type_list.append("none") # cond_idx = 0 or other
42
- # return condition_type_list
43
-
44
-
45
- def get_condition_type_list(condition_ids_parts: tuple):
46
- condition_type_list = []
47
- for condition_ids in condition_ids_parts:
48
- cond_idx = int(torch.mean(condition_ids[:, :, 0]).item())
49
- if cond_idx in condition_dict.values(): # all conditions use one indivisual mlp
50
- condition_type_list.append("subject")
51
- else:
52
- # condition_type_list.append("none") # cond_idx = 0 or other
53
- condition_type_list.append("subject") # NOTE remove none branch
54
- return condition_type_list
55
-
56
-
57
- def encode_images(pipeline, images: Tensor):
58
- images = pipeline.image_processor.preprocess(images)
59
- images = images.to(pipeline.device).to(pipeline.dtype)
60
- images = pipeline.vae.encode(images).latent_dist.sample()
61
- images = (
62
- images - pipeline.vae.config.shift_factor
63
- ) * pipeline.vae.config.scaling_factor
64
- # images_tokens = pipeline._pack_latents(images, *images.shape)
65
- # images_ids = pipeline._prepare_latent_image_ids(
66
- # images.shape[0],
67
- # images.shape[2],
68
- # images.shape[3],
69
- # pipeline.device,
70
- # pipeline.dtype,
71
- # )
72
- # if images_tokens.shape[1] != images_ids.shape[0]:
73
- # images_ids = pipeline._prepare_latent_image_ids(
74
- # images.shape[0],
75
- # images.shape[2] // 2,
76
- # images.shape[3] // 2,
77
- # pipeline.device,
78
- # pipeline.dtype,
79
- # )
80
- return images
81
-
82
-
83
- class Condition(object):
84
- def __init__(
85
- self,
86
- condition_type: str,
87
- raw_img: Union[Image.Image, torch.Tensor] = None,
88
- condition: Union[Image.Image, torch.Tensor] = None,
89
- mask=None,
90
- position_delta=None,
91
- ) -> None:
92
- self.condition_type = condition_type
93
- assert raw_img is not None or condition is not None
94
- if raw_img is not None:
95
- self.condition = self.get_condition(condition_type, raw_img)
96
- else:
97
- self.condition = condition
98
- self.position_delta = position_delta
99
- # TODO: Add mask support
100
- assert mask is None, "Mask not supported yet"
101
-
102
- def get_condition(
103
- self, condition_type: str, raw_img: Union[Image.Image, torch.Tensor]
104
- ) -> Union[Image.Image, torch.Tensor]:
105
- """
106
- Returns the condition image.
107
- """
108
- if condition_type == "depth":
109
- from transformers import pipeline
110
-
111
- depth_pipe = pipeline(
112
- task="depth-estimation",
113
- model="LiheYoung/depth-anything-small-hf",
114
- device="cuda",
115
- )
116
- source_image = raw_img.convert("RGB")
117
- condition_img = depth_pipe(source_image)["depth"].convert("RGB")
118
- return condition_img
119
- elif condition_type == "canny":
120
- img = np.array(raw_img)
121
- edges = cv2.Canny(img, 100, 200)
122
- edges = Image.fromarray(edges).convert("RGB")
123
- return edges
124
- elif condition_type == "subject":
125
- return raw_img
126
- elif condition_type == "coloring":
127
- return raw_img.convert("L").convert("RGB")
128
- elif condition_type == "deblurring":
129
- condition_image = (
130
- raw_img.convert("RGB")
131
- .filter(ImageFilter.GaussianBlur(10))
132
- .convert("RGB")
133
- )
134
- return condition_image
135
- elif condition_type == "fill":
136
- return raw_img.convert("RGB")
137
- return self.condition
138
-
139
- @property
140
- def type_id(self) -> int:
141
- """
142
- Returns the type id of the condition.
143
- """
144
- return condition_dict[self.condition_type]
145
-
146
- @classmethod
147
- def get_type_id(cls, condition_type: str) -> int:
148
- """
149
- Returns the type id of the condition.
150
- """
151
- return condition_dict[condition_type]
152
-
153
- def encode(self, pipe) -> Tuple[torch.Tensor, torch.Tensor, int]:
154
- """
155
- Encodes the condition into tokens, ids and type_id.
156
- """
157
- if self.condition_type in list(condition_dict.keys()):
158
- tokens, ids = encode_images(pipe, self.condition)
159
- else:
160
- raise NotImplementedError(
161
- f"Condition type {self.condition_type} not implemented"
162
- )
163
- if self.position_delta is None and "subject" in self.condition_type:
164
- self.position_delta = [0, -self.condition.size[0] // 16]
165
- if self.position_delta is not None:
166
- ids[:, :, 1] += self.position_delta[0]
167
- ids[:, :, 2] += self.position_delta[1]
168
- type_id = torch.ones_like(ids[:, :, :1]) * self.type_id
169
- return tokens, ids, type_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models/model.py CHANGED
@@ -6,7 +6,7 @@ import random
6
  import torch
7
  import numpy as np
8
  import requests
9
- from .cotyle_utils import get_suppression_coefficient
10
  from io import BytesIO
11
  from typing import Union, List, Optional, Any, Dict, Tuple, Callable
12
 
 
6
  import torch
7
  import numpy as np
8
  import requests
9
+ from .utils import get_suppression_coefficient
10
  from io import BytesIO
11
  from typing import Union, List, Optional, Any, Dict, Tuple, Callable
12
 
models/normalization-----.py DELETED
@@ -1,482 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2024 HuggingFace Inc.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
-
16
- import numbers
17
- from typing import Dict, Optional, Tuple
18
-
19
- import torch
20
- import torch.nn as nn
21
- import torch.nn.functional as F
22
-
23
- from diffusers.utils import is_torch_version
24
- from diffusers.models.activations import get_activation
25
- from diffusers.models.embeddings import (
26
- CombinedTimestepLabelEmbeddings,
27
- PixArtAlphaCombinedTimestepSizeEmbeddings,
28
- )
29
-
30
-
31
- class AdaLayerNorm(nn.Module):
32
- r"""
33
- Norm layer modified to incorporate timestep embeddings.
34
-
35
- Parameters:
36
- embedding_dim (`int`): The size of each embedding vector.
37
- num_embeddings (`int`, *optional*): The size of the embeddings dictionary.
38
- output_dim (`int`, *optional*):
39
- norm_elementwise_affine (`bool`, defaults to `False):
40
- norm_eps (`bool`, defaults to `False`):
41
- chunk_dim (`int`, defaults to `0`):
42
- """
43
-
44
- def __init__(
45
- self,
46
- embedding_dim: int,
47
- num_embeddings: Optional[int] = None,
48
- output_dim: Optional[int] = None,
49
- norm_elementwise_affine: bool = False,
50
- norm_eps: float = 1e-5,
51
- chunk_dim: int = 0,
52
- ):
53
- super().__init__()
54
-
55
- self.chunk_dim = chunk_dim
56
- output_dim = output_dim or embedding_dim * 2
57
-
58
- if num_embeddings is not None:
59
- self.emb = nn.Embedding(num_embeddings, embedding_dim)
60
- else:
61
- self.emb = None
62
-
63
- self.silu = nn.SiLU()
64
- self.linear = nn.Linear(embedding_dim, output_dim)
65
- self.norm = nn.LayerNorm(output_dim // 2, norm_eps, norm_elementwise_affine)
66
-
67
- def forward(
68
- self, x: torch.Tensor, timestep: Optional[torch.Tensor] = None, temb: Optional[torch.Tensor] = None
69
- ) -> torch.Tensor:
70
- if self.emb is not None:
71
- temb = self.emb(timestep)
72
-
73
- temb = self.linear(self.silu(temb))
74
-
75
- if self.chunk_dim == 1:
76
- # This is a bit weird why we have the order of "shift, scale" here and "scale, shift" in the
77
- # other if-branch. This branch is specific to CogVideoX for now.
78
- shift, scale = temb.chunk(2, dim=1)
79
- shift = shift[:, None, :]
80
- scale = scale[:, None, :]
81
- else:
82
- scale, shift = temb.chunk(2, dim=0)
83
-
84
- x = self.norm(x) * (1 + scale) + shift
85
- return x
86
-
87
-
88
- class FP32LayerNorm(nn.LayerNorm):
89
- def forward(self, inputs: torch.Tensor) -> torch.Tensor:
90
- origin_dtype = inputs.dtype
91
- return F.layer_norm(
92
- inputs.float(),
93
- self.normalized_shape,
94
- self.weight.float() if self.weight is not None else None,
95
- self.bias.float() if self.bias is not None else None,
96
- self.eps,
97
- ).to(origin_dtype)
98
-
99
-
100
- class AdaLayerNormZero(nn.Module):
101
- r"""
102
- Norm layer adaptive layer norm zero (adaLN-Zero).
103
-
104
- Parameters:
105
- embedding_dim (`int`): The size of each embedding vector.
106
- num_embeddings (`int`): The size of the embeddings dictionary.
107
- """
108
-
109
- def __init__(self, embedding_dim: int, num_embeddings: Optional[int] = None, norm_type="layer_norm", bias=True):
110
- super().__init__()
111
- if num_embeddings is not None:
112
- self.emb = CombinedTimestepLabelEmbeddings(num_embeddings, embedding_dim)
113
- else:
114
- self.emb = None
115
-
116
- self.silu = nn.SiLU()
117
- self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=bias)
118
- if norm_type == "layer_norm":
119
- self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
120
- elif norm_type == "fp32_layer_norm":
121
- self.norm = FP32LayerNorm(embedding_dim, elementwise_affine=False, bias=False)
122
- else:
123
- raise ValueError(
124
- f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
125
- )
126
-
127
- def forward(
128
- self,
129
- x: torch.Tensor,
130
- timestep: Optional[torch.Tensor] = None,
131
- class_labels: Optional[torch.LongTensor] = None,
132
- hidden_dtype: Optional[torch.dtype] = None,
133
- emb: Optional[torch.Tensor] = None,
134
- ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
135
- if self.emb is not None:
136
- emb = self.emb(timestep, class_labels, hidden_dtype=hidden_dtype)
137
- emb = self.linear(self.silu(emb))
138
- shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = emb.chunk(6, dim=1)
139
- x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
140
- return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
141
-
142
-
143
- class AdaLayerNormZeroSingle(nn.Module):
144
- r"""
145
- Norm layer adaptive layer norm zero (adaLN-Zero).
146
-
147
- Parameters:
148
- embedding_dim (`int`): The size of each embedding vector.
149
- num_embeddings (`int`): The size of the embeddings dictionary.
150
- """
151
-
152
- def __init__(self, embedding_dim: int, norm_type="layer_norm", bias=True):
153
- super().__init__()
154
-
155
- self.silu = nn.SiLU()
156
- self.linear = nn.Linear(embedding_dim, 3 * embedding_dim, bias=bias)
157
- if norm_type == "layer_norm":
158
- self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
159
- else:
160
- raise ValueError(
161
- f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
162
- )
163
-
164
- @torch.compile(dynamic=True)
165
- def forward(
166
- self,
167
- x: torch.Tensor,
168
- emb: Optional[torch.Tensor] = None,
169
- ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
170
- emb = self.linear(self.silu(emb))
171
- shift_msa, scale_msa, gate_msa = emb.chunk(3, dim=1)
172
- x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
173
- return x, gate_msa
174
-
175
-
176
- class LuminaRMSNormZero(nn.Module):
177
- """
178
- Norm layer adaptive RMS normalization zero.
179
-
180
- Parameters:
181
- embedding_dim (`int`): The size of each embedding vector.
182
- """
183
-
184
- def __init__(self, embedding_dim: int, norm_eps: float, norm_elementwise_affine: bool):
185
- super().__init__()
186
- self.silu = nn.SiLU()
187
- self.linear = nn.Linear(
188
- min(embedding_dim, 1024),
189
- 4 * embedding_dim,
190
- bias=True,
191
- )
192
- self.norm = RMSNorm(embedding_dim, eps=norm_eps, elementwise_affine=norm_elementwise_affine)
193
-
194
- def forward(
195
- self,
196
- x: torch.Tensor,
197
- emb: Optional[torch.Tensor] = None,
198
- ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
199
- # emb = self.emb(timestep, encoder_hidden_states, encoder_mask)
200
- emb = self.linear(self.silu(emb))
201
- scale_msa, gate_msa, scale_mlp, gate_mlp = emb.chunk(4, dim=1)
202
- x = self.norm(x) * (1 + scale_msa[:, None])
203
-
204
- return x, gate_msa, scale_mlp, gate_mlp
205
-
206
-
207
- class AdaLayerNormSingle(nn.Module):
208
- r"""
209
- Norm layer adaptive layer norm single (adaLN-single).
210
-
211
- As proposed in PixArt-Alpha (see: https://arxiv.org/abs/2310.00426; Section 2.3).
212
-
213
- Parameters:
214
- embedding_dim (`int`): The size of each embedding vector.
215
- use_additional_conditions (`bool`): To use additional conditions for normalization or not.
216
- """
217
-
218
- def __init__(self, embedding_dim: int, use_additional_conditions: bool = False):
219
- super().__init__()
220
-
221
- self.emb = PixArtAlphaCombinedTimestepSizeEmbeddings(
222
- embedding_dim, size_emb_dim=embedding_dim // 3, use_additional_conditions=use_additional_conditions
223
- )
224
-
225
- self.silu = nn.SiLU()
226
- self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=True)
227
-
228
- def forward(
229
- self,
230
- timestep: torch.Tensor,
231
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
232
- batch_size: Optional[int] = None,
233
- hidden_dtype: Optional[torch.dtype] = None,
234
- ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
235
- # No modulation happening here.
236
- embedded_timestep = self.emb(timestep, **added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_dtype)
237
- return self.linear(self.silu(embedded_timestep)), embedded_timestep
238
-
239
-
240
- class AdaGroupNorm(nn.Module):
241
- r"""
242
- GroupNorm layer modified to incorporate timestep embeddings.
243
-
244
- Parameters:
245
- embedding_dim (`int`): The size of each embedding vector.
246
- num_embeddings (`int`): The size of the embeddings dictionary.
247
- num_groups (`int`): The number of groups to separate the channels into.
248
- act_fn (`str`, *optional*, defaults to `None`): The activation function to use.
249
- eps (`float`, *optional*, defaults to `1e-5`): The epsilon value to use for numerical stability.
250
- """
251
-
252
- def __init__(
253
- self, embedding_dim: int, out_dim: int, num_groups: int, act_fn: Optional[str] = None, eps: float = 1e-5
254
- ):
255
- super().__init__()
256
- self.num_groups = num_groups
257
- self.eps = eps
258
-
259
- if act_fn is None:
260
- self.act = None
261
- else:
262
- self.act = get_activation(act_fn)
263
-
264
- self.linear = nn.Linear(embedding_dim, out_dim * 2)
265
-
266
- def forward(self, x: torch.Tensor, emb: torch.Tensor) -> torch.Tensor:
267
- if self.act:
268
- emb = self.act(emb)
269
- emb = self.linear(emb)
270
- emb = emb[:, :, None, None]
271
- scale, shift = emb.chunk(2, dim=1)
272
-
273
- x = F.group_norm(x, self.num_groups, eps=self.eps)
274
- x = x * (1 + scale) + shift
275
- return x
276
-
277
-
278
- class AdaLayerNormContinuous(nn.Module):
279
- def __init__(
280
- self,
281
- embedding_dim: int,
282
- conditioning_embedding_dim: int,
283
- # NOTE: It is a bit weird that the norm layer can be configured to have scale and shift parameters
284
- # because the output is immediately scaled and shifted by the projected conditioning embeddings.
285
- # Note that AdaLayerNorm does not let the norm layer have scale and shift parameters.
286
- # However, this is how it was implemented in the original code, and it's rather likely you should
287
- # set `elementwise_affine` to False.
288
- elementwise_affine=True,
289
- eps=1e-5,
290
- bias=True,
291
- norm_type="layer_norm",
292
- ):
293
- super().__init__()
294
- self.silu = nn.SiLU()
295
- self.linear = nn.Linear(conditioning_embedding_dim, embedding_dim * 2, bias=bias)
296
- if norm_type == "layer_norm":
297
- self.norm = LayerNorm(embedding_dim, eps, elementwise_affine, bias)
298
- elif norm_type == "rms_norm":
299
- self.norm = RMSNorm(embedding_dim, eps, elementwise_affine)
300
- else:
301
- raise ValueError(f"unknown norm_type {norm_type}")
302
-
303
- def forward(self, x: torch.Tensor, conditioning_embedding: torch.Tensor) -> torch.Tensor:
304
- # convert back to the original dtype in case `conditioning_embedding`` is upcasted to float32 (needed for hunyuanDiT)
305
- emb = self.linear(self.silu(conditioning_embedding).to(x.dtype))
306
- scale, shift = torch.chunk(emb, 2, dim=1)
307
- x = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
308
- return x
309
-
310
-
311
- class LuminaLayerNormContinuous(nn.Module):
312
- def __init__(
313
- self,
314
- embedding_dim: int,
315
- conditioning_embedding_dim: int,
316
- # NOTE: It is a bit weird that the norm layer can be configured to have scale and shift parameters
317
- # because the output is immediately scaled and shifted by the projected conditioning embeddings.
318
- # Note that AdaLayerNorm does not let the norm layer have scale and shift parameters.
319
- # However, this is how it was implemented in the original code, and it's rather likely you should
320
- # set `elementwise_affine` to False.
321
- elementwise_affine=True,
322
- eps=1e-5,
323
- bias=True,
324
- norm_type="layer_norm",
325
- out_dim: Optional[int] = None,
326
- ):
327
- super().__init__()
328
- # AdaLN
329
- self.silu = nn.SiLU()
330
- self.linear_1 = nn.Linear(conditioning_embedding_dim, embedding_dim, bias=bias)
331
- if norm_type == "layer_norm":
332
- self.norm = LayerNorm(embedding_dim, eps, elementwise_affine, bias)
333
- else:
334
- raise ValueError(f"unknown norm_type {norm_type}")
335
- # linear_2
336
- if out_dim is not None:
337
- self.linear_2 = nn.Linear(
338
- embedding_dim,
339
- out_dim,
340
- bias=bias,
341
- )
342
-
343
- def forward(
344
- self,
345
- x: torch.Tensor,
346
- conditioning_embedding: torch.Tensor,
347
- ) -> torch.Tensor:
348
- # convert back to the original dtype in case `conditioning_embedding`` is upcasted to float32 (needed for hunyuanDiT)
349
- emb = self.linear_1(self.silu(conditioning_embedding).to(x.dtype))
350
- scale = emb
351
- x = self.norm(x) * (1 + scale)[:, None, :]
352
-
353
- if self.linear_2 is not None:
354
- x = self.linear_2(x)
355
-
356
- return x
357
-
358
-
359
- class CogVideoXLayerNormZero(nn.Module):
360
- def __init__(
361
- self,
362
- conditioning_dim: int,
363
- embedding_dim: int,
364
- elementwise_affine: bool = True,
365
- eps: float = 1e-5,
366
- bias: bool = True,
367
- ) -> None:
368
- super().__init__()
369
-
370
- self.silu = nn.SiLU()
371
- self.linear = nn.Linear(conditioning_dim, 6 * embedding_dim, bias=bias)
372
- self.norm = nn.LayerNorm(embedding_dim, eps=eps, elementwise_affine=elementwise_affine)
373
-
374
- def forward(
375
- self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor, temb: torch.Tensor
376
- ) -> Tuple[torch.Tensor, torch.Tensor]:
377
- shift, scale, gate, enc_shift, enc_scale, enc_gate = self.linear(self.silu(temb)).chunk(6, dim=1)
378
- hidden_states = self.norm(hidden_states) * (1 + scale)[:, None, :] + shift[:, None, :]
379
- encoder_hidden_states = self.norm(encoder_hidden_states) * (1 + enc_scale)[:, None, :] + enc_shift[:, None, :]
380
- return hidden_states, encoder_hidden_states, gate[:, None, :], enc_gate[:, None, :]
381
-
382
-
383
- if is_torch_version(">=", "2.1.0"):
384
- LayerNorm = nn.LayerNorm
385
- else:
386
- # Has optional bias parameter compared to torch layer norm
387
- # TODO: replace with torch layernorm once min required torch version >= 2.1
388
- class LayerNorm(nn.Module):
389
- def __init__(self, dim, eps: float = 1e-5, elementwise_affine: bool = True, bias: bool = True):
390
- super().__init__()
391
-
392
- self.eps = eps
393
-
394
- if isinstance(dim, numbers.Integral):
395
- dim = (dim,)
396
-
397
- self.dim = torch.Size(dim)
398
-
399
- if elementwise_affine:
400
- self.weight = nn.Parameter(torch.ones(dim))
401
- self.bias = nn.Parameter(torch.zeros(dim)) if bias else None
402
- else:
403
- self.weight = None
404
- self.bias = None
405
-
406
- def forward(self, input):
407
- return F.layer_norm(input, self.dim, self.weight, self.bias, self.eps)
408
-
409
-
410
- class RMSNorm(nn.Module):
411
- def __init__(self, dim, eps: float, elementwise_affine: bool = True):
412
- super().__init__()
413
-
414
- self.eps = eps
415
-
416
- if isinstance(dim, numbers.Integral):
417
- dim = (dim,)
418
-
419
- self.dim = torch.Size(dim)
420
-
421
- if elementwise_affine:
422
- self.weight = nn.Parameter(torch.ones(dim))
423
- else:
424
- self.weight = None
425
-
426
- @torch.compile(dynamic=True)
427
- def forward(self, hidden_states):
428
- input_dtype = hidden_states.dtype
429
- variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
430
- hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
431
-
432
- if self.weight is not None:
433
- # convert into half-precision if necessary
434
- if self.weight.dtype in [torch.float16, torch.bfloat16]:
435
- hidden_states = hidden_states.to(self.weight.dtype)
436
- hidden_states = hidden_states * self.weight
437
- else:
438
- hidden_states = hidden_states.to(input_dtype)
439
-
440
- return hidden_states
441
-
442
-
443
- class GlobalResponseNorm(nn.Module):
444
- # Taken from https://github.com/facebookresearch/ConvNeXt-V2/blob/3608f67cc1dae164790c5d0aead7bf2d73d9719b/models/utils.py#L105
445
- def __init__(self, dim):
446
- super().__init__()
447
- self.gamma = nn.Parameter(torch.zeros(1, 1, 1, dim))
448
- self.beta = nn.Parameter(torch.zeros(1, 1, 1, dim))
449
-
450
- def forward(self, x):
451
- gx = torch.norm(x, p=2, dim=(1, 2), keepdim=True)
452
- nx = gx / (gx.mean(dim=-1, keepdim=True) + 1e-6)
453
- return self.gamma * (x * nx) + self.beta + x
454
-
455
-
456
- class SpatialNorm(nn.Module):
457
- """
458
- Spatially conditioned normalization as defined in https://arxiv.org/abs/2209.09002.
459
-
460
- Args:
461
- f_channels (`int`):
462
- The number of channels for input to group normalization layer, and output of the spatial norm layer.
463
- zq_channels (`int`):
464
- The number of channels for the quantized vector as described in the paper.
465
- """
466
-
467
- def __init__(
468
- self,
469
- f_channels: int,
470
- zq_channels: int,
471
- ):
472
- super().__init__()
473
- self.norm_layer = nn.GroupNorm(num_channels=f_channels, num_groups=32, eps=1e-6, affine=True)
474
- self.conv_y = nn.Conv2d(zq_channels, f_channels, kernel_size=1, stride=1, padding=0)
475
- self.conv_b = nn.Conv2d(zq_channels, f_channels, kernel_size=1, stride=1, padding=0)
476
-
477
- def forward(self, f: torch.Tensor, zq: torch.Tensor) -> torch.Tensor:
478
- f_size = f.shape[-2:]
479
- zq = F.interpolate(zq, size=f_size, mode="nearest")
480
- norm_f = self.norm_layer(f)
481
- new_f = norm_f * self.conv_y(zq) + self.conv_b(zq)
482
- return new_f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models/quant.py CHANGED
@@ -102,7 +102,7 @@ class VectorQuantizer(nn.Module):
102
  # update vocab_usage
103
  prob_per_class_is_chosen = indices.bincount(minlength=self.vocab_size).to(dtype=torch.bfloat16)
104
  handler = tdist.all_reduce(prob_per_class_is_chosen, async_op=True) if (
105
- self.training and dist.initialized()) else None
106
  if handler is not None:
107
  handler.wait()
108
  prob_per_class_is_chosen /= prob_per_class_is_chosen.sum()
 
102
  # update vocab_usage
103
  prob_per_class_is_chosen = indices.bincount(minlength=self.vocab_size).to(dtype=torch.bfloat16)
104
  handler = tdist.all_reduce(prob_per_class_is_chosen, async_op=True) if (
105
+ self.training) else None #TODO
106
  if handler is not None:
107
  handler.wait()
108
  prob_per_class_is_chosen /= prob_per_class_is_chosen.sum()
models/{cotyle_utils.py → utils.py} RENAMED
File without changes