当前模型：# -- coding: utf-8 --**
import torch
import torch.nn as nn
import torch.nn.functional as F
# import torch_geometric.transforms as T
# from torch_geometric.nn import GMMConv,global_mean_pool
import os
import sys
import pdb
from models import torchvision_resnet
from timm.models.layers import PatchEmbed, Mlp, DropPath, trunc_normal_, lecun_normal_
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)



class Attention(nn.Module):
    # fused_attn: Final[bool]

    def __init__(
            self,
            dim,
            num_heads=6,
            qkv_bias=False,
            qk_norm=False,
            attn_drop=0.,
            proj_drop=0.,
            norm_layer=nn.LayerNorm,
    ):
        super().__init__()
        assert dim % num_heads == 0, 'dim should be divisible by num_heads'
        self.num_heads = num_heads
        self.head_dim = dim // num_heads
        self.scale = self.head_dim ** -0.5
        self.fused_attn = False

        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
        self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
        self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity()
        self.attn_drop = nn.Dropout(attn_drop)
        self.proj = nn.Linear(dim, dim)
        self.proj_drop = nn.Dropout(proj_drop)

    def forward(self, x):
        B, N, C = x.shape
        qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
        q, k, v = qkv.unbind(0)
        q, k = self.q_norm(q), self.k_norm(k)

        if self.fused_attn:
            x = F.scaled_dot_product_attention(
                q, k, v,
                dropout_p=self.attn_drop.p,
            )
        else:
            q = q * self.scale
            attn = q @ k.transpose(-2, -1)
            attn = attn.softmax(dim=-1)
            attn = self.attn_drop(attn)
            x = attn @ v

        x = x.transpose(1, 2).reshape(B, N, C)
        x = self.proj(x)
        x = self.proj_drop(x)
        return x

class PatchEmbed(nn.Module):
    """ 2D Image to Patch Embedding
    """
    def __init__(self, img_size=8, patch_size=4, in_chans=512, embed_dim=768, norm_layer=None, flatten=True):
        super().__init__()
        img_size = (img_size,img_size)
        patch_size = (patch_size,patch_size)
        self.img_size = img_size
        self.patch_size = patch_size
        self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
        self.num_patches = self.grid_size[0] * self.grid_size[1]
        self.flatten = flatten

        self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
        self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()

    def forward(self, x):
        B, C, H, W = x.shape
        assert H == self.img_size[0], f"Input image height ({H}) doesn't match model ({self.img_size[0]})."
        assert W == self.img_size[1], f"Input image width ({W}) doesn't match model ({self.img_size[1]})."
        x = self.proj(x)
        if self.flatten:
            x = x.flatten(2).transpose(1, 2)  # BCHW -> BNC
        x = self.norm(x)
        return x
class LayerScale(nn.Module):
    def __init__(self, dim, init_values=1e-5, inplace=False):
        super().__init__()
        self.inplace = inplace
        self.gamma = nn.Parameter(init_values * torch.ones(dim))

    def forward(self, x):
        return x.mul_(self.gamma) if self.inplace else x * self.gamma

class ST_Transformer_block(torch.nn.Module):
    def __init__(self,dim=768,num_heads=4,mlp_ratio=4,attn_drop=0.,drop=0.,drop_path=0.,
                 qkv_bias=False,init_values=None):
        super(ST_Transformer_block, self).__init__()
        self.norm1 = nn.LayerNorm(dim)
        self.norm2 = nn.LayerNorm(dim)
        self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
        self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity()
        self.mlp1 = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=nn.GELU, drop=drop)
        self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop)
        self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
        self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()

    def forward(self,input):
        temporal_form = input + self.drop_path1(self.ls1(self.attn(self.norm1(input))))
        temporal_form = self.norm2(temporal_form)
        temporal_form_out = temporal_form + self.drop_path2(self.ls2(self.mlp1(temporal_form)))#torch.Size([4, 9, 512])

        return temporal_form_out
    
class Net(torch.nn.Module):
    def init(self, pretrained=None, batchNorm=True, init_std=0.05,
                 dim=24, clip_len=8, num_heads=6, mlp_ratio=4.,
                 qkv_bias=False, drop=0., attn_drop=0., init_values=None, drop_path=0., embed_dim=768):
        super(Net, self).init()
        self.patch_emd = PatchEmbed(img_size=8, patch_size=4, in_chans=512, embed_dim=embed_dim, norm_layer=None, flatten=True)
        self.drop = drop
        drop_rate = 0.
        self.ST_Transformer_blocks = nn.ModuleList([
            ST_Transformer_block(dim=dim, num_heads=num_heads, mlp_ratio=mlp_ratio,
                                 attn_drop=attn_drop, drop=drop, qkv_bias=qkv_bias,
                                 init_values=init_values, drop_path=drop_path) for _ in range(5)])

        self.clip_len = clip_len
        self.batchNorm = batchNorm
        self.resnet18_feature_extractor = torchvision_resnet.resnet18(pretrained=True)
        self.pos_drop = nn.Dropout(p=drop_rate)
        self.pos_embed = nn.Parameter(torch.zeros([1, self.clip_len4, embed_dim], requires_grad=True))

        self.fc1 = torch.nn.Linear(embed_dim, 512)
        self.bn = torch.nn.SyncBatchUm((512))
        self.drop_out = torch.nn.Dropout()
        self.fc2 = torch.nn.Linear(512, 24)

    def forward(self, data_frame):
        # B C N H W
        B, C, N, H, W = data_frame.shape
        data_frame = data_frame.permute(0, 2, 1, 3, 4)
        # Scaling and Reshape
        res_img_F = F.interpolate(data_frame, size=[self.clip_len, 240, 240], mode='trilinear')
        res_img = res_img_F.permute(0, 2, 1, 3, 4).reshape(self.clip_lenB, C, 240, 240)
        img_with_feature = self.resnet18_feature_extractor(res_img)

        # Patch embedding
        patched_data = self.patch_emd(img_with_feature)
        input_former_data_ori = patched_data.reshape(B, -1, patched_data.shape[2])

        # Positional encoding and transformer block sequence
        input_former_data = self.pos_drop(input_former_data_ori + self.pos_embed)
        x = input_former_data
        for block in self.ST_Transformer_blocks:
            x = block(x)

        # MLP and classification head
        x = torch.mean(x, 1)  # [b, dim]
        x = self.fc1(x)
        x = F.elu(self.bn(x))
        x = self.drop_out(x)
        x = self.fc2(x)

        return F.log_softmax(x, dim=1)
是否可以作为特征提取器？