Mixed precision I: FP16, BF16, master weights and loss scaling
Training in 16 bits can double Tensor Core throughput and halve activation memory, but doing so naively can diverge or stall. We study three failures, gradient underflow, activation overflow, and updates absorbed by rounding, and a recipe addressing them: FP32 master weights and accumulation, dynamic loss scaling, and a per-operation precision policy. The lesson concludes with pure BF16, stochastic rounding, and Kahan summation in the optimizer.
After this lesson you can
- Explain using the floating-point number line why FP16 needs loss scaling and BF16 does not.
- Implement a dynamic loss scaler from scratch with growth, backoff, and skipped steps.
- Demonstrate BF16 update stagnation under round-to-nearest and show that stochastic rounding is unbiased.
- Decide which operations should remain in FP32 and verify the autocast policy.
- Measure time, memory and loss curves on the RTX 4060 for FP32, scaled FP16, BF16 autocast and pure BF16.
Before you start
Fewer bits change two distinct things
Mixed precision assigns different formats to operations and states: it is not the same as indiscriminately converting the entire network to 16 bits. The goal is to reduce traffic and use fast matrix units without losing small updates or overflowing sensitive operations. Performance depends on the GPU, shapes, and implementation; measure it over the full step.
Recall the floating-point formats. FP16 has one sign bit, five exponent bits, and ten fraction bits; BF16 has one, eight, and seven. Including the implicit bit, their normal precisions are 11 and 8 bits, respectively. FP16 has maximum 65504, smallest positive normal and smallest positive subnormal . BF16 shares FP32’s exponent field: its smallest normal is , although its precision is much lower. Subnormal handling depends on the device and operation.
FP32 has eight exponent bits and 23 fraction bits. TF32 is a Tensor Core compute path with FP32 range and ten fraction bits for operands, not a 16-bit storage tensor. For eligible FP32 products it can round inputs and accumulate in FP32; enabling it does not guarantee every operation uses it. The PyTorch CUDA documentation explains its controls and version and operation dependencies. Therefore, when comparing with FP32, also record the matmul policy.
Three failures have different mechanisms. A small gradient can round to zero, a large activation can overflow, and an update can be too small to change the represented weight. BF16 reduces the range problem relative to FP16, but does not eliminate precision errors or guarantee stable training. Micikevicius et al. study master weights, scaling and FP32 product accumulation for FP16 training; Kalamkar et al. study BF16.
Range and precision are not interchangeable. Range describes the extreme magnitudes a format can represent; precision determines the separation between neighboring values within a region. In FP16, is the smallest positive subnormal, but that does not mean every smaller magnitude necessarily becomes zero: the result depends on rounding and whether the operation preserves subnormals. Moving into the normal range requires reaching , a stronger requirement than simply producing a nonzero subnormal.
Around one, the BF16 neighbors are and : spacing changes across the power of two. A positive update strictly smaller than rounds back to one under round-to-nearest; a negative one with magnitude strictly smaller than also returns to one. At midpoints, check the tie-breaking rule. This asymmetry explains why an informal “half ulp” rule needs to specify the neighbor and the direction of the step.
This scalar control forces the three effects separately in NumPy. It does not show that all gradients or activations in a real model have those magnitudes.
import numpy as np
with np.errstate(over='ignore', under='ignore'):
small = np.float16(1e-8)
large = np.float16(1e5)
unchanged = np.float16(np.float16(1) + np.float16(1e-4))
print('gradiente pequeño:', small)
print('activación grande:', large)
print('peso tras actualizar:', unchanged)
assert small == 0 and np.isinf(large) and unchanged == np.float16(1)Scaled loss and skipped steps
Multiplying by a positive scale multiplies all its gradients by by the chain rule. Loss scaling thus shifts small gradients into FP16’s representable range. Before the optimizer, divide by and check that they are finite. If there is inf or NaN, skip the step and reduce the scale. Values already lost to rounding cannot be recovered by division; scaling prevents certain losses during backward, but does not reconstruct information.
The dynamic scaler increases after a streak of finite steps and backs off when it detects a failure. This figure simulates that rule with explicit gradients: 1 at each step except a spike of 100, with overflow if the product exceeds 65504. This is neither training nor a history of real gradients.
Order matters: unscale before clipping the norm. If scaled gradients are clipped at threshold , the effective threshold on the original gradient is . Finiteness must also be checked after accumulating every microbatch contributing to the step, using a consistent scale throughout accumulation.
With multiple microbatches, if every loss uses the same scale , the accumulated sum is and one division at the end recovers the sum of represented gradients. If changes between microbatches, dividing the total by a single scale no longer reconstructs that sum. Similarly, norm clipping should use the unscaled gradient and threshold chosen for the update, not a version whose magnitude depends on the scaling policy.
Skipping a step also affects optimizer state. When a non-finite gradient is detected, advancing weights or moments with it would contaminate subsequent steps. The scaler must therefore tell training whether the optimizer actually ran; a schedule advanced per update may need the same information. Reducing the scale attempts to make the next backward finite, but does not fix division by zero or invalid data that already produced NaN in forward.
Consider . The gradient becomes , above the smallest FP16 normal; after conversion it is divided by 8192, with that conversion’s rounding error. By contrast, a gradient of magnitude 10 scaled by the same factor gives 81920, above the maximum finite 65504. One scale must serve the whole step: protecting the small tail without overflowing the large one is precisely the tradeoff the dynamic scaler attempts to adapt.
import numpy as np
class DynamicLossScaler:
def __init__(self, scale=128.0, interval=4, growth=2.0, backoff=0.5):
self.scale = scale
self.interval = interval
self.growth = growth
self.backoff = backoff
self.good = 0
def unscale(self, grads):
return [g/self.scale for g in grads]
def update(self, found_inf):
if found_inf:
self.scale *= self.backoff
self.good = 0
return False
self.good += 1
if self.good == self.interval:
self.scale *= self.growth
self.good = 0
return True
scaler = DynamicLossScaler(interval=2)
print('desescalado:', scaler.unscale([np.array([128., 256.])])[0])
for bad in [False, False, True, False, False]:
applied = scaler.update(bad)
print('paso aplicado:', applied, 'escala siguiente:', scaler.scale)
assert 8192*1e-8 >= 2**-14 and 4096*1e-8 < 2**-14
print('factor mínimo potencia de dos:', 8192)The simulation detects failure after it occurs; PyTorch implements its own policy and can reduce the scale below one. Excessive scaling can cause overflow in an intermediate operation before the final gradient is examined. Locate the operation rather than assuming the scaler cures every NaN.
The next figure uses a real gradient from the NumPy GPT in lesson 11: a checkpoint downloaded after 100 steps, evaluated with input First and target irst . Each Q projection tensor has 4096 components. Scaling is applied after calculating the gradient in NumPy, then it is converted to count zeros and infinities; BF16 is emulated by rounding from FP32 to nearest, ties to even. It does not simulate FP16 backward operations or predict their stability, and one example does not characterize a training distribution. The reference file has SHA-256 6b18675dc6f98c9e412920ffa5accaab7da039d6ac88134a7911a52189414d8f; its loss for this example is approximately 2.40672.
The horizontal displacement on a logarithmic scale follows directly from for . Increasing the exponent can rescue small magnitudes but also push others beyond the finite range. Original exact zeros are not counted as underflows, and converting a value near a boundary depends on rounding, not just the interval it falls into. In real backward computation, each intermediate operation can also round before the final gradient observed here exists.
To repeat the calculation with your own model, download gpt-numpy.npz from lesson 11 and save that lesson’s first code cell as gpt_numpy.py. Locally, place both files alongside the run or set ORYON_GPT_NUMPY and ORYON_GPT_CODE to their paths. Your checkpoint and counts may differ; it must contain the sample’s characters.
import os
from pathlib import Path
import numpy as np
scope = {}
code_path = Path(os.environ.get('ORYON_GPT_CODE', 'gpt_numpy.py'))
exec(code_path.read_text(encoding='utf-8'), scope)
weights = Path(os.environ.get('ORYON_GPT_NUMPY', 'gpt-numpy.npz'))
model, chars = scope['load_npz'](weights.read_bytes())
stoi = {c: i for i, c in enumerate(chars)}
assert all(c in stoi for c in 'First '), 'La muestra necesita estos caracteres en el vocabulario.'
ids = np.array([[stoi[c] for c in 'First']])
targets = np.array([[stoi[c] for c in 'irst ']])
loss, grads = model.loss_and_grads(ids, targets)
edges = [-np.inf, -24, -16, -12, -8, -4, 0, 8, 16, np.inf]
print('pérdida:', loss)
for layer in range(model.config['layers']):
grad = grads[f'block.{layer}.q.w'].ravel()
for exponent in (0, 30):
scaled = grad * 2**exponent
with np.errstate(over='ignore', under='ignore'):
fp16 = scaled.astype(np.float16)
nonzero = np.abs(scaled[scaled != 0])
bins = np.histogram(np.log2(nonzero), bins=edges)[0]
print(layer, exponent, 'intervalos:', bins, 'ceros FP16:',
np.count_nonzero((scaled != 0) & (fp16 == 0)),
'infinitos FP16:', np.count_nonzero(np.isinf(fp16)))npm run lab and open the connection link.Weights, accumulation, and small updates
The FP32 master copy preserves weight state for the optimizer. The network may use a lower-precision copy in selected operations; the optimizer accumulates updates on the master copy. Standard PyTorch autocast keeps original parameters in FP32 and creates conversions for eligible operations: it is not necessarily an implementation with two permanent copies. Gradients of FP32 parameters and Adam states usually remain in FP32. Memory accounting depends on the actual code.
In a region of a format where has representable neighbors and , round-to-nearest returns if falls strictly between the midpoints and . Left and right spacing can differ at a power of two. For a positive step the condition is ; at the midpoint the tie-breaking rule matters. Repeatedly applying that same update to the rounded weight can freeze it.
A master copy retains steps that would not individually change the working copy: the optimizer accumulates on the FP32 value and the network sees a changed rounded copy once it crosses a midpoint. This does not guarantee an identical trajectory to FP32, because activations and gradients may have been rounded earlier. Moreover, keeping BF16 and FP32 copies simultaneously adds weight memory; potential activation or traffic savings must be calculated for the whole step, not assumed to halve every component.
For example, for one billion parameters, a BF16 working copy takes approximately 2 decimal GB, the FP32 master 4 GB, and two FP32 moments another 8 GB: 14 GB total for those four tensors. A scheme with FP32 weights and two FP32 moments takes 12 GB for those three tensors. Both exclude gradients, activations, temporaries, and metadata; some libraries retain or create copies with different lifetimes. These numbers explain why counting only matmul precision can poorly predict peak memory.
Stochastic rounding chooses between two neighbors : it returns with probability and with the complementary probability. Then . This property is conditional on and finite neighbors, not a guarantee that an entire nonlinear trajectory is unbiased. Kahan compensated summation saves part of the rounding error for later steps; its precision and the compensator format are implementation decisions. Zamirai et al. study both remedies in BF16 training.
The two techniques preserve information differently. Stochastic rounding can move the weight by one neighbor even when the step itself is smaller; over time its local expectation respects the pre-rounding contribution. Kahan keeps a residual that modifies the next addition to compensate for part of the previous error. If that residual is also stored in few bits, compensation has losses of its own; if stored in FP32, count its four bytes per parameter and do not call the state exclusively BF16.
For one conversion with neighbors and and probability of choosing , variance is . Thus unbiasedness does not mean zero error in each conversion. Variation depends on where the value lies between neighbors and on local spacing; in a sequence of updates, future values depend on previous rounding. The conditional-expectation proof does not allow replacing an evaluation across multiple seeds with a single trajectory.
In one form of Kahan summation, if is the stored error and the new update, compute , round , and store . At the next step, subtract that estimated error before adding. This sign convention matches the code below; other presentations store the residual with the opposite sign and change the formula. Do not mix lines from the two conventions.
The next isolated test rounds the bits of a positive FP32 number to simulated BF16. It compares one thousand small additions, not a training curve. The compensator is stored in FP32, so this is not a pure BF16 implementation. The generator is seeded so you can repeat the stochastic trajectory.
import numpy as np
def bf16_nearest(x):
x = np.asarray(x, dtype=np.float32)
bits = x.view(np.uint32)
rounded = bits + np.uint32(0x7fff) + ((bits >> np.uint32(16)) & np.uint32(1))
return (rounded & np.uint32(0xffff0000)).view(np.float32)
def bf16_stochastic(x, rng):
x = np.asarray(x, dtype=np.float32)
bits = x.view(np.uint32)
noise = rng.integers(0, 65536, size=x.shape, dtype=np.uint32)
return ((bits + noise) & np.uint32(0xffff0000)).view(np.float32)
rng = np.random.default_rng(17)
nearest = np.float32(1)
stochastic = np.float32(1)
compensated = np.float32(1)
carry = np.float32(0)
delta = np.float32(-0.0001)
for _ in range(1000):
nearest = bf16_nearest(nearest + delta)
stochastic = bf16_stochastic(stochastic + delta, rng)
y = delta - carry
new = bf16_nearest(compensated + y)
carry = (new - compensated) - y
compensated = new
print('FP32 ideal:', 1 + 1000*float(delta))
print('BF16 cercano:', nearest)
print('BF16 estocástico, una semilla:', stochastic)
print('BF16 con compensador FP32:', compensated)The next lab trains a tiny MLP on reproducible synthetic data. It emulates formats when storing the results of each operation, with products and reductions computed in FP32 and rounded afterward: it does not emulate every Tensor Core detail or measure GPU performance. In pure modes stored weights are rounded at every step; in mixed mode the master copy remains FP32. SGD isolates rounding effects without attributing these results to AdamW or a transformer.
import numpy as np
data_rng = np.random.default_rng(123)
X = data_rng.normal(size=(32, 2)).astype(np.float32)
Y = (0.6*X[:, :1] - 0.3*X[:, 1:]).astype(np.float32)
init_rng = np.random.default_rng(45)
initial = [init_rng.normal(0, 0.2, (2, 8)).astype(np.float32),
init_rng.normal(0, 0.2, (8, 1)).astype(np.float32)]
def quant(x, mode, rng):
x = np.asarray(x, dtype=np.float32)
if mode == 'fp32':
return x
if mode in ('fp16', 'mixto', 'mixto-dinamico'):
return x.astype(np.float16).astype(np.float32)
return bf16_stochastic(x, rng) if mode == 'bf16-sr' else bf16_nearest(x)
def train(mode, steps=160):
rng = np.random.default_rng(7)
pure = mode not in ('fp32', 'mixto', 'mixto-dinamico')
weights = [quant(w.copy(), mode, rng) if pure else w.copy() for w in initial]
residual = [np.zeros_like(w) for w in weights]
history = []
scales = []
skipped = 0
scaler = DynamicLossScaler(scale=128., interval=16)
for step in range(steps):
q = lambda x: quant(x, mode, rng)
W1, W2 = [q(w) for w in weights]
H = q(np.tanh(q(q(X) @ W1)))
prediction = q(H @ W2)
error = q(prediction - q(Y))
loss = float(np.mean((prediction-Y)**2))
history.append(loss)
# Los dos modos mixtos desescalan antes del paso.
scale = scaler.scale if mode == 'mixto-dinamico' else (128 if mode == 'mixto' else 1)
scales.append(scale)
upstream = q(error * np.float32(2*scale/len(X)))
scaled_grad2 = q(H.T @ upstream)
scaled_grad1 = q(q(X).T @ q(q(upstream @ W2.T) * q(1-H*H)))
if mode == 'mixto-dinamico':
bad = not all(np.isfinite(g).all() for g in (scaled_grad1, scaled_grad2))
if not scaler.update(bad):
skipped += 1
continue
grad1, grad2 = scaled_grad1 / scale, scaled_grad2 / scale
for i, grad in enumerate((grad1, grad2)):
update = -np.float32(0.03)*grad
if mode == 'bf16-kahan':
y = update - residual[i]
new = q(weights[i] + y)
residual[i] = (new - weights[i]) - y
weights[i] = new
elif mode == 'bf16-kahan16':
y = q(q(update) - residual[i])
new = q(weights[i] + y)
residual[i] = q(q(new - weights[i]) - y)
weights[i] = new
elif pure:
weights[i] = q(weights[i] + update)
else:
weights[i] = weights[i] + update
assert np.isfinite(history).all()
return history, scales, skipped
histories = {mode: train(mode) for mode in ('fp32', 'fp16', 'mixto', 'mixto-dinamico', 'bf16', 'bf16-sr', 'bf16-kahan', 'bf16-kahan16')}
for mode, (loss, scales, skipped) in histories.items():
print(mode, 'pérdida en pasos 0, 40, 80, 120, 159:',
[round(loss[i], 6) for i in (0, 40, 80, 120, 159)])
if mode == 'mixto-dinamico':
print('escalas en los mismos pasos:', [scales[i] for i in (0, 40, 80, 120, 159)],
'pasos omitidos:', skipped)The results are from this run and this single seed. The bf16-kahan16 mode also rounds the compensator and each operation of that update to emulated BF16; nevertheless, this experiment’s matrix products and reductions accumulate in FP32. To evaluate quality differences, repeat with multiple seeds, separate validation data, and a real configuration; agreement or separation in this toy example does not prove a recipe generally dominates.
To locate the three failures within a network, consider this scalar MLP with two linear layers, , , . The values are not chosen as a sample of typical training: they are inputs constructed to expose each mechanism. When scaling the loss, the small gradient is rounded after multiplication by the scale and then unscaled; the result is an approximation, not exact recovery. In the second case, keeping the product in FP32 avoids infinity, but a later conversion to FP16 would overflow again.
import numpy as np
# x=10⁻⁴, w1=w2=1, y=0: dL/dw1 es aproximadamente 10⁻⁸.
x = np.float32(1e-4)
grad = x*x
plain = np.float16(grad)
scaled = np.float16(grad*8192).astype(np.float32)/8192
print('gradiente FP32, FP16, escalado y desescalado:', grad, plain, scaled)
assert plain == 0 and scaled > 0
# La activación oculta es 256*256: queda fuera del rango finito FP16.
with np.errstate(over='ignore'):
h16 = np.float16(np.float16(256)*np.float16(256))
h32 = np.float32(256)*np.float32(256)
print('activación FP16 y FP32:', h16, h32)
assert np.isinf(h16) and np.isfinite(h32)
# Una actualización sobre un parámetro almacenado en FP16 puede desaparecer.
w16 = np.float16(1)
w16_next = np.float16(w16 + np.float16(-1e-4))
w32_next = np.float32(1) + np.float32(-1e-4)
print('peso actualizado FP16 y maestro FP32:', w16_next, w32_next)
assert w16_next == w16 and w32_next != np.float32(1)Autocast does not mean “everything in 16 bits”
The per-operation autocast policy selects type by operation and device. In the PyTorch CUDA reference, matmul is among operations that may run in FP16; softmax, layer_norm, exp and sum are among those that may run in FP32. This applies to eligible operations, not every similarly named function: in-place forms, out arguments, explicit dtype, and unlisted operations need attention. Lists change with version and device.
Long reductions deserve particular attention because many small terms can be lost when accumulated into a large value. A matmul may receive 16-bit operands and accumulate internally at higher precision, but details depend on the backend and its options; inspecting only the returned tensor type does not prove what happened inside the kernel. Weight storage type, operation input type, internal accumulator type, and result type are four decisions worth recording separately.
Measure the course GPT
This lab continues the small checkpoint from lesson 12 in four modes. Save its “GPT PyTorch y cargadores” cell as gpt_pytorch.py, generate gpt-pytorch-small.pt with its parity cell, and save the lesson 11 text to corpus.txt using Path('corpus.txt').write_text(corpus, encoding='utf-8'). Environment variables allow other paths. Training and validation windows are separated before sampling. Each mode starts from the same checkpoint and receives the same batches; only one seed and a small number of steps are used. Figures are printed from your run, not prerecorded results.
Matching batches helps compare recipes by removing one source of variation, but it does not make all operations identical: autocast chooses types per operation and the example BF16 optimizer has rounded states. We also do not separate multiple seeds, lengths, or learning-rate settings here. Validation loss comes from a fixed batch of a small corpus; a difference can motivate a broader test, but is insufficient to conclude that a format preserves quality on another task or scale.
In pure BF16 the example optimizer stores weights and moments in BF16, performs update arithmetic in FP32, and stochastically rounds the new weight to BF16. Thus “pure” describes stored states, not every operation. The other modes keep parameters and AdamW states in FP32; autocast chooses operation types. Hooks show module input and output types, but do not necessarily reveal the internal precision of a fused kernel. Performance depends on the environment and concurrent load, and this small test does not characterize training at scale.
Timing includes batch construction and transfer and extraction of each loss to CPU, which synchronizes the GPU. Peak is process-allocated memory, not total capacity or memory traffic; warm-up operations do not update weights. If a non-finite loss occurs, that recipe stops and throughput counts tokens attempted up to that point.
import os, time
from pathlib import Path
import torch
from torch import nn
assert torch.cuda.is_available(), 'este experimento requiere CUDA'
scope = {}
exec(Path(os.environ.get('ORYON_GPT_TORCH_CODE', 'gpt_pytorch.py')).read_text(encoding='utf-8'), scope)
checkpoint = Path(os.environ.get('ORYON_GPT_TORCH', 'gpt-pytorch-small.pt'))
text = Path(os.environ.get('ORYON_CORPUS', 'corpus.txt')).read_text(encoding='utf-8')
base, chars = scope['load_checkpoint'](checkpoint, map_location='cpu')
stoi = {c:i for i,c in enumerate(chars)}
assert len(text) > 4000 and all(c in stoi for c in text), 'El texto debe usar el vocabulario del checkpoint.'
tokens = torch.tensor([stoi[c] for c in text], dtype=torch.long)
split = int(len(tokens)*0.8)
train, valid = tokens[:split], tokens[split:]
context = base.config['context']
assert len(valid) > context+1
steps = int(os.environ.get('ORYON_STEPS', '20'))
assert steps > 0
device = 'cuda'
print('GPU:', torch.cuda.get_device_name(), 'PyTorch:', torch.__version__, 'pasos:', steps)
print('TF32 permitido para matmul:', torch.backends.cuda.matmul.allow_tf32)
def stochastic_bf16(x):
# Redondeo probabilístico de FP32 finito hacia vecinos BF16, sin copia maestra.
bits = x.contiguous().view(torch.int32)
noise = torch.randint(0,65536,bits.shape,device=bits.device,dtype=torch.int32)
return ((bits + noise) & -65536).view(torch.float32).to(torch.bfloat16)
class BF16AdamW:
def __init__(self, parameters, lr=3e-4):
self.params = list(parameters); self.lr = lr; self.t = 0
self.m = [torch.zeros_like(p) for p in self.params]
self.v = [torch.zeros_like(p) for p in self.params]
@torch.no_grad()
def step(self):
self.t += 1
for p,m,v in zip(self.params,self.m,self.v):
g = p.grad.float()
m.copy_((0.9*m.float()+0.1*g).to(torch.bfloat16))
v.copy_((0.95*v.float()+0.05*g*g).to(torch.bfloat16))
mh = m.float()/(1-0.9**self.t); vh = v.float()/(1-0.95**self.t)
update = mh/(vh.sqrt()+1e-8)
# Misma política explícita para todos los parámetros en los cuatro modos.
new = p.float()*(1-self.lr*0.01)-self.lr*update
p.copy_(stochastic_bf16(new))
def batch(data, generator, batch_size=4):
starts = torch.randint(len(data)-context, (batch_size,), generator=generator)
xx = torch.stack([data[i:i+context] for i in starts.tolist()])
yy = torch.stack([data[i+1:i+context+1] for i in starts.tolist()])
return xx.to(device), yy.to(device)
for mode in ('fp32','fp16','bf16-autocast','bf16-estados'):
torch.manual_seed(41)
net, _ = scope['load_checkpoint'](checkpoint, map_location='cpu')
net = net.float().to(device)
pure = mode == 'bf16-estados'
if pure: net = net.to(torch.bfloat16)
opt = BF16AdamW(net.parameters()) if pure else torch.optim.AdamW(net.parameters(),lr=3e-4,weight_decay=0.01,betas=(0.9,0.95))
scaler = torch.amp.GradScaler('cuda', enabled=(mode == 'fp16'))
gen = torch.Generator().manual_seed(123)
seen = {}
def hook(name):
def record(module, inputs, output):
seen[name] = (str(inputs[0].dtype), str(output.dtype))
return record
handles = [module.register_forward_hook(hook(name)) for name,module in net.named_modules()
if name in ('blocks.0.n1','blocks.0.attn.q','blocks.0.mlp.fc')]
amp = mode in ('fp16','bf16-autocast')
dtype = torch.float16 if mode == 'fp16' else torch.bfloat16
losses, scales = [], []
# Calentamiento sin actualizar pesos ni consumir el generador de entrenamiento.
wx,wy = batch(train,torch.Generator().manual_seed(999))
for _ in range(2):
net.zero_grad(set_to_none=True)
with torch.autocast('cuda',dtype=dtype,enabled=amp):
_,warm_loss,_ = net(wx,wy)
warm_loss.backward()
net.zero_grad(set_to_none=True)
torch.cuda.synchronize(); torch.cuda.reset_peak_memory_stats(); start = time.perf_counter()
net.train()
for _ in range(steps):
xx,yy = batch(train,gen)
net.zero_grad(set_to_none=True)
with torch.autocast('cuda',dtype=dtype,enabled=amp):
_,loss,_ = net(xx,yy)
losses.append(float(loss.detach())); scales.append(scaler.get_scale())
if not torch.isfinite(loss): break
if mode == 'fp16':
scaler.scale(loss).backward(); scaler.step(opt); scaler.update()
else:
loss.backward(); opt.step()
torch.cuda.synchronize(); elapsed = time.perf_counter()-start
peak = torch.cuda.max_memory_allocated()/2**20
net.eval()
vx,vy = batch(valid,torch.Generator().manual_seed(321))
with torch.no_grad(), torch.autocast('cuda',dtype=dtype,enabled=amp):
_,vloss,_ = net(vx,vy)
print(mode, 'tokens/s:', round(len(losses)*4*context/elapsed), 'pico MiB:', round(peak,2),
'pérdidas inicial/final/validación:', round(losses[0],4),round(losses[-1],4),round(float(vloss),4),
'escala inicial/final:', scales[0],scales[-1], 'hooks:', seen)
points = sorted(set(round(i*(len(losses)-1)/4) for i in range(5)))
print('paso, pérdida, escala:', [(i,round(losses[i],4),scales[i]) for i in points])
for handle in handles: handle.remove()
del net,opt,scalernpm run lab and open the connection link.Exercises
Step 1 of 3. Where is w + Δ?
Step 1 of 2. What is the expectation?
class DynamicLossScaler:
def __init__(self):
pass
def unscale(self, grads):
pass
def update(self, found_inf):
pass