Minibatch training: gradient noise and batch size
Minibatches turn gradients into noisy estimates. Study epochs and shuffling, measure gradient noise during training, examine critical batch size and the steps-versus-examples frontier, and assess learning-rate scaling and large-batch generalization.
After this lesson you can
- Implement a minibatch iterator with epoch shuffling and compare sampling without and with replacement.
- Measure network gradient variance as batch size changes and check 1/B scaling.
- Measure gradient noise during training and estimate a critical batch size for a specific problem.
- Apply linear learning-rate scaling with warmup and recognize its limits.
- Use controlled experiments to investigate batch size and update count in generalization gaps.
Before you start
An approximate direction
A full-gradient update uses every available example to estimate a direction. A minibatch uses only some: each update costs less and its direction fluctuates. That fluctuation is not always helpful or harmful; it can allow more updates for the same number of examples processed, but also limits step precision. Full batches remain useful, for example as a reference in a small test.
An epoch is one pass through the training set; a step is one update. With examples and nominal batch size , an epoch has steps if the final incomplete batch is retained and if discarded. Retaining it avoids omitting examples, but its mean uses its actual size. When averaging batch losses to obtain an epoch mean, weight by the number of examples in each batch rather than assigning the smaller final batch equal weight.
Shuffling a new permutation each epoch avoids a fixed order correlated with labels. At a fixed point, a uniform sample without replacement is unbiased; during a training epoch, the current parameter depends on examples already seen and the remaining ones are not generally an independent uniform sample conditional on that parameter. HaoChen and Sra study reshuffling benefits under specific convexity and regularity assumptions, not a guarantee of superiority for every nonconvex network.
How much does a gradient vary?
Fix parameters and let denote the gradient of example . Define and population covariance . If indices are chosen independently and uniformly with replacement, and
The first equality uses independence and the second separates variance and mean. Without replacement, with and , correction appears; in particular the full batch from that population has zero variance. This formula uses the definition of with divisor . A different covariance convention changes the factor’s form. The exercise asks you to prove it, and the lab compares both sampling methods without updating parameters during measurement.
When , the simple scale compares individual gradient variation with the squared mean gradient. It is undefined if . A decrease in can make it grow, but neither loss nor this ratio must vary monotonically. The figure shows a real short Fashion-MNIST run: loss falls between checkpoints while noise estimates fluctuate.
In the figure’s measurement, the reference gradient is calculated on a fixed training subset and each test batch is drawn with replacement from that subset. The cloud is a projection onto two directions, not the whole parameter space. The two-batch estimate uses finitely many samples and can be unstable. The local code producing these data appears below; arithmetic and hardware can introduce small differences on repetition.
From variance to a critical batch size
The steps-versus-examples frontier asks how many updates and examples are needed to reach a goal. Increasing can initially reduce steps, but each step consumes more examples. In a local quadratic approximation with positive semidefinite Hessian , mean gradient , covariance , and finite traces, using an iid minibatch with replacement at that fixed point, the approximate expected loss change in one step is
Minimizing this expression with respect to gives , where and . The simple scale replaces curvature weighting and is a proxy, not generally identical to . If with , the two coincide. McCandlish and colleagues study this relationship and an empirical frontier; it does not turn a noisy measurement into an exact law for every training run.
In that one-dimensional model, and noise has variance . For , with centered noise independent of state and variance ,
The graph counts the first step when expected loss crosses the target. This is not the expected first crossing time of a trajectory. For , the recurrence has a stationary floor; if it lies above the target, no arrival time is invented. The number of examples is times the number of steps and excludes validation costs and hardware effects.
Measure a scale instead of guessing it
The equality for yields two estimators. For , sample means and of squared norms, and iid batches at a fixed point,
Each component is unbiased under that sampling; their ratio need not be. With finite samples either can be negative and a denominator near zero makes the ratio unstable. Average quantities before dividing, show the sample count, and do not hide a nonpositive denominator. The formulas require the gradient to remain fixed while batches are drawn.
The first cell reproduces the tensor engine from the previous lesson. The following cells train a small MLP on a fixed load_digits subset, compute per-example gradients, and compare the empirical trace with and the finite-population correction. The reserved test split is not used here: the purpose is to check an identity on the chosen set, not estimate generalization.
import numpy as np
from copy import deepcopy
def unbroadcast(grad, shape):
grad = np.asarray(grad)
while grad.ndim > len(shape):
grad = grad.sum(axis=0)
for axis, size in enumerate(shape):
if size == 1 and grad.shape[axis] != 1:
grad = grad.sum(axis=axis, keepdims=True)
if grad.shape != tuple(shape):
raise ValueError('formas incompatibles')
return grad
class Tensor:
def __init__(self, data, parents=(), backward=None):
self.data = np.array(data, dtype=np.float64, copy=True)
self.grad = np.zeros_like(self.data)
self.parents = tuple(parents)
self._backward = backward or (lambda: None)
@staticmethod
def wrap(x): return x if isinstance(x, Tensor) else Tensor(x)
def __add__(self, other):
other = Tensor.wrap(other)
a_shape, b_shape = self.data.shape, other.data.shape
out = Tensor(self.data + other.data, (self, other))
def backward():
self.grad += unbroadcast(out.grad, a_shape)
other.grad += unbroadcast(out.grad, b_shape)
out._backward = backward
return out
__radd__ = __add__
def __mul__(self, other):
other = Tensor.wrap(other)
a, b = self.data.copy(), other.data.copy()
out = Tensor(a*b, (self, other))
def backward():
self.grad += unbroadcast(out.grad*b, a.shape)
other.grad += unbroadcast(out.grad*a, b.shape)
out._backward = backward
return out
__rmul__ = __mul__
def __neg__(self): return self * -1
def __sub__(self, other): return self + (-Tensor.wrap(other))
def __rsub__(self, other): return Tensor.wrap(other) - self
def __matmul__(self, other):
other = Tensor.wrap(other)
a, b = self.data.copy(), other.data.copy()
if a.ndim != 2 or b.ndim != 2:
raise ValueError('matmul admite matrices 2D')
out = Tensor(a @ b, (self, other))
def backward():
self.grad += out.grad @ b.T
other.grad += a.T @ out.grad
out._backward = backward
return out
def tanh(self):
y = np.tanh(self.data)
out = Tensor(y, (self,))
out._backward = lambda: self._accumulate(out.grad*(1-y*y))
return out
def sigmoid(self):
x = self.data
y = np.exp(-np.logaddexp(0, -x))
out = Tensor(y, (self,))
out._backward = lambda: self._accumulate(out.grad*y*(1-y))
return out
def relu(self):
mask = self.data > 0
out = Tensor(np.maximum(self.data, 0), (self,))
out._backward = lambda: self._accumulate(out.grad*mask)
return out
def exp(self):
y = np.exp(self.data)
out = Tensor(y, (self,))
out._backward = lambda: self._accumulate(out.grad*y)
return out
def log(self):
x = self.data.copy()
if np.any(x <= 0): raise ValueError('log exige entrada positiva')
out = Tensor(np.log(x), (self,))
out._backward = lambda: self._accumulate(out.grad/x)
return out
def _accumulate(self, value): self.grad += value
def sum(self, axis=None, keepdims=False):
shape = self.data.shape
axes = tuple(range(len(shape))) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
axes = tuple(a % len(shape) for a in axes) if shape else ()
out = Tensor(self.data.sum(axis=axis, keepdims=keepdims), (self,))
def backward():
g = out.grad
if not keepdims:
for a in sorted(axes): g = np.expand_dims(g, a)
self.grad += np.broadcast_to(g, shape)
out._backward = backward
return out
def mean(self, axis=None, keepdims=False):
axes = tuple(range(self.data.ndim)) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
count = int(np.prod([self.data.shape[a] for a in axes]))
return self.sum(axis, keepdims) * (1.0/count)
def max(self, axis=None, keepdims=False):
shape = self.data.shape
axes = tuple(range(len(shape))) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
axes = tuple(a % len(shape) for a in axes) if shape else ()
maxima = self.data.max(axis=axis, keepdims=True)
mask = self.data == maxima
counts = mask.sum(axis=axis, keepdims=True)
out = Tensor(self.data.max(axis=axis, keepdims=keepdims), (self,))
def backward():
g = out.grad
if not keepdims:
for a in sorted(axes): g = np.expand_dims(g, a)
self.grad += mask * (g/counts)
out._backward = backward
return out
def reshape(self, *shape):
original = self.data.shape
out = Tensor(self.data.reshape(*shape), (self,))
out._backward = lambda: self._accumulate(out.grad.reshape(original))
return out
def transpose(self, *axes):
perm = (tuple(axes[0]) if len(axes) == 1 and isinstance(axes[0], (tuple, list))
else tuple(axes) if axes else tuple(reversed(range(self.data.ndim))))
transposed = self.data.transpose(perm) # NumPy valida la permutación.
normalized = tuple(a % self.data.ndim for a in perm) if self.data.ndim else ()
inverse = np.argsort(normalized)
out = Tensor(transposed, (self,))
out._backward = lambda: self._accumulate(out.grad.transpose(inverse))
return out
def __getitem__(self, index):
# También pueden mutarse listas o estructuras anidadas de índices.
index = deepcopy(index)
out = Tensor(self.data[index], (self,))
def backward(): np.add.at(self.grad, index, out.grad)
out._backward = backward
return out
@staticmethod
def concat(tensors, axis=0):
tensors = tuple(tensors)
cuts = np.cumsum([t.data.shape[axis] for t in tensors])[:-1]
out = Tensor(np.concatenate([t.data for t in tensors], axis=axis), tensors)
def backward():
for tensor, g in zip(tensors, np.split(out.grad, cuts, axis=axis)):
tensor.grad += g
out._backward = backward
return out
def backward(self, seed=None):
if seed is None:
if self.data.size != 1: raise ValueError('salida no escalar: proporciona semilla')
seed = np.ones_like(self.data)
seed = np.asarray(seed, dtype=float)
if seed.shape != self.data.shape: raise ValueError('forma de semilla incorrecta')
topo, seen, stack = [], set(), [(self, False)]
while stack:
node, done = stack.pop()
if done: topo.append(node)
elif node not in seen:
seen.add(node)
stack.append((node, True))
stack.extend((p, False) for p in reversed(node.parents))
for node in topo:
if node.parents: node.grad.fill(0)
self.grad += seed
for node in reversed(topo): node._backward()
return len(topo)
def cross_entropy(logits, labels):
z = logits.data.copy()
labels = np.asarray(labels)
if (z.ndim != 2 or z.shape[0] == 0 or z.shape[1] == 0 or
labels.ndim != 1 or labels.shape[0] != z.shape[0] or
not np.issubdtype(labels.dtype, np.integer) or
np.any(labels < 0) or np.any(labels >= z.shape[1])):
raise ValueError('formas o etiquetas incorrectas')
shifted = z - np.max(z, axis=1, keepdims=True)
exp = np.exp(shifted)
probabilities = exp/exp.sum(axis=1, keepdims=True)
loss = np.mean(np.log(exp.sum(axis=1))-shifted[np.arange(len(labels)), labels])
delta = probabilities.copy()
delta[np.arange(len(labels)), labels] -= 1
delta /= len(labels)
out = Tensor(loss, (logits,))
out._backward = lambda: logits._accumulate(out.grad*delta)
return outfrom sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
features, labels = load_digits(return_X_y=True)
features = features/16
train_index, heldout = train_test_split(np.arange(len(labels)), test_size=0.2,
stratify=labels, random_state=42)
chosen = np.random.default_rng(17).choice(train_index, 128, replace=False)
X, y = features[chosen], labels[chosen]
init = np.random.default_rng(31)
params = [Tensor(init.normal(0, np.sqrt(2/64), (64, 16))), Tensor(np.zeros(16)),
Tensor(init.normal(0, np.sqrt(2/16), (16, 10))), Tensor(np.zeros(10))]
shuffle = np.random.default_rng(77)
def logits(x): return (Tensor(x) @ params[0] + params[1]).relu() @ params[2] + params[3]
def train_epochs(n):
for _ in range(n):
for ids in np.array_split(shuffle.permutation(len(y)), 4):
for p in params: p.grad.fill(0)
loss = cross_entropy(logits(X[ids]), y[ids])
loss.backward()
for p in params: p.data -= 0.1*p.grad
def measure(label):
# En un punto fijo: no se cambia ningún parámetro durante este bucle.
per_example = []
for i in range(len(y)):
for p in params: p.grad.fill(0)
out = cross_entropy(logits(X[i:i+1]), y[i:i+1])
out.backward()
per_example.append(np.concatenate([p.grad.ravel().copy() for p in params]))
matrix = np.array(per_example)
G = matrix.mean(axis=0)
sigma_trace = np.mean(np.sum((matrix-G)**2, axis=1))
g2 = G@G
full_loss = float(cross_entropy(logits(X), y).data)
print(label, 'pérdida', full_loss, 'traza Sigma', sigma_trace,
'norma media al cuadrado', g2, 'escala simple', sigma_trace/g2 if g2 > 0 else float('nan'))
draws = np.random.default_rng(102)
for batch in (1, 4, 16, 64):
variance = 0.
for _ in range(200):
ids = draws.integers(0, len(y), size=batch)
delta = matrix[ids].mean(axis=0)-G
variance += delta@delta
print('B, traza empírica, predicción con reemplazo', batch, variance/200, sigma_trace/batch)
for batch in (16, 64, len(y)):
variance = 0.
for _ in range(200):
ids = draws.choice(len(y), size=batch, replace=False)
delta = matrix[ids].mean(axis=0)-G
variance += delta@delta
predicted = (sigma_trace/batch)*(len(y)-batch)/(len(y)-1)
print('B, traza empírica, predicción sin reemplazo', batch, variance/200, predicted)
small, big = 8, 64
gs, gb = [], []
for _ in range(100):
a = matrix[draws.integers(0, len(y), size=small)].mean(axis=0)
b = matrix[draws.integers(0, len(y), size=big)].mean(axis=0)
gs.append(a@a); gb.append(b@b)
es, eb = np.mean(gs), np.mean(gb)
estimate_g2 = (big*eb-small*es)/(big-small)
estimate_s = (es-eb)/(1/small-1/big)
print('estimador dos lotes G², traza, cociente:', estimate_g2, estimate_s,
estimate_s/estimate_g2 if estimate_g2 > 0 else float('nan'))measure('inicial')train_epochs(3)
measure('tras 3 épocas')train_epochs(9)
measure('tras 12 épocas')The cell’s simulations use finitely many draws. Differences from the prediction reflect sampling error as well as rounding; they are not an exact proof of the identity. The two-batch ratio is an estimate, not the true value. Change the seed and number of draws and observe variation.
Scaling the learning rate is not a universal law
The linear rule proposes multiplying by the same factor as in an appropriate regime; warmup gradually increases the rate initially to avoid excessively large early steps. In Goyal and colleagues, ResNet-50 on ImageNet moved from , to , , with gradual five-epoch warmup. Table 1 reports validation top-1 errors of and , respectively, versus without gradual warmup for the large batch; these are means and deviations over five runs under that protocol, not promises for another network.
The scaling rule depends on optimizer, stage, and task. For adaptive methods, square-root rules with additional hyperparameter adjustments have been proposed under stochastic-approximation assumptions; Malladi and colleagues do not establish that multiplying by the square root suffices for every use of AdamW. Check stability and validation across a range rather than treating a recipe as a guarantee.
What does temperature mean?
For a one-dimensional approximation with iid noise of variance , an SGD discretization has noise amplitude . If also approximated by a diffusion with time step and constant additive noise, its effective temperature is and ideal stationary density is proportional to . The relationship describes that model under its assumptions; it is not a universal temperature for a network with state-dependent noise. Smith and Le develop another scaling convention that includes dataset size.
Generalization and budgets
The debate on large batches and generalization requires controlling more than one variable. Keskar and colleagues report test accuracy with a small batch versus with a large batch for their C1 network on CIFAR-10 and relate their observations to sharpness; this does not prove every gap is explained solely by fewer steps. Dinh and colleagues show that some sharpness measures change under function-preserving reparameterizations. Shallue and colleagues collect results from 168160 models and 35 workloads and study the roles of budgets and tuning. None of these results supports a universal rule that large batches always generalize worse.
At minimum, compare different seeds and rates tuned using validation. Matching epochs approximately fixes examples processed, but not steps; matching steps changes the number of examples and computation. On a memory-limited GPU, the largest batch that fits is not automatically best: compare memory, examples per second, and required steps. Equal-step and equal-example experiments answer different questions; neither alone establishes the cause of a gap.
Real Fashion-MNIST experiment
The first local cell reproduces the short measurement underlying the noise figure: an MLP, explicit subset and seeds, a reference gradient over a fixed subset, and projections of real batches. It writes JSON at the path given by ORYON_NOISE_OUTPUT, or in the current directory if unset. The scale fluctuates between checkpoints in this run; the synthetic control does not replace these data.
"""Medición breve: Fashion-MNIST real, dos tamaños de lote y gradiente completo de un subconjunto."""
import json
import math
import os
from pathlib import Path
import torch
from torch import nn
from torchvision.datasets import FashionMNIST
torch.set_num_threads(1)
torch.manual_seed(71)
torch.cuda.manual_seed_all(71)
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
torch.use_deterministic_algorithms(True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Mismo contenido oficial y MD5 definidos por torchvision; el mirror original S3 usa HTTP.
FashionMNIST.mirrors = ['https://raw.githubusercontent.com/zalandoresearch/fashion-mnist/master/data/fashion/']
root = Path.home() / '.cache' / 'atlas-data'
dataset = FashionMNIST(root, train=True, download=True)
generator = torch.Generator().manual_seed(72)
train_ids = torch.randperm(len(dataset), generator=generator)[:8192]
images = dataset.data[train_ids].to(device=device, dtype=torch.float32).reshape(-1, 784) / 255
labels = dataset.targets[train_ids].to(device=device)
probe_n = 2048
probe_x, probe_y = images[:probe_n], labels[:probe_n]
model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10)).to(device)
parameters = tuple(model.parameters())
optimizer = torch.optim.SGD(parameters, lr=0.1)
train_rng = torch.Generator().manual_seed(73)
probe_rng = torch.Generator().manual_seed(74)
projection_rng = torch.Generator().manual_seed(75)
batch_small, batch_large, samples = 32, 256, 128
group = batch_large // batch_small
def gradient(x, y):
loss = nn.functional.cross_entropy(model(x), y)
pieces = torch.autograd.grad(loss, parameters)
return loss.detach(), torch.cat([part.detach().reshape(-1) for part in pieces])
def measure(step):
full_loss, full_grad = gradient(probe_x, probe_y)
draws = torch.randint(probe_n, (samples, batch_small), generator=probe_rng)
small = []
for indexes in draws:
_, g = gradient(probe_x[indexes.to(device)], probe_y[indexes.to(device)])
small.append(g)
gradients = torch.stack(small)
groups = gradients.reshape(samples // group, group, -1).mean(dim=1)
small_norm2 = gradients.square().sum(dim=1).mean()
large_norm2 = groups.square().sum(dim=1).mean()
trace_two = (small_norm2-large_norm2) / (1/batch_small - 1/batch_large)
norm_two = (batch_large*large_norm2 - batch_small*small_norm2) / (batch_large-batch_small)
full_norm2 = full_grad.square().sum()
# Estima la traza de Σ a partir de la varianza muestral de los 128 gradientes de B=32.
trace_sample = batch_small * (gradients-gradients.mean(dim=0)).square().sum() / (samples-1)
axis1 = full_grad / full_grad.norm()
axis2 = torch.randn(full_grad.shape, generator=projection_rng).to(device)
axis2 -= (axis2 @ axis1) * axis1
axis2 /= axis2.norm()
cloud = torch.stack((gradients @ axis1, gradients @ axis2), dim=1).cpu().tolist()
result = {
'step': step, 'loss': float(full_loss), 'full_grad_norm2': float(full_norm2),
'small_mean_norm2': float(small_norm2), 'large_mean_norm2': float(large_norm2),
'trace_two_batch': float(trace_two), 'norm2_two_batch': float(norm_two),
'noise_two_batch': float(trace_two / norm_two) if norm_two > 0 else None,
'trace_sample': float(trace_sample), 'noise_full_reference': float(trace_sample / full_norm2),
'full_projection': [float(full_grad @ axis1), float(full_grad @ axis2)], 'cloud': cloud,
}
print('paso', step, 'pérdida', result['loss'], 'B ruido 2 lotes', result['noise_two_batch'],
'B ruido con gradiente completo', result['noise_full_reference'], flush=True)
return result
checkpoints = {0, 50, 200, 600}
history = [measure(0)]
order = torch.randperm(len(images), generator=train_rng)
cursor = 0
for step in range(1, max(checkpoints)+1):
if cursor+64 > len(order):
order = torch.randperm(len(images), generator=train_rng)
cursor = 0
batch = order[cursor:cursor+64].to(device)
cursor += 64
optimizer.zero_grad(set_to_none=True)
loss = nn.functional.cross_entropy(model(images[batch]), labels[batch])
loss.backward()
optimizer.step()
if step in checkpoints: history.append(measure(step))
output = {
'dataset': 'Fashion-MNIST train oficial; subconjunto de 8192 sin reemplazo',
'source': 'https://github.com/zalandoresearch/fashion-mnist',
'device': str(device), 'seed_model': 71, 'seed_subset': 72, 'seed_training': 73,
'seed_probes': 74, 'seed_projection': 75, 'probe_population': probe_n,
'architecture': [784, 128, 10], 'activation': 'ReLU', 'loss': 'entropía cruzada media',
'training_batch': 64, 'optimizer': 'SGD sin momentum', 'learning_rate': 0.1,
'small_batch': batch_small, 'large_batch': batch_large, 'small_samples': samples,
'sampling': 'con reemplazo dentro de cada lote y entre lotes; lotes grandes agrupan ocho lotes pequeños independientes',
'projection': 'eje 1: gradiente completo normalizado; eje 2: nuevo vector normal reproducible ortogonalizado en cada checkpoint',
'history': history,
}
target = Path(os.environ.get('ORYON_NOISE_OUTPUT', 'fashion-noise.json'))
target.write_text(json.dumps(output, ensure_ascii=False, indent=2), encoding='utf-8')
print('resultado:', target, 'dispositivo:', device, flush=True)
del model, images, labels, parameters, optimizer, probe_x, probe_y, loss, batch
if device.type == 'cuda': torch.cuda.empty_cache()npm run lab and open the connection link.The second cell compares batch sizes from 32 to 4096 with fixed rate and linear scaling with epoch-stepped warmup. It separates validation from training and records the first end-of-epoch evaluation to reach the target; it does not know the exact first crossing step. Duration includes complete training and validations, not time to target. The official test set is evaluated at the end of each nondivergent run; do not use it to select hyperparameters. A run that does not reach the target is marked accordingly, even if a batch processed more examples or loss became non-finite.
The additional equal-step comparison samples with replacement for both batches, while the epoch sweep uses permutations without replacement. Comparing the two protocols also changes sampling, so no single cause is isolated. The result is saved as JSON with policies, seeds, steps, examples, accuracy, and time. The full run includes several seeds; the small test uses one and does not settle inference about generalization. By default the full sweep runs; ORYON_VERIFY_SHORT=1 selects the small test used to verify the lesson.
import json
import math
import os
import time
from pathlib import Path
import torch
from torch import nn
from torchvision.datasets import FashionMNIST
if not torch.cuda.is_available():
raise RuntimeError('se necesita CUDA')
torch.set_num_threads(1)
torch.backends.cuda.matmul.allow_tf32 = False
device = torch.device('cuda')
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
FashionMNIST.mirrors = ['https://raw.githubusercontent.com/zalandoresearch/fashion-mnist/master/data/fashion/']
dataset = FashionMNIST(Path.home()/'.cache'/'atlas-data', train=True, download=True)
test_dataset = FashionMNIST(Path.home()/'.cache'/'atlas-data', train=False, download=True)
split_rng = torch.Generator().manual_seed(101)
indices = torch.randperm(len(dataset), generator=split_rng)
n_train, n_validation = (2048, 1024) if short else (50000, 10000)
train_ids = indices[:n_train]
validation_ids = indices[n_train:n_train+n_validation]
X_train = dataset.data[train_ids].to(device=device, dtype=torch.float32).reshape(-1, 784)/255
y_train = dataset.targets[train_ids].to(device=device)
X_val = dataset.data[validation_ids].to(device=device, dtype=torch.float32).reshape(-1, 784)/255
y_val = dataset.targets[validation_ids].to(device=device)
test_count = 1024 if short else len(test_dataset)
X_test = test_dataset.data[:test_count].to(device=device, dtype=torch.float32).reshape(-1, 784)/255
y_test = test_dataset.targets[:test_count].to(device=device)
batches = [32, 128, 512] if short else [32, 64, 128, 256, 512, 1024, 2048, 4096]
seeds = [7] if short else [7, 11]
epochs = 3 if short else 12
target = 0.70 if short else 0.85
def accuracy(model, inputs, targets):
model.eval()
correct = 0
with torch.no_grad():
for x, y in zip(inputs.split(512), targets.split(512)):
correct += int((model(x).argmax(dim=1)==y).sum())
return correct/len(targets)
def make_model(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
return nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10)).to(device)
def run(batch, policy, seed):
model = make_model(seed)
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
generator = torch.Generator().manual_seed(seed+100)
steps, seen, first_hit, history = 0, 0, None, []
torch.cuda.synchronize(device)
start = time.perf_counter()
for epoch in range(epochs):
order = torch.randperm(n_train, generator=generator)
model.train()
for ids in order.split(batch):
ids = ids.to(device)
# El calentamiento es lineal durante cinco épocas, incluida la primera.
lr = 0.1 if policy == 'fijo' else 0.1*(batch/32)*min(1, (epoch+1)/5)
for group in optimizer.param_groups: group['lr'] = lr
optimizer.zero_grad(set_to_none=True)
loss = nn.functional.cross_entropy(model(X_train[ids]), y_train[ids])
if not bool(torch.isfinite(loss)):
print('pérdida no finita; entrenamiento interrumpido', batch, policy, seed, flush=True)
return {'batch':batch, 'policy':policy, 'seed':seed, 'hit':first_hit, 'diverged':True, 'history':history}
loss.backward()
optimizer.step()
steps += 1
seen += len(ids)
val_accuracy = accuracy(model, X_val, y_val)
history.append({'epoch':epoch+1, 'steps':steps, 'examples':seen, 'accuracy':val_accuracy})
if first_hit is None and val_accuracy >= target:
first_hit = {'steps':steps, 'examples':seen, 'epoch':epoch+1}
torch.cuda.synchronize(device)
elapsed = time.perf_counter()-start
test_accuracy = accuracy(model, X_test, y_test)
result = {'batch':batch, 'policy':policy, 'seed':seed, 'hit':first_hit,
'diverged':False, 'history':history, 'seconds':elapsed, 'final_test_accuracy':test_accuracy}
print(json.dumps(result, ensure_ascii=False), flush=True)
del model, optimizer, loss
torch.cuda.empty_cache()
return result
results = [run(batch, policy, seed) for seed in seeds
for batch in batches for policy in ('fijo', 'lineal_warmup')]
def equal_steps(batch, seed, steps):
model = make_model(seed)
opt = torch.optim.SGD(model.parameters(), lr=0.1)
generator = torch.Generator().manual_seed(seed+400)
model.train()
for _ in range(steps):
ids = torch.randint(n_train, (batch,), generator=generator).to(device)
opt.zero_grad(set_to_none=True)
loss = nn.functional.cross_entropy(model(X_train[ids]), y_train[ids])
loss.backward()
opt.step()
val_accuracy = accuracy(model, X_val, y_val)
test_accuracy = accuracy(model, X_test, y_test)
print('mismos pasos, muestreo con reemplazo:', batch, steps, batch*steps, val_accuracy, test_accuracy, flush=True)
del model, opt, loss
torch.cuda.empty_cache()
return {'batch':batch, 'seed':seed, 'steps':steps, 'examples':batch*steps,
'validation_accuracy':val_accuracy, 'final_test_accuracy':test_accuracy}
matched_steps = 16 if short else 2*math.ceil(n_train/128)
equal_results = [equal_steps(batch, seed, matched_steps) for seed in seeds
for batch in ((128, 512) if short else (128, 4096))]
output = {'dataset':'Fashion-MNIST oficial', 'train':n_train, 'validation':n_validation, 'test':test_count,
'target':target, 'epochs':epochs, 'batch_sweep':results,
'equal_steps_with_replacement':equal_results}
path = Path(os.environ.get('ORYON_BATCH_OUTPUT', 'fashion-batch-sweep.json'))
path.write_text(json.dumps(output, ensure_ascii=False, indent=2), encoding='utf-8')
print('salida guardada en', path, flush=True)
del X_train, y_train, X_val, y_val, X_test, y_test
torch.cuda.empty_cache()npm run lab and open the connection link.import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 4))
shown = 0
for policy, marker in [('fijo', 'o'), ('lineal_warmup', 's')]:
for row in results:
hit = row['hit']
if row['policy'] != policy or hit is None:
continue
ax.scatter(hit['examples'], hit['steps'], marker=marker, label=policy)
ax.annotate('B='+str(row['batch']), (hit['examples'], hit['steps']), fontsize=7)
shown += 1
if shown:
handles, names = ax.get_legend_handles_labels()
unique = dict(zip(names, handles))
ax.legend(unique.values(), unique.keys())
ax.set_xscale('log')
ax.set_yscale('log')
else:
ax.text(0.5, 0.5, 'Ningún caso alcanzó la meta', ha='center', va='center', transform=ax.transAxes)
ax.set_xlabel('Ejemplos procesados hasta el primer control que alcanza la meta')
ax.set_ylabel('Pasos hasta ese control')
ax.set_title('Solo se representan metas alcanzadas')
fig.tight_layout()
plt.show()
print('casos sin meta observada:', sum(row['hit'] is None for row in results), 'de', len(results))npm run lab and open the connection link.Exercises
Step 1 of 3. If Iᵢ indicates that element i is in the batch, what is its expectation?
import numpy as np
def minibatches(n, batch_size, epochs, seed, drop_last=False):
passThe following cell checks the exercises’ numerical calculations and, for a small vector population, enumerates all samples of a given size to check the covariance formula. Enumeration is an independent check for that example, not a proof for every case.
from itertools import combinations
population = np.array([[1., 2.], [2., -1.], [0., 3.], [-1., 0.]])
N, B = len(population), 2
G = population.mean(axis=0)
centered = population-G
Sigma = centered.T @ centered/N
means = np.array([population[list(ids)].mean(axis=0) for ids in combinations(range(N), B)])
observed = (means-G).T @ (means-G)/len(means)
predicted = Sigma/B*(N-B)/(N-1)
print('error máximo de covarianza:', np.max(np.abs(observed-predicted)))
simple = 120/3
print('escala simple y tasa relativa del ejemplo:', simple, 1/(1+simple/40))A minibatch estimates a direction at a fixed point; noise depends on sampling and batch size. The simple scale is useful but does not necessarily equal the curvature-weighted scale. To choose batch size and rate, measure steps, examples, time, memory, and validation under comparable protocols.