Repository navigation
Expand file tree
/
Copy pathmlp.py
More file actions
379 lines (330 loc) · 11.8 KB
/
Copy pathmlp.py
File metadata and controls
379 lines (330 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import os
import pickle
import time
from dataclasses import dataclass
from typing import Optional
import jax
import jax.numpy as jnp
from common import (
VOCAB_SIZE,
build_tokenized_dataset,
create_grain_loader,
itos,
load_names,
)
from layers import (
Layer,
BatchNorm1d,
Embedding,
Flatten,
Linear,
OneHot,
Sequential,
Tanh,
calibrate_batchnorm_stats,
)
from telemetry import TensorBoardLogger, compute_diagnostics
@dataclass
class MLPConfig:
"""Configuration for the MLP character language model."""
data_path: str = "names.txt"
save_dir: str = "models"
ngram_size: int = 9
emb_size: Optional[int] = 10 # None for one-hot; int for embedding table
hidden_dim: int = 200
learning_rate: float = 0.1
lr_decay_step: float = 0.8 # Fraction of steps after which LR is decayed
lr_decay_factor: float = 0.1
num_steps: int = 100000
batch_size: int = 32
reg_weight: float = 0.01 # L2 regularization weight
use_kaiming: bool = True
use_batchnorm: bool = True
bn_momentum: float = 0.001
bn_eps: float = 1e-5
use_tensorboard: bool = True
tb_log_dir: str = "runs/mlp"
tb_log_interval: int = 50
tb_hist_interval: int = 200
train_ratio: float = 0.8
seed: int = 0
num_samples: int = 10
max_length: int = 20
log_interval: int = 200
def build_mlp(config: MLPConfig) -> Sequential:
"""Constructs a modular Sequential MLP model based on MLPConfig."""
context_len = config.ngram_size - 1
layers: list[Layer] = []
if config.emb_size is not None:
layers.append(Embedding(VOCAB_SIZE, config.emb_size))
in_dim = context_len * config.emb_size
else:
layers.append(OneHot(VOCAB_SIZE))
in_dim = context_len * VOCAB_SIZE
layers.append(Flatten())
weight_scale = "kaiming" if config.use_kaiming else "fan_in"
# When followed by BatchNorm, Linear bias is redundant and omitted
layers.append(
Linear(
in_features=in_dim,
out_features=config.hidden_dim,
bias=not config.use_batchnorm,
weight_scale=weight_scale,
)
)
if config.use_batchnorm:
layers.append(
BatchNorm1d(
num_features=config.hidden_dim,
eps=config.bn_eps,
momentum=config.bn_momentum,
)
)
layers.append(Tanh())
# Output projection to vocabulary logits
layers.append(
Linear(
in_features=config.hidden_dim,
out_features=VOCAB_SIZE,
bias=True,
weight_scale=0.01,
)
)
return Sequential(layers)
def make_train_step(model: Sequential, return_grads: bool = False):
"""Creates a JIT-compiled train step closure for a modular Sequential model."""
@jax.jit
def step(
params: list[dict[str, jnp.ndarray]],
state: list[dict[str, jnp.ndarray]],
x_batch: jnp.ndarray,
y_batch: jnp.ndarray,
lr: float,
reg_weight: float,
):
def loss_fn(p):
logits, new_s = model(p, state, x_batch, training=True)
logprobs = jax.nn.log_softmax(logits, axis=-1)
target_logprobs = jnp.take_along_axis(logprobs, y_batch[:, None], axis=1)
nll = -jnp.mean(target_logprobs)
l2_weights = [
0.5 * jnp.sum(layer_p["w"] ** 2)
for layer_p in p
if "w" in layer_p
]
l2_loss = sum(l2_weights) if l2_weights else 0.0
return nll + reg_weight * l2_loss, new_s
(loss, new_state), grads = jax.value_and_grad(loss_fn, has_aux=True)(params)
new_params = jax.tree.map(lambda p, g: p - lr * g, params, grads)
if return_grads:
return new_params, new_state, loss, grads
return new_params, new_state, loss
return step
def evaluate(
model: Sequential,
params: list[dict[str, jnp.ndarray]],
state: list[dict[str, jnp.ndarray]],
xs: jnp.ndarray,
ys: jnp.ndarray,
batch_size: int = 1024,
) -> tuple[float, float]:
"""Evaluates NLL and perplexity over dataset splits in batches."""
total_nll = 0.0
n_samples = xs.shape[0]
for i in range(0, n_samples, batch_size):
xb = xs[i : i + batch_size]
yb = ys[i : i + batch_size]
logits, _ = model(params, state, xb, training=False)
logprobs = jax.nn.log_softmax(logits, axis=-1)
target_logprobs = jnp.take_along_axis(logprobs, yb[:, None], axis=1)
total_nll += float(-jnp.sum(target_logprobs))
mean_nll = total_nll / n_samples
perplexity = float(jnp.exp(mean_nll))
return mean_nll, perplexity
def sample_nn(
model: Sequential,
params: list[dict[str, jnp.ndarray]],
state: list[dict[str, jnp.ndarray]],
key: jax.Array,
context_len: int,
num_samples: int = 10,
max_length: int = 20,
) -> list[str]:
"""Generates names autoregressively from the network."""
generated_names = []
for _ in range(num_samples):
cur_tokens = [0] * context_len
out_chars = []
for _ in range(max_length):
key, subkey = jax.random.split(key)
context = jnp.array(cur_tokens[-context_len:], dtype=jnp.int32)
logits, _ = model(params, state, context, training=False)
next_token = int(jax.random.categorical(subkey, logits))
if next_token == 0:
break
out_chars.append(itos(next_token))
cur_tokens.append(next_token)
generated_names.append("".join(out_chars))
return generated_names
def main(config: MLPConfig = MLPConfig()):
print("=" * 60)
print(f" jakemore: {config.ngram_size}-gram MLP Language Model (JAX)")
print("=" * 60)
# 1. Load dataset, shuffle names with JAX PRNG, & build tokenized n-grams
names = load_names(config.data_path)
base_key = jax.random.key(config.seed)
shuffle_key, init_key, master_key = jax.random.split(base_key, 3)
perm = jax.random.permutation(shuffle_key, len(names))
names = [names[int(i)] for i in perm]
split_idx = int(round(len(names) * config.train_ratio))
train_xs, train_ys = build_tokenized_dataset(
names[:split_idx], ngram_size=config.ngram_size
)
test_xs, test_ys = build_tokenized_dataset(
names[split_idx:], ngram_size=config.ngram_size
)
total_transitions = train_xs.shape[0] + test_xs.shape[0]
print(
f"Loaded {len(names):,} names ({total_transitions:,} {config.ngram_size}-gram transitions)"
)
print(f"Train set: {train_xs.shape[0]:,} transitions")
print(f"Test set: {test_xs.shape[0]:,} transitions")
print(
f"Embedding: {f'{config.emb_size}-dim table' if config.emb_size is not None else 'One-hot'}"
)
print(f"Hidden Dim: {config.hidden_dim} (tanh)")
print(
f"BatchNorm: {'Enabled (alpha=' + str(config.bn_momentum) + ')' if config.use_batchnorm else 'Disabled'}"
)
print(
f"LR: {config.learning_rate} (decay {config.lr_decay_factor}x @ {int(config.lr_decay_step * 100)}%) | Steps: {config.num_steps:,} | Batch: {config.batch_size}\n"
)
# 2. Build modular model and initialize parameters and state
model = build_mlp(config)
params, state = model.init(init_key)
param_count = model.param_count(params)
print(f"Model Parameters: {param_count:,}\n")
# 3. Create JIT-compiled train step & optional TensorBoard logger
step_fn = make_train_step(model, return_grads=config.use_tensorboard)
tb_logger = None
if config.use_tensorboard:
tb_logger = TensorBoardLogger(log_dir=config.tb_log_dir)
print(f"TensorBoard: Enabled -> logdir: '{config.tb_log_dir}'")
train_loader = create_grain_loader(
train_xs,
train_ys,
batch_size=config.batch_size,
seed=config.seed,
repeat=True,
)
train_iter = iter(train_loader)
print("Training:")
start = time.perf_counter()
for step in range(1, config.num_steps + 1):
batch = next(train_iter)
xb = jnp.array(batch["x"], dtype=jnp.int32)
yb = jnp.array(batch["y"], dtype=jnp.int32)
lr = (
config.learning_rate
if (step / config.num_steps) < config.lr_decay_step
else config.learning_rate * config.lr_decay_factor
)
if config.use_tensorboard:
params, state, loss, grads = step_fn(
params,
state,
xb,
yb,
lr=lr,
reg_weight=config.reg_weight,
)
else:
params, state, loss = step_fn(
params,
state,
xb,
yb,
lr=lr,
reg_weight=config.reg_weight,
)
# TensorBoard telemetry logging
if tb_logger is not None:
should_log_diag = (
step % config.tb_log_interval == 0 or step == config.num_steps
)
should_log_hist = (
step % config.tb_hist_interval == 0 or step == config.num_steps
)
diag = None
if should_log_diag:
diag = compute_diagnostics(model, params, state, grads, xb, lr)
tb_logger.log_step(
step=step,
loss=float(loss),
lr=lr,
diagnostics=diag,
log_histograms=should_log_hist,
)
if step % config.log_interval == 0 or step == config.num_steps:
print(
f" Step {step:6d}/{config.num_steps:,} | Train Loss: {loss.item():.4f}"
)
stop = time.perf_counter()
train_time = stop - start
# 4. Calibrate BatchNorm statistics & Evaluate NLL / Perplexity
if config.use_batchnorm:
state = calibrate_batchnorm_stats(params, state, model, [train_xs])
train_nll, train_perplexity = evaluate(model, params, state, train_xs, train_ys)
test_nll, test_perplexity = evaluate(model, params, state, test_xs, test_ys)
print(f"\nTrain Time: {train_time:.2f} s")
print(
f"Train NLL: {train_nll:.4f} | Train Perplexity: {train_perplexity:.4f}"
)
print(
f"Test NLL: {test_nll:.4f} | Test Perplexity: {test_perplexity:.4f}"
)
# 5. Log evaluation metrics to TensorBoard and close
if tb_logger is not None:
tb_logger.log_scalars(
{
"eval/train_nll": train_nll,
"eval/train_perplexity": train_perplexity,
"eval/test_nll": test_nll,
"eval/test_perplexity": test_perplexity,
},
step=config.num_steps,
)
tb_logger.close()
print(f"\nTensorBoard logs written to '{config.tb_log_dir}/'")
print(f"Run dashboard via: uv run tensorboard --logdir {config.tb_log_dir}")
# 6. Generate sample names
master_key, sample_key = jax.random.split(master_key)
generated = sample_nn(
model,
params,
state,
sample_key,
context_len=config.ngram_size - 1,
num_samples=config.num_samples,
max_length=config.max_length,
)
print("\nGenerated Names:")
for idx, name in enumerate(generated, start=1):
print(f" {idx:2d}. {name}")
# 7. Save model checkpoint
os.makedirs(config.save_dir, exist_ok=True)
save_path = os.path.join(config.save_dir, "mlp_model.pkl")
model_data = {
"params": params,
"state": state,
"config": config,
"train_nll": train_nll,
"train_perplexity": train_perplexity,
"test_nll": test_nll,
"test_perplexity": test_perplexity,
}
with open(save_path, "wb") as f:
pickle.dump(model_data, f)
print(f"\nModel saved to '{save_path}'\n")
if __name__ == "__main__":
main()