Networks¶
Complete networks written in HNDL, from examples/networks/. Each entry is resolved from its
declared contract; the shape tables and parameter counts below are generated by python -m hndl.docs.
Fully connected autoencoder¶
Compress a 28×28 image through a 32-unit bottleneck and reconstruct it. The decoder's final width is inferred from the reshape target and the output contract.
examples/networks/autoencoder.hndl
# A fully connected autoencoder for 28×28 grayscale images (MNIST-sized).
# The image is flattened to 784 values, squeezed through a 32-unit bottleneck,
# and reconstructed back into the same [B, 1, 28, 28] shape.
# Encoder: 784 -> 128 -> 32.
flatten()
linear(128)
relu()
linear(32, name="code") # The bottleneck; model["code"] is the 32-unit layer.
relu()
# Decoder: 32 -> 128 -> 784. The final width is inferred from the reshape
# target, which the output contract fixes at 1·28·28 = 784.
linear(128)
relu()
linear(name="reconstruction")
sigmoid() # Pixels in (0, 1), matching normalized inputs.
reshape(1, 28, 28)
Input ['B', 1, 28, 28] → output ['B', 1, 28, 28].
Network: [B, 1, 28, 28] -> [B, 1, 28, 28] dtype=float32
index name operation input shape output shape
0 n0 flatten [B, 1, 28, 28] [B, 784]
1 n1 linear [B, 784] [B, 128]
2 n2 relu [B, 128] [B, 128]
3 code linear [B, 128] [B, 32]
4 n4 relu [B, 32] [B, 32]
5 n5 linear [B, 32] [B, 128]
6 n6 relu [B, 128] [B, 128]
7 reconstruction linear [B, 128] [B, 784]
8 n8 sigmoid [B, 784] [B, 784]
9 n9 reshape [B, 784] [B, 1, 28, 28]
Parameters: 209,968. Classic MNIST autoencoder with a 784-128-32-128-784 stack; 784·128+128 + 128·32+32 + 32·128+128 + 128·784+784 = 209,968 parameters, cross-checked against the equivalent torch.nn.Sequential.
Tiny CLIP Dual-Encoder Vision-Language Model¶
A multimodal dual-encoder aligning vision and text representations: convolutional patch stem with cls_token and ViT block for images, learned embedding and causal transformer block with gather_token for text, QuickGELU projection heads, L2 normalization, and scaled dot-product similarity.
examples/networks/clip_dual_encoder_tiny.hndl
# Tiny CLIP dual-encoder model: convolutional visual stem with class token and
# vision transformer, text transformer with end-of-text token gathering, QuickGELU
# projection heads, L2 normalization, matrix multiplication, and scale.
img = conv(image, 32, kernel_size=4, stride=4, name="img_stem")
img = reshape(img, 32, 64)
img = transpose(img, 1, 2)
img = cls_token(img, name="img_cls")
img = pos_embed(img, 65, name="img_pos")
img = transformer_block(img, 4, name="img_block")
img_cls = pool_tokens(img, mode="first")
img_proj = linear(img_cls, 64, bias=False, name="img_proj")
img_act = quick_gelu(img_proj)
img_norm = l2_norm(img_act, dim=-1, name="img_norm")
txt = embedding(text, 256, 64, name="text_emb")
txt = pos_embed(txt, 16, name="text_pos")
txt = transformer_block(txt, 4, name="text_block")
txt_eos = gather_token(txt, text, name="text_gather")
txt_proj = linear(txt_eos, 64, bias=False, name="text_proj")
txt_act = quick_gelu(txt_proj)
txt_norm = l2_norm(txt_act, dim=-1, name="text_norm")
img_v = reshape(img_norm, 1, 64)
txt_v = reshape(txt_norm, 64, 1)
sim = matmul(img_v, txt_v)
sim = scale(sim, 14.28)
output = reshape(sim, 1)
Input image=['B', 3, 32, 32], text=['B', 16] (input_dtype="{'text': 'int64'}") → output ['B', 1].
Network: image=[B, 3, 32, 32], text=[B, 16] -> [B, 1] dtype=float32 input_dtype=text=int64
name operation input shapes output shapes
img_stem conv x=input:image:[B, 3, 32, 32] out=[B, 32, 8, 8]
n1 reshape x=node:img_stem/out:[B, 32, 8, 8] out=[B, 32, 64]
n2 transpose x=node:n1/out:[B, 32, 64] out=[B, 64, 32]
img_cls cls_token x=node:n2/out:[B, 64, 32] out=[B, 65, 32]
img_pos pos_embed x=node:img_cls/out:[B, 65, 32] out=[B, 65, 32]
img_block transformer_block x=node:img_pos/out:[B, 65, 32] out=[B, 65, 32]
n6 pool_tokens x=node:img_block/out:[B, 65, 32] out=[B, 32]
img_proj linear x=node:n6/out:[B, 32] out=[B, 64]
n8 quick_gelu x=node:img_proj/out:[B, 64] out=[B, 64]
img_norm l2_norm x=node:n8/out:[B, 64] out=[B, 64]
text_emb embedding ids=input:text:[B, 16] out=[B, 16, 64]
text_pos pos_embed x=node:text_emb/out:[B, 16, 64] out=[B, 16, 64]
text_block transformer_block x=node:text_pos/out:[B, 16, 64] out=[B, 16, 64]
text_gather gather_token x=node:text_block/out:[B, 16, 64], ids=input:text:[B, 16] out=[B, 64]
text_proj linear x=node:text_gather/out:[B, 64] out=[B, 64]
n15 quick_gelu x=node:text_proj/out:[B, 64] out=[B, 64]
text_norm l2_norm x=node:n15/out:[B, 64] out=[B, 64]
n17 reshape x=node:img_norm/out:[B, 64] out=[B, 1, 64]
n18 reshape x=node:text_norm/out:[B, 64] out=[B, 64, 1]
n19 matmul a=node:n17/out:[B, 1, 64], b=node:n18/out:[B, 64, 1] out=[B, 1, 1]
n20 scale x=node:n19/out:[B, 1, 1] out=[B, 1, 1]
n21 reshape x=node:n20/out:[B, 1, 1] out=[B, 1]
Parameters: 89,920. Architecture follows Radford et al. 2021, "Learning Transferable Visual Models From Natural Language Supervision" (CLIP, arXiv:2103.00020); parameter count checked against plain PyTorch: vision (img_stem 1,568, img_cls 32, img_pos 2,080, img_block 12,704, img_proj 2,048; vision total = 18,432) + text (text_emb 16,384, text_pos 1,024, text_block 49,984, text_proj 4,096; text total = 71,488); total checked via model.parameters() = 89,920.
Conditional GAN discriminator¶
A conditional discriminator with two named inputs and two named outputs. The one-hot label y is projected onto a 28×28 plane and stacked on the image x as a second channel; two "down2" convolutions reduce the result to a 128×7×7 map. The flattened map is published as features for a feature-matching loss, and the head produces raw logits — apply a sigmoid, or use BCEWithLogitsLoss, in the loss rather than in the network.
examples/networks/conditional_discriminator.hndl
# A conditional GAN discriminator for 28x28 grayscale digits. It takes two
# external inputs: the image "x" and a one-hot class label "y".
# Project the label onto its own 28x28 plane and stack it on the image as an
# extra channel, the usual conditional-GAN trick.
plane = linear(y, 784, name="label_projection")
label = reshape(plane, 1, 28, 28, name="label_plane")
concat(x, label, name="conditioned") # [B, 2, 28, 28]
# Two strided convolutions halve the image: 28 -> 14 -> 7.
conv(64, policy="down2", name="stage1")
leaky_relu(0.2)
conv(128, policy="down2", bias=False, name="stage2")
batch_norm()
leaky_relu(0.2)
# Both public outputs are named: the 128x7x7 map flattened into "features",
# which a feature-matching loss can read, and the real/fake "logits".
features = flatten(name="features")
logits = linear(1, name="logits")
Input x=['B', 1, 28, 28], y=['B', 10] → output logits=['B', 1], features=['B', 6272].
Network: x=[B, 1, 28, 28], y=[B, 10] -> logits=[B, 1], features=[B, 6272] dtype=float32
name operation input shapes output shapes
label_projection linear x=input:y:[B, 10] out=[B, 784]
label_plane reshape x=node:label_projection/out:[B, 784] out=[B, 1, 28, 28]
conditioned concat x0=input:x:[B, 1, 28, 28], x1=node:label_plane/out:[B, 1, 28, 28] out=[B, 2, 28, 28]
stage1 conv x=node:conditioned/out:[B, 2, 28, 28] out=[B, 64, 14, 14]
n4 leaky_relu x=node:stage1/out:[B, 64, 14, 14] out=[B, 64, 14, 14]
stage2 conv x=node:n4/out:[B, 64, 14, 14] out=[B, 128, 7, 7]
n6 batch_norm x=node:stage2/out:[B, 128, 7, 7] out=[B, 128, 7, 7]
n7 leaky_relu x=node:n6/out:[B, 128, 7, 7] out=[B, 128, 7, 7]
features flatten x=node:n7/out:[B, 128, 7, 7] out=[B, 6272]
logits linear x=node:features/out:[B, 6272] out=[B, 1]
Parameters: 148,337. Mirza & Osindero, "Conditional Generative Adversarial Nets" (2014), in the usual DCGAN form; 10·784+784 + 2·64·4·4+64 + 64·128·4·4 + 2·128 + 6272+1 = 148,337 parameters.
Tiny ConvNeXt Vision Classifier¶
A ConvNeXt-style convolutional vision network: 4×4 patchifying convolution, 2 stages of 7×7 depthwise convolutions with GroupNorm, inverted 1×1 pointwise convolutions (4× expansion), and learned residual scale, followed by global average pooling and a linear classifier.
examples/networks/convnext_tiny.hndl
# ConvNeXt-style stage at 32x32 scale: 4x4 patchify stem, 7x7 depthwise
# convolutions, inverted 4x pointwise bottleneck, and learned residual scaling.
conv(64, kernel_size=4, stride=4, name="patch_stem")
x = group_norm(1, name="stem_norm")
for _ in range(2):
h = conv(x, 64, kernel_size=7, padding=3, groups=64, name="dwconv")
h = group_norm(h, 1, name="norm")
h = conv(h, 256, kernel_size=1, name="pwconv1")
h = gelu(h)
h = conv(h, 64, kernel_size=1, name="pwconv2")
h = learned_scale(h, init_value=1e-6, name="gamma")
x = add(x, h, name="residual")
global_avg_pool(x)
layer_norm(name="head_norm")
linear(name="head")
Input ['B', 3, 32, 32] → output ['B', 10].
Network: [B, 3, 32, 32] -> [B, 10] dtype=float32
name operation input shapes output shapes
patch_stem conv x=input:x:[B, 3, 32, 32] out=[B, 64, 8, 8]
stem_norm group_norm x=node:patch_stem/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
dwconv0 conv x=node:stem_norm/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
norm0 group_norm x=node:dwconv0/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
pwconv1_0 conv x=node:norm0/out:[B, 64, 8, 8] out=[B, 256, 8, 8]
n5 gelu x=node:pwconv1_0/out:[B, 256, 8, 8] out=[B, 256, 8, 8]
pwconv2_0 conv x=node:n5/out:[B, 256, 8, 8] out=[B, 64, 8, 8]
gamma0 learned_scale x=node:pwconv2_0/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
residual0 add a=node:stem_norm/out:[B, 64, 8, 8], b=node:gamma0/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
dwconv1 conv x=node:residual0/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
norm1 group_norm x=node:dwconv1/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
pwconv1_1 conv x=node:norm1/out:[B, 64, 8, 8] out=[B, 256, 8, 8]
n12 gelu x=node:pwconv1_1/out:[B, 256, 8, 8] out=[B, 256, 8, 8]
pwconv2_1 conv x=node:n12/out:[B, 256, 8, 8] out=[B, 64, 8, 8]
gamma1 learned_scale x=node:pwconv2_1/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
residual1 add a=node:residual0/out:[B, 64, 8, 8], b=node:gamma1/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
n16 global_avg_pool x=node:residual1/out:[B, 64, 8, 8] out=[B, 64]
head_norm layer_norm x=node:n16/out:[B, 64] out=[B, 64]
head linear x=node:head_norm/out:[B, 64] out=[B, 10]
Parameters: 76,876. Architecture follows Liu et al. 2022, "A ConvNet for the 2020s" (ConvNeXt, CVPR 2022, arXiv:2201.03545) and Woo et al. 2023, "ConvNeXt V2" (arXiv:2301.00808); parameter count checked against plain PyTorch: patch_stem 64·3·4·4+64 = 3,136, stem_norm 64·2 = 128, 2 blocks each (dwconv 64·1·7·7+64 = 3,200, norm 64·2 = 128, pwconv1 256·64·1·1+256 = 16,640, pwconv2 64·256·1·1+64 = 16,448, gamma 1; block total 36,417) = 72,834, head_norm 64·2 = 128, head 64·10+10 = 650; total 3,136 + 128 + 72,834 + 128 + 650 = 76,876.
Tiny ConvNeXt-V2 Vision Classifier¶
A ConvNeXt-V2 convolutional architecture incorporating Global Response Normalization (GRN) and DropPath stochastic depth: 4×4 patchifying convolution stem, 2 stages of 7×7 depthwise convolutions with GroupNorm, inverted 1×1 pointwise convolutions (4× expansion) with GELU and GRN, learned residual scale, followed by global average pooling and a linear classifier.
examples/networks/convnext_v2_tiny.hndl
# ConvNeXt-V2 block stage: 4x4 patchify stem, 7x7 depthwise convolutions with
# GroupNorm, inverted 4x pointwise convolutions, GELU, Global Response
# Normalization (GRN), learned residual scaling, and DropPath stochastic depth.
conv(64, kernel_size=4, stride=4, name="patch_stem")
x = group_norm(1, name="stem_norm")
for _ in range(2):
h = conv(x, 64, kernel_size=7, padding=3, groups="depthwise", name="dwconv")
h = group_norm(h, 1, name="norm")
h = conv(h, 256, kernel_size=1, name="pwconv1")
h = gelu(h)
h = grn(h, name="grn")
h = conv(h, 64, kernel_size=1, name="pwconv2")
h = learned_scale(h, init_value=1e-6, name="gamma")
h = drop_path(h, 0.0, name="drop")
x = add(x, h, name="residual")
global_avg_pool(x)
layer_norm(name="head_norm")
linear(10, name="head")
Input ['B', 3, 32, 32] → output ['B', 10].
Network: [B, 3, 32, 32] -> [B, 10] dtype=float32
name operation input shapes output shapes
patch_stem conv x=input:x:[B, 3, 32, 32] out=[B, 64, 8, 8]
stem_norm group_norm x=node:patch_stem/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
dwconv0 conv x=node:stem_norm/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
norm0 group_norm x=node:dwconv0/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
pwconv1_0 conv x=node:norm0/out:[B, 64, 8, 8] out=[B, 256, 8, 8]
n5 gelu x=node:pwconv1_0/out:[B, 256, 8, 8] out=[B, 256, 8, 8]
grn0 grn x=node:n5/out:[B, 256, 8, 8] out=[B, 256, 8, 8]
pwconv2_0 conv x=node:grn0/out:[B, 256, 8, 8] out=[B, 64, 8, 8]
gamma0 learned_scale x=node:pwconv2_0/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
drop0 drop_path x=node:gamma0/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
residual0 add a=node:stem_norm/out:[B, 64, 8, 8], b=node:drop0/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
dwconv1 conv x=node:residual0/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
norm1 group_norm x=node:dwconv1/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
pwconv1_1 conv x=node:norm1/out:[B, 64, 8, 8] out=[B, 256, 8, 8]
n14 gelu x=node:pwconv1_1/out:[B, 256, 8, 8] out=[B, 256, 8, 8]
grn1 grn x=node:n14/out:[B, 256, 8, 8] out=[B, 256, 8, 8]
pwconv2_1 conv x=node:grn1/out:[B, 256, 8, 8] out=[B, 64, 8, 8]
gamma1 learned_scale x=node:pwconv2_1/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
drop1 drop_path x=node:gamma1/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
residual1 add a=node:residual0/out:[B, 64, 8, 8], b=node:drop1/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
n20 global_avg_pool x=node:residual1/out:[B, 64, 8, 8] out=[B, 64]
head_norm layer_norm x=node:n20/out:[B, 64] out=[B, 64]
head linear x=node:head_norm/out:[B, 64] out=[B, 10]
Parameters: 77,900. Architecture follows Woo et al. 2023, "ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders" (arXiv:2301.00808); parameter count checked against plain PyTorch: patch_stem 64·3·4·4+64 = 3,136, stem_norm 64·2 = 128, 2 blocks each (dwconv 64·1·7·7+64 = 3,200, norm 64·2 = 128, pwconv1 256·64·1·1+256 = 16,640, grn 256·2 = 512, pwconv2 64·256·1·1+64 = 16,448, gamma 1; block total 36,929) = 73,858, head_norm 64·2 = 128, head 64·10+10 = 650; total 3,136 + 128 + 73,858 + 128 + 650 = 77,900.
DCGAN discriminator¶
The DCGAN discriminator for 64×64 RGB images: four "down2" convolutions with leaky ReLU, batch-normalized after the first stage, reduce the image to a 512×4×4 map that is flattened and projected to a single logit. The output is a raw score — apply a sigmoid, or use BCEWithLogitsLoss, in the loss rather than in the network.
examples/networks/dcgan_discriminator.hndl
# DCGAN discriminator (Radford et al., 2015) for 64x64 RGB images.
# Four strided convolutions halve the image each time: 64 -> 32 -> 16 -> 8 -> 4.
# The "down2" policy supplies the canonical kernel 4, stride 2, padding 1.
# The first stage has no normalization, so it keeps its bias.
conv(64, policy="down2", name="stage1")
leaky_relu(0.2)
# Every later stage is conv -> batch_norm -> leaky_relu. batch_norm's own bias
# makes the convolution bias redundant, so bias=False there.
conv(128, policy="down2", bias=False, name="stage2")
batch_norm()
leaky_relu(0.2)
conv(256, policy="down2", bias=False, name="stage3")
batch_norm()
leaky_relu(0.2)
conv(512, policy="down2", bias=False, name="stage4")
batch_norm()
leaky_relu(0.2)
# The 512x4x4 map flattens to 8192; the head's width follows the output contract.
flatten()
linear(name="logit")
Input ['B', 3, 64, 64] → output ['B', 1].
Network: [B, 3, 64, 64] -> [B, 1] dtype=float32
index name operation input shape output shape
0 stage1 conv [B, 3, 64, 64] [B, 64, 32, 32]
1 n1 leaky_relu [B, 64, 32, 32] [B, 64, 32, 32]
2 stage2 conv [B, 64, 32, 32] [B, 128, 16, 16]
3 n3 batch_norm [B, 128, 16, 16] [B, 128, 16, 16]
4 n4 leaky_relu [B, 128, 16, 16] [B, 128, 16, 16]
5 stage3 conv [B, 128, 16, 16] [B, 256, 8, 8]
6 n6 batch_norm [B, 256, 8, 8] [B, 256, 8, 8]
7 n7 leaky_relu [B, 256, 8, 8] [B, 256, 8, 8]
8 stage4 conv [B, 256, 8, 8] [B, 512, 4, 4]
9 n9 batch_norm [B, 512, 4, 4] [B, 512, 4, 4]
10 n10 leaky_relu [B, 512, 4, 4] [B, 512, 4, 4]
11 n11 flatten [B, 512, 4, 4] [B, 8192]
12 logit linear [B, 8192] [B, 1]
Parameters: 2,765,633. Radford, Metz & Chintala, "Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks" (2015), in the form of the PyTorch DCGAN example; the count was checked against the equivalent torch.nn stack — 3·64·4·4+64 + 64·128·4·4 + 2·128 + 128·256·4·4 + 2·256 + 256·512·4·4 + 2·512 + 8192+1 = 2,765,633.
DCGAN generator¶
Project a 100-dimensional latent vector to a 4×4×1024 seed, then upsample with four doubling transposed convolutions to a 3×64×64 image. The projection width, the seed size and the three output channels are all inferred from the contract.
examples/networks/dcgan_generator.hndl
# DCGAN generator (Radford et al. 2015, figure 1): a 100-dimensional latent
# vector becomes a 64×64 RGB image. Four doubling stages divide 64 by 16, so
# the contract fixes the seed at 4×4 and the projection at 1024·4·4 = 16384.
# Every convolution that feeds a batch_norm drops its bias, as in the reference.
linear(bias=False, name="project") # [B, 100] -> [B, 16384]
reshape(1024, name="seed") # -> [B, 1024, 4, 4]
batch_norm(name="seed_norm")
relu()
deconv(512, policy="up2", bias=False, name="up8") # 4×4 -> 8×8
batch_norm()
relu()
deconv(256, policy="up2", bias=False, name="up16") # 8×8 -> 16×16
batch_norm()
relu()
deconv(128, policy="up2", bias=False, name="up32") # 16×16 -> 32×32
batch_norm()
relu()
# 32×32 -> 64×64. The 3 output channels come from the contract, and this last
# stage keeps its bias because no normalization follows it.
deconv(policy="up2", name="to_rgb")
tanh() # images in (-1, 1)
Input ['B', 100] → output ['B', 3, 64, 64].
Network: [B, 100] -> [B, 3, 64, 64] dtype=float32
index name operation input shape output shape
0 project linear [B, 100] [B, 16384]
1 seed reshape [B, 16384] [B, 1024, 4, 4]
2 seed_norm batch_norm [B, 1024, 4, 4] [B, 1024, 4, 4]
3 n3 relu [B, 1024, 4, 4] [B, 1024, 4, 4]
4 up8 deconv [B, 1024, 4, 4] [B, 512, 8, 8]
5 n5 batch_norm [B, 512, 8, 8] [B, 512, 8, 8]
6 n6 relu [B, 512, 8, 8] [B, 512, 8, 8]
7 up16 deconv [B, 512, 8, 8] [B, 256, 16, 16]
8 n8 batch_norm [B, 256, 16, 16] [B, 256, 16, 16]
9 n9 relu [B, 256, 16, 16] [B, 256, 16, 16]
10 up32 deconv [B, 256, 16, 16] [B, 128, 32, 32]
11 n11 batch_norm [B, 128, 32, 32] [B, 128, 32, 32]
12 n12 relu [B, 128, 32, 32] [B, 128, 32, 32]
13 to_rgb deconv [B, 128, 32, 32] [B, 3, 64, 64]
14 n14 tanh [B, 3, 64, 64] [B, 3, 64, 64]
Parameters: 12,658,435. Radford, Metz & Chintala 2015 (DCGAN), figure 1: project and reshape to 4×4×1024, then 8×8×512, 16×16×256, 32×32×128, 64×64×3. The count was checked by building the same stack in plain torch — Linear(100, 16384, bias=False), four ConvTranspose2d(kernel 4, stride 2, padding 1) with bias=False under each of the four BatchNorm2d layers and bias=True on the final RGB stage — which also gives 12,658,435. The PyTorch DCGAN tutorial differs: it starts from a 100×1×1 ConvTranspose2d rather than a linear projection, and its ngf=64 feature maps make the stack 512/256/128/64/3 instead of the paper's 1024/512/256/128/3.
Tiny DeepSeekMoE Causal Decoder¶
A 32-token hybrid shared and routed mixture-of-experts causal decoder: learned token embeddings, 2 transformer layers pairing pre-RMSNorm and RoPE attention with parallel shared SwiGLU and top-2-of-4 routed experts, a final RMSNorm, and an untied vocabulary head whose width comes from the output contract.
examples/networks/deepseek_moe_tiny.hndl
# Hybrid Shared + Routed Mixture-of-Experts causal decoder (DeepSeekMoE / Qwen-MoE style).
h = embedding(256, 128, name="tok_emb")
for _ in range(2):
a = attention(rms_norm(h, name="attn_norm"), 4, causal=True, rope=True, bias=False, name="attn")
h = add(h, a, name="attn_res")
n = rms_norm(h, name="ffn_norm")
shared = swiglu(n, 256, bias=False, name="shared_expert")
routed = moe(n, 4, 256, top_k=2, expert_kind="swiglu", bias=False, scoring="sigmoid", name="routed_experts", init={"router.weight": normal(std=0.02)})
combined = add(shared, routed, name="moe_sum")
h = add(h, combined, name="ffn_res")
rms_norm(h, name="final_norm")
linear(bias=False, name="lm_head")
Input ['B', 32] (input_dtype="int64") → output ['B', 32, 256].
Network: [B, 32] -> [B, 32, 256] dtype=float32 input_dtype=int64
name operation input shapes output shapes
tok_emb embedding ids=input:x:[B, 32] out=[B, 32, 128]
attn_norm0 rms_norm x=node:tok_emb/out:[B, 32, 128] out=[B, 32, 128]
attn0 attention x=node:attn_norm0/out:[B, 32, 128] out=[B, 32, 128]
attn_res0 add a=node:tok_emb/out:[B, 32, 128], b=node:attn0/out:[B, 32, 128] out=[B, 32, 128]
ffn_norm0 rms_norm x=node:attn_res0/out:[B, 32, 128] out=[B, 32, 128]
shared_expert0 swiglu x=node:ffn_norm0/out:[B, 32, 128] out=[B, 32, 128]
routed_experts0 moe x=node:ffn_norm0/out:[B, 32, 128] out=[B, 32, 128]
moe_sum0 add a=node:shared_expert0/out:[B, 32, 128], b=node:routed_experts0/out:[B, 32, 128] out=[B, 32, 128]
ffn_res0 add a=node:attn_res0/out:[B, 32, 128], b=node:moe_sum0/out:[B, 32, 128] out=[B, 32, 128]
attn_norm1 rms_norm x=node:ffn_res0/out:[B, 32, 128] out=[B, 32, 128]
attn1 attention x=node:attn_norm1/out:[B, 32, 128] out=[B, 32, 128]
attn_res1 add a=node:ffn_res0/out:[B, 32, 128], b=node:attn1/out:[B, 32, 128] out=[B, 32, 128]
ffn_norm1 rms_norm x=node:attn_res1/out:[B, 32, 128] out=[B, 32, 128]
shared_expert1 swiglu x=node:ffn_norm1/out:[B, 32, 128] out=[B, 32, 128]
routed_experts1 moe x=node:ffn_norm1/out:[B, 32, 128] out=[B, 32, 128]
moe_sum1 add a=node:shared_expert1/out:[B, 32, 128], b=node:routed_experts1/out:[B, 32, 128] out=[B, 32, 128]
ffn_res1 add a=node:attn_res1/out:[B, 32, 128], b=node:moe_sum1/out:[B, 32, 128] out=[B, 32, 128]
final_norm rms_norm x=node:ffn_res1/out:[B, 32, 128] out=[B, 32, 128]
lm_head linear x=node:final_norm/out:[B, 32, 128] out=[B, 32, 256]
Parameters: 1,181,312. Architecture follows Dai et al. 2024, "DeepSeekMoE: Towards Ultimate Expert Specialization in Mixture-of-Experts Language Models" (arXiv:2401.06066); parameter count checked against plain PyTorch: embedding 256·128 = 32,768, 2 layers with (RMSNorm 128 + 4·(128·128) attention + RMSNorm 128 + 3·(128·256) shared SwiGLU + router 128·4 + 4·3·(128·256) routed SwiGLU experts) = 2·557,824 = 1,115,648, final RMSNorm 128, head 128·256 = 32,768; total 32,768 + 1,115,648 + 128 + 32,768 = 1,181,312.
Tiny Diffusion Transformer (DiT)¶
A 32×32 Diffusion Transformer: 4×4 patchifying convolution stem, 2 DiT blocks pairing adaptive LayerNorm-Zero (AdaLN-Zero) conditioning modulation with QK-normalized self-attention and SwiGLU feed-forward networks, followed by an AdaLN-Zero final modulation, 1×1 unpatchify projection, and 4× pixel_shuffle.
examples/networks/dit_tiny.hndl
# Diffusion Transformer (DiT) at 32x32 scale: 4x4 patchify stem, 2 DiT blocks
# with AdaLN-Zero conditioning modulation, self-attention with QK-norm,
# SwiGLU feed-forward networks, and 4x4 sub-pixel unpatchify head.
x = patch_embed(x, 128, 4, name="patch_stem")
x = pos_embed(x, 64, name="pos_emb")
for _ in range(2):
normed_attn, gate_attn = adaln_zero(x, cond, name="attn_adaln")
a = attention(normed_attn, 4, qk_norm="rms_norm", name="attn")
x = add(x, broadcast_mul(a, gate_attn), name="attn_res")
normed_ffn, gate_ffn = adaln_zero(x, cond, name="ffn_adaln")
f = swiglu(normed_ffn, 384, bias=False, name="ffn")
x = add(x, broadcast_mul(f, gate_ffn), name="ffn_res")
normed_out = adaln_zero(x, cond, gate=False, name="final_adaln")
transpose(normed_out, 1, 2, name="tokens_to_channels")
reshape(128, 8, 8, name="to_spatial")
conv(48, kernel_size=1, name="unpatchify")
pixel_shuffle(4, name="to_pixels")
Input x=['B', 3, 32, 32], cond=['B', 128] → output ['B', 3, 32, 32].
Network: x=[B, 3, 32, 32], cond=[B, 128] -> [B, 3, 32, 32] dtype=float32
name operation input shapes output shapes
patch_stem patch_embed x=input:x:[B, 3, 32, 32] out=[B, 64, 128]
pos_emb pos_embed x=node:patch_stem/out:[B, 64, 128] out=[B, 64, 128]
attn_adaln0 adaln_zero x=node:pos_emb/out:[B, 64, 128], cond=input:cond:[B, 128] out=[B, 64, 128], gate=[B, 64, 128]
attn0 attention x=node:attn_adaln0/out:[B, 64, 128] out=[B, 64, 128]
n4 broadcast_mul a=node:attn0/out:[B, 64, 128], b=node:attn_adaln0/gate:[B, 64, 128] out=[B, 64, 128]
attn_res0 add a=node:pos_emb/out:[B, 64, 128], b=node:n4/out:[B, 64, 128] out=[B, 64, 128]
ffn_adaln0 adaln_zero x=node:attn_res0/out:[B, 64, 128], cond=input:cond:[B, 128] out=[B, 64, 128], gate=[B, 64, 128]
ffn0 swiglu x=node:ffn_adaln0/out:[B, 64, 128] out=[B, 64, 128]
n8 broadcast_mul a=node:ffn0/out:[B, 64, 128], b=node:ffn_adaln0/gate:[B, 64, 128] out=[B, 64, 128]
ffn_res0 add a=node:attn_res0/out:[B, 64, 128], b=node:n8/out:[B, 64, 128] out=[B, 64, 128]
attn_adaln1 adaln_zero x=node:ffn_res0/out:[B, 64, 128], cond=input:cond:[B, 128] out=[B, 64, 128], gate=[B, 64, 128]
attn1 attention x=node:attn_adaln1/out:[B, 64, 128] out=[B, 64, 128]
n12 broadcast_mul a=node:attn1/out:[B, 64, 128], b=node:attn_adaln1/gate:[B, 64, 128] out=[B, 64, 128]
attn_res1 add a=node:ffn_res0/out:[B, 64, 128], b=node:n12/out:[B, 64, 128] out=[B, 64, 128]
ffn_adaln1 adaln_zero x=node:attn_res1/out:[B, 64, 128], cond=input:cond:[B, 128] out=[B, 64, 128], gate=[B, 64, 128]
ffn1 swiglu x=node:ffn_adaln1/out:[B, 64, 128] out=[B, 64, 128]
n16 broadcast_mul a=node:ffn1/out:[B, 64, 128], b=node:ffn_adaln1/gate:[B, 64, 128] out=[B, 64, 128]
ffn_res1 add a=node:attn_res1/out:[B, 64, 128], b=node:n16/out:[B, 64, 128] out=[B, 64, 128]
final_adaln adaln_zero x=node:ffn_res1/out:[B, 64, 128], cond=input:cond:[B, 128] out=[B, 64, 128]
tokens_to_channels transpose x=node:final_adaln/out:[B, 64, 128] out=[B, 128, 64]
to_spatial reshape x=node:tokens_to_channels/out:[B, 128, 64] out=[B, 128, 8, 8]
unpatchify conv x=node:to_spatial/out:[B, 128, 8, 8] out=[B, 48, 8, 8]
to_pixels pixel_shuffle x=node:unpatchify/out:[B, 48, 8, 8] out=[B, 3, 32, 32]
Parameters: 678,960. Architecture follows Peebles & Xie 2023, "Scalable Diffusion Models with Transformers" (DiT, ICCV 2023, arXiv:2212.09748); parameter count checked against plain PyTorch: patch_stem 128·3·4·4+128 = 6,272, pos_emb 64·128 = 8,192, 2 DiT blocks each (attn_adaln 128·384+384 = 49,536, attn 4·(128·128+128)+64 = 66,112, ffn_adaln 128·384+384 = 49,536, SwiGLU 3·(128·384) = 147,456; block total 312,640) = 625,280, final_adaln 128·256+256 = 33,024, unpatchify 48·128·1·1+48 = 6,192, pixel_shuffle 0; total 6,272 + 8,192 + 625,280 + 33,024 + 6,192 = 678,960.
Tiny EnCodec Neural Audio Autoencoder¶
An audio compression autoencoder featuring strictly causal 1D strided convolutions, learned periodic Snake activations, and causal transposed 1D convolutions for exact-length waveform reconstruction.
examples/networks/encodec_autoencoder_tiny.hndl
# EnCodec-style neural audio autoencoder: causal 1D strided convolutional encoder,
# Snake periodic activation function, and causal 1D transposed convolutional decoder.
pad(0, 0, name="input_pad")
conv1d(32, kernel_size=7, causal=True, name="enc_conv1")
snake(channels=32, name="enc_act1")
conv1d(64, kernel_size=4, stride=2, causal=True, name="enc_conv2")
snake(channels=64, name="enc_act2")
conv1d(128, kernel_size=4, stride=2, causal=True, name="enc_conv3")
snake(channels=128, name="enc_act3")
deconv1d(64, kernel_size=4, stride=2, causal=True, name="dec_conv1")
snake(channels=64, name="dec_act1")
deconv1d(32, kernel_size=4, stride=2, causal=True, name="dec_conv2")
snake(channels=32, name="dec_act2")
conv1d(1, kernel_size=7, causal=True, name="dec_conv3")
Input ['B', 1, 1024] → output ['B', 1, 1024].
Network: [B, 1, 1024] -> [B, 1, 1024] dtype=float32
index name operation input shape output shape
0 input_pad pad [B, 1, 1024] [B, 1, 1024]
1 enc_conv1 conv1d [B, 1, 1024] [B, 32, 1024]
2 enc_act1 snake [B, 32, 1024] [B, 32, 1024]
3 enc_conv2 conv1d [B, 32, 1024] [B, 64, 512]
4 enc_act2 snake [B, 64, 512] [B, 64, 512]
5 enc_conv3 conv1d [B, 64, 512] [B, 128, 256]
6 enc_act3 snake [B, 128, 256] [B, 128, 256]
7 dec_conv1 deconv1d [B, 128, 256] [B, 64, 512]
8 dec_act1 snake [B, 64, 512] [B, 64, 512]
9 dec_conv2 deconv1d [B, 64, 512] [B, 32, 1024]
10 dec_act2 snake [B, 32, 1024] [B, 32, 1024]
11 dec_conv3 conv1d [B, 32, 1024] [B, 1, 1024]
Parameters: 83,009. Architecture follows Défossez et al. 2022, "High Fidelity Neural Audio Compression" (EnCodec, arXiv:2210.13438) and Ziying et al. 2020, "Neural Additive Models / Snake" (arXiv:2006.08195); parameter count checked against plain PyTorch: encoder (enc_conv1 32·1·7+32 = 256, enc_act1 32, enc_conv2 64·32·4+64 = 8,256, enc_act2 64, enc_conv3 128·64·4+128 = 32,896, enc_act3 128) + decoder (dec_conv1 128·64·4+64 = 32,832, dec_act1 64, dec_conv2 64·32·4+32 = 8,224, dec_act2 32, dec_conv3 1·32·7+1 = 225); total = 256 + 32 + 8,256 + 64 + 32,896 + 128 + 32,832 + 64 + 8,224 + 32 + 225 = 83,009.
ESPCN 2x Super-Resolution Network¶
An Efficient Sub-Pixel Convolutional Neural Network for 2× image super-resolution: feature extraction convolutions at low resolution followed by a sub-pixel convolution layer with pixel_shuffle(2) where output channel width (12 = 3 × 2²) is automatically inferred backward by HNDL's constraint solver.
examples/networks/espcn_super_res.hndl
# ESPCN (Shi et al. 2016) 2x image super-resolution network: feature maps stay
# at 16x16 and the final conv channel count (12) is inferred backward from
# pixel_shuffle(2) and the [B, 3, 32, 32] output contract.
conv(64, kernel_size=5, padding=2, name="conv1")
tanh()
conv(32, kernel_size=3, padding=1, name="conv2")
tanh()
conv(kernel_size=3, padding=1, name="subpixel_conv")
pixel_shuffle(2, name="upscale")
Input ['B', 3, 16, 16] → output ['B', 3, 32, 32].
Network: [B, 3, 16, 16] -> [B, 3, 32, 32] dtype=float32
index name operation input shape output shape
0 conv1 conv [B, 3, 16, 16] [B, 64, 16, 16]
1 n1 tanh [B, 64, 16, 16] [B, 64, 16, 16]
2 conv2 conv [B, 64, 16, 16] [B, 32, 16, 16]
3 n3 tanh [B, 32, 16, 16] [B, 32, 16, 16]
4 subpixel_conv conv [B, 32, 16, 16] [B, 12, 16, 16]
5 upscale pixel_shuffle [B, 12, 16, 16] [B, 3, 32, 32]
Parameters: 26,796. Architecture follows Shi et al. 2016, "Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network" (CVPR 2016, arXiv:1609.05158); parameter count checked against plain PyTorch: conv1 64·3·5·5+64 = 4,864, conv2 32·64·3·3+32 = 18,464, subpixel_conv 12·32·3·3+12 = 3,468, pixel_shuffle 0; total 4,864 + 18,464 + 3,468 = 26,796.
Tiny GPT¶
A 64-token GPT-2-style decoder: learned token and position embeddings, four causal pre-norm transformer blocks with a tanh-approximated GELU feed-forward, a final layer norm, and an untied language-model head whose width is inferred from the output contract.
examples/networks/gpt_tiny.hndl
# A tiny GPT-2-style decoder: 64 token ids in, one logit per vocabulary entry out.
# Vocabulary 256, model width 128, four causal blocks.
# Stem: a vector per token id, plus a learned absolute position for each of the 64 slots.
embedding(256, 128, name="wte")
pos_embed(64, name="wpe")
# Four pre-norm causal blocks: 4 heads of width 32, 4x feed-forward, tanh-approximated GELU.
# The loop appends the iteration to the name, so the blocks are block0 ... block3.
for _ in range(4):
transformer_block(4, activation="gelu_tanh", causal=True, name="block")
# Final normalization, then the language-model head. Its width is the vocabulary
# size, so the output contract determines it; GPT-2 ties it to wte, HNDL does not.
layer_norm(name="ln_f")
linear(bias=False, name="lm_head")
Input ['B', 64] (input_dtype="int64") → output ['B', 64, 256].
Network: [B, 64] -> [B, 64, 256] dtype=float32 input_dtype=int64
index name operation input shape output shape
0 wte embedding [B, 64] [B, 64, 128]
1 wpe pos_embed [B, 64, 128] [B, 64, 128]
2 block0 transformer_block [B, 64, 128] [B, 64, 128]
3 block1 transformer_block [B, 64, 128] [B, 64, 128]
4 block2 transformer_block [B, 64, 128] [B, 64, 128]
5 block3 transformer_block [B, 64, 128] [B, 64, 128]
6 ln_f layer_norm [B, 64, 128] [B, 64, 128]
7 lm_head linear [B, 64, 128] [B, 64, 256]
Parameters: 867,072. Block structure follows Radford et al. 2019, "Language Models are Unsupervised Multitask Learners" (GPT-2); the count was checked against the same architecture built in plain torch (256·128 + 64·128 + 4·(4·128 + 4·(128·128+128) + (512·128+512) + (128·512+128)) + 2·128 + 128·256 = 867,072), with the head untied rather than shared with the token embedding.
Hopfield classifier¶
Classify a 28×28 image by projecting it to a 128-wide query, retrieving from a 64-pattern modern Hopfield memory, and reading out the classes. The final width is inferred from the output contract.
examples/networks/hopfield_classifier.hndl
# A modern Hopfield layer as the hidden layer of a 28×28 grayscale classifier.
flatten()
# Project the image to the query width; the memory acts on this last axis.
linear(128, name="query")
# 64 stored patterns of width 128, the only parameters of the layer.
# beta=0.25 keeps the softmax soft, so a query retrieves a mixture of the
# patterns it lies closest to instead of snapping to one; a single update is
# exactly attention with the stored patterns as both keys and values.
hopfield(64, beta=0.25, steps=1, name="memory")
relu()
# Width inferred from the output contract: 10 classes.
linear(name="logits")
Input ['B', 1, 28, 28] → output ['B', 10].
Network: [B, 1, 28, 28] -> [B, 10] dtype=float32
index name operation input shape output shape
0 n0 flatten [B, 1, 28, 28] [B, 784]
1 query linear [B, 784] [B, 128]
2 memory hopfield [B, 128] [B, 128]
3 n3 relu [B, 128] [B, 128]
4 logits linear [B, 128] [B, 10]
Parameters: 109,962. Hopfield layer of Ramsauer et al., "Hopfield Networks is All You Need" (2020), whose only parameter is the stored-pattern matrix; 784·128+128 + 64·128 + 128·10+10 = 109,962 parameters.
Tiny Kimi Linear Hybrid 3:1 Decoder¶
A 64-token Kimi Linear hybrid language model: learned token embeddings, 3 Kimi Delta Attention (KDA) layers with fine-grained channel-wise decay, causal short conv1d, per-head L2 normalization and SwiGLU FFNs, interleaved with 1 global NoPE Multi-Head Latent Attention (MLA) layer with compressed KV latent caching, followed by final RMSNorm and linear head.
examples/networks/kimi_linear_tiny.hndl
# Kimi Linear 3:1 hybrid causal decoder: 3 Kimi Delta Attention (KDA) layers
# with channel-wise decay and causal short conv1d, interleaved with 1 global
# NoPE Multi-Head Latent Attention (MLA) layer and SwiGLU feed-forward blocks.
h = embedding(256, 128, name="tok_emb")
for _ in range(3):
h = add(h, gated_delta_attention(rms_norm(h, name="kda_norm"), 4, decay_kind="channel", conv_size=4, name="kda"))
h = add(h, swiglu(rms_norm(h, name="ffn_norm"), 384, bias=False, name="ffn"))
h = add(h, latent_attention(rms_norm(h, name="mla_norm"), 4, kv_lora_rank=32, qk_rope_head_dim=0, causal=True, name="mla"))
h = add(h, swiglu(rms_norm(h, name="mla_ffn_norm"), 384, bias=False, name="mla_ffn"))
rms_norm(h, name="final_norm")
linear(bias=False, name="lm_head")
Input ['B', 64] (input_dtype="int64") → output ['B', 64, 256].
Network: [B, 64] -> [B, 64, 256] dtype=float32 input_dtype=int64
name operation input shapes output shapes
tok_emb embedding ids=input:x:[B, 64] out=[B, 64, 128]
kda_norm0 rms_norm x=node:tok_emb/out:[B, 64, 128] out=[B, 64, 128]
kda0 gated_delta_attention x=node:kda_norm0/out:[B, 64, 128] out=[B, 64, 128]
n3 add a=node:tok_emb/out:[B, 64, 128], b=node:kda0/out:[B, 64, 128] out=[B, 64, 128]
ffn_norm0 rms_norm x=node:n3/out:[B, 64, 128] out=[B, 64, 128]
ffn0 swiglu x=node:ffn_norm0/out:[B, 64, 128] out=[B, 64, 128]
n6 add a=node:n3/out:[B, 64, 128], b=node:ffn0/out:[B, 64, 128] out=[B, 64, 128]
kda_norm1 rms_norm x=node:n6/out:[B, 64, 128] out=[B, 64, 128]
kda1 gated_delta_attention x=node:kda_norm1/out:[B, 64, 128] out=[B, 64, 128]
n9 add a=node:n6/out:[B, 64, 128], b=node:kda1/out:[B, 64, 128] out=[B, 64, 128]
ffn_norm1 rms_norm x=node:n9/out:[B, 64, 128] out=[B, 64, 128]
ffn1 swiglu x=node:ffn_norm1/out:[B, 64, 128] out=[B, 64, 128]
n12 add a=node:n9/out:[B, 64, 128], b=node:ffn1/out:[B, 64, 128] out=[B, 64, 128]
kda_norm2 rms_norm x=node:n12/out:[B, 64, 128] out=[B, 64, 128]
kda2 gated_delta_attention x=node:kda_norm2/out:[B, 64, 128] out=[B, 64, 128]
n15 add a=node:n12/out:[B, 64, 128], b=node:kda2/out:[B, 64, 128] out=[B, 64, 128]
ffn_norm2 rms_norm x=node:n15/out:[B, 64, 128] out=[B, 64, 128]
ffn2 swiglu x=node:ffn_norm2/out:[B, 64, 128] out=[B, 64, 128]
n18 add a=node:n15/out:[B, 64, 128], b=node:ffn2/out:[B, 64, 128] out=[B, 64, 128]
mla_norm rms_norm x=node:n18/out:[B, 64, 128] out=[B, 64, 128]
mla latent_attention x=node:mla_norm/out:[B, 64, 128] out=[B, 64, 128]
n21 add a=node:n18/out:[B, 64, 128], b=node:mla/out:[B, 64, 128] out=[B, 64, 128]
mla_ffn_norm rms_norm x=node:n21/out:[B, 64, 128] out=[B, 64, 128]
mla_ffn swiglu x=node:mla_ffn_norm/out:[B, 64, 128] out=[B, 64, 128]
n24 add a=node:n21/out:[B, 64, 128], b=node:mla_ffn/out:[B, 64, 128] out=[B, 64, 128]
final_norm rms_norm x=node:n24/out:[B, 64, 128] out=[B, 64, 128]
lm_head linear x=node:final_norm/out:[B, 64, 128] out=[B, 64, 256]
Parameters: 955,808. Architecture follows Moonshot AI 2025, "Kimi Linear: An Expressive, Efficient Attention Architecture" (arXiv:2510.26692) and DeepSeek-AI 2024, "DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model" (arXiv:2405.04434); parameter count checked against plain PyTorch: embedding 256·128 = 32,768, 3 KDA blocks each (RMSNorm 128 + KDA 84,736 + RMSNorm 128 + SwiGLU 147,456 = 232,448) = 697,344, 1 MLA block (RMSNorm 128 + MLA 45,088 + RMSNorm 128 + SwiGLU 147,456 = 192,800), final RMSNorm 128, head 128·256 = 32,768; total 32,768 + 697,344 + 192,800 + 128 + 32,768 = 955,808.
LeNet-5¶
The classic convolutional digit classifier: two 5×5 convolution and 2×2 average-pooling stages, then 120- and 84-unit tanh layers. The final width is inferred from the output contract.
examples/networks/lenet5.hndl
# LeNet-5 (LeCun et al. 1998) for 32×32 grayscale digits.
# Valid 5×5 convolutions and 2×2 average pooling: 32 -> 28 -> 14 -> 10 -> 5.
# C1/S2: six feature maps, then subsampling.
conv(6, kernel_size=5, name="c1")
tanh()
avg_pool(2, name="s2")
# C3/S4: sixteen feature maps, then subsampling. Leaves [B, 16, 5, 5].
conv(16, kernel_size=5, name="c3")
tanh()
avg_pool(2, name="s4")
# C5/F6: the classifier head over the 400 flattened features.
flatten()
linear(120, name="c5")
tanh()
linear(84, name="f6")
tanh()
# The output width is inferred from the contract (10 classes).
linear(name="output")
Input ['B', 1, 32, 32] → output ['B', 10].
Network: [B, 1, 32, 32] -> [B, 10] dtype=float32
index name operation input shape output shape
0 c1 conv [B, 1, 32, 32] [B, 6, 28, 28]
1 n1 tanh [B, 6, 28, 28] [B, 6, 28, 28]
2 s2 avg_pool [B, 6, 28, 28] [B, 6, 14, 14]
3 c3 conv [B, 6, 14, 14] [B, 16, 10, 10]
4 n4 tanh [B, 16, 10, 10] [B, 16, 10, 10]
5 s4 avg_pool [B, 16, 10, 10] [B, 16, 5, 5]
6 n6 flatten [B, 16, 5, 5] [B, 400]
7 c5 linear [B, 400] [B, 120]
8 n8 tanh [B, 120] [B, 120]
9 f6 linear [B, 120] [B, 84]
10 n10 tanh [B, 84] [B, 84]
11 output linear [B, 84] [B, 10]
Parameters: 61,706. LeCun et al., "Gradient-Based Learning Applied to Document Recognition" (Proc. IEEE, 1998), in the usual modern reading with fully connected C5/F6 layers; checked against the equivalent torch.nn stack: 156 + 2,416 + 48,120 + 10,164 + 850 = 61,706 parameters.
Tiny LLaMA Causal Decoder¶
A 64-token LLaMA-style causal language model: learned token embeddings, 4 transformer layers pairing pre-RMSNorm and 4-head RoPE causal attention with bias-free SwiGLU feed-forward networks, a final RMSNorm, and an untied vocabulary head whose width is inferred from the output contract.
examples/networks/llama_tiny.hndl
# LLaMA-style causal decoder at toy scale: pre-RMSNorm, rotary position
# embeddings, bias-free attention, and SwiGLU feed-forward blocks.
h = embedding(256, 128, name="tok_emb")
for _ in range(4):
a = attention(rms_norm(h, name="attn_norm"), 4, causal=True, rope=True, bias=False, name="attn")
h = add(h, a, name="attn_res")
f = swiglu(rms_norm(h, name="ffn_norm"), 384, bias=False, name="ffn")
h = add(h, f, name="ffn_res")
rms_norm(h, name="final_norm")
linear(bias=False, name="lm_head")
Input ['B', 64] (input_dtype="int64") → output ['B', 64, 256].
Network: [B, 64] -> [B, 64, 256] dtype=float32 input_dtype=int64
name operation input shapes output shapes
tok_emb embedding ids=input:x:[B, 64] out=[B, 64, 128]
attn_norm0 rms_norm x=node:tok_emb/out:[B, 64, 128] out=[B, 64, 128]
attn0 attention x=node:attn_norm0/out:[B, 64, 128] out=[B, 64, 128]
attn_res0 add a=node:tok_emb/out:[B, 64, 128], b=node:attn0/out:[B, 64, 128] out=[B, 64, 128]
ffn_norm0 rms_norm x=node:attn_res0/out:[B, 64, 128] out=[B, 64, 128]
ffn0 swiglu x=node:ffn_norm0/out:[B, 64, 128] out=[B, 64, 128]
ffn_res0 add a=node:attn_res0/out:[B, 64, 128], b=node:ffn0/out:[B, 64, 128] out=[B, 64, 128]
attn_norm1 rms_norm x=node:ffn_res0/out:[B, 64, 128] out=[B, 64, 128]
attn1 attention x=node:attn_norm1/out:[B, 64, 128] out=[B, 64, 128]
attn_res1 add a=node:ffn_res0/out:[B, 64, 128], b=node:attn1/out:[B, 64, 128] out=[B, 64, 128]
ffn_norm1 rms_norm x=node:attn_res1/out:[B, 64, 128] out=[B, 64, 128]
ffn1 swiglu x=node:ffn_norm1/out:[B, 64, 128] out=[B, 64, 128]
ffn_res1 add a=node:attn_res1/out:[B, 64, 128], b=node:ffn1/out:[B, 64, 128] out=[B, 64, 128]
attn_norm2 rms_norm x=node:ffn_res1/out:[B, 64, 128] out=[B, 64, 128]
attn2 attention x=node:attn_norm2/out:[B, 64, 128] out=[B, 64, 128]
attn_res2 add a=node:ffn_res1/out:[B, 64, 128], b=node:attn2/out:[B, 64, 128] out=[B, 64, 128]
ffn_norm2 rms_norm x=node:attn_res2/out:[B, 64, 128] out=[B, 64, 128]
ffn2 swiglu x=node:ffn_norm2/out:[B, 64, 128] out=[B, 64, 128]
ffn_res2 add a=node:attn_res2/out:[B, 64, 128], b=node:ffn2/out:[B, 64, 128] out=[B, 64, 128]
attn_norm3 rms_norm x=node:ffn_res2/out:[B, 64, 128] out=[B, 64, 128]
attn3 attention x=node:attn_norm3/out:[B, 64, 128] out=[B, 64, 128]
attn_res3 add a=node:ffn_res2/out:[B, 64, 128], b=node:attn3/out:[B, 64, 128] out=[B, 64, 128]
ffn_norm3 rms_norm x=node:attn_res3/out:[B, 64, 128] out=[B, 64, 128]
ffn3 swiglu x=node:ffn_norm3/out:[B, 64, 128] out=[B, 64, 128]
ffn_res3 add a=node:attn_res3/out:[B, 64, 128], b=node:ffn3/out:[B, 64, 128] out=[B, 64, 128]
final_norm rms_norm x=node:ffn_res3/out:[B, 64, 128] out=[B, 64, 128]
lm_head linear x=node:final_norm/out:[B, 64, 128] out=[B, 64, 256]
Parameters: 918,656. Architecture follows Touvron et al. 2023, "LLaMA: Open and Efficient Foundation Language Models" (arXiv:2302.13971) and Touvron et al. 2023, "Llama 2: Open Foundation and Fine-Tuned Chat Models" (arXiv:2307.09288); parameter count checked against plain PyTorch: embedding 256·128 = 32,768, 4 layers with (RMSNorm 128 + 4·(128·128) attention + RMSNorm 128 + 3·(128·384) SwiGLU) = 4·213,248 = 852,992, final RMSNorm 128, head 128·256 = 32,768; total 32,768 + 852,992 + 128 + 32,768 = 918,656.
Multilayer perceptron¶
Flatten a 28×28 image and classify it with two ReLU hidden layers. The final width is inferred from the output contract.
examples/networks/mlp.hndl
# A two-hidden-layer perceptron for 28×28 grayscale images (MNIST-sized).
flatten()
linear(256)
relu()
dropout(0.2)
linear(128)
relu()
linear()
Input ['B', 1, 28, 28] → output ['B', 10].
Network: [B, 1, 28, 28] -> [B, 10] dtype=float32
index name operation input shape output shape
0 n0 flatten [B, 1, 28, 28] [B, 784]
1 n1 linear [B, 784] [B, 256]
2 n2 relu [B, 256] [B, 256]
3 n3 dropout [B, 256] [B, 256]
4 n4 linear [B, 256] [B, 128]
5 n5 relu [B, 128] [B, 128]
6 n6 linear [B, 128] [B, 10]
Parameters: 235,146. Classic MNIST baseline; 784·256+256 + 256·128+128 + 128·10+10 = 235,146 parameters.
Mixture-of-experts transformer¶
A causal language model on 32 token ids: learned token and position embeddings, two pre-norm blocks that pair 4-head causal attention with a top-2-of-4 sparse mixture of experts, then a final norm and a bias-free vocabulary head whose width comes from the output contract.
examples/networks/moe_transformer.hndl
# A causal language model whose feed-forward is a sparse mixture of experts.
# Two pre-norm blocks over 32 token positions of a 100-word vocabulary.
# Stem: token ids -> 64-wide sequence, plus a learned absolute position table.
embedding(100, 64, name="tokens")
x0 = pos_embed(32, name="positions")
# Block 1. Pre-norm: normalize a copy, then add the unnormalized stream back.
h = layer_norm(x0, name="block1_attn_norm")
a = attention(h, 4, causal=True, name="block1_attn") # 4 heads of width 16
r = add(a, x0, name="block1_attn_residual")
h2 = layer_norm(r, name="block1_moe_norm")
m = moe(h2, 4, 128, top_k=2, name="block1_moe") # 4 experts, 2 per token
x1 = add(m, r, name="block1_moe_residual")
# Block 2, identical in shape; every layer is its own module.
h3 = layer_norm(x1, name="block2_attn_norm")
a2 = attention(h3, 4, causal=True, name="block2_attn")
r2 = add(a2, x1, name="block2_attn_residual")
h4 = layer_norm(r2, name="block2_moe_norm")
m2 = moe(h4, 4, 128, top_k=2, name="block2_moe")
x2 = add(m2, r2, name="block2_moe_residual")
# Final norm and the untied output head; its width is the vocabulary size,
# which the output contract already fixes at 100.
layer_norm(x2, name="final_norm")
linear(bias=False, name="lm_head")
Input ['B', 32] (input_dtype="int64") → output ['B', 32, 100].
Network: [B, 32] -> [B, 32, 100] dtype=float32 input_dtype=int64
name operation input shapes output shapes
tokens embedding ids=input:x:[B, 32] out=[B, 32, 64]
positions pos_embed x=node:tokens/out:[B, 32, 64] out=[B, 32, 64]
block1_attn_norm layer_norm x=node:positions/out:[B, 32, 64] out=[B, 32, 64]
block1_attn attention x=node:block1_attn_norm/out:[B, 32, 64] out=[B, 32, 64]
block1_attn_residual add a=node:block1_attn/out:[B, 32, 64], b=node:positions/out:[B, 32, 64] out=[B, 32, 64]
block1_moe_norm layer_norm x=node:block1_attn_residual/out:[B, 32, 64] out=[B, 32, 64]
block1_moe moe x=node:block1_moe_norm/out:[B, 32, 64] out=[B, 32, 64]
block1_moe_residual add a=node:block1_moe/out:[B, 32, 64], b=node:block1_attn_residual/out:[B, 32, 64] out=[B, 32, 64]
block2_attn_norm layer_norm x=node:block1_moe_residual/out:[B, 32, 64] out=[B, 32, 64]
block2_attn attention x=node:block2_attn_norm/out:[B, 32, 64] out=[B, 32, 64]
block2_attn_residual add a=node:block2_attn/out:[B, 32, 64], b=node:block1_moe_residual/out:[B, 32, 64] out=[B, 32, 64]
block2_moe_norm layer_norm x=node:block2_attn_residual/out:[B, 32, 64] out=[B, 32, 64]
block2_moe moe x=node:block2_moe_norm/out:[B, 32, 64] out=[B, 32, 64]
block2_moe_residual add a=node:block2_moe/out:[B, 32, 64], b=node:block2_attn_residual/out:[B, 32, 64] out=[B, 32, 64]
final_norm layer_norm x=node:block2_moe_residual/out:[B, 32, 64] out=[B, 32, 64]
lm_head linear x=node:final_norm/out:[B, 32, 64] out=[B, 32, 100]
Parameters: 181,888. Top-k expert routing follows Shazeer et al. 2017 ("Outrageously Large Neural Networks") and the Switch Transformer (Fedus et al. 2021); the count was checked against an equivalent plain-PyTorch build: embedding 100·64 = 6,400, positions 32·64 = 2,048, five layer norms 5·128 = 640, two attentions 2·4·(64·64+64) = 33,280, two MoE layers 2·(4·64 + 4·(128·64+128 + 64·128+64)) = 133,120, head 100·64 = 6,400, total 181,888.
NeRF Continuous Coordinate Radiance Field¶
A neural radiance field coordinate network: combined random Fourier and log-spaced sinusoidal positional features on 3D spatial coordinates, MLP trunk with rotary embeddings, and split outputs for RGB color and volume density.
examples/networks/nerf_coord_field.hndl
# Neural Radiance Field (NeRF) coordinate field: random Fourier feature mapping,
# sinusoidal positional embeddings, multi-layer perceptron trunk, rotary embeddings,
# and split prediction for view-independent density and RGB color.
f_emb = fourier_features(coords, 16)
s_emb = sinusoidal_embed(coords, 24)
h = concat(f_emb, s_emb, axis=1)
h = linear(h, 64, name="trunk1")
h = relu(h)
h = reshape(h, 4, 16)
h = rope(h, heads=2)
h = reshape(h, 64)
h = linear(h, 64, name="trunk2")
h = relu(h)
h = linear(h, 4, name="head")
rgb, density = split(h, size=3, dim=1)
rgb = dy_tanh(rgb, dim=3, name="rgb_act")
density = relu(density, name="density_act")
Input coords=['B', 3] → output rgb=['B', 3], density=['B', 1].
Network: coords=[B, 3] -> rgb=[B, 3], density=[B, 1] dtype=float32
name operation input shapes output shapes
n0 fourier_features x=input:coords:[B, 3] out=[B, 32]
n1 sinusoidal_embed x=input:coords:[B, 3] out=[B, 24]
n2 concat x0=node:n0/out:[B, 32], x1=node:n1/out:[B, 24] out=[B, 56]
trunk1 linear x=node:n2/out:[B, 56] out=[B, 64]
n4 relu x=node:trunk1/out:[B, 64] out=[B, 64]
n5 reshape x=node:n4/out:[B, 64] out=[B, 4, 16]
n6 rope x=node:n5/out:[B, 4, 16] out=[B, 4, 16]
n7 reshape x=node:n6/out:[B, 4, 16] out=[B, 64]
trunk2 linear x=node:n7/out:[B, 64] out=[B, 64]
n9 relu x=node:trunk2/out:[B, 64] out=[B, 64]
head linear x=node:n9/out:[B, 64] out=[B, 4]
n11 split x=node:head/out:[B, 4] first=[B, 3], rest=[B, 1]
rgb_act dy_tanh x=node:n11/first:[B, 3] out=[B, 3]
density_act relu x=node:n11/rest:[B, 1] out=[B, 1]
Parameters: 8,075. Architecture follows Mildenhall et al. 2020, "NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis" (arXiv:2003.08934) and Tancik et al. 2020, "Fourier Features Let Networks Learn High Frequency Functions in Low Dimensional Domains" (NeurIPS 2020); parameter count checked against plain PyTorch: trunk1 56·64+64 = 3,648, trunk2 64·64+64 = 4,160, head 64·4+4 = 260, rgb_act dy_tanh(dim=3, affine=True) 1 + 3 + 3 = 7; total = 3,648 + 4,160 + 260 + 7 = 8,075.
Tiny Qwen3 GQA QK-Norm Causal Decoder¶
A 64-token Qwen3-style causal language model: learned token embeddings, 4 transformer blocks combining pre-RMSNorm, Grouped-Query Attention (4 query heads, 2 key/value heads), per-head QK-RMSNorm, high-frequency RoPE (theta = 1,000,000), and bias-free SwiGLU feed-forward networks, followed by a final RMSNorm and vocabulary head.
examples/networks/qwen3_gqa_qknorm.hndl
# Qwen3-style causal decoder: pre-RMSNorm, Grouped-Query Attention (GQA, 4 q-heads,
# 2 kv-heads), per-head QK-RMSNorm, high-theta RoPE (1,000,000), and SwiGLU.
embedding(256, 128, name="tok_emb")
for _ in range(4):
transformer_block(
4, kv_heads=2, hidden=384, ffn_kind="swiglu",
norm="rms_norm", qk_norm="rms_norm",
causal=True, rope=True, rope_theta=1000000.0, bias=False,
name="block",
)
rms_norm(name="final_norm")
linear(bias=False, name="lm_head")
Input ['B', 64] (input_dtype="int64") → output ['B', 64, 256].
Network: [B, 64] -> [B, 64, 256] dtype=float32 input_dtype=int64
index name operation input shape output shape
0 tok_emb embedding [B, 64] [B, 64, 128]
1 block0 transformer_block [B, 64, 128] [B, 64, 128]
2 block1 transformer_block [B, 64, 128] [B, 64, 128]
3 block2 transformer_block [B, 64, 128] [B, 64, 128]
4 block3 transformer_block [B, 64, 128] [B, 64, 128]
5 final_norm rms_norm [B, 64, 128] [B, 64, 128]
6 lm_head linear [B, 64, 128] [B, 64, 256]
Parameters: 853,376. Architecture follows Qwen Team 2024/2025, "Qwen2.5 Technical Report" (arXiv:2412.15115); parameter count checked against plain PyTorch: embedding 256·128 = 32,768, 4 blocks with (norm1 128 + q_proj 128·128 + k_proj 128·64 + v_proj 128·64 + q_norm 32 + k_norm 32 + o_proj 128·128 + norm2 128 + SwiGLU 3·(128·384)) = 4·196,928 = 787,712, final RMSNorm 128, head 128·256 = 32,768; total 32,768 + 787,712 + 128 + 32,768 = 853,376.
ResNet-18¶
The 18-layer residual network: a 7×7/2 stem with max pooling, then four stages of two basic blocks at 64, 128, 256 and 512 channels, a global average pool, and one classifier whose 1000 outputs come from the output contract.
examples/networks/resnet18.hndl
# ResNet-18 (He et al., 2015) for 224x224 ImageNet classification.
# Four stages of two basic blocks each; every stage but the first halves
# height and width and doubles the channel count, ending at 512 on 7x7.
# Stem: 7x7/2 convolution, then 3x3/2 max pooling. 224 -> 112 -> 56.
# The convolution omits its bias because the batch norm that follows cancels it.
conv(64, kernel_size=7, stride=2, padding=3, bias=False, name="stem_conv")
batch_norm(name="stem_norm")
relu()
max_pool(3, stride=2, padding=1, name="stem_pool")
# layer1: 64 channels at 56x56. Both shortcuts are identities - stride 1, same width.
resblock(64, name="layer1_0")
resblock(64, name="layer1_1")
# layer2: 128 channels at 28x28. A strided block projects its shortcut with 1x1 conv + norm.
resblock(128, stride=2, name="layer2_0")
resblock(128, name="layer2_1")
# layer3: 256 channels at 14x14.
resblock(256, stride=2, name="layer3_0")
resblock(256, name="layer3_1")
# layer4: 512 channels at 7x7.
resblock(512, stride=2, name="layer4_0")
resblock(512, name="layer4_1")
# Head: average each of the 512 channels over 7x7, then one classifier.
# Its 1000 outputs are inferred from the output contract.
global_avg_pool()
linear(name="fc")
Input ['B', 3, 224, 224] → output ['B', 1000].
Network: [B, 3, 224, 224] -> [B, 1000] dtype=float32
index name operation input shape output shape
0 stem_conv conv [B, 3, 224, 224] [B, 64, 112, 112]
1 stem_norm batch_norm [B, 64, 112, 112] [B, 64, 112, 112]
2 n2 relu [B, 64, 112, 112] [B, 64, 112, 112]
3 stem_pool max_pool [B, 64, 112, 112] [B, 64, 56, 56]
4 layer1_0 resblock [B, 64, 56, 56] [B, 64, 56, 56]
5 layer1_1 resblock [B, 64, 56, 56] [B, 64, 56, 56]
6 layer2_0 resblock [B, 64, 56, 56] [B, 128, 28, 28]
7 layer2_1 resblock [B, 128, 28, 28] [B, 128, 28, 28]
8 layer3_0 resblock [B, 128, 28, 28] [B, 256, 14, 14]
9 layer3_1 resblock [B, 256, 14, 14] [B, 256, 14, 14]
10 layer4_0 resblock [B, 256, 14, 14] [B, 512, 7, 7]
11 layer4_1 resblock [B, 512, 7, 7] [B, 512, 7, 7]
12 n12 global_avg_pool [B, 512, 7, 7] [B, 512]
13 fc linear [B, 512] [B, 1000]
Parameters: 11,689,512. He et al., "Deep Residual Learning for Image Recognition" (CVPR 2016), configuration ResNet-18; the count equals torchvision.models.resnet18(), sum(p.numel() for p in m.parameters()) == 11,689,512, because hndl's resblock is torchvision's BasicBlock — bias-free 3×3 convolutions with batch norm, and a 1×1 convolution plus norm on each downsampling shortcut.
SAGAN self-attention block¶
The self-attention block of the Self-Attention GAN over a 64-channel 16×16 feature map, written as the single spatial_attention operator: three 1×1 projections, a 256×256 attention map, and a learned gate that starts at zero so the block begins as the identity. The default reduction of 8 gives the paper's C/8 query width, and the batch stays symbolic throughout.
examples/networks/sagan_attention.hndl
# A SAGAN self-attention block (Zhang et al. 2018, section 3) over a
# [B, 64, 16, 16] feature map. Every position attends to every other, so the
# block sees the whole map where a 3x3 convolution sees a neighbourhood.
#
# N = 16*16 = 256 positions, C = 64 channels, and the query/key width is
# C/8 = 8 as in the paper: reduction=8 is the default.
#
# The one operator carries the whole block — the three 1x1 projections, the
# 256x256 attention map, and the learned gate that starts at 0 so the block
# begins as the identity and the network decides how much attention to admit.
spatial_attention()
Input ['B', 64, 16, 16] → output ['B', 64, 16, 16].
Network: [B, 64, 16, 16] -> [B, 64, 16, 16] dtype=float32
index name operation input shape output shape
0 n0 spatial_attention [B, 64, 16, 16] [B, 64, 16, 16]
Parameters: 5,201. Zhang, Goodfellow, Metaxas & Odena, "Self-Attention Generative Adversarial Networks" (ICML 2019, arXiv 2018), section 3: f and g project to C/8 = 8 channels, h keeps C = 64, the attention map is softmax(f(x)^T g(x)) over the key positions, and the output is y = gamma * o + x with gamma initialized to 0. The count matches the same block in plain torch — three Conv2d(1×1) layers with bias (64·8+8 twice and 64·64+64) plus the single gamma — which also gives 5,201.
Small U-Net¶
An encoder–decoder with skip connections for 32×32 segmentation: two 16- and 32-channel down stages, a 64-channel bottleneck, and two up stages that concatenate the matching encoder tensor before convolving. The single output channel of the 1×1 head is inferred from the output contract.
examples/networks/unet_small.hndl
# A small U-Net for 32×32 segmentation: two down stages, a bottleneck, two up
# stages. Every 3×3 convolution uses padding 1, so only the pools and the
# upsamples change the resolution.
# --- Encoder stage 1: 32×32, 16 channels --------------------------------------
conv(16, kernel_size=3, padding=1)
relu()
conv(16, kernel_size=3, padding=1)
skip1 = relu(name="skip1") # [B, 16, 32, 32], kept for the last merge
max_pool(2) # -> 16×16
# --- Encoder stage 2: 16×16, 32 channels --------------------------------------
conv(32, kernel_size=3, padding=1)
relu()
conv(32, kernel_size=3, padding=1)
skip2 = relu(name="skip2") # [B, 32, 16, 16], kept for the first merge
max_pool(2) # -> 8×8
# --- Bottleneck: 8×8, 64 channels ---------------------------------------------
conv(64, kernel_size=3, padding=1)
relu()
conv(64, kernel_size=3, padding=1)
relu()
# --- Decoder stage 2: back to 16×16 -------------------------------------------
upsample(2) # nearest-neighbour, no parameters
conv(32, kernel_size=3, padding=1) # the "up-conv" that halves the channels
upconv2 = relu(name="upconv2")
concat(skip2, upconv2) # 32 + 32 -> 64 channels
conv(32, kernel_size=3, padding=1)
relu()
conv(32, kernel_size=3, padding=1)
relu()
# --- Decoder stage 1: back to 32×32 -------------------------------------------
upsample(2)
conv(16, kernel_size=3, padding=1)
upconv1 = relu(name="upconv1")
concat(skip1, upconv1) # 16 + 16 -> 32 channels
conv(16, kernel_size=3, padding=1)
relu()
conv(16, kernel_size=3, padding=1)
relu()
# --- Head: one logit per pixel; the single channel comes from the contract ----
conv(kernel_size=1, name="logits")
Input ['B', 3, 32, 32] → output ['B', 1, 32, 32].
Network: [B, 3, 32, 32] -> [B, 1, 32, 32] dtype=float32
name operation input shapes output shapes
n0 conv x=input:x:[B, 3, 32, 32] out=[B, 16, 32, 32]
n1 relu x=node:n0/out:[B, 16, 32, 32] out=[B, 16, 32, 32]
n2 conv x=node:n1/out:[B, 16, 32, 32] out=[B, 16, 32, 32]
skip1 relu x=node:n2/out:[B, 16, 32, 32] out=[B, 16, 32, 32]
n4 max_pool x=node:skip1/out:[B, 16, 32, 32] out=[B, 16, 16, 16]
n5 conv x=node:n4/out:[B, 16, 16, 16] out=[B, 32, 16, 16]
n6 relu x=node:n5/out:[B, 32, 16, 16] out=[B, 32, 16, 16]
n7 conv x=node:n6/out:[B, 32, 16, 16] out=[B, 32, 16, 16]
skip2 relu x=node:n7/out:[B, 32, 16, 16] out=[B, 32, 16, 16]
n9 max_pool x=node:skip2/out:[B, 32, 16, 16] out=[B, 32, 8, 8]
n10 conv x=node:n9/out:[B, 32, 8, 8] out=[B, 64, 8, 8]
n11 relu x=node:n10/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
n12 conv x=node:n11/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
n13 relu x=node:n12/out:[B, 64, 8, 8] out=[B, 64, 8, 8]
n14 upsample x=node:n13/out:[B, 64, 8, 8] out=[B, 64, 16, 16]
n15 conv x=node:n14/out:[B, 64, 16, 16] out=[B, 32, 16, 16]
upconv2 relu x=node:n15/out:[B, 32, 16, 16] out=[B, 32, 16, 16]
n17 concat x0=node:skip2/out:[B, 32, 16, 16], x1=node:upconv2/out:[B, 32, 16, 16] out=[B, 64, 16, 16]
n18 conv x=node:n17/out:[B, 64, 16, 16] out=[B, 32, 16, 16]
n19 relu x=node:n18/out:[B, 32, 16, 16] out=[B, 32, 16, 16]
n20 conv x=node:n19/out:[B, 32, 16, 16] out=[B, 32, 16, 16]
n21 relu x=node:n20/out:[B, 32, 16, 16] out=[B, 32, 16, 16]
n22 upsample x=node:n21/out:[B, 32, 16, 16] out=[B, 32, 32, 32]
n23 conv x=node:n22/out:[B, 32, 32, 32] out=[B, 16, 32, 32]
upconv1 relu x=node:n23/out:[B, 16, 32, 32] out=[B, 16, 32, 32]
n25 concat x0=node:skip1/out:[B, 16, 32, 32], x1=node:upconv1/out:[B, 16, 32, 32] out=[B, 32, 32, 32]
n26 conv x=node:n25/out:[B, 32, 32, 32] out=[B, 16, 32, 32]
n27 relu x=node:n26/out:[B, 16, 32, 32] out=[B, 16, 32, 32]
n28 conv x=node:n27/out:[B, 16, 32, 32] out=[B, 16, 32, 32]
n29 relu x=node:n28/out:[B, 16, 32, 32] out=[B, 16, 32, 32]
logits conv x=node:n29/out:[B, 16, 32, 32] out=[B, 1, 32, 32]
Parameters: 129,841. Ronneberger, Fischer & Brox, "U-Net: Convolutional Networks for Biomedical Image Segmentation" (MICCAI 2015), scaled down to 16/32/64 channels with padded 3×3 convolutions and nearest-neighbour up-convolutions; the count was checked against the same architecture written as a plain torch.nn.Module (448 + 2320 + 4640 + 9248 + 18496 + 36928 + 18464 + 18464 + 9248 + 4624 + 4624 + 2320 + 17 = 129,841 over its 13 convolutions).
Tiny Vision Transformer¶
A ViT-Tiny-shaped classifier for 32×32 RGB images: a 4×4 patch stem of width 192, a learned class token and position table, four pre-norm transformer blocks with 3 heads, then a final layer norm and a linear head read off the class position.
examples/networks/vit_tiny.hndl
# A tiny Vision Transformer (ViT) for 32x32 RGB images.
# Width 192, depth 4, 3 heads (head width 64) — ViT-Tiny proportions at CIFAR scale.
# Stem: 4x4 patches of a 32x32 image give (32/4)*(32/4) = 64 tokens of width 192.
patch_embed(192, 4, name="patches")
# Prepend the learned [CLS] summary position, then add absolute positions.
cls_token(name="cls")
pos_embed(65) # 64 patch tokens + the class token
# Encoder: four pre-norm blocks, gelu feed-forward of width 4*192 = 768.
for _ in range(4):
transformer_block(3, mlp_ratio=4)
# Head: normalize, read the class position, classify.
layer_norm(name="final_norm")
pool_tokens("first")
linear() # 10 classes, inferred from the output contract
Input ['B', 3, 32, 32] → output ['B', 10].
Network: [B, 3, 32, 32] -> [B, 10] dtype=float32
index name operation input shape output shape
0 patches patch_embed [B, 3, 32, 32] [B, 64, 192]
1 cls cls_token [B, 64, 192] [B, 65, 192]
2 n2 pos_embed [B, 65, 192] [B, 65, 192]
3 n3 transformer_block [B, 65, 192] [B, 65, 192]
4 n4 transformer_block [B, 65, 192] [B, 65, 192]
5 n5 transformer_block [B, 65, 192] [B, 65, 192]
6 n6 transformer_block [B, 65, 192] [B, 65, 192]
7 final_norm layer_norm [B, 65, 192] [B, 65, 192]
8 n8 pool_tokens [B, 65, 192] [B, 192]
9 n9 linear [B, 192] [B, 10]
Parameters: 1,803,850. Dosovitskiy et al. 2020, "An Image Is Worth 16x16 Words" (ViT), in the ViT-Tiny configuration (width 192, 3 heads, mlp_ratio 4) at depth 4 with a 4×4 patch stem on 32×32 inputs; checked against an equivalent plain-PyTorch build: 9,408 stem + 192 class token + 12,480 positions + 4·444,864 blocks + 384 final norm + 1,930 head = 1,803,850.
Tiny Whisper Audio Seq2Seq Model¶
A speech-to-text sequence-to-sequence model: 2-layer 1D convolutional audio stem downsampling 40-channel log-mel spectrogram frames by 2x, a 64-width transformer encoder, and a 16-token causal decoder with self-attention, acoustic cross-attention, and SwiGLU feed-forward networks.
examples/networks/whisper_seq2seq_tiny.hndl
# Whisper-style speech-to-token encoder-decoder: 2-layer Conv1d acoustic stem
# downsampling spectrogram frames by 2x, bidirectional encoder, and causal
# decoder attending to acoustic features via cross_attention.
conv1d(x, 64, kernel_size=3, padding=1, name="stem1")
gelu()
conv1d(64, kernel_size=3, stride=2, padding=1, name="stem2")
gelu()
enc = transpose(1, 2, name="to_seq")
enc = pos_embed(enc, 32, name="enc_pos")
enc = transformer_block(enc, 4, norm="rms_norm", name="enc_block")
dec = embedding(tokens, 128, 64, name="dec_emb")
dec = pos_embed(dec, 16, name="dec_pos")
dec = add(dec, attention(rms_norm(dec, name="self_norm"), 4, causal=True, rope=True, bias=False, name="self_attn"))
dec = add(dec, cross_attention(rms_norm(dec, name="cross_norm"), enc, 4, bias=False, name="cross_attn"))
dec = add(dec, swiglu(rms_norm(dec, name="ffn_norm"), 192, bias=False, name="ffn"))
rms_norm(dec, name="out_norm")
linear(bias=False, name="head")
Input x=['B', 40, 64], tokens=['B', 16] (input_dtype="{'tokens': 'int64'}") → output ['B', 16, 128].
Network: x=[B, 40, 64], tokens=[B, 16] -> [B, 16, 128] dtype=float32 input_dtype=tokens=int64
name operation input shapes output shapes
stem1 conv1d x=input:x:[B, 40, 64] out=[B, 64, 64]
n1 gelu x=node:stem1/out:[B, 64, 64] out=[B, 64, 64]
stem2 conv1d x=node:n1/out:[B, 64, 64] out=[B, 64, 32]
n3 gelu x=node:stem2/out:[B, 64, 32] out=[B, 64, 32]
to_seq transpose x=node:n3/out:[B, 64, 32] out=[B, 32, 64]
enc_pos pos_embed x=node:to_seq/out:[B, 32, 64] out=[B, 32, 64]
enc_block transformer_block x=node:enc_pos/out:[B, 32, 64] out=[B, 32, 64]
dec_emb embedding ids=input:tokens:[B, 16] out=[B, 16, 64]
dec_pos pos_embed x=node:dec_emb/out:[B, 16, 64] out=[B, 16, 64]
self_norm rms_norm x=node:dec_pos/out:[B, 16, 64] out=[B, 16, 64]
self_attn attention x=node:self_norm/out:[B, 16, 64] out=[B, 16, 64]
n11 add a=node:dec_pos/out:[B, 16, 64], b=node:self_attn/out:[B, 16, 64] out=[B, 16, 64]
cross_norm rms_norm x=node:n11/out:[B, 16, 64] out=[B, 16, 64]
cross_attn cross_attention x=node:cross_norm/out:[B, 16, 64], context=node:enc_block/out:[B, 32, 64] out=[B, 16, 64]
n14 add a=node:n11/out:[B, 16, 64], b=node:cross_attn/out:[B, 16, 64] out=[B, 16, 64]
ffn_norm rms_norm x=node:n14/out:[B, 16, 64] out=[B, 16, 64]
ffn swiglu x=node:ffn_norm/out:[B, 16, 64] out=[B, 16, 64]
n17 add a=node:n14/out:[B, 16, 64], b=node:ffn/out:[B, 16, 64] out=[B, 16, 64]
out_norm rms_norm x=node:n17/out:[B, 16, 64] out=[B, 16, 64]
head linear x=node:out_norm/out:[B, 16, 64] out=[B, 16, 128]
Parameters: 159,296. Architecture follows Radford et al. 2022, "Robust Speech Recognition via Large-Scale Weak Supervision" (Whisper, arXiv:2212.04356); parameter count checked against plain PyTorch: encoder (stem1 64·40·3+64 = 7,744, stem2 64·64·3+64 = 12,352, pos 32·64 = 2,048, block 64 + 4·(64·64+64) + 64 + 64·256+256 + 256·64+64 = 49,856; total 72,000) + decoder (emb 128·64 = 8,192, pos 16·64 = 1,024, self_norm 64, self_attn 4·(64·64) = 16,384, cross_norm 64, cross_attn 4·(64·64) = 16,384, ffn_norm 64, ffn 3·(64·192) = 36,864, out_norm 64, head 64·128 = 8,192; total 87,296); total 72,000 + 87,296 = 159,296.