MCPcopy Create free account
hub / github.com/CompVis/zigma / TimestepEmbedder

Class TimestepEmbedder

model_zigma.py:232–275  ·  view source on GitHub ↗

Embeds scalar timesteps into vector representations.

Source from the content-addressed store, hash-verified

230
231
232class TimestepEmbedder(nn.Module):
233 """
234 Embeds scalar timesteps into vector representations.
235 """
236
237 def __init__(self, hidden_size, dtype, frequency_embedding_size=256):
238 super().__init__()
239 self.mlp = nn.Sequential(
240 nn.Linear(frequency_embedding_size, hidden_size, bias=True),
241 nn.SiLU(),
242 nn.Linear(hidden_size, hidden_size, bias=True),
243 )
244 self.dtype = dtype
245 self.frequency_embedding_size = frequency_embedding_size
246
247 @staticmethod
248 def timestep_embedding(t, dim, dtype, max_period=10000):
249 """
250 Create sinusoidal timestep embeddings.
251 :param t: a 1-D Tensor of N indices, one per batch element.
252 These may be fractional.
253 :param dim: the dimension of the output.
254 :param max_period: controls the minimum frequency of the embeddings.
255 :return: an (N, D) Tensor of positional embeddings.
256 """
257 # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
258 half = dim // 2
259 freqs = torch.exp(
260 -math.log(max_period) * torch.arange(start=0, end=half, dtype=dtype) / half
261 ).to(device=t.device)
262 args = t[:, None].float() * freqs[None]
263 embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
264 if dim % 2:
265 embedding = torch.cat(
266 [embedding, torch.zeros_like(embedding[:, :1])], dim=-1
267 )
268 return embedding
269
270 def forward(self, t):
271 t_freq = self.timestep_embedding(
272 t, self.frequency_embedding_size, dtype=self.dtype
273 )
274 t_emb = self.mlp(t_freq.to(dtype=self.dtype))
275 return t_emb
276
277
278class LabelEmbedder(nn.Module):

Callers 1

__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected