MCPcopy Create free account
hub / github.com/huggingface/diffusers / AdaLayerNorm

Class AdaLayerNorm

src/diffusers/models/normalization.py:27–81  ·  view source on GitHub ↗

r""" Norm layer modified to incorporate timestep embeddings. Parameters: embedding_dim (`int`): The size of each embedding vector. num_embeddings (`int`, *optional*): The size of the embeddings dictionary. output_dim (`int`, *optional*): norm_elementwise_affi

Source from the content-addressed store, hash-verified

25
26
27class AdaLayerNorm(nn.Module):
28 r"""
29 Norm layer modified to incorporate timestep embeddings.
30
31 Parameters:
32 embedding_dim (`int`): The size of each embedding vector.
33 num_embeddings (`int`, *optional*): The size of the embeddings dictionary.
34 output_dim (`int`, *optional*):
35 norm_elementwise_affine (`bool`, defaults to `False):
36 norm_eps (`bool`, defaults to `False`):
37 chunk_dim (`int`, defaults to `0`):
38 """
39
40 def __init__(
41 self,
42 embedding_dim: int,
43 num_embeddings: int | None = None,
44 output_dim: int | None = None,
45 norm_elementwise_affine: bool = False,
46 norm_eps: float = 1e-5,
47 chunk_dim: int = 0,
48 ):
49 super().__init__()
50
51 self.chunk_dim = chunk_dim
52 output_dim = output_dim or embedding_dim * 2
53
54 if num_embeddings is not None:
55 self.emb = nn.Embedding(num_embeddings, embedding_dim)
56 else:
57 self.emb = None
58
59 self.silu = nn.SiLU()
60 self.linear = nn.Linear(embedding_dim, output_dim)
61 self.norm = nn.LayerNorm(output_dim // 2, norm_eps, norm_elementwise_affine)
62
63 def forward(
64 self, x: torch.Tensor, timestep: torch.Tensor | None = None, temb: torch.Tensor | None = None
65 ) -> torch.Tensor:
66 if self.emb is not None:
67 temb = self.emb(timestep)
68
69 temb = self.linear(self.silu(temb))
70
71 if self.chunk_dim == 1:
72 # This is a bit weird why we have the order of "shift, scale" here and "scale, shift" in the
73 # other if-branch. This branch is specific to CogVideoX and OmniGen for now.
74 shift, scale = temb.chunk(2, dim=1)
75 shift = shift[:, None, :]
76 scale = scale[:, None, :]
77 else:
78 scale, shift = temb.chunk(2, dim=0)
79
80 x = self.norm(x) * (1 + scale) + shift
81 return x
82
83
84class FP32LayerNorm(nn.LayerNorm):

Callers 8

__init__Method · 0.85
__init__Method · 0.85
__init__Method · 0.85
__init__Method · 0.85
__init__Method · 0.85
__init__Method · 0.85
__init__Method · 0.85
__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…