FlameF0X commited on
Commit
4276930
·
verified ·
1 Parent(s): 945b2ae

Create modeling_snowflake.py

Browse files
Files changed (1) hide show
  1. modeling_snowflake.py +112 -0
modeling_snowflake.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import math
4
+
5
+ # --- Submodule: FusedQKVAttention ---
6
+ class FusedQKVAttention(nn.Module):
7
+ def __init__(self, d_model, num_heads):
8
+ super().__init__()
9
+ self.d_model = d_model
10
+ self.num_heads = num_heads
11
+ self.head_dim = d_model // num_heads
12
+ # Fused QKV projection
13
+ self.qkv_proj = nn.Linear(d_model, 3 * d_model)
14
+ self.wo = nn.Linear(d_model, d_model)
15
+ # Initialize weights for better training stability
16
+ nn.init.xavier_uniform_(self.qkv_proj.weight)
17
+ nn.init.xavier_uniform_(self.wo.weight)
18
+ nn.init.zeros_(self.qkv_proj.bias)
19
+ nn.init.zeros_(self.wo.bias)
20
+
21
+ def forward(self, x, attention_mask=None):
22
+ batch_size, seq_len, _ = x.shape
23
+ # Fused projection and reshape
24
+ qkv = self.qkv_proj(x).reshape(batch_size, seq_len, 3, self.num_heads, self.head_dim)
25
+ qkv = qkv.permute(2, 0, 3, 1, 4) # [3, batch, heads, seq_len, head_dim]
26
+ q, k, v = qkv[0], qkv[1], qkv[2]
27
+ # Compute attention with memory efficiency
28
+ attention_scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
29
+ if attention_mask is not None:
30
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
31
+ attention_scores = attention_scores.masked_fill(attention_mask == 0, float('-inf'))
32
+ attention_weights = torch.softmax(attention_scores, dim=-1)
33
+ # Apply attention and reshape
34
+ context = torch.matmul(attention_weights, v)
35
+ context = context.transpose(1, 2).reshape(batch_size, seq_len, self.d_model)
36
+ return self.wo(context)
37
+
38
+
39
+ # --- Submodule: EnhancedFeedForward ---
40
+ class EnhancedFeedForward(nn.Module):
41
+ def __init__(self, d_model, ff_dim, dropout=0.1):
42
+ super().__init__()
43
+ self.linear1 = nn.Linear(d_model, ff_dim)
44
+ self.dropout1 = nn.Dropout(dropout)
45
+ self.linear2 = nn.Linear(ff_dim, d_model)
46
+ self.dropout2 = nn.Dropout(dropout)
47
+ self.activation = nn.GELU()
48
+ # Initialize weights for better training
49
+ nn.init.xavier_uniform_(self.linear1.weight)
50
+ nn.init.xavier_uniform_(self.linear2.weight)
51
+ nn.init.zeros_(self.linear1.bias)
52
+ nn.init.zeros_(self.linear2.bias)
53
+
54
+ def forward(self, x):
55
+ return self.dropout2(self.linear2(self.dropout1(self.activation(self.linear1(x)))))
56
+
57
+
58
+ # --- Submodule: EnhancedTransformerBlock ---
59
+ class EnhancedTransformerBlock(nn.Module):
60
+ def __init__(self, d_model, num_heads, ff_dim, dropout=0.1):
61
+ super().__init__()
62
+ self.attention = FusedQKVAttention(d_model, num_heads)
63
+ self.norm1 = nn.LayerNorm(d_model, eps=1e-6)
64
+ self.dropout1 = nn.Dropout(dropout)
65
+ self.feed_forward = EnhancedFeedForward(d_model, ff_dim, dropout)
66
+ self.norm2 = nn.LayerNorm(d_model, eps=1e-6)
67
+ self.dropout2 = nn.Dropout(dropout)
68
+
69
+ def forward(self, x, attention_mask=None):
70
+ # Pre-norm architecture
71
+ attn_input = self.norm1(x)
72
+ attn_output = self.attention(attn_input, attention_mask)
73
+ x = x + self.dropout1(attn_output)
74
+ ff_input = self.norm2(x)
75
+ ff_output = self.feed_forward(ff_input)
76
+ x = x + self.dropout2(ff_output)
77
+ return x
78
+
79
+
80
+ # --- Main Model Class: Snowflake4CausalLM ---
81
+ class Snowflake4CausalLM(nn.Module):
82
+ def __init__(self, vocab_size, max_seq_length, d_model, num_heads, num_layers, ff_dim, dropout=0.1):
83
+ super().__init__()
84
+ self.embedding = nn.Embedding(vocab_size, d_model)
85
+ # Initialize positional encodings without in-place modification
86
+ self.pos_encoding = nn.Parameter(torch.zeros(1, max_seq_length, d_model))
87
+ position = torch.arange(max_seq_length).unsqueeze(1).float()
88
+ div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
89
+ pos_enc = torch.zeros(1, max_seq_length, d_model)
90
+ pos_enc[0, :, 0::2] = torch.sin(position * div_term)
91
+ pos_enc[0, :, 1::2] = torch.cos(position * div_term)
92
+ self.pos_encoding.data = pos_enc.data
93
+ self.layers = nn.ModuleList([
94
+ EnhancedTransformerBlock(d_model, num_heads, ff_dim, dropout)
95
+ for _ in range(num_layers)
96
+ ])
97
+ self.final_norm = nn.LayerNorm(d_model, eps=1e-6)
98
+ self.dropout = nn.Dropout(dropout)
99
+ self.fc_out = nn.Linear(d_model, vocab_size)
100
+ # Tie embedding and output weights for memory efficiency and better generalization
101
+ self.fc_out.weight = self.embedding.weight
102
+ # Initialize embedding weights
103
+ nn.init.normal_(self.embedding.weight, mean=0, std=0.02)
104
+
105
+ def forward(self, input_ids, attention_mask=None):
106
+ seq_length = input_ids.size(1)
107
+ x = self.embedding(input_ids) + self.pos_encoding[:, :seq_length, :]
108
+ x = self.dropout(x)
109
+ for layer in self.layers:
110
+ x = layer(x, attention_mask)
111
+ x = self.final_norm(x)
112
+ return self.fc_out(x)