Skip to content

Commit

Permalink
feature(xyy):add HPT model and test_hpt
Browse files Browse the repository at this point in the history
  • Loading branch information
luodi-7 committed Dec 4, 2024
1 parent 32f147f commit f3d5507
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions ding/model/template/hpt.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ def init_cross_attn(self):
"""Initialize cross-attention module and learnable tokens."""
token_num = 16
self.tokens = nn.Parameter(torch.randn(1, token_num, 128) * INIT_CONST)
self.cross_attention = CrossAttention(128, heads=8, dim_head=64, dropout=0.1)
self.cross_attention = CrossAttention(
128, heads=8, dim_head=64, dropout=0.1)

def compute_latent(self, x: torch.Tensor) -> torch.Tensor:
"""
Expand All @@ -112,10 +113,12 @@ def compute_latent(self, x: torch.Tensor) -> torch.Tensor:
"""
# Using the Feature Extractor
stem_feat = self.feature_extractor(x)
stem_feat = stem_feat.reshape(stem_feat.shape[0], -1, stem_feat.shape[-1]) # (B, N, 128)
stem_feat = stem_feat.reshape(
stem_feat.shape[0], -1, stem_feat.shape[-1]) # (B, N, 128)
# Calculating latent tokens using CrossAttention
stem_tokens = self.tokens.repeat(len(stem_feat), 1, 1) # (B, 16, 128)
stem_tokens = self.cross_attention(stem_tokens, stem_feat) # (B, 16, 128)
stem_tokens = self.cross_attention(
stem_tokens, stem_feat) # (B, 16, 128)
return stem_tokens

def forward(self, x: torch.Tensor) -> torch.Tensor:
Expand Down Expand Up @@ -195,7 +198,8 @@ def forward(self, x: torch.Tensor, context: torch.Tensor, mask: Optional[torch.T
h = self.heads
q = self.to_q(x)
k, v = self.to_kv(context).chunk(2, dim=-1)
q, k, v = map(lambda t: rearrange(t, "b n (h d) -> (b h) n d", h=h), (q, k, v))
q, k, v = map(lambda t: rearrange(
t, "b n (h d) -> (b h) n d", h=h), (q, k, v))
sim = torch.einsum("b i d, b j d -> b i j", q, k) * self.scale

if mask is not None:
Expand Down

0 comments on commit f3d5507

Please sign in to comment.