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 9d30de8 commit 7afb21d
Showing 1 changed file with 6 additions and 12 deletions.
18 changes: 6 additions & 12 deletions ding/model/template/hpt.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,7 @@ 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 @@ -119,12 +118,10 @@ 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 @@ -174,8 +171,7 @@ class CrossAttention(nn.Module):
dropout (:obj:`float`, optional): The dropout probability. Defaults to 0.0.
"""

def __init__(self, query_dim: int, heads: int = 8,
dim_head: int = 64, dropout: float = 0.0):
def __init__(self, query_dim: int, heads: int = 8, dim_head: int = 64, dropout: float = 0.0):
super().__init__()
inner_dim = dim_head * heads
context_dim = query_dim
Expand All @@ -188,8 +184,7 @@ def __init__(self, query_dim: int, heads: int = 8,

self.dropout = nn.Dropout(dropout)

def forward(self, x: torch.Tensor, context: torch.Tensor,
mask: Optional[torch.Tensor] = None) -> torch.Tensor:
def forward(self, x: torch.Tensor, context: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
"""
Overview:
Forward pass of the CrossAttention module.
Expand All @@ -206,8 +201,7 @@ def forward(self, x: torch.Tensor, context: torch.Tensor,
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 7afb21d

Please sign in to comment.