Skip to content

nn (Neural Networks)

Module¤

Module ¤

Module()

Base class for layers and models; Tensor and Module attributes are found by parameters() and state_dict().

Methods:

  • load –

    Load parameters from a .npz file written by save(); fails if any name or shape differs.

  • named_parameters –

    (dotted name, tensor) for every trainable tensor, named as in state_dict().

  • parameters –

    Collect every trainable Tensor in this module and its children.

  • save –

    Write all parameters to a .npz file through a temp file and rename, so a crash keeps the old one.

  • to –

    Move every tensor to device and/or cast it to dtype in place, so optimizers keep their references.

Source code in stackgrad/module.py
12
13
def __init__(self):
  self._training = True

load ¤

load(path)

Load parameters from a .npz file written by save(); fails if any name or shape differs.

Source code in stackgrad/module.py
74
75
76
77
78
79
80
81
82
def load(self, path):
  """Load parameters from a .npz file written by save(); fails if any name or shape differs."""
  with np.load(path) as data:
    state = {k: data[k] for k in data.files}
  expected = {k: v.shape for k, v in self.state_dict().items()}
  got = {k: v.shape for k, v in state.items()}
  assert got == expected, f"{path} does not match this model: {sorted(set(got) ^ set(expected))[:4] or 'shapes differ'}"
  self.load_state_dict(state)
  return self

named_parameters ¤

named_parameters(prefix='')

(dotted name, tensor) for every trainable tensor, named as in state_dict().

Source code in stackgrad/module.py
32
33
34
35
36
37
38
def named_parameters(self, prefix=""):
  """(dotted name, tensor) for every trainable tensor, named as in state_dict()."""
  for name, val in self._attrs():
    if isinstance(val, Tensor) and val.requires_grad:
      yield prefix + name, val
    elif isinstance(val, Module):
      yield from val.named_parameters(f"{prefix}{name}.")

parameters ¤

parameters()

Collect every trainable Tensor in this module and its children.

Source code in stackgrad/module.py
28
29
30
def parameters(self):
  """Collect every trainable `Tensor` in this module and its children."""
  return list({id(p): p for _, p in self.named_parameters()}.values())  # tied weights must not step twice

save ¤

save(path)

Write all parameters to a .npz file through a temp file and rename, so a crash keeps the old one.

Source code in stackgrad/module.py
67
68
69
70
71
72
def save(self, path):
  """Write all parameters to a .npz file through a temp file and rename, so a crash keeps the old one."""
  path = Path(path)
  tmp = path.with_name(path.name + ".tmp.npz")  # savez appends .npz to a name without it
  np.savez(tmp, **self.state_dict())
  os.replace(tmp, path)

to ¤

to(device=None, dtype=None)

Move every tensor to device and/or cast it to dtype in place, so optimizers keep their references.

Source code in stackgrad/module.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def to(self, device=None, dtype=None):
  """Move every tensor to `device` and/or cast it to `dtype` in place, so optimizers keep their references."""
  moved = []
  for val in self.__dict__.values():
    items = val if isinstance(val, (list, tuple)) else [val]
    for item in items:
      if isinstance(item, Tensor):
        copy = item.to(device, dtype)
        item.data, item.device, item.grad = copy.data, copy.device, None
        moved.append(item)
      elif isinstance(item, Module):
        item.to(device, dtype)
  # realize now: a lazy MLX cast is tied to this thread's stream, and the serving engine runs on another
  for t in moved:
    backend.get(t.device).realize(t.data)
  return self

Sequential ¤

Sequential(*layers)

Bases: Module

Chain modules so the output of each feeds the next.

Source code in stackgrad/module.py
113
114
115
def __init__(self, *layers):
  super().__init__()
  self.layers = list(layers)

Neural Network classes¤

Linear ¤

Linear(
  in_features, out_features, bias=True, init="kaiming"
)

Bases: Module

Fully-connected layer y = x @ W + b over the last dim, Kaiming init by default (init='xavier').

