Frontier: training with little communication
Networks between data centers or across the internet are orders of magnitude slower than NVLink. This lesson surveys research on training without synchronization at every step: Local SGD, DiLoCo and its streaming version, gradient compression with error feedback, DeMo and early decentralized LLM training. We implement methods on small problems and the course GPT, comparing token and communication budgets explicitly.
After this lesson you can
- Implement Local SGD and DiLoCo and compare loss versus communicated bytes with data parallelism.
- Explain the role of the outer Nesterov-momentum optimizer on the pseudo-gradient.
- Demonstrate why error feedback recovers gradient-compression convergence.
- Estimate required bandwidth for each scheme from model, step and synchronization frequency.
- Read decentralized-training results and open questions critically.
Before you start
What if the network cannot keep up?
Synchronous data parallelism combines gradients at every step. When GPUs are in different centers, frequent synchronization can occupy a large fraction of time. Reduced-communication research changes when or what is transmitted. Comparison must fix processed tokens, total work, and byte-accounting rules: the same number of local steps with more replicas consumes more data.
Local SGD
In Local SGD, workers start from the same , perform updates with their own minibatches, and average parameters. If and all use SGD without momentum or scale differences, the average is
For equally sized minibatches and mean loss, this is the same step as SGD on their union of size . If sizes differ, weight by example count. This equivalence does not automatically extend to AdamW: averaging local adaptive updates is generally not equivalent to applying AdamW to the mean gradient.
With , later gradients are evaluated at different weights and replicas can drift apart. Data heterogeneity, rate, and step count change drift; reduced communication is not free. Stich’s analyses require specific assumptions about function and noise. A convergence result in that framework does not guarantee the same quality for every transformer or data partition.
Imagine two centers with texts from different domains. Both start the first step at the same weight, but each moves toward a local objective. At the second step they already compute gradients at different points. Even if their mean gradient at the first point matched the combined-data gradient, the average of their two trajectories need not match two steps of the global model. Reducing reunites them earlier; increasing it allows longer network-free work and potentially more divergence.
A fair comparison must state whether examples repeat, how many samples each replica processes, and whether aggregate compute cost includes all GPUs. At equal tokens, a method may use less communication yet need more operations per token; at equal bytes, it may process different data quantities. The curves answer different questions. Validation loss must be measured on the same data with the same protocol for each method.
DiLoCo and an outer optimizer
DiLoCo maintains a global model and one replica per worker. Each replica runs local AdamW for steps and returns pseudo-gradient . Those displacements are averaged and an outer optimizer is used; outer SGD with rate one and no momentum makes the new simply the mean of local models. Sign matters: points opposite the local displacement and is subtracted in the outer step.
Under one common Nesterov convention, and . Initialization and momentum conventions can vary across libraries. This momentum summarizes displacements from prior rounds; it is not the same state as inner AdamW moments. Replicas receive global parameters on synchronization but retain individual inner states: save them to resume the same algorithm.
The DiLoCo paper studies and an outer Nesterov optimizer in its experiments. One comparison uses eight workers and counts 500 times fewer communications than DP by frequency, under its table’s conditions and budgets. That frequency ratio does not automatically mean 500 times fewer bytes if types, metadata, or collectives change. This lesson’s GPT test uses two small replicas and does not reproduce those results.
The outer step introduces its own hyperparameters. Outer rate one without momentum averages, but a different rate interpolates or extrapolates the mean displacement; Nesterov also uses momentum history. An aggressive rate may advance faster on one small problem and be unstable on another. To isolate its effect, hold data, inner steps, and local optimizer fixed while changing only outer rate. The lab ablation retains the same initialization and batch sequence for each combination.
Saving only global weights does not reproduce a continuation with local AdamW: each worker’s moments formed from its own data and trajectory. Also save outer momentum, round number, and data positions. If a worker leaves and another joins, the initialization policy for those states becomes part of the algorithm; copying weights alone cannot establish that exactly the same trajectory resumed.
For an ideal ring with ranks and a tensor of elements of bytes, each rank sends bytes per all-reduce. Divide by time between synchronizations to obtain average bandwidth, not instantaneous peak or actual collective time. For example, with two ranks, 1B BF16 parameters, and two steps per second, DP sends 14.4 decimal TB per rank in one hour; synchronizing a BF16 tensor every 500 steps reduces that ideal count to 28.8 GB. This assumes one full collective per step or round, without metadata or latency.
Transmit by fragments
Streaming DiLoCo synchronizes fragments at staggered times instead of waiting to transmit the whole model at once. The paper studies sequential and striped fragments, overlap, and low-precision pseudo-gradients. If each fragment completes a round every steps, fragmenting distributes volume over time; by itself it does not reduce total tensor bytes. Quantization can reduce them but adds scales, metadata, and error. Overlap requires network and compute resources simultaneously available, and parameters used during overlap may have different ages.
Compress and remember
Gradient compression reduces transmitted information. Top-k keeps coordinates of largest magnitude and must also send indices; signSGD sends signs under a specific update rule; PowerSGD approximates matrices with low-rank factors. A small tensor or expensive index format may not save bytes over a dense tensor. Sparse-sum efficiency and accumulation precision also matter.
With error feedback, define , , and , with . Summing over steps,
The identity is exact for any compressor: unsent information remains in the residual. If bounded, the average difference between sums vanishes as grows. This alone does not prove arbitrary optimization converges: gradients depend on different trajectories, a variable rate requires adjusted accounting, and the residual may be unbounded. Karimireddy et al. prove convergence results under their assumptions; it is incorrect to promise that all compression with memory works for every problem.
For example, if a small coordinate stays outside top-k for several steps, its residual accumulates and may eventually enter the selection. Without memory that contribution is discarded every step. Compensation can cause a larger later update, so the residual trajectory is neither identical to the dense trajectory nor necessarily smoother. The figure’s experiment lets you change rate to observe this tradeoff on one quadratic.
The communication budget depends on aggregation. With a logical coordinator each worker sends its compressed representation and receives the global result; in a dense ring one counts fragments each rank sends in reduce-scatter and all-gather. These figures cannot be directly mixed without conversion to the same unit. Examples print the convention used and exclude protocol, scale exchange, and retransmissions.
Momentum and changing participants
DeMo maintains local momentum, transforms it by blocks, selects coefficients, and communicates a sparse representation. Unsent momentum is retained by subtracting the reconstructed part: it acts as error memory. The discrete cosine transform is one studied basis; it does not mean only high frequencies must be sent, since coefficients are selected by magnitude. Index, projection, and all-gather costs still count.
Decentralized training adds speed heterogeneity, failures, and participants joining or leaving. INTELLECT-1 reports a 10B model trained on 1T tokens with distributed contributions and describes dynamic groups, quantized communication, and recovery. Its report is evidence for its configuration, not a quality or security guarantee for arbitrary participants. A real implementation must define contribution validation, group changes, data protection, and state preservation on resume.
Decentralized can describe many topologies: multiple centers under common administration, independent participants, or groups coordinated by a central service. Each has different failure and trust concerns. A slow node can delay a synchronous round; excluding it reduces waiting but changes which data and states contribute. An asynchronous update can use stale weights, so record their age and compare the same token budget when evaluating the effect.
Lab: classification and bytes
Four workers traverse heterogeneous synthetic-data shards, with the same 1920 examples per method. The DP reference and Local SGD use SGD; DiLoCo uses inner AdamW and outer Nesterov, so curves also reflect the optimizer. Top-k uses two of six coordinates with 4-byte indices and 4-byte values; sign uses one bit per coordinate rounded to bytes. A logical coordinator is counted: each worker uploads and the update is densely broadcast, without protocols or latency. NumPy computes in float64 while bytes assume FP32. No curve measures a real network.
import numpy as np
import matplotlib.pyplot as plt
K,D,B,STEPS,H=4,6,8,60,5
rng=np.random.default_rng(41)
X=rng.normal(size=(K,128,D)) + np.linspace(-0.7,0.7,K)[:,None,None]
truth=np.array([1.,-0.8,0.5,-0.3,0.2,-0.4])
labels=(np.einsum('knd,d->kn',X,truth)>0).astype(float)
def sigmoid(x): return 1/(1+np.exp(-np.clip(x,-40,40)))
def gradient(w,rank,t):
idx=(np.arange(B)+t*B)%128; x=X[rank,idx]; y=labels[rank,idx]
return x.T@(sigmoid(x@w)-y)/B
def loss(w):
z=np.einsum('knd,d->kn',X,w)
return float(np.mean(np.logaddexp(0,z)-labels*z))
def topk(v,k):
indices=np.argpartition(np.abs(v),-k)[-k:]; out=np.zeros_like(v);out[indices]=v[indices];return out
def run(mode):
w=np.zeros(D); records=[(0,loss(w))]; sent=0; memory=np.zeros((K,D)); inner_m=np.zeros((K,D));inner_v=np.zeros((K,D)); velocity=np.zeros(D); local=np.tile(w,(K,1))
for t in range(STEPS):
if mode in ('dp','topk','topk-ef','sign'):
grads=np.stack([gradient(w,r,t) for r in range(K)])
if mode in ('topk','topk-ef'):
payload=grads+(memory if mode=='topk-ef' else 0)
packed=np.stack([topk(x,2) for x in payload])
if mode=='topk-ef': memory=payload-packed
g=packed.mean(axis=0); sent+=K*(2*(4+4)+D*4)
elif mode=='sign':
g=np.sign(grads).mean(axis=0);sent+=K*((D+7)//8+D*4)
else: g=grads.mean(axis=0);sent+=2*K*D*4
w-=0.08*g
else:
for r in range(K):
g=gradient(local[r],r,t)
if mode=='local': local[r]-=0.08*g
else:
inner_m[r]=.9*inner_m[r]+.1*g;inner_v[r]=.999*inner_v[r]+.001*g*g
mh=inner_m[r]/(1-.9**(t+1));vh=inner_v[r]/(1-.999**(t+1))
local[r]*=(1-.03*.01);local[r]-=.03*mh/(np.sqrt(vh)+1e-8)
if (t+1)%H==0:
average=local.mean(axis=0)
if mode=='local': w=average
else:
pseudo=w-average;velocity=.9*velocity+pseudo;w-=.7*(pseudo+.9*velocity)
local[:]=w;sent+=2*K*D*4
if (t+1)%H==0: records.append((sent,loss(w)))
return np.array(records)
fig,ax=plt.subplots()
for mode in ('dp','local','diloco','topk','topk-ef','sign'):
curve=run(mode);ax.plot(curve[:,0],curve[:,1],marker='.',label=mode)
print(mode,'pérdida',round(curve[-1,1],5),'bytes modelo centralizado',int(curve[-1,0]),'ejemplos',K*B*STEPS)
ax.set(xlabel='Bytes totales modelados (subida y bajada)',ylabel='Pérdida logística',title='Mismos ejemplos; métodos y bytes distintos')
ax.legend();fig.tight_layout();plt.show()
Lab: GPT and token budget
The GPT classes from p06-l03 are used with two blocks and small dimensions on synthetic sequences of consecutive tokens. Two replicas are emulated sequentially on the CUDA GPU; each method processes 384 tokens with the same data at each step. DP uses AdamW on the mean gradient; DiLoCo retains per-replica AdamW and applies outer Nesterov. and two outer rates are tested. Evaluation uses the first 16 positions of the same synthetic pattern: this checks flow, not natural-language quality or scaling. FP32 bytes correspond to an ideal ring per rank, not an executed network.
"""GPT-2 desde cero con carga de pesos Hugging Face y controles reproducibles."""
import math
import os
from pathlib import Path
import torch
from torch import nn
import torch.nn.functional as F
torch.set_num_threads(4)
class GPTLinear(nn.Linear):
def forward(self, x):
weight = self.weight.t().contiguous()
return torch.addmm(self.bias, x.reshape(-1, x.size(-1)), weight).view(*x.shape[:-1], self.out_features)
class CausalSelfAttention(nn.Module):
def __init__(self, d, heads, dropout):
super().__init__()
assert d % heads == 0
self.heads, self.d = heads, d
self.p = dropout
self.resid_drop = nn.Dropout(dropout)
self.c_attn = GPTLinear(d, 3*d)
self.c_proj = GPTLinear(d, d)
def forward(self, x):
b, t, d = x.shape
q, k, v = self.c_attn(x).split(d, dim=-1)
def split(z):
return z.view(b, t, self.heads, d//self.heads).transpose(1, 2)
out = F.scaled_dot_product_attention(split(q), split(k), split(v),
is_causal=True, dropout_p=self.p if self.training else 0.0)
out = out.transpose(1, 2).contiguous().view(b, t, d)
return self.resid_drop(self.c_proj(out))
class MLP(nn.Module):
def __init__(self, d, dropout):
super().__init__()
self.c_fc = GPTLinear(d, 4*d)
self.c_proj = GPTLinear(4*d, d)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
x = self.c_fc(x)
x = 0.5*x*(1.0 + torch.tanh(math.sqrt(2.0/math.pi)*(x + 0.044715*torch.pow(x, 3.0))))
return self.dropout(self.c_proj(x))
class Block(nn.Module):
def __init__(self, d, heads, dropout):
super().__init__()
self.ln_1 = nn.LayerNorm(d, eps=1e-5)
self.attn = CausalSelfAttention(d, heads, dropout)
self.ln_2 = nn.LayerNorm(d, eps=1e-5)
self.mlp = MLP(d, dropout)
def forward(self, x):
x = x + self.attn(self.ln_1(x))
return x + self.mlp(self.ln_2(x))
class Transformer(nn.Module):
def __init__(self, vocab, context, layers, heads, d, dropout):
super().__init__()
self.wte = nn.Embedding(vocab, d)
self.wpe = nn.Embedding(context, d)
self.drop = nn.Dropout(dropout)
self.h = nn.ModuleList([Block(d, heads, dropout) for _ in range(layers)])
self.ln_f = nn.LayerNorm(d, eps=1e-5)
class GPT(nn.Module):
def __init__(self, vocab=50257, context=1024, layers=12, heads=12, d=768, scaled=True, dropout=0.1):
super().__init__()
self.context, self.layers, self.d = context, layers, d
self.transformer = Transformer(vocab, context, layers, heads, d, dropout)
self.transformer.apply(self._init)
self.lm_head = nn.Linear(d, vocab, bias=False)
self.lm_head.weight = self.transformer.wte.weight
if scaled:
for block in self.transformer.h:
nn.init.normal_(block.attn.c_proj.weight, std=0.02/math.sqrt(2*layers))
nn.init.normal_(block.mlp.c_proj.weight, std=0.02/math.sqrt(2*layers))
@staticmethod
def _init(module):
if isinstance(module, (nn.Linear, nn.Embedding)):
nn.init.normal_(module.weight, mean=0, std=0.02)
if isinstance(module, nn.Linear) and module.bias is not None:
nn.init.zeros_(module.bias)
def forward(self, ids, return_residual=False):
b, t = ids.shape
if t > self.context:
raise ValueError('El contexto supera el límite del modelo')
z = self.transformer.drop(self.transformer.wte(ids) + self.transformer.wpe(torch.arange(t, device=ids.device)))
residuals = [z]
for block in self.transformer.h:
z = block(z)
residuals.append(z)
logits = self.lm_head(self.transformer.ln_f(z))
return (logits, residuals) if return_residual else logits
import copy
assert torch.cuda.is_available(), 'Se necesita una GPU CUDA para este laboratorio'
device=torch.device('cuda')
torch.set_num_threads(1)
K,B,T,STEPS=2,2,8,12
torch.manual_seed(17)
base=GPT(vocab=16,context=T,layers=2,heads=2,d=16,dropout=0.0).to(device)
initial=copy.deepcopy(base.state_dict())
params=sum(p.numel() for p in base.parameters())
def batch(worker,step):
starts=torch.tensor([(worker*8+(step*2+j)%8) for j in range(B)],device=device)
seq=(starts[:,None]+torch.arange(T+1,device=device)[None,:])%16
return seq[:,:-1],seq[:,1:]
def objective(model,x,y):
return F.cross_entropy(model(x).reshape(-1,16),y.reshape(-1))
@torch.no_grad()
def evaluate(model):
starts=torch.arange(16,device=device)
seq=(starts[:,None]+torch.arange(T+1,device=device)[None,:])%16
return float(objective(model,seq[:,:-1],seq[:,1:]))
def new_model():
model=GPT(vocab=16,context=T,layers=2,heads=2,d=16,dropout=0.0).to(device)
model.load_state_dict(initial);return model
def baseline():
model=new_model(); opt=torch.optim.AdamW(model.parameters(),lr=0.002,weight_decay=0.01)
for s in range(STEPS):
opt.zero_grad(set_to_none=True)
for worker in range(K):
x,y=batch(worker,s); (objective(model,x,y)/K).backward()
opt.step()
return evaluate(model)
def diloco(H,outer_lr):
global_model=new_model(); workers=[new_model() for _ in range(K)]
inner=[torch.optim.AdamW(w.parameters(),lr=0.002,weight_decay=0.01) for w in workers]
outer=torch.optim.SGD(global_model.parameters(),lr=outer_lr,momentum=0.9,nesterov=True)
for start in range(0,STEPS,H):
for w in workers: w.load_state_dict(global_model.state_dict())
for local in range(H):
for rank,w in enumerate(workers):
inner[rank].zero_grad(set_to_none=True)
x,y=batch(rank,start+local); objective(w,x,y).backward(); inner[rank].step()
outer.zero_grad(set_to_none=True)
with torch.no_grad():
for params_group in zip(global_model.parameters(),*(w.parameters() for w in workers)):
global_param,*local_params=params_group
global_param.grad=sum(global_param.detach()-p.detach() for p in local_params)/K
outer.step()
return evaluate(global_model)
if __name__=='__main__':
print('GPU:',torch.cuda.get_device_name(),'parámetros:',params,'tokens por método:',K*B*T*STEPS)
print('Pérdida inicial:',round(evaluate(base),5))
print('DP AdamW pérdida:',round(baseline(),5),'bytes/rango estimados:',STEPS*2*(K-1)//K*params*4)
for H in (1,3,6):
for eta in (0.5,1.0):
loss=diloco(H,eta);vol=(STEPS//H)*2*(K-1)//K*params*4
print(f'DiLoCo H={H}, lr externo={eta}: pérdida={loss:.5f}, bytes/rango estimados={vol}')
print('Bytes enviados ideales por rango para ring all-reduce FP32; sin red real.')
npm run lab and open the connection link.Exercises
Step 1 of 2. What local displacement does worker r produce?
Step 1 of 2. If uₜ=gₜ+eₜ₋₁ and eₜ=uₜ−qₜ, what is qₜ?
import numpy as np
def topk_error_feedback(grad,memory,k):
...