A continued-pretraining loop needs two small pieces of logic: a schedule that re-warms and re-decays, and a batch sampler that mixes in old data at a fixed rate. Both are framework-independent.
import math, random
def lr_at(step, total, peak=3e-4, floor=3e-5, warmup_frac=0.01):
"""Re-warm linearly, then re-decay with a cosine back to the floor."""
warm = int(total * warmup_frac)
if step < warm:
return peak * (step + 1) / warm
t = (step - warm) / max(1, total - warm)
return floor + 0.5 * (peak - floor) * (1 + math.cos(math.pi * t))
def batch_sources(batch_size, replay_frac, rng):
"""Each sequence comes from the old corpus with probability replay_frac."""
return ["old" if rng.random() < replay_frac else "new" for _ in range(batch_size)]
rng = random.Random(0)
total = 10_000
for step in [0, 50, 99, 100, 2_500, 5_000, 9_999]:
print(f"step {step:>5}: lr {lr_at(step, total):.2e}")
counts = {"old": 0, "new": 0}
for _ in range(1_000):
for s in batch_sources(32, replay_frac=0.05, rng=rng):
counts[s] += 1
print(counts, f"replay share {counts['old'] / sum(counts.values()):.3f}")
Output:
step 0: lr 3.00e-06
step 50: lr 1.53e-04
step 99: lr 3.00e-04
step 100: lr 3.00e-04
step 2500: lr 2.63e-04
step 5000: lr 1.67e-04
step 9999: lr 3.00e-05
{'old': 1640, 'new': 30360} replay share 0.051
The learning rate climbs to its peak over the first 1% of steps, then follows a cosine back to the floor. Sampling per sequence lands at 5.1% replay against a 5% target. Ibrahim et al. compare runs at equal total tokens, so replayed tokens replace new ones rather than being added.
Try it: Set warmup_frac to 0 and the peak to the floor value. That is the no-re-warming baseline: forgetting falls, and so does adaptation to the new corpus.