Source code in stackgrad/layers.py
19
20
21
22
23
24
25
26
27
def __init__(self, in_features, out_features, bias=True, init='kaiming'):
  super().__init__()
  assert in_features > 0 and out_features > 0, "features must be positive"
  if init == 'xavier':
    scale = np.sqrt(2.0 / (in_features + out_features))
  else:
    scale = np.sqrt(2.0 / in_features)
  self.weight = Tensor(normal((in_features, out_features), scale), requires_grad=True)
  self.bias = Tensor(np.zeros(out_features, np.float32), requires_grad=True) if bias else None

Conv2d ¤

Conv2d(
  in_channels,
  out_channels,
  kernel_size,
  stride=1,
  padding=0,
)

Bases: Module

2D convolution over (N, C, H, W) input, implemented with im2col.

Source code in stackgrad/conv.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0):
  super().__init__()
  assert in_channels > 0 and out_channels > 0, "channels must be positive"
  self.in_channels = in_channels
  self.out_channels = out_channels
  self.kernel_size = kernel_size if isinstance(kernel_size, tuple) else (kernel_size, kernel_size)
  self.stride = stride
  self.padding = padding

  kh, kw = self.kernel_size
  assert kh > 0 and kw > 0, "kernel_size must be positive"
  fan_in = in_channels * kh * kw
  scale = np.sqrt(2.0 / fan_in)
  self.weight = Tensor(normal((out_channels, in_channels * kh * kw), scale), requires_grad=True)
  self.bias = Tensor(np.zeros(out_channels, dtype=np.float32), requires_grad=True)

MaxPool2d ¤

MaxPool2d(kernel_size, stride=None)

Bases: Module

Max pooling over (N, C, H, W) input: im2col, then max over each patch.

Source code in stackgrad/conv.py
40
41
42
43
def __init__(self, kernel_size, stride=None):
  super().__init__()
  self.kernel_size = kernel_size if isinstance(kernel_size, tuple) else (kernel_size, kernel_size)
  self.stride = stride if stride is not None else self.kernel_size[0]

Flatten ¤

Flatten()

Bases: Module

Flatten all dims except the batch dim into one.

Source code in stackgrad/module.py
12
13
def __init__(self):
  self._training = True

Embedding ¤

Embedding(num_embeddings, embed_dim)

Bases: Module

Lookup table mapping integer ids to dense vectors.

Source code in stackgrad/layers.py
114
115
116
117
def __init__(self, num_embeddings, embed_dim):
  super().__init__()
  assert num_embeddings > 0 and embed_dim > 0, "sizes must be positive"
  self.weight = Tensor(normal((num_embeddings, embed_dim), 0.02), requires_grad=True)

LayerNorm ¤

LayerNorm(num_features, eps=1e-05)

Bases: Module

Normalize over the last dimension of any (..., num_features) input.

Source code in stackgrad/layers.py
78
79
80
81
82
83
def __init__(self, num_features, eps=1e-5):
  super().__init__()
  assert num_features > 0, "num_features must be positive"
  self.gamma = Tensor(np.ones(num_features, dtype=np.float32), requires_grad=True)
  self.beta = Tensor(np.zeros(num_features, dtype=np.float32), requires_grad=True)
  self.eps = eps

RMSNorm ¤

RMSNorm(num_features, eps=1e-05)

Bases: Module

Divide each vector by its root-mean-square, then scale. LayerNorm without the mean and bias.

Source code in stackgrad/layers.py
172
173
174
175
def __init__(self, num_features, eps=1e-5):
  super().__init__()
  self.weight = Tensor(np.ones(num_features, dtype=np.float32), requires_grad=True)
  self.eps = eps

GroupNorm ¤

GroupNorm(num_groups, num_channels, eps=1e-05)

Bases: Module

Normalize each group of channels of an (N, C, ...) input, then scale and shift each channel.

Source code in stackgrad/layers.py
 96
 97
 98
 99
