手写transformer

#!/user/bin/env python3
# -*- coding: utf-8 -*-
# @Time     : 2022-09-29 15:18
# @Author   : Lyt
# @IDE      : PyCharm    
# @FileName : transformer.py
# @Blog     : https://blog.csdn.net/m0_53292725?type=blog

import torch
import torch.nn as nn
from einops import rearrange


class Attention(nn.Module):
    def __init__(self, dim, head_dim=64, heads=8, dropout=0.):
        super(Attention, self).__init__()

        inner_dim = head_dim * heads
        self.heads = heads
        self.softmax = nn.Softmax(dim=-1)
        self.to_qkv = nn.Linear(dim, inner_dim*3)
        self.to_out = nn.Sequential(nn.Linear(inner_dim, dim),
                                    nn.Dropout(dropout))
        self.scale = head_dim ** -0.5



    def forward(self, x):
        qkv = self.to_qkv(x).chunk(3, dim=-1)
        q, k, v = map(lambda t:rearrange(t, 'b n (h d) -> b h n d', h=self.heads), qkv)
        dots = torch.matmul(q, k.transpose(-1, -2))*self.scale
        attend = self.softmax(dots)
        out = torch.matmul(attend, v)
        out = rearrange(out, 'b h n d -> b n (h d)')
        return self.to_out(out)

    
class Norm(nn.Module): # 先 norm 再进norm里的那一层 这里是attention 和 feedforward
    def __init__(self, dim, fn):
        super(Norm, self).__init__()
        self.norm = nn.LayerNorm(dim)
        self.fn = fn

    def forward(self, x, **kwargs):  #
        return self.fn(self.norm(x), **kwargs)
    
        
class FeedForward(nn.Module):
    def __init__(self, dim, hidden_dim, dropout=0.):
        super(FeedForward, self).__init__() 
        self.net = nn.Sequential(
            nn.Linear(dim, hidden_dim), 
            nn.GELU(), 
            nn.Dropout(dropout),
            nn.Linear(hidden_dim, dim),
            nn.Dropout(dropout)
        )
        
    def forward(self, x):
        return self.net(x)
    
    
class Transformer(nn.Module):
    def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout=0.):
        super(Transformer, self).__init__()   
        self.layers = nn.ModuleList([])
        for _ in range(depth):
            self.layers.append(nn.ModuleList([
                Norm(dim, Attention(dim, dim_head=dim_head, heads=heads, dropout=dropout)),
                Norm(dim, FeedForward(dim, mlp_dim, dropout=dropout))
            ]))

    def forward(self, x):
        for att, ff in self.layers:
            x = att(x) + x
            x = ff(x) + x
        return x

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lyttonkeepgoing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值