Best practices & LR schedule visualiser

Guidelines distilled from the scaling-law literature and from how JBit behaves, paired with an interactive learning-rate curve designer.

Learning-rate schedule visualiser (interactive curve)

Pick a preset or tweak peak LR, floor LR, warm-up, and total steps. Hover or drag across the canvas to inspect exact step values and copy the C++20 builder snippet.

Schedule Presets

Engineering & scaling-law guidelines

Category Filter
Showing 37 guidelines

Data & tokenizer

Train the tokenizer on the data you will train on

A tokenizer trained on foreign text wastes context on long token sequences. Check the average tokens per word on a sample: well-fitted English BPE is roughly 1.3–1.5.

Size the vocabulary with the model

A larger vocabulary shortens sequences but adds d × V parameters twice (embedding and head). For small models (a few million parameters) use 4K–16K; recommendModel() proposes a size from your data and model scale.

Keep the chat special tokens

Chat training uses one special token per marker (<|im_start|>, role tokens, <|im_end|>). A tokenizer without them falls back to a text template that works but is less clean.

Split documents with an explicit separator

Use one separator (e.g. <|endoftext|>) between documents so packing does not blend unrelated text and attention segments stay isolated.

Hold out validation data

Keep a few percent of the corpus outside training and evaluate it regularly: loss on training data alone tells you nothing about generalisation.

Model shape

Use pre-LayerNorm for deeper models

setPreLayerNorm(true) / .preLayerNorm() trains stably at depth and with higher learning rates. Post-LN (the original layout) is the default for compatibility; it needs more careful warm-up.

Keep d_model divisible by heads, head size 64 or 128

Head dimension of 64–128 is the usual sweet spot; also friendlier to GPU kernels.

Feed-forward &approx; 4 &times; d_model

The standard ratio; the advisor uses it unless you set a multiplier.

Match model size to data, not to ambition

Roughly 20 effective training tokens per non-embedding parameter is a good target; repeating data more than ~4 epochs gives sharply diminishing returns. Use printTrainingAdvice for a data-driven suggestion, then validate with a short pilot.

Choose the context window deliberately

Attention cost grows with the square of the window (without flash attention). Train on the window you will serve; extending later is possible (extendContextWindow, RoPE scaling / YaRN) but needs fine-tuning.

Optimisation

AdamW + warm-up + cosine decay is the safe default

ADAM_W, warm-up of about 1–5% of steps, cosine to roughly 10% of the peak. Use WARMUP_STABLE_DECAY when you do not know the final length in advance.

Clip gradients globally

gradientClipping(1.0f) clips the norm over the whole model (also across GPUs), which protects against rare loss spikes.

Average, do not sum, the loss gradient

setLossGradientMean(true) makes the update independent of the number of tokens in the batch, so the learning rate transfers between batch sizes.

Learning rate scales down with model size

Small models (<50M) tolerate 1e-3 to 3e-3; hundreds of millions need ~3e-4 to 6e-4; billions less. Fine-tuning uses 10–30× lower than pre-training.

Use gradient accumulation instead of tiny batches

setEffectiveBatchSize(64, 8): the memory of 8, the optimisation of 64. Language models usually want effective batches of tens to hundreds of sequences.

Weight decay on weights only

weightDecay(0.1f) with AdamW is typical for transformers; do not apply decay to biases / norms (JBit's AdamW applies it as decoupled decay).

Training runs

Always pass a checkpoint file to smart* functions

smartPreTraining(…, "run.ckpt", 500) stores weights, optimizer state, global step and corpus position: a crashed run restarts with the same command.

Set the maximum step before the first step

The LR schedule is derived from setMaxGlobalStep(). Interrupting with a small limit and resuming with a larger one changes the schedule (the data order stays identical).

Pilot first

Train a 1% slice for a few hundred steps: the loss must fall smoothly, and a deliberately tiny dataset should be memorised (overfit test). If not, something is wrong with data or settings — fix that before spending hours.

Watch loss, gradient norm, learning rate and throughput

The progress monitor prints them; a loss that is NaN or jumps up by orders of magnitude means lower the learning rate, check clipping, or inspect the data.

Save the tokenizer next to the weights

A model is useless without the exact tokenizer it was trained with. Keep tokenizer.json with every checkpoint.

Make runs reproducible

Same data order is guaranteed by the corpus cursor; dropout masks and GPU reduction order can still differ slightly between CPU and GPU or between GPU counts.

Fine-tuning & chat

Pre-train first, then chat-tune

Chat tuning teaches format and behaviour, not language. Starting from a model that has never seen text rarely works.

Train on assistant tokens only

This is the default of ChatOptions (context is masked). Enable trainOnUser only for deliberate experiments.

Use the same template at inference

chatInference and training share one template; when serving through JBitServer rebuild a ChatConversation from the request messages instead of concatenating strings.

Mix in general data

Fine-tuning only on a narrow set makes the model forget; mix some pre-training text or diverse conversations and use a low learning rate.

Long conversations are split, not truncated

The default SPLIT keeps every assistant turn trained exactly once with the system prompt repeated; TRUNCATE drops everything after the first window.

Encoder-decoder: no packing

Cross-attention cannot isolate packed samples; use gradient accumulation for throughput instead.

GPU & performance

Enable CUDA per model at run time

.cudaIfAvailable() degrades gracefully to the CPU. Build with -DJACOBIT_CUDA_CUBLAS=ON to use cuBLAS GEMMs.

Use flash attention for windows &ge; 512

O(L) attention memory instead of O(L²) per head; allows larger windows or micro-batches.

Multi-GPU: replicate for speed, layer-split for capacity

Data-parallel replication (multiGpuAuto) speeds training when the model fits on one card. LAYER_SPLIT lets a bigger model fit but runs stages sequentially; HYBRID combines both. Gradient reduction is staged through host memory, so benefits are largest for big windows.

Fit memory with micro-batch first

If you run out of memory, lower the micro-batch (keep the effective batch), then enable flash attention, then reduce the window.

Reduce build time with module selection

-DJACOBIT_MODELS=DECODER_ONLY compiles only what you use.

Test without a GPU

The CUDA emulator (make -C tests/cuda_emulation verify) runs the real .cu sources on the CPU to check parity with the CPU path. It validates logic, not speed or real-hardware behaviour.

Code & project hygiene

Prefer builders for configuration, models for control

Builders are concise and validate order; for experiments that change settings between phases keep the model reference and call setters.

Check return values of I/O and log failures

Audio encoders call ffmpeg: make sure it is on the PATH; a failed encode is reported on stderr.

One model object is not thread-safe

Serve with serializeRequests = true (default) or give each worker its own model copy.

Run behind a reverse proxy in production

JBitServer has no TLS and uses one thread per connection: bind to 127.0.0.1, put nginx / caddy in front, set an apiKey.

Version everything that defines a run

Source revision, tokenizer file, corpus snapshot id, hyper-parameters and the checkpoint: you need all of them to reproduce or resume.