100
101
def __init__(self, num_groups, num_channels, eps=1e-5):
  super().__init__()
  assert num_channels % num_groups == 0, "channels must split evenly into groups"
  self.num_groups, self.eps = num_groups, eps
  self.weight = Tensor(np.ones(num_channels, dtype=np.float32), requires_grad=True)
  self.bias = Tensor(np.zeros(num_channels, dtype=np.float32), requires_grad=True)

BatchNorm1d ¤

BatchNorm1d(num_features, eps=1e-05, momentum=0.1)

Bases: Module

Normalize a (batch, features) input per feature, tracking running stats for eval.

Source code in stackgrad/layers.py
139
140
141
142
143
144
145
146
147
def __init__(self, num_features, eps=1e-5, momentum=0.1):
  super().__init__()
  assert num_features > 0, "num_features must be positive"
  self.gamma = Tensor(np.ones(num_features, dtype=np.float32), requires_grad=True)
  self.beta = Tensor(np.zeros(num_features, dtype=np.float32), requires_grad=True)
  self.eps = eps
  self.momentum = momentum
  self.running_mean = np.zeros(num_features, dtype=np.float32)
  self.running_var = np.ones(num_features, dtype=np.float32)

Dropout ¤

Dropout(p=0.5)

Bases: Module

Zero each activation with probability p during training, scaling the rest; a no-op in eval.

Source code in stackgrad/layers.py
125
126
127
128
def __init__(self, p=0.5):
  super().__init__()
  assert 0.0 <= p < 1.0, "dropout probability must be in [0, 1)"
  self.p = p

SwiGLU ¤

SwiGLU(d_model, d_ff)

Bases: Module

Gated feed-forward from Llama and Qwen: w2(silu(w1 x) * w3 x), no biases.

Source code in stackgrad/layers.py
207
208
209
210
211
def __init__(self, d_model, d_ff):
  super().__init__()
  self.w1 = Linear(d_model, d_ff, bias=False)
  self.w2 = Linear(d_ff, d_model, bias=False)
  self.w3 = Linear(d_model, d_ff, bias=False)

Attention ¤

Attention(
  d_model,
  n_heads,
  n_kv_heads=None,
  rope_theta=10000.0,
  head_dim=None,
  qk_norm=False,
  norm_eps=1e-05,
  rope=True,
)

Bases: Module

Multi-head attention with RoPE and grouped-query heads; qk_norm adds Qwen3's per-head RMSNorm on q, k.

Source code in stackgrad/attention.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def __init__(self, d_model, n_heads, n_kv_heads=None, rope_theta=10000.0, head_dim=None, qk_norm=False, norm_eps=1e-5,
             rope=True):
  super().__init__()
  self.rope = rope  # False is the NoPE ablation: causal masking alone orders tokens
  self.n_heads = n_heads
  self.n_kv_heads = n_kv_heads or n_heads
  self.head_dim = head_dim or d_model // n_heads
  self.rope_theta = rope_theta
  self.q_proj = Linear(d_model, n_heads * self.head_dim, bias=False)
  self.k_proj = Linear(d_model, self.n_kv_heads * self.head_dim, bias=False)
  self.v_proj = Linear(d_model, self.n_kv_heads * self.head_dim, bias=False)
  self.o_proj = Linear(n_heads * self.head_dim, d_model, bias=False)
  self.q_norm = RMSNorm(self.head_dim, norm_eps) if qk_norm else None
  self.k_norm = RMSNorm(self.head_dim, norm_eps) if qk_norm else None
  self.record, self.recorded = False, None  # record=True keeps the last q and k, for drawing attention maps

KVCache ¤

KVCache(k=None, v=None, n=0, rope=None)

Keys and values of earlier positions, written in place into buffers that grow 256 positions at a time, so decode steps keep their shapes.

Methods:

  • reserve –

    Grows the buffers to fit T more positions.

  • update –

    Writes k, v (B, Hkv, T, D) at position n; returns the whole buffers, valid up to the new n.

