Finding Problems

Tokenizer Bottlenecks

Scaling beyond the initial training runs exposed bottlenecks in how I loaded, tokenised and used the data. The original pipeline was memory bound and inefficient, with operations such as:

  • "\n\n".join(segments)
  • BPETokenizer._train() → corpus = list(text.encode("utf-8")) , this would probably overflow the RAM.
  • The current dataset and pipeline just does not fundamentally support streaming, which I need it to in order to scale up the experiments.

But the good news is that the training pipeline shouldn’t really be affected by this, most of the issue seems to be within the tokeniser code. As i see it we have 2 issues,

  1. BPE training on a 1B corpus is just going to take too long, even running for 50-100k would be time consuming and might still not be in the best interest as i scale to bigger experiments.
  2. Currently the corpus is being tokenised and materialised completely at training time, there isnt a true-streaming capability as of now.

Solved in this commit

Metric calculation and aggregation stalling training

# Cadances as per the config of the run
	log_every_n_steps= 25, # for step metrics
	diagnostics_every_n_steps= 100, # default for diagnostics
	layer_grad_norms_every_n_steps= 500,
	parameter_optimizer_norms_every_n_steps=500, # for update/weight ratio freq
	attention_entropy_every_n_steps=250,

My initial suspicion was that metric calculations offloaded to the CPU were stalling training. The later compile investigation showed that repeated graph compilation was also a major contributor.

  • Why why there isnt a spike at step 750 is a mystery to me !?
  • Also idk how only step 100 takes that long for basic diagnostics but every other step%100 is low?

At this point, the aggregate timings did not isolate the cost of each metric:

StepWhat firesSpike magnitude
100diagnostics (activation norms)~19s
250attention entropy only~29s - larger
500diagnostics + attention entropy~20s

This was attempted to be solved in this commit

Stateful Loader Multiprocessing and Prefetching

I tested multiprocessing and prefetching for the stateful loader in this commit

 train_loader = StatefulDataLoader(
        train_dataset,
        batch_size=batching.loader_batch_size,
        pin_memory=pin_memory,
-       num_workers=0,
+       num_workers=2,
+       prefetch_factor=2,
+       multiprocessing_context="spawn"
    )

The trial did not show a useful improvement, so I kept num_workers=0. These runs did not establish the dataloader as the bottleneck.


Bigger GPUs

The original GPT-2 was probably train on V100 or TPUs of the era, and training gpt2 made famous by @karapathy on A100s and recently on H100s. So using a 40GB A100 or RTX A6000 doesn’t really make sense at the moment.

Initial back-of-the-envelope estimates

We are using a 10B Token dataset: HuggingFaceFW/fineweb sample-10BT.

Chinchilla recommends 20 tokens per param as the token budget for reasonable training runs. While llama recommends a 1000:1 for token:param, which lands us around 125B tokens on a single run which kinda insane to try at the moment! (also the above dataset is only 10B tokens)

On an 40GB A100, including torch.compile and final model upload, the train time for B=128 MB=32 @ 1k steps was 34mins.

So a chinchilla regime approximation 20 toks : 1 param would mean → 19k steps → taking around 11-11.25hrs on the 40GB-A100

Thats a bit too expensive and it makes sense to upgrade to a better GPU at this point, looking at my options i see the A100 vs H100 both at 80GB while the H100 costs close to 2x the price of A100.

First the new 80GB VRAM easily allows doubling the micro-batch size to 64 and the effective batch to 512. ( mb → 2x , eff_batch → 4x ) Considering the same throughput increasing the mb should not since the num of matrix ops is same only the size of the matrix has increased. The eff_batch should making the step time also go up 4x since we are going to be running more grad_acc before a backward pass to hit the 512 batch-size.

Basically we should have 2x the speed compared to the 40GB-A100 on the same task cutting the train time to at least around 5.5hrs on a 80GB-A100 (assuming all other latencies are constants like torch compile, data loaders etc).

Based on some redditors and googling i hear that a H100 can potentially provide a 2-3x performance gain over a A100, which can potentially drop the training run to sub ~2-2.5hrs which is great!

These were budgeting estimates, not measured A100/H100 speedups. The following A100 comparison exposed instrumentation problems that made simple step-time comparisons unreliable.

Moving from 40 → 80GB A100

wandb run group: phase1/stage-1

In a quick dry run comparison i immediately spotted this issue of randoms stalling in train, and these spikes coincide with the metrics aggregation cadence which is likely the issue, hence i ran a small probe run to isolate which metric gates might be the root cause and found the following:

wandb run group: phase1/stage-1/latency-cadence-probe

These results are on wandb under the group phase1/stage-1/latency-cadence-probe , it is pretty evident that the issue stems from the metric collection and affects both forward and backward passes:

  • Forward pass:

    • seems severely affected by diagnostics, probe-collision and attention entropy.
  • Backward pass:

    • the control has very low latency but every other variant is equally slow so im not sure why.

These are the cumulative total:

MetricsEngine timing summary (ms):
  after_backward:
    global_grad_norm: 586.589 !!
    layer_grad_norm: 7.411
    layernorm_grad_norm: 0.014
    loss_metrics: 0.010
    parameter_optimizer_norms: 0.003
    step_timing_memory: 0.003
    forward_hook_metrics: 0.002
  after_microbatch_backward:
    loss_metrics: 0.094
    step_timing_memory: 0.016
    global_grad_norm: 0.014
    layer_grad_norm: 0.012
    forward_hook_metrics: 0.012
    layernorm_grad_norm: 0.012
    parameter_optimizer_norms: 0.010
  after_optimizer_step:
    parameter_optimizer_norms: 1224.786 !!
    step_timing_memory: 0.070
    loss_metrics: 0.008
    forward_hook_metrics: 0.003
    layernorm_grad_norm: 0.003
    global_grad_norm: 0.003
    layer_grad_norm: 0.002
  collect_epoch_metrics:
    loss_metrics: 0.013
    step_timing_memory: 0.009
    global_grad_norm: 0.001
    layer_grad_norm: 0.000
    layernorm_grad_norm: 0.000
    parameter_optimizer_norms: 0.000
    forward_hook_metrics: 0.000
  collect_step_metrics:
    forward_hook_metrics: 3.022
    loss_metrics: 0.060
    step_timing_memory: 0.016
    layer_grad_norm: 0.007
    global_grad_norm: 0.006
    layernorm_grad_norm: 0.006
    parameter_optimizer_norms: 0.005
  on_step_start:
    parameter_optimizer_norms: 948.666 !!
    step_timing_memory: 0.210
    forward_hook_metrics: 0.085
    loss_metrics: 0.018
    layer_grad_norm: 0.018
    layernorm_grad_norm: 0.013
    global_grad_norm: 0.012
  on_train_end:
    forward_hook_metrics: 0.088
    parameter_optimizer_norms: 0.003
    step_timing_memory: 0.001
    loss_metrics: 0.001
    global_grad_norm: 0.001
    layer_grad_norm: 0.000
    layernorm_grad_norm: 0.000
  on_train_start:
    forward_hook_metrics: 0.081
    step_timing_memory: 0.004
    loss_metrics: 0.001
    global_grad_norm: 0.000
    layer_grad_norm: 0.000
    layernorm_grad_norm: 0.000
    parameter_optimizer_norms: 0.000
 

The investigation also exposed an assumption in the optimizer metrics: some calculations expected Adam-style parameter groups. This was a limitation of the metrics implementation, not evidence about model performance.


Side quest : torch.compile recompilation spikes (resolved)

Before kicking off the Stage 1 baseline training run at scale, I got pulled into what looked like a small instrumentation question and became a several-day detour into torch.compile internals.

The trigger was a latency-cadence probe five short runs that sweep different metric-collection cadences, including a collision variant that fires every diagnostic group at the same step. The collision variant was showing very large step-time spikes (tens of seconds on A100), and in a particularly bad configuration the end-to-end run was ~4× slower than the supposedly-worse pre-fix baseline. That didn’t line up with any reasonable theory of “metrics are expensive,” so I dug in.

The short version: three independent bugs were each forcing torch.compile to recompile the forward graph.

  1. A lazily-grown positional-encoding buffer whose shape changed on the first forward.
  2. A forward hook whose closure captured a mutable boolean dynamo walked into __closure__[0].cell_contents and guarded on it, and the flag flipped on every metric-cadence step.
  3. The attention-entropy hook had the same closure-cell pattern, first on a capture flag, then on a stash dict transitioning from empty to populated.

The fix was to pre-materialize the pos-enc buffer in __init__ and decorate the hook bodies with @torch._dynamo.disable. End state: five distinct dynamo frames (one per disable boundary), each compiled exactly once, zero guard-failure recompiles. In these probes, cadence boundaries no longer triggered recompilation; the actual metric computation still contributed to step time.

The full writeup, with verbatim tlparse guard strings, W&B run IDs, step-level timing tables, and the commit-level diff of the fixes, is in Debugging torch.compile & stories of recompilation.

Two lessons from this:

  • Across the tested cadences, activation norms and attention entropy no longer caused guard-failure recompiles. Metric collection still has a cost, but that cost is distinct from graph recompilation.
  • tlparse and TORCH_LOGS=recompiles made the guard failures visible and helped distinguish instrumentation overhead from compiler behaviour.

Conclusion

Stage 1 became as much an investigation of the training harness as of the model. Scaling the GPT-2-style baseline to FineWeb exposed memory-heavy tokenisation, metric overhead and misleading timing spikes. The most useful result was separating those effects: the multiprocessing loader trial did not show a clear benefit, while the compile probes traced large stalls to a changing positional-encoding buffer and mutable state captured by diagnostic hooks.

Pre-materialising the positional buffer and keeping the hook bodies outside Dynamo tracing removed guard-failure recompiles in the tested runs. Each of the five Dynamo frames compiled once. That gave me a much clearer basis for interpreting training timings: a slow diagnostic step could reflect the work of collecting metrics, rather than silently compiling the forward graph again. The linked Debugging torch.compile & stories of recompilation writeup captures the detailed evidence.

The 123.7M-parameter FineWeb baseline reached the Hugging Face upload step, but the recorded attempt failed with 401 Unauthorized, and its artifact directory lacked metrics.jsonl. This page therefore does not establish a successful model publication, a complete reproducible artifact, or a generalisation benchmark result. The GPU speedups estimated earlier are also not validated by the results recorded here.

My main takeaway is that the harness shapes what an experiment appears to say. Before interpreting a throughput difference as a model or hardware improvement, I needed to understand what the data pipeline, diagnostics and compiler were doing. That debugging work is the lasting result of this stage.