import torchfrom torch import nnimport torch.nn.functional as Fimport transformersfrom transformers import AutoTokenizer,AutoConfig,AutoModelimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib as mpl
class MultiHeadAttention(nn.Module): def __init__(self,config): super().__init__() embed_dim = config.hidden_size num_heads = config.num_attention_heads # 768/12 == 64 head_dim = embed_dim//num_heads self.hands = nn.ModuleList([ AttentionHead(embed_dim,head_dim) for _ in range(num_heads) ]) # 768==>768 self.output_layer = nn.Linear(embed_dim,embed_dim) def forward(self,hidden_state): print(f'input hidden_state:{hidden_state.shape}') print(f'head(hidden_state):{self.heads[11](hidden_state).shape}') x = torch.cat([head(hidden_state) for head in self.heads],dim=-1) print(f'cat heads:{x.shape}') x = self.output_layer(x) return x
mha = MultoHeadAttention(config)
# input# config.vocab_size:30522# config.hidden_size:768=64*12# lookup-table,learnabletoken_embedding = nn.Embedding(config.vocab_size,config.hidden_size)# token_embeddingsample_text = 'time files like an arrow'model_input = tokenizer(sample_text,return_tensors='pt',add_special_tokens=False)# forward of embeddings moduleinput_embeddings = token_embedding(model_inputs['input_ids'])# batch_size,seq_len,seq_leninput_embeddings.shape
attn_output = mha(input_embeddings)
FFN
ReLU:x1
GELU:xϕ(x)
ϕ(x)=21+Erf(2x)
x = np.arange(-5,5,0.01)plt.plot(x,nn.ReLU()(torch.from_numpy(x)))plt.plot(x,nn.LeakyReLU(negetive_slope=0.1)(torch.from_numpy(x)))plt.plot(x,nn.GELU()(torch.from_numpy(x))plt.legend(['relu','lrelu','gelu'])
class FeedForward(nn.Module): def __init__(self,config): super().__init() # config.intermediate_size:4*h == 4*768 == 3072 # (intermediate) self.fc1 = nn.Linear(config.hidden_size,config.intermediate_size) # (output) self.fc2 = nn.Linear(config.intermediate_size,config.hidden_size) self.gelu = nn.GELU() self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self,x): #b,s,h ==> b,s,4h x = self.fc1(x) x = self.gelu(x) #b,s,4h ==> b,s,h x = self.fc2(x) x = self.dropout(x) return x