Source code in stackgrad/attention.py
35
36
37
38
def __init__(self, k=None, v=None, n=0, rope=None):
  # n counts the positions written: an int, or an array inside the compiled decode step, which brings its (cos, sin) as rope;
  # trace is that step, kept on a model's first cache
  self.k, self.v, self.n, self.rope, self.trace = k, v, n, rope, None

reserve ¤

reserve(T)

Grows the buffers to fit T more positions.

Source code in stackgrad/attention.py
42
43
44
45
46
def reserve(self, T):
  """Grows the buffers to fit T more positions."""
  if self.n + T > self.k.shape[2]:
    grow = ((0, 0), (0, 0), (0, -(-(self.n + T) // 256) * 256 - self.k.shape[2]), (0, 0))
    self.k, self.v = (Tensor(backend.get(t.device).pad(t.data, grow), device=t.device) for t in (self.k, self.v))

update ¤

update(k, v)

Writes k, v (B, Hkv, T, D) at position n; returns the whole buffers, valid up to the new n.

Source code in stackgrad/attention.py
48
49
50
51
52
53
54
55
56
def update(self, k, v):
  """Writes k, v (B, Hkv, T, D) at position n; returns the whole buffers, valid up to the new n."""
  if self.k is None:
    self.k, self.v = k[:, :, :0], v[:, :, :0]  # empty, so reserve() allocates
  if self.rope is None:  # inside the compiled step n is an array, and the caller made room
    self.reserve(k.shape[2])
  self.k, self.v = _apply(mlops.Write, self.k, k, pos=self.n), _apply(mlops.Write, self.v, v, pos=self.n)
  self.n = self.n + k.shape[2]
  return self.k, self.v

TransformerLM ¤

TransformerLM(
  vocab_size,
  context_length,
  d_model,
  n_layers,
  n_heads,
  d_ff,
  n_kv_heads=None,
  rope_theta=10000.0,
  head_dim=None,
  qk_norm=False,
  norm_eps=1e-05,
  tie_embeddings=False,
  norm="pre",
  rope=True,
  ffn="swiglu",
  attn_res=False,
  attn_res_block=8,
)

Bases: Module

Decoder-only transformer LM: the CS336 model by default, Qwen3 with the options qwen3.py sets.

Methods:

  • attn_res –

    Block Attention Residuals over the embedding x: the hidden states before the final norm.

  • forward –

    idx (B, T) ints -> logits (B, T, vocab); caches is one KVCache per block, pad (B,) the left padding.

  • generate –

    Extends idx (B, T0) by up to max_new_tokens until every row emits eos_id; pad (B,) is left padding.

  • hidden –

    Final normalized hidden states (B, T, d_model): the model without the output projection.

  • project –

    Hidden states -> logits, through the head or the tied embedding table.

Source code in stackgrad/gpt.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def __init__(self, vocab_size, context_length, d_model, n_layers, n_heads, d_ff,
             n_kv_heads=None, rope_theta=10000.0, head_dim=None, qk_norm=False, norm_eps=1e-5, tie_embeddings=False,
             norm="pre", rope=True, ffn="swiglu", attn_res=False, attn_res_block=8):
  super().__init__()
  assert not attn_res or norm == "pre", "Attention Residuals is defined on pre-norm blocks"
  self.context_length = context_length
  self.attn_res_block = attn_res_block
  self.depth = [DepthAttention(d_model, norm_eps) for _ in range(2 * n_layers + 1)] if attn_res else None
  self.embed = Embedding(vocab_size, d_model)
  self.blocks = [Block(d_model, n_heads, n_kv_heads, d_ff, rope_theta, head_dim, qk_norm, norm_eps, norm, rope, ffn)
                 for _ in range(n_layers)]
  self.norm = None if norm == "none" else RMSNorm(d_model, norm_eps)  # "none" removes every RMSNorm, the final one too
  self.head = None if tie_embeddings else Linear(d_model, vocab_size, bias=False)
  self.checkpoint_blocks = False  # recompute each block in backward instead of storing its activations

  if getattr(SKIP_INIT, "on", False):  # a checkpoint will overwrite every weight
    return
  for p in self.parameters():  # CS336 init
    if p.ndim == 2:
      p.data = trunc_normal(p.shape, np.sqrt(2.0 / sum(p.shape)))
  self.embed.weight.data = trunc_normal(self.embed.weight.shape, 1.0)

attn_res ¤

attn_res(x, caches=None, pad=None)

Block Attention Residuals over the embedding x: the hidden states before the final norm.

Source code in stackgrad/gpt.py
110
111
112
113
114
115
116
117
118
119
120
def attn_res(self, x, caches=None, pad=None):
  """Block Attention Residuals over the embedding x: the hidden states before the final norm."""
  # shortcut: no activation checkpointing here; add it per block if attn_res ever trains a model too big to fit
  blocks, partial = [x], None  # finished block sums (the embedding first), and the running sum of this block
  layers = [f for i, b in enumerate(self.blocks) for f in b.sublayers(None if caches is None else caches[i], pad)]
  for i, f in enumerate(layers):
    out = f(self.depth[i](blocks if partial is None else blocks + [partial]))
    partial = out if partial is None else partial + out
    if (i + 1) % self.attn_res_block == 0:
      blocks, partial = blocks + [partial], None
  return self.depth[-1](blocks if partial is None else blocks + [partial])

forward ¤

forward(idx, caches=None, pad=None)

idx (B, T) ints -> logits (B, T, vocab); caches is one KVCache per block, pad (B,) the left padding.

Source code in stackgrad/gpt.py
70
71
72
def forward(self, idx, caches=None, pad=None):
  """idx (B, T) ints -> logits (B, T, vocab); caches is one KVCache per block, pad (B,) the left padding."""
  return self.project(self.hidden(idx, caches, pad))

generate ¤

generate(
  idx,
  max_new_tokens,
  temperature=1.0,
  top_k=None,
  top_p=None,
  eos_id=None,
  pad=None,
)

Extends idx (B, T0) by up to max_new_tokens until every row emits eos_id; pad (B,) is left padding.

Source code in stackgrad/gpt.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None, top_p=None, eos_id=None, pad=None):
  """Extends idx (B, T0) by up to max_new_tokens until every row emits eos_id; pad (B,) is left padding."""
  idx = np.asarray(idx)
  assert idx.shape[1] + max_new_tokens <= self.context_length, "prompt + new tokens exceed context_length"
  caches = [KVCache() for _ in self.blocks]
  done = np.zeros(len(idx), dtype=bool)
  with no_grad():
    logits = self.project(self.hidden(idx, caches, pad)[:, -1])
    for _ in range(max_new_tokens):
      if top_k is None and top_p is None:
        next_id = sample_on_device(logits, temperature)
      else:
        next_id = sample(logits.numpy(), temperature, top_k, top_p)
      idx = np.concatenate([idx, next_id[:, None]], axis=1)
      if eos_id is not None:
        done |= next_id == eos_id
        if done.all():
          break
      logits = self.project(self.hidden(next_id[:, None], caches, pad)[:, -1])
  return idx

hidden ¤

hidden(idx, caches=None, pad=None)

Final normalized hidden states (B, T, d_model): the model without the output projection.

Source code in stackgrad/gpt.py
74
75
76
77
78
79
def hidden(self, idx, caches=None, pad=None):
  """Final normalized hidden states (B, T, d_model): the model without the output projection."""
  x = self.embed(idx)
  if getattr(backend.get(x.device), "capture", None) and caches and caches[0].n and pad is None and not grad_enabled():
    return self._decode(x, caches)
  return self._layers(x, caches, pad)

project ¤

project(h)

Hidden states -> logits, through the head or the tied embedding table.

Source code in stackgrad/gpt.py
122
123
124
def project(self, h):
  """Hidden states -> logits, through the head or the tied embedding table."""
  return self.head(h) if self.head is not None else h @ self.embed.weight.T

Activations¤

ReLU ¤

ReLU()

Bases: Module

Rectified linear unit, max(0, x).

Source code in stackgrad/module.py
12
13
def __init__(self):
  self._training = True

Sigmoid ¤

Sigmoid()

Bases: Module

Logistic sigmoid, 1 / (1 + e**-x).

Source code in stackgrad/module.py
12
13
def __init__(self):
  self._training = True

Tanh ¤

Tanh()

Bases: Module

Hyperbolic tangent.

Source code in stackgrad/module.py
12
13
def __init__(self):
  self._training = True

GELU ¤

GELU()

Bases: Module

Source code in stackgrad/module.py
12
13
def __init__(self):
  self._training = True

Softmax ¤

Softmax(axis=-1)

Bases: Module

Softmax over axis, turning logits into a probability distribution.

Source code in stackgrad/layers.py
63
64
65
def __init__(self, axis=-1):
  super().__init__()
  self.axis = axis

Functional¤

Functions:

  • gelu –

    Gaussian error linear unit (tanh approximation, as in GPT-2).

  • log_softmax –

    Log of softmax over axis. More stable than softmax(x).log().

  • relu –

    Rectified linear unit, max(0, x).

  • sigmoid –

    Logistic sigmoid, 1 / (1 + e**-x).

  • silu –

    x * sigmoid(x), the gate activation in SwiGLU.

  • softmax –

    Softmax over axis, max-subtracted so exp cannot overflow.

  • tanh –

    Hyperbolic tangent.

gelu ¤

gelu(x)

Gaussian error linear unit (tanh approximation, as in GPT-2).

log_softmax ¤

log_softmax(x, axis=-1)

Log of softmax over axis. More stable than softmax(x).log().

relu ¤

relu(x)

Rectified linear unit, max(0, x).

sigmoid ¤

sigmoid(x)

Logistic sigmoid, 1 / (1 + e**-x).

silu ¤

silu(x)

x * sigmoid(x), the gate activation in SwiGLU.

softmax ¤

softmax(x, axis=-1)

Softmax over axis, max-subtracted so exp cannot overflow.

tanh ¤

tanh(x)

Hyperbolic tangent.

Loss Functions¤

mse_loss ¤

mse_loss(input, target)

Mean squared error between predictions and targets.

Source code in stackgrad/loss.py
 9
10
11
def mse_loss(input, target):
  """Mean squared error between predictions and targets."""
  return ((input - target) ** 2).mean()

bce_loss ¤

bce_loss(input, target)

Binary cross-entropy on probabilities, not logits.

Source code in stackgrad/loss.py
14
15
16
17
def bce_loss(input, target):
  """Binary cross-entropy on probabilities, not logits."""
  p = input.clamp(1e-7, 1 - 1e-7)
  return -(target * p.log() + (1.0 - target) * (1.0 - p).log()).mean()

cross_entropy_loss ¤

cross_entropy_loss(input, target)

Softmax cross-entropy over the last axis; target holds class indices or one-hot rows.

Source code in stackgrad/loss.py
20
21
22
23
24
25
26
27
28
def cross_entropy_loss(input, target):
  """Softmax cross-entropy over the last axis; `target` holds class indices or one-hot rows."""
  log_probs = F.log_softmax(input, axis=-1)
  labels = target.numpy() if isinstance(target, Tensor) else np.asarray(target)
  if labels.shape == input.shape:
    return -(log_probs * target).sum() / (math.prod(input.shape) // input.shape[-1])
  labels = labels.reshape(-1).astype(np.int64)
  log_probs = log_probs.reshape(-1, input.shape[-1])
  return -log_probs[np.arange(len(labels)), labels].mean()

Optimizers¤

SGD ¤

SGD(params, lr=0.001, momentum=0.0, weight_decay=0.0)

Bases: Optimizer

Stochastic gradient descent with optional momentum and weight decay.

Source code in stackgrad/optim.py
26
27
28
29
def __init__(self, params, lr=1e-3, momentum=0.0, weight_decay=0.0):
  super().__init__(params, lr, weight_decay)
  self.momentum = momentum
  self.velocities = [0.0] * len(self.params)  # a scalar 0 broadcasts on any backend

Adam ¤

Adam(
  params,
  lr=0.001,
  betas=(0.9, 0.999),
  eps=1e-08,
  weight_decay=0.0,
)

Bases: Optimizer

Adam optimizer with bias-corrected first and second moment estimates.

Source code in stackgrad/optim.py
45
46
47
48
49
50
51
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.0):
  super().__init__(params, lr, weight_decay)
  self.beta1, self.beta2 = betas
  self.eps = eps
  self.t = 0
  self.m = [0.0] * len(self.params)  # a scalar 0 broadcasts on any backend
  self.v = [0.0] * len(self.params)

AdamW ¤

AdamW(
  params,
  lr=0.001,
  betas=(0.9, 0.999),
  eps=1e-08,
  weight_decay=0.01,
)

Bases: Adam

Adam with decoupled weight decay: shrink the weights instead of adding wd * p to the gradient.

Source code in stackgrad/optim.py
71
72
73
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.01):
  super().__init__(params, lr, betas, eps, weight_decay=0.0)
  self.decay = weight_decay

cosine_lr ¤

cosine_lr(step, max_lr, min_lr, warmup_steps, total_steps)

Linear warmup to max_lr, cosine decay to min_lr at total_steps, then flat.

Source code in stackgrad/optim.py
82
83
84
85
86
87
88
89
def cosine_lr(step, max_lr, min_lr, warmup_steps, total_steps):
  """Linear warmup to max_lr, cosine decay to min_lr at total_steps, then flat."""
  if step < warmup_steps:
    return max_lr * step / warmup_steps
  if step > total_steps:
    return min_lr
  progress = (step - warmup_steps) / max(total_steps - warmup_steps, 1)  # warmup == total: the last step is the peak
  return min_lr + 0.5 * (1 + math.cos(math.pi * progress)) * (max_lr - min_lr)

clip_grad_norm ¤

clip_grad_norm(params, max_norm)

Clip gradient norm across all parameters (like torch.nn.utils.clip_grad_norm_).

Source code in stackgrad/optim.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def clip_grad_norm(params, max_norm):
  """Clip gradient norm across all parameters (like torch.nn.utils.clip_grad_norm_)."""
  # one device sum and one host sync, not one per parameter
  total_norm = float(sum((p.grad * p.grad).sum() for p in params if p.grad is not None)) ** 0.5
  if total_norm > max_norm:
    scale = max_norm / (total_norm + 1e-12)
    for p in params:
      if p.grad is not None:
        p.grad = p.grad * scale
  return total_norm

LossScaler ¤

LossScaler(scale=2.0 ** 15, interval=1000)

Dynamic loss scaling for autocast("float16"): halve on overflow, double after interval clean steps.

Methods:

  • unscale –

    Divide every gradient by the scale. Returns False, and halves the scale, if any of them overflowed.

Source code in stackgrad/optim.py
106
107
def __init__(self, scale=2.0 ** 15, interval=1000):
  self.scale, self.interval, self.clean = scale, interval, 0

unscale ¤

unscale(params)

Divide every gradient by the scale. Returns False, and halves the scale, if any of them overflowed.

Source code in stackgrad/optim.py
109
110
111
112
113
114
115
116
117
118
119
120
121
def unscale(self, params):
  """Divide every gradient by the scale. Returns False, and halves the scale, if any of them overflowed."""
  total = float(sum((p.grad * p.grad).sum() for p in params if p.grad is not None))
  if not math.isfinite(total):
    self.scale, self.clean = self.scale / 2, 0
    return False
  for p in params:
    if p.grad is not None:
      p.grad = p.grad / self.scale
  self.clean += 1
  if self.clean % self.interval == 0:
    self.scale *= 2
  return True

Load/Save¤

load_safetensors ¤

load_safetensors(path)
Source code in stackgrad/state.py
8
9
def load_safetensors(path):
  return dict(iter_safetensors(path))

iter_safetensors ¤

iter_safetensors(path)
Source code in stackgrad/state.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def iter_safetensors(path):
  with open(path, "rb") as f:
    n = int.from_bytes(f.read(8), "little")
    header = json.loads(f.read(n))
  raw = np.memmap(path, dtype=np.uint8, mode="r", offset=8 + n)
  for name, info in header.items():
    if name == "__metadata__":
      continue
    start, end = info["data_offsets"]
    b = raw[start:end]
    if info["dtype"] == "BF16":
      # bf16 is the top half of an f32, so shifting its bits up 16 rebuilds the f32 exactly
      arr = (b.view(np.uint16).astype(np.uint32) << 16).view(np.float32)
    else:
      arr = np.array(b.view(_DTYPES[info["dtype"]]))
    yield name, arr.reshape(info["shape"])

Module.save, Module.load, Module.state_dict, and Module.load_state_dict are listed under Module.

Data¤

DataLoader ¤

DataLoader(
  x, y, batch_size=32, shuffle=True, drop_last=False
)

Iterate over (x, y) in mini-batches, optionally shuffling each epoch.

Source code in stackgrad/data.py
 6
 7
 8
 9
10
11
12
def __init__(self, x, y, batch_size=32, shuffle=True, drop_last=False):
  self.x = x
  self.y = y
  self.batch_size = batch_size
  self.shuffle = shuffle
  self.drop_last = drop_last
  self.n = x.shape[0]

Gradient checking¤

numerical_gradient ¤

numerical_gradient(f, inputs, eps=1e-05)

Estimate gradients of f w.r.t. each input by central differences.

Source code in stackgrad/grad_check.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def numerical_gradient(f, inputs, eps=1e-5):
  """Estimate gradients of `f` w.r.t. each input by central differences."""
  grads = []
  # perturb in float64 for precision
  orig_data = [inp.data.copy() for inp in inputs]
  for inp in inputs:
    inp.data = inp.data.astype(np.float64)
  f64_data = [inp.data.copy() for inp in inputs]

  for k, inp in enumerate(inputs):
    grad = np.zeros(inp.data.shape, dtype=np.float64)
    it = np.nditer(f64_data[k], flags=['multi_index'])
    while not it.finished:
      idx = it.multi_index
      old_val = f64_data[k][idx]

      inp.data = f64_data[k].copy()
      inp.data[idx] = old_val + eps
      loss_plus = float(f().data)

      inp.data = f64_data[k].copy()
      inp.data[idx] = old_val - eps
      loss_minus = float(f().data)

      grad[idx] = (loss_plus - loss_minus) / (2 * eps)
      it.iternext()
    inp.data = f64_data[k].copy()
    grads.append(grad.astype(np.float32))

  for inp, od in zip(inputs, orig_data):
    inp.data = od
  return grads

check_gradient ¤

check_gradient(
  f, inputs, eps=1e-05, atol=0.0001, rtol=0.001
)

Compare backward() gradients against numerical ones, raising AssertionError past the tolerance.

Source code in stackgrad/grad_check.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def check_gradient(f, inputs, eps=1e-5, atol=1e-4, rtol=1e-3):
  """Compare backward() gradients against numerical ones, raising AssertionError past the tolerance."""
  for inp in inputs:
    inp.zero_grad()
  loss = f()
  loss.backward()
  analytic = [inp.grad.copy() for inp in inputs]

  numerical = numerical_gradient(f, inputs, eps)

  for i, (a, n) in enumerate(zip(analytic, numerical)):
    if not np.allclose(a, n, atol=atol, rtol=rtol):
      max_diff = np.max(np.abs(a - n))
      raise AssertionError(
          f"Gradient check failed for input {i}: max diff = {max_diff}\n"
          f"Analytic:\n{a}\nNumerical:\n{n}"
      )
  return True