HawkLabofficial commited on
Commit
c1b2214
·
verified ·
1 Parent(s): dc25be1

Upload model.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. model.py +162 -0
model.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HawkGPT 0.4 — Optimized: RMSNorm, GQA, no biases, float32 stable."""
2
+
3
+ import math
4
+ import tensorflow as tf
5
+ from tensorflow import keras
6
+ from tensorflow.keras import layers
7
+
8
+ import config
9
+
10
+
11
+ class RMSNorm(layers.Layer):
12
+ """RMSNorm — faster than LayerNorm, no mean computation, same quality."""
13
+ def __init__(self, dim: int, eps: float = 1e-6, **kwargs):
14
+ super().__init__(**kwargs)
15
+ self.eps = eps
16
+ self.scale = self.add_weight(name="scale", shape=(dim,), initializer="ones")
17
+
18
+ def call(self, x: tf.Tensor) -> tf.Tensor:
19
+ rms = tf.sqrt(tf.reduce_mean(tf.square(x), axis=-1, keepdims=True) + self.eps)
20
+ return x / rms * self.scale
21
+
22
+
23
+ class GroupedQueryAttention(layers.Layer):
24
+ """GQA: 8 query heads, 2 KV heads. Saves VRAM, enables larger batch."""
25
+ def __init__(self, embed_dim: int, num_heads: int, num_kv_heads: int, dropout: float = 0.0, **kwargs):
26
+ super().__init__(**kwargs)
27
+ assert embed_dim % num_heads == 0
28
+ self.num_heads = num_heads
29
+ self.num_kv_heads = num_kv_heads
30
+ self.head_dim = embed_dim // num_heads
31
+ self.kv_dim = num_kv_heads * self.head_dim
32
+
33
+ self.q_proj = layers.Dense(embed_dim, use_bias=False)
34
+ self.k_proj = layers.Dense(self.kv_dim, use_bias=False)
35
+ self.v_proj = layers.Dense(self.kv_dim, use_bias=False)
36
+ self.out_proj = layers.Dense(embed_dim, use_bias=False)
37
+ self.dropout = layers.Dropout(dropout)
38
+ self.scale = math.sqrt(self.head_dim)
39
+
40
+ # Precompute ALiBi slopes (constant per head)
41
+ slopes = [-2.0 ** (-8.0 * h / num_heads) for h in range(num_heads)]
42
+ self._alibi_slopes = tf.constant(slopes, dtype=tf.float32)
43
+
44
+ def call(self, x: tf.Tensor, training: bool = False) -> tf.Tensor:
45
+ B, T, C = tf.shape(x)[0], tf.shape(x)[1], tf.shape(x)[2]
46
+
47
+ q = self.q_proj(x) # (B, T, embed_dim)
48
+ k = self.k_proj(x) # (B, T, kv_dim)
49
+ v = self.v_proj(x) # (B, T, kv_dim)
50
+
51
+ q = tf.reshape(q, (B, T, self.num_heads, self.head_dim))
52
+ q = tf.transpose(q, (0, 2, 1, 3)) # (B, H, T, D)
53
+
54
+ k = tf.reshape(k, (B, T, self.num_kv_heads, self.head_dim))
55
+ k = tf.transpose(k, (0, 2, 1, 3)) # (B, KV, T, D)
56
+ v = tf.reshape(v, (B, T, self.num_kv_heads, self.head_dim))
57
+ v = tf.transpose(v, (0, 2, 1, 3)) # (B, KV, T, D)
58
+
59
+ # Expand KV heads to match Q heads
60
+ k = tf.repeat(k, self.num_heads // self.num_kv_heads, axis=1)
61
+ v = tf.repeat(v, self.num_heads // self.num_kv_heads, axis=1)
62
+
63
+ # Scaled dot-product attention
64
+ att = tf.matmul(q, tf.transpose(k, (0, 1, 3, 2))) / self.scale
65
+
66
+ # ALiBi — compute on fly for exact T (safe with tf.Tensor)
67
+ slopes = tf.cast(self._alibi_slopes, att.dtype)
68
+ positions = tf.range(T, dtype=tf.float32)
69
+ positions = tf.cast(positions, att.dtype)
70
+ dist = tf.abs(positions[:, None] - positions[None, :])
71
+ att = att + slopes[:, None, None] * dist[None, :, :]
72
+
73
+ # Causal mask — softmax in float32 for numerical stability
74
+ causal_mask = tf.linalg.band_part(tf.ones((T, T)), -1, 0)
75
+ causal_mask = tf.reshape(causal_mask, (1, 1, T, T))
76
+ # Softmax in float32 to avoid float16 overflow
77
+ att_f32 = tf.cast(att, tf.float32)
78
+ att_f32 = tf.where(tf.equal(causal_mask, 0), tf.constant(-1e9, dtype=tf.float32), att_f32)
79
+ att_f32 = tf.nn.softmax(att_f32, axis=-1)
80
+ att = tf.cast(att_f32, v.dtype) # back to float16
81
+
82
+ att = self.dropout(att, training=training)
83
+
84
+ out = tf.matmul(att, v)
85
+ out = tf.transpose(out, (0, 2, 1, 3))
86
+ out = tf.reshape(out, (B, T, C))
87
+ return self.out_proj(out)
88
+
89
+
90
+ class FeedForward(layers.Layer):
91
+ def __init__(self, embed_dim: int, ff_dim: int, dropout: float = 0.0, **kwargs):
92
+ super().__init__(**kwargs)
93
+ self.net = keras.Sequential([
94
+ layers.Dense(ff_dim, activation="gelu", use_bias=False),
95
+ layers.Dense(embed_dim, use_bias=False),
96
+ layers.Dropout(dropout),
97
+ ])
98
+
99
+ def call(self, x: tf.Tensor, training: bool = False) -> tf.Tensor:
100
+ return self.net(x, training=training)
101
+
102
+
103
+ class TransformerBlock(layers.Layer):
104
+ """Standard pre-norm Transformer block: norm → attn → add → norm → ffn → add."""
105
+ def __init__(self, embed_dim: int, num_heads: int, num_kv_heads: int, ff_dim: int, dropout: float = 0.0, **kwargs):
106
+ super().__init__(**kwargs)
107
+ self.ln1 = RMSNorm(embed_dim)
108
+ self.attn = GroupedQueryAttention(embed_dim, num_heads, num_kv_heads, dropout)
109
+ self.ln2 = RMSNorm(embed_dim)
110
+ self.ff = FeedForward(embed_dim, ff_dim, dropout)
111
+
112
+ def call(self, x: tf.Tensor, training: bool = False) -> tf.Tensor:
113
+ x = x + self.attn(self.ln1(x), training=training)
114
+ x = x + self.ff(self.ln2(x), training=training)
115
+ return x
116
+
117
+
118
+ class GPTModel(keras.Model):
119
+ def __init__(
120
+ self,
121
+ vocab_size: int,
122
+ embed_dim: int = config.EMBED_DIM,
123
+ num_heads: int = config.NUM_HEADS,
124
+ num_kv_heads: int = config.NUM_KV_HEADS,
125
+ num_layers: int = config.NUM_LAYERS,
126
+ ff_dim: int = config.FF_DIM,
127
+ dropout: float = config.DROPOUT,
128
+ **kwargs,
129
+ ):
130
+ super().__init__(**kwargs)
131
+ self.embed_dim = embed_dim
132
+
133
+ self.token_emb = layers.Embedding(vocab_size, embed_dim, embeddings_initializer="normal")
134
+
135
+ self.blocks = [
136
+ TransformerBlock(embed_dim, num_heads, num_kv_heads, ff_dim, dropout)
137
+ for _ in range(num_layers)
138
+ ]
139
+ self.ln_final = RMSNorm(embed_dim)
140
+ self.head = layers.Dense(vocab_size, use_bias=False)
141
+
142
+ def call(self, input_ids: tf.Tensor, training: bool = False) -> tf.Tensor:
143
+ x = self.token_emb(input_ids)
144
+
145
+ for block in self.blocks:
146
+ x = block(x, training=training)
147
+
148
+ x = self.ln_final(x)
149
+ return self.head(x)
150
+
151
+ def count_params(self) -> int:
152
+ return sum(tf.size(v).numpy() for v in self.trainable_variables)
153
+
154
+
155
+ def build_model(vocab_size: int) -> GPTModel:
156
+ model = GPTModel(vocab_size=vocab_size)
157
+ dummy = tf.zeros((1, config.MAX_SEQ_LEN), dtype=tf.int32)
158
+ model(dummy)
159
+ # Weight tying
160
+ model.head.kernel.assign(tf.transpose(model.token_emb.embeddings))
161
+ print(f"Model built: {model.count_params():,} parameters")
162
+ return model