MCPcopy Create free account
hub / github.com/MeiGen-AI/MultiTalk / WanSelfAttention

Class WanSelfAttention

wan/modules/model.py:105–159  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

103
104
105class WanSelfAttention(nn.Module):
106
107 def __init__(self,
108 dim,
109 num_heads,
110 window_size=(-1, -1),
111 qk_norm=True,
112 eps=1e-6):
113 assert dim % num_heads == 0
114 super().__init__()
115 self.dim = dim
116 self.num_heads = num_heads
117 self.head_dim = dim // num_heads
118 self.window_size = window_size
119 self.qk_norm = qk_norm
120 self.eps = eps
121
122 # layers
123 self.q = nn.Linear(dim, dim)
124 self.k = nn.Linear(dim, dim)
125 self.v = nn.Linear(dim, dim)
126 self.o = nn.Linear(dim, dim)
127 self.norm_q = WanRMSNorm(dim, eps=eps) if qk_norm else nn.Identity()
128 self.norm_k = WanRMSNorm(dim, eps=eps) if qk_norm else nn.Identity()
129
130 def forward(self, x, seq_lens, grid_sizes, freqs):
131 r"""
132 Args:
133 x(Tensor): Shape [B, L, num_heads, C / num_heads]
134 seq_lens(Tensor): Shape [B]
135 grid_sizes(Tensor): Shape [B, 3], the second dimension contains (F, H, W)
136 freqs(Tensor): Rope freqs, shape [1024, C / num_heads / 2]
137 """
138 b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim
139
140 # query, key, value function
141 def qkv_fn(x):
142 q = self.norm_q(self.q(x)).view(b, s, n, d)
143 k = self.norm_k(self.k(x)).view(b, s, n, d)
144 v = self.v(x).view(b, s, n, d)
145 return q, k, v
146
147 q, k, v = qkv_fn(x)
148
149 x = flash_attention(
150 q=rope_apply(q, grid_sizes, freqs),
151 k=rope_apply(k, grid_sizes, freqs),
152 v=v,
153 k_lens=seq_lens,
154 window_size=self.window_size)
155
156 # output
157 x = x.flatten(2)
158 x = self.o(x)
159 return x
160
161
162class WanT2VCrossAttention(WanSelfAttention):

Callers 1

__init__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected