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

Class T5RelativeEmbedding

wan/modules/t5.py:226–269  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

224
225
226class T5RelativeEmbedding(nn.Module):
227
228 def __init__(self, num_buckets, num_heads, bidirectional, max_dist=128):
229 super(T5RelativeEmbedding, self).__init__()
230 self.num_buckets = num_buckets
231 self.num_heads = num_heads
232 self.bidirectional = bidirectional
233 self.max_dist = max_dist
234
235 # layers
236 self.embedding = nn.Embedding(num_buckets, num_heads)
237
238 def forward(self, lq, lk):
239 device = self.embedding.weight.device
240 # rel_pos = torch.arange(lk).unsqueeze(0).to(device) - \
241 # torch.arange(lq).unsqueeze(1).to(device)
242 rel_pos = torch.arange(lk, device=device).unsqueeze(0) - \
243 torch.arange(lq, device=device).unsqueeze(1)
244 rel_pos = self._relative_position_bucket(rel_pos)
245 rel_pos_embeds = self.embedding(rel_pos)
246 rel_pos_embeds = rel_pos_embeds.permute(2, 0, 1).unsqueeze(
247 0) # [1, N, Lq, Lk]
248 return rel_pos_embeds.contiguous()
249
250 def _relative_position_bucket(self, rel_pos):
251 # preprocess
252 if self.bidirectional:
253 num_buckets = self.num_buckets // 2
254 rel_buckets = (rel_pos > 0).long() * num_buckets
255 rel_pos = torch.abs(rel_pos)
256 else:
257 num_buckets = self.num_buckets
258 rel_buckets = 0
259 rel_pos = -torch.min(rel_pos, torch.zeros_like(rel_pos))
260
261 # embeddings for small and large positions
262 max_exact = num_buckets // 2
263 rel_pos_large = max_exact + (torch.log(rel_pos.float() / max_exact) /
264 math.log(self.max_dist / max_exact) *
265 (num_buckets - max_exact)).long()
266 rel_pos_large = torch.min(
267 rel_pos_large, torch.full_like(rel_pos_large, num_buckets - 1))
268 rel_buckets += torch.where(rel_pos < max_exact, rel_pos, rel_pos_large)
269 return rel_buckets
270
271
272class T5Encoder(nn.Module):

Callers 4

__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