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
Tensorin 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
deviceand/or cast it todtypein place, so optimizers keep their references.
Source code in stackgrad/module.py
12 13 | |
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 | |
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 | |
parameters
¤
parameters()
Collect every trainable Tensor in this module and its children.
Source code in stackgrad/module.py
28 29 30 | |
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 | |
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 | |
Sequential
¤
Sequential(*layers)
Bases: Module
Chain modules so the output of each feeds the next.
Source code in stackgrad/module.py
113 114 115 | |
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 | |
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 | |
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 | |
Flatten
¤
Flatten()
Bases: Module
Flatten all dims except the batch dim into one.
Source code in stackgrad/module.py
12 13 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
reserve
¤
reserve(T)
Grows the buffers to fit T more positions.
Source code in stackgrad/attention.py
42 43 44 45 46 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
project
¤
project(h)
Hidden states -> logits, through the head or the tied embedding table.
Source code in stackgrad/gpt.py
122 123 124 | |
Activations¤
ReLU
¤
ReLU()
Bases: Module
Rectified linear unit, max(0, x).
Source code in stackgrad/module.py
12 13 | |
Sigmoid
¤
Sigmoid()
Bases: Module
Logistic sigmoid, 1 / (1 + e**-x).
Source code in stackgrad/module.py
12 13 | |
Tanh
¤
Tanh()
Bases: Module
Hyperbolic tangent.
Source code in stackgrad/module.py
12 13 | |
GELU
¤
GELU()
Softmax
¤
Softmax(axis=-1)
Bases: Module
Softmax over axis, turning logits into a probability distribution.
Source code in stackgrad/layers.py
63 64 65 | |
Functional¤
Functions:
-
gelu–Gaussian error linear unit (tanh approximation, as in GPT-2).
-
log_softmax–Log of softmax over
axis. More stable thansoftmax(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 soexpcannot overflow. -
tanh–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 | |
bce_loss
¤
bce_loss(input, target)
Binary cross-entropy on probabilities, not logits.
Source code in stackgrad/loss.py
14 15 16 17 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
Load/Save¤
load_safetensors
¤
load_safetensors(path)
Source code in stackgrad/state.py
8 9 | |
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 | |
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 | |
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 | |
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 | |