From your framework to PyTorch: training on the local GPU
Map the custom micro-framework to PyTorch, check layerwise gradient parity, and apply MLP training to the local GPU. Relate step time to FLOPs, arithmetic intensity and launch overhead, then build a reproducible training and resumption template.
After this lesson you can
- Translate the micro-framework MLP into nn.Module and identify the PyTorch counterpart of each piece.
- Design a layerwise parity test with dtype-appropriate tolerances and explain legitimate discrepancies.
- Estimate step FLOPs with the 6N rule and compare with measured performance and an explicitly selected GPU peak.
- Measure MLP examples per second as batch size and width vary and examine possible bottlenecks.
- Assemble a training template with evaluation, logging and resumption using the tools from m00.
Before you start
- 15Tensor autograd engineModule and parameters abstractionSaved tensors designCost of backpropagation in dense networks
- 00autograd dynamic graphbackward semanticsnn.ModulePyTorch optimizer APICanonical training and evaluation loopCustom autograd functions and gradcheckCUDA asynchronous executionTraining memory budgetReference implementation testingTolerance-based numerical assertionsFull training checkpointExact resumption
- 09Roofline modelArithmetic intensity
The same graph, another implementation
You have built an engine that saves operations and propagates adjoints. PyTorch does the same at a different scale: torch.Tensor holds data, shape, device and, where applicable, grad; a recorded operation connects its result to its backward function through grad_fn. nn.Module registers parameters and submodules, and an optimizer updates the parameters it receives. This correspondence between the micro-framework and PyTorch turns a large API into familiar pieces.
One difference matters from the first step: nn.Linear stores weights as (salidas, entradas) and computes , while the previous lesson’s layer stores as (entradas, salidas) and computes . To compare them, copy the transposed weight and transpose its gradient before comparing. Checking shapes or final losses alone does not catch every error.
Leaf gradients accumulate. In PyTorch, optimizer.zero_grad(set_to_none=True) leaves grad as None until the next contribution; our engine fills existing arrays with zeros. These states are not identical: if a parameter receives no gradient, an optimizer can treat None and a zero tensor differently. The dynamic graph and its rules are explained in autograd; here you apply them to your MLP.
Compare before optimizing
A parity test fixes data, parameters, reduction, dtype, and the convention at nondifferentiable points. Compare the forward pass and activation adjoints as well as each parameter gradient. With mean loss, both our engine and CrossEntropyLoss divide by the number of examples; if one computes a sum, its gradients are times those of the mean on the same batch. An error first appearing in a layer guides the search, but does not automatically identify the cause.
For values near zero, the ratio can explode even when absolute error is small. A condition such as combines both scales; tolerances are justified by dtype, reduction size, and operation, not a universal magic number. Changing summation order can alter the last bits. In some NVIDIA float32 multiplications, TF32 can reduce internal operand precision while retaining float32 output: this does not mean every operation uses Tensor Cores or that every difference is a bug. PyTorch CUDA semantics documents the behavior and controls.
A custom operation in PyTorch
An torch.autograd.Function separates forward and backward. ctx.save_for_backward saves tensors needed by the derivative and lets PyTorch manage their lifecycle and mutations. For fused cross-entropy, the backward pass of mean loss multiplies by the incoming seed: even for scalar output, forgetting that seed breaks compositions that scale the loss. The save_for_backward documentation describes its restrictions and higher-order derivatives.
The following implementation requires finite floating-point logits of shape with and valid integer labels on the same device. It saves probabilities computed during forward and supports the first derivative; it does not build a graph for differentiating its backward pass again. once_differentiable makes that limitation explicit. gradcheck checks first-order derivatives and does not automatically test double backward.
The local cell copies the current implementation from the previous lesson to be self-contained. It compares each activation and gradient in float64 with equal weights and data, validates a cross-entropy function with gradcheck, and compares 100 SGD updates. The original Tensor forces float64; an explicit float32 variant is compared with PyTorch float32 and with float64. The experiment uses CPU and the tolerances in the code; it is not a GPU TF32 measurement.
# Motor copiado de m15-l09, seguido de una variante explícita float32.
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 out
# Misma implementación con cada dato de Tensor convertido a float32.
class Tensor32:
def __init__(self, data, parents=(), backward=None):
self.data = np.array(data, dtype=np.float32, 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, Tensor32) else Tensor32(x)
def __add__(self, other):
other = Tensor32.wrap(other)
a_shape, b_shape = self.data.shape, other.data.shape
out = Tensor32(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 = Tensor32.wrap(other)
a, b = self.data.copy(), other.data.copy()
out = Tensor32(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 + (-Tensor32.wrap(other))
def __rsub__(self, other): return Tensor32.wrap(other) - self
def __matmul__(self, other):
other = Tensor32.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 = Tensor32(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 = Tensor32(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 = Tensor32(y, (self,))
out._backward = lambda: self._accumulate(out.grad*y*(1-y))
return out
def relu(self):
mask = self.data > 0
out = Tensor32(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 = Tensor32(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 = Tensor32(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 = Tensor32(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 = Tensor32(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 = Tensor32(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 = Tensor32(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 = Tensor32(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 = Tensor32(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_entropy32(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 = Tensor32(loss, (logits,))
out._backward = lambda: logits._accumulate(out.grad*delta)
return out
import torch
from torch import nn
from torch.autograd import Function, gradcheck
from torch.autograd.function import once_differentiable
torch.set_num_threads(1)
torch.manual_seed(23)
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
class CrossEntropyMean(Function):
@staticmethod
def forward(ctx, logits, labels):
if logits.ndim != 2 or logits.shape[0] == 0 or logits.shape[1] == 0:
raise ValueError('logits deben tener forma (B, C), con B y C positivos')
if not logits.is_floating_point():
raise TypeError('logits deben ser de coma flotante')
if not bool(torch.isfinite(logits).all()):
raise ValueError('logits deben ser finitos')
if labels.device != logits.device:
raise ValueError('logits y etiquetas deben estar en el mismo dispositivo')
if labels.ndim != 1 or labels.shape[0] != logits.shape[0]:
raise ValueError('etiquetas deben tener forma (B,)')
if labels.dtype != torch.long:
raise TypeError('etiquetas deben tener dtype torch.long')
if torch.any(labels < 0) or torch.any(labels >= logits.shape[1]):
raise ValueError('etiqueta fuera de rango')
shifted = logits - logits.max(dim=1, keepdim=True).values
logp = shifted - shifted.logsumexp(dim=1, keepdim=True)
probabilities = logp.exp()
ctx.save_for_backward(probabilities, labels)
return -logp[torch.arange(logits.shape[0], device=logits.device), labels].mean()
@staticmethod
@once_differentiable
def backward(ctx, grad_output):
probabilities, labels = ctx.saved_tensors
delta = probabilities.clone()
delta[torch.arange(labels.shape[0], device=labels.device), labels] -= 1
return grad_output * delta / labels.shape[0], None
class Model(nn.Module):
def __init__(self, dtype):
super().__init__()
self.first = nn.Linear(4, 5, dtype=dtype)
self.last = nn.Linear(5, 3, dtype=dtype)
def forward(self, x):
z1 = self.first(x)
hidden = z1.relu()
z2 = self.last(hidden)
return z1, hidden, z2
random = np.random.default_rng(23)
data = random.normal(size=(7, 4))
labels = np.array([0, 1, 2, 0, 2, 1, 0], dtype=np.int64)
weights = [random.normal(scale=0.3, size=(4, 5)), random.normal(scale=0.2, size=5),
random.normal(scale=0.3, size=(5, 3)), random.normal(scale=0.2, size=3)]
def load_torch(dtype):
model = Model(dtype)
with torch.no_grad():
model.first.weight.copy_(torch.tensor(weights[0].T, dtype=dtype))
model.first.bias.copy_(torch.tensor(weights[1], dtype=dtype))
model.last.weight.copy_(torch.tensor(weights[2].T, dtype=dtype))
model.last.bias.copy_(torch.tensor(weights[3], dtype=dtype))
return model
def own_forward(parameters, tensor_type=Tensor):
x = tensor_type(data)
z1 = x @ parameters[0] + parameters[1]
hidden = z1.relu()
z2 = hidden @ parameters[2] + parameters[3]
return x, z1, hidden, z2
def torch_forward(model, dtype):
x = torch.tensor(data, dtype=dtype, requires_grad=True)
z1, hidden, z2 = model(x)
for node in (z1, hidden, z2): node.retain_grad()
return x, z1, hidden, z2
def maxdiff(a, b):
return float(np.max(np.abs(np.asarray(a) - np.asarray(b))))
own_params = [Tensor(w) for w in weights]
net64 = load_torch(torch.float64)
own_nodes = own_forward(own_params)
torch_nodes = torch_forward(net64, torch.float64)
own_loss = cross_entropy(own_nodes[-1], labels)
torch_loss = CrossEntropyMean.apply(torch_nodes[-1], torch.tensor(labels))
own_loss.backward()
torch_loss.backward()
for name, a, b in zip(('entrada', 'lineal 1', 'ReLU', 'lineal 2'), own_nodes, torch_nodes):
assert np.allclose(a.data, b.detach().numpy(), rtol=1e-10, atol=1e-12)
assert np.allclose(a.grad, b.grad.numpy(), rtol=1e-10, atol=1e-12)
print(name, 'error salida', maxdiff(a.data, b.detach().numpy()), 'error adjunto', maxdiff(a.grad, b.grad.numpy()))
torch_params = [net64.first.weight.grad.numpy().T, net64.first.bias.grad.numpy(),
net64.last.weight.grad.numpy().T, net64.last.bias.grad.numpy()]
for name, own, ref in zip(('W1', 'b1', 'W2', 'b2'), own_params, torch_params):
assert np.allclose(own.grad, ref, rtol=1e-10, atol=1e-12)
print(name, 'error gradiente', maxdiff(own.grad, ref))
assert np.allclose(own_loss.data, torch_loss.detach().numpy(), rtol=1e-10, atol=1e-12)
print('pérdidas float64', float(own_loss.data), float(torch_loss.detach()))
# Tensor32 es una copia explícita de l09 que convierte cada nodo a float32.
net32 = load_torch(torch.float32)
nodes32 = torch_forward(net32, torch.float32)
loss32 = CrossEntropyMean.apply(nodes32[-1], torch.tensor(labels))
loss32.backward()
own_params32 = [Tensor32(w) for w in weights]
own_nodes32 = own_forward(own_params32, Tensor32)
own_loss32 = cross_entropy32(own_nodes32[-1], labels)
own_loss32.backward()
for name, own, ref in zip(('entrada', 'lineal 1', 'ReLU', 'lineal 2'), own_nodes32, nodes32):
assert own.data.dtype == np.float32 and own.grad.dtype == np.float32
assert np.allclose(own.data, ref.detach().numpy(), rtol=1e-4, atol=1e-6)
assert np.allclose(own.grad, ref.grad.numpy(), rtol=1e-4, atol=1e-6)
print('motor float32 vs PyTorch float32', name, 'error salida', maxdiff(own.data, ref.detach().numpy()), 'error adjunto', maxdiff(own.grad, ref.grad.numpy()))
torch_params32 = [net32.first.weight.grad.numpy().T, net32.first.bias.grad.numpy(),
net32.last.weight.grad.numpy().T, net32.last.bias.grad.numpy()]
for name, own, ref in zip(('W1', 'b1', 'W2', 'b2'), own_params32, torch_params32):
assert own.data.dtype == np.float32 and own.grad.dtype == np.float32
assert np.allclose(own.grad, ref, rtol=1e-4, atol=1e-6)
print('motor float32 vs PyTorch float32', name, 'error gradiente', maxdiff(own.grad, ref))
assert np.allclose(own_loss32.data, loss32.detach().numpy(), rtol=1e-4, atol=1e-6)
print('pérdidas float32', float(own_loss32.data), float(loss32.detach()))
for name, own, ref in zip(('entrada', 'lineal 1', 'ReLU', 'lineal 2'), own_nodes32, torch_nodes):
assert np.allclose(own.data, ref.detach().numpy(), rtol=1e-4, atol=1e-6)
assert np.allclose(own.grad, ref.grad.numpy(), rtol=1e-4, atol=1e-6)
print('motor float32 vs PyTorch float64', name, 'error salida', maxdiff(own.data, ref.detach().numpy()), 'error adjunto', maxdiff(own.grad, ref.grad.numpy()))
for name, own, ref in zip(('W1', 'b1', 'W2', 'b2'), own_params32, torch_params):
assert np.allclose(own.grad, ref, rtol=1e-4, atol=1e-6)
print('motor float32 vs PyTorch float64', name, 'error gradiente', maxdiff(own.grad, ref))
for name, a, b in zip(('entrada', 'lineal 1', 'ReLU', 'lineal 2'), torch_nodes, nodes32):
assert np.allclose(a.detach().numpy(), b.detach().numpy(), rtol=1e-4, atol=1e-6)
assert np.allclose(a.grad.numpy(), b.grad.numpy(), rtol=1e-4, atol=1e-6)
print('float32 vs float64', name, 'error salida', maxdiff(a.detach().numpy(), b.detach().numpy()), 'error adjunto', maxdiff(a.grad.numpy(), b.grad.numpy()))
for name, p64, p32 in zip(('W1', 'b1', 'W2', 'b2'), net64.parameters(), net32.parameters()):
assert np.allclose(p64.grad.numpy(), p32.grad.numpy(), rtol=1e-4, atol=1e-6)
print('float32 vs float64', name, 'error gradiente', maxdiff(p64.grad.numpy(), p32.grad.numpy()))
test_logits = torch.randn(4, 3, dtype=torch.float64, requires_grad=True)
test_labels = torch.tensor([0, 2, 1, 2])
assert gradcheck(CrossEntropyMean.apply, (test_logits, test_labels), eps=1e-6, atol=1e-5, rtol=1e-3)
assert torch.allclose(CrossEntropyMean.apply(test_logits, test_labels), nn.functional.cross_entropy(test_logits, test_labels), rtol=1e-12, atol=1e-12)
print('entropía cruzada: gradcheck y pérdida de referencia correctos')
for bad_logits, bad_labels in [
(torch.tensor([[float('nan'), 0.]]), torch.tensor([0])),
(torch.zeros(2, 3), torch.tensor([0., 1.])),
(torch.zeros(2, 3), torch.tensor([[0], [1]])),
(torch.zeros(2, 3), torch.tensor([0, 3])),
(torch.zeros(0, 3), torch.empty(0, dtype=torch.long)),
(torch.zeros(2, 3), torch.empty(2, dtype=torch.long, device='meta')),
]:
try:
CrossEntropyMean.apply(bad_logits, bad_labels)
except (ValueError, TypeError):
pass
else:
raise AssertionError('una entrada inválida fue aceptada')
first = torch.autograd.grad(CrossEntropyMean.apply(test_logits, test_labels), test_logits, create_graph=True)[0]
try:
torch.autograd.grad(first.sum(), test_logits)
except RuntimeError:
print('entradas inválidas y doble backward: rechazados')
else:
raise AssertionError('el backward de orden superior debería rechazarse')
# 100 actualizaciones de SGD, sin barajado, con datos idénticos y sin optimizador con estado.
own_params = [Tensor(w) for w in weights]
model = load_torch(torch.float64)
optimizer = torch.optim.SGD(model.parameters(), lr=0.05)
trajectory_error = 0.
parameter_error = 0.
for step in range(100):
for p in own_params: p.grad.fill(0)
optimizer.zero_grad(set_to_none=True)
own_output = own_forward(own_params)[-1]
own_loss = cross_entropy(own_output, labels)
torch_output = model(torch.tensor(data, dtype=torch.float64))[-1]
loss = CrossEntropyMean.apply(torch_output, torch.tensor(labels))
own_loss.backward()
loss.backward()
trajectory_error = max(trajectory_error, abs(float(own_loss.data)-float(loss.detach())))
for p in own_params: p.data -= 0.05*p.grad
optimizer.step()
trained = [model.first.weight.detach().numpy().T, model.first.bias.detach().numpy(),
model.last.weight.detach().numpy().T, model.last.bias.detach().numpy()]
parameter_error = max(parameter_error, *(maxdiff(p.data, t) for p, t in zip(own_params, trained)))
for p, t in zip(own_params, trained): assert np.allclose(p.data, t, rtol=1e-10, atol=1e-12)
print('100 pasos SGD, pérdida final', float(own_loss.data), 'máxima diferencia de pérdidas', trajectory_error, 'máxima diferencia de parámetros', parameter_error)npm run lab and open the connection link.The 100-step result is a trajectory test for this network, these data, and this stateless SGD. It does not guarantee two large training runs agree bit for bit: reduction, hardware, kernels, and precision can change operation order. If using a custom function in an application, add domain, shape, and edge-case tests appropriate to it.
From FLOPs to time
A weight matrix with entries and a batch costs approximately FLOPs in the forward pass if we count two per multiply-add. Weight and input gradients add approximately another , giving the rule for the full step. It omits activations, biases, loss, optimizer, communication, and memory. If input-data gradients are unnecessary, the first layer omits one product: for the matrix count becomes .
For multiplication , an ideal traffic model reads each operand once and writes the result once. With bytes per element, intensity is FLOPs per byte. This is an ideal traffic count, not a measurement of cache or actual traffic. The roofline bounds ideal performance by , where is peak compute, bandwidth, and arithmetic intensity.
The bound does not show what limits a real run. Launches, occupancy, caches, conversions, loss, and optimizer can dominate; peaks also depend on dtype and compute mode. Choose the denominator explicitly before discussing a fraction of peak. The rule divided by time and an assumed peak is an approximation, not a direct measurement of executed FLOPs or the complete definition of MFU studied in distributed training.
The shared GPU used in this check identifies itself as RTX 4060 Laptop. The NVIDIA laptop table describes ranges for that family; the clock and power of a specific unit can vary. Do not assign a laptop the peak of a desktop card merely because they share a name. In the figure, enter figures appropriate to the mode and device being modeled, or retain explicitly hypothetical values.
An interruptible template
The following experiment splits load_digits into training, validation, and test sets. Evaluation uses model.eval() and torch.no_grad(): the first changes the behavior of layers such as dropout, while the second avoids recording the graph. It saves parameters, SGD-with-momentum state, epoch count, and CPU and CUDA generator states used for permutation and dropout. The CSV records validation per epoch and the test set is consulted at the end.
The code compares an uninterrupted run with one interrupted and resumed at an epoch boundary, on the same device, versions, and deterministic configuration. It does not promise equality across machines or mid-epoch resumption; the latter would also require saving the permutation and batch position. It saves checkpoints and metrics in a new directory whose name it prints. See the PyTorch saving guide and exact resumption to extend the template with a scheduler or mixed precision if used.
import os
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8')
import copy
import csv
import tempfile
import time
import statistics
from pathlib import Path
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
import numpy as np
if not torch.cuda.is_available():
raise RuntimeError('se necesita CUDA')
torch.set_num_threads(1)
torch.use_deterministic_algorithms(True)
torch.backends.cuda.matmul.allow_tf32 = False
device = torch.device('cuda')
features, labels = load_digits(return_X_y=True)
train_val, test_index = train_test_split(np.arange(len(labels)), test_size=0.2,
stratify=labels, random_state=42)
train_index, valid_index = train_test_split(train_val, test_size=0.2,
stratify=labels[train_val], random_state=43)
X_cpu = torch.tensor(features/16, dtype=torch.float32)
y_cpu = torch.tensor(labels, dtype=torch.long)
X_gpu, y_gpu = X_cpu.to(device), y_cpu.to(device)
def build_model():
return nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Dropout(0.1),
nn.Linear(128, 10)).to(device)
def epoch(model, optimizer, sampler, ids, batch=64):
model.train()
shuffled = ids[torch.randperm(len(ids), generator=sampler).to(device)]
for ix in shuffled.split(batch):
optimizer.zero_grad(set_to_none=True)
loss = nn.functional.cross_entropy(model(X_gpu[ix]), y_gpu[ix])
loss.backward()
optimizer.step()
def evaluate(model, ids):
model.eval()
with torch.no_grad():
logits = model(X_gpu[ids])
return float(nn.functional.cross_entropy(logits, y_gpu[ids])), float((logits.argmax(1)==y_gpu[ids]).float().mean())
def save_checkpoint(path, model, optimizer, sampler, completed):
torch.save({'model': model.state_dict(), 'optimizer': optimizer.state_dict(),
'completed': completed, 'sampler_rng': sampler.get_state(),
'cpu_rng': torch.get_rng_state(), 'cuda_rng': torch.cuda.get_rng_state_all()}, path)
def load_checkpoint(path, model, optimizer, sampler):
state = torch.load(path, map_location=device, weights_only=True)
model.load_state_dict(state['model'])
optimizer.load_state_dict(state['optimizer'])
sampler.set_state(state['sampler_rng'].cpu())
torch.set_rng_state(state['cpu_rng'].cpu())
torch.cuda.set_rng_state_all([s.cpu() for s in state['cuda_rng']])
return state['completed']
train_ids = torch.tensor(train_index, device=device)
valid_ids = torch.tensor(valid_index, device=device)
test_ids = torch.tensor(test_index, device=device)
torch.manual_seed(11)
base = build_model()
initial = copy.deepcopy(base.state_dict())
del base
def setup():
model = build_model()
model.load_state_dict(initial)
opt = torch.optim.SGD(model.parameters(), lr=0.03, momentum=0.9)
sampler = torch.Generator().manual_seed(99)
torch.manual_seed(101)
torch.cuda.manual_seed_all(101)
return model, opt, sampler
continuous, optimizer, sampler = setup()
for _ in range(4): epoch(continuous, optimizer, sampler, train_ids)
reference = copy.deepcopy(continuous.state_dict())
interrupted, optimizer, sampler = setup()
run_dir = Path(os.environ['ORYON_RUN_DIR']) if 'ORYON_RUN_DIR' in os.environ else Path(tempfile.mkdtemp(prefix='oryon-m15-l10-'))
run_dir.mkdir(parents=True, exist_ok=True)
initial_metrics = []
for _ in range(2):
epoch(interrupted, optimizer, sampler, train_ids)
initial_metrics.append(evaluate(interrupted, valid_ids))
path = run_dir/'checkpoint-2.pt'
save_checkpoint(path, interrupted, optimizer, sampler, 2)
restored = build_model()
restored_optimizer = torch.optim.SGD(restored.parameters(), lr=0.03, momentum=0.9)
restored_sampler = torch.Generator()
completed = load_checkpoint(path, restored, restored_optimizer, restored_sampler)
with (run_dir/'metricas.csv').open('w', newline='', encoding='utf-8') as stream:
writer = csv.writer(stream)
writer.writerow(['epoch', 'validation_loss', 'validation_accuracy'])
for index, metrics in enumerate(initial_metrics, start=1):
writer.writerow([index, *metrics])
for index in range(completed, 4):
epoch(restored, restored_optimizer, restored_sampler, train_ids)
metrics = evaluate(restored, valid_ids)
writer.writerow([index+1, *metrics])
save_checkpoint(run_dir/f'checkpoint-{index+1}.pt', restored, restored_optimizer, restored_sampler, index+1)
# eval no consume RNG para este modelo; la ruta continua no evalúa entre épocas.
print('máximo error al reanudar', max((reference[k]-restored.state_dict()[k]).abs().max().item() for k in reference))
print('evaluación final', evaluate(restored, test_ids))
print('checkpoints y métricas guardados en', run_dir)
loader = DataLoader(TensorDataset(X_cpu, y_cpu), batch_size=64, shuffle=False,
num_workers=0, pin_memory=True)
def time_training(source):
# Las dos mediciones usan una copia y el mismo orden; no alteran el modelo evaluado.
measured_model = copy.deepcopy(restored)
measured_optimizer = torch.optim.SGD(measured_model.parameters(), lr=0.01)
measured_model.train()
torch.manual_seed(202)
torch.cuda.manual_seed_all(202)
torch.cuda.synchronize()
start = time.perf_counter()
if source == 'resident':
batches = zip(X_gpu.split(64), y_gpu.split(64))
else:
batches = ((x.to(device, non_blocking=True), y.to(device, non_blocking=True)) for x, y in loader)
for x, y in batches:
measured_optimizer.zero_grad(set_to_none=True)
loss = nn.functional.cross_entropy(measured_model(x), y)
loss.backward()
measured_optimizer.step()
torch.cuda.synchronize()
elapsed = time.perf_counter()-start
del measured_model, measured_optimizer
return elapsed
for source in ('resident', 'loader'):
time_training(source) # calentamiento
samples = [time_training(source) for _ in range(3)]
print(source, 'mediana de segundos de entrenamiento de extremo a extremo', statistics.median(samples))
del continuous, interrupted, restored, optimizer, restored_optimizer, X_gpu, y_gpu
torch.cuda.empty_cache()npm run lab and open the connection link.The small comparison of DataLoader with resident data measures end-to-end training on network copies, including data copies in the loader case. It processes the complete dataset only to measure the pipeline, discards the resulting networks, and keeps the evaluated model separate. It synchronizes before and after and reports the median of three passes after warmup. One configuration does not prove one method is always better; test your own preprocessing too. Times on a shared GPU fluctuate.
Measuring batch size and width on the GPU
CUDA operations are asynchronous relative to the CPU. Warm up execution, record CUDA events around the passes, and synchronize the final event before reading its duration. An unsynchronized CPU clock can measure only work submission. The code computes examples per second and two counts: and the matrix count omitting the input gradient. It also reports peak tensor memory allocated by this process, not total reserved memory or other processes’ usage.
MLP training throughput depends on batch size and width: more work per launch can increase examples per second, but memory and arithmetic also grow. A larger batch changes the number of updates per pass over the data, so more examples per second does not automatically mean faster learning or better generalization.
By default the sweep provides the designed widths and batches. Before each case it checks free CUDA memory and skips configurations exceeding a conservative estimate; that estimate cannot guarantee avoiding out-of-memory errors if concurrent usage changes or kernels need more temporaries. The lesson’s test used a small selection of widths and batches; timings from running the full sweep are your own and cannot be inferred from that short test. To repeat the brief check, set ORYON_VERIFY_SHORT to 1 before running the local cell.
The budget separates float32 parameters, gradients, stateless SGD, data, and an activation estimate, plus a buffer for unmodeled items. SGD with momentum would also need an accumulator per parameter; other optimizers have different states. This count does not precisely include kernel temporaries or allocator-reserved memory. peak_allocated_bytes measures tensors allocated during each case, not a guarantee about the next. To estimate a ratio to peak, enter a positive ORYON_PEAK_TFLOPS value appropriate to the dtype and mode measured; without it the cell does not invent a denominator.
import os
import gc
import json
import math
import time
import torch
from torch import nn
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
peak_input = os.environ.get('ORYON_PEAK_TFLOPS')
supplied_peak = float(peak_input) if peak_input is not None else None
if supplied_peak is not None and (not math.isfinite(supplied_peak) or supplied_peak <= 0):
raise ValueError('ORYON_PEAK_TFLOPS debe ser un número finito positivo')
def counts(h, batch):
weights = 784*h + h*h + 10*h
biases = 2*h + 10
approx_6n = 6*batch*weights
# La entrada X no requiere gradiente.
matrix_flops = approx_6n - 2*batch*784*h
return weights, biases, approx_6n, matrix_flops
def memory_budget(h, batch):
weights, biases, _, _ = counts(h, batch)
# Parámetros y gradientes float32. SGD de este ejemplo no usa momentum.
parameters = 4*(weights + biases)
gradients = parameters
optimizer_state = 0
data = 4*batch*784 + 8*batch # entrada float32 y etiquetas int64
# Aproximación deliberada, no medición ni límite del pico real de activaciones.
activations_estimate = 4*batch*(6*h + 10)
subtotal = parameters + gradients + optimizer_state + data + activations_estimate
cushion = int(0.5*subtotal) + 256*1024**2
return {'parameter_bytes': parameters, 'gradient_bytes': gradients,
'optimizer_state_bytes': optimizer_state, 'data_bytes': data,
'activation_bytes_heuristic': activations_estimate,
'subtotal_bytes': subtotal, 'cushion_bytes': cushion,
'estimated_bytes': subtotal + cushion}
if not torch.cuda.is_available():
raise RuntimeError('se necesita CUDA para la medición')
torch.set_num_threads(1)
torch.backends.cuda.matmul.allow_tf32 = False
torch.manual_seed(123)
torch.cuda.manual_seed_all(123)
device = torch.device('cuda')
print('device:', torch.cuda.get_device_name(device), flush=True)
widths = [256, 512, 1024] if short else [256, 512, 1024, 2048, 4096, 8192]
batches = [32, 128, 512] if short else [32, 64, 128, 256, 512, 1024, 2048, 4096]
warmup = 2 if short else 5
repeats = 4 if short else 20
results = []
for h in widths:
for batch in batches:
n, biases, flops, matrix_flops = counts(h, batch)
free, total = torch.cuda.mem_get_info(device)
budget = memory_budget(h, batch)
# Heurística: kernels, caché y otros procesos pueden cambiar el pico real.
if budget['estimated_bytes'] > free*0.6:
print('omitido por memoria libre', h, batch, free, json.dumps(budget), flush=True)
continue
model = nn.Sequential(nn.Linear(784, h), nn.ReLU(), nn.Linear(h, h),
nn.ReLU(), nn.Linear(h, 10)).to(device)
opt = torch.optim.SGD(model.parameters(), lr=0.001)
X = torch.randn(batch, 784, device=device)
y = torch.randint(0, 10, (batch,), device=device)
def step():
opt.zero_grad(set_to_none=True)
loss = nn.functional.cross_entropy(model(X), y)
loss.backward()
opt.step()
for _ in range(warmup): step()
torch.cuda.synchronize(device)
torch.cuda.reset_peak_memory_stats(device)
begin = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
begin.record()
for _ in range(repeats): step()
end.record()
end.synchronize()
seconds = begin.elapsed_time(end)/1000/repeats
peak = torch.cuda.max_memory_allocated(device)
matrix_tflops = matrix_flops/seconds/1e12
result = {'h': h, 'batch': batch, 'weights': n, 'biases': biases, 'seconds': seconds,
'samples_per_second': batch/seconds, 'flops_approx': flops,
'matrix_flops_without_input_gradient': matrix_flops,
'matrix_tflops_without_input_gradient': matrix_tflops,
'memory_budget_heuristic': budget,
'peak_allocated_bytes': peak}
if supplied_peak is not None:
# Cociente aproximado, no contador real de FLOPs ni utilización medida.
result['peak_tflops_supplied'] = supplied_peak
result['matrix_flops_fraction_of_supplied_peak_approx'] = matrix_tflops/supplied_peak
results.append(result)
print(json.dumps(result), flush=True)
del model, opt, X, y, begin, end
gc.collect()
torch.cuda.empty_cache()npm run lab and open the connection link.Exercises
import numpy as np
def compare_grads(model_ref, model_test, rtol, atol):
passAfter solving the numerical exercises, check the calculations and assumptions with this cell. Classification by intensity uses only the given crossover, not a measurement of the bottleneck.
N = 784*4096 + 4096*4096 + 4096*10
flops = 6*512*N
print('pesos, FLOPs y milisegundos a 20 TFLOP/s:', N, flops, flops/(20e12)*1000)
for B in (16, 2048):
arithmetic = 2*B*1024*1024
traffic = 2*(B*1024 + 1024*1024 + B*1024)
print('lote e intensidad en FLOPs/byte:', B, arithmetic/traffic)Compare weights, activations, and gradients before attributing a discrepancy to precision. CUDA timing requires synchronization, and and the roofline are models with assumptions, not exact counters. A reproducible template also saves optimizer state and relevant generator states.