Please enable JavaScript to use CodeHS

AI Explained

Build it yourself

The best way to understand modern AI is to build a tiny version. In this tutorial you will recreate a 2-input, 1-output neural network in PyTorch and train it to learn the AND gate.

AI ~15 min High school
Capstone

The full picture

You have now seen the pieces: numbers, vectors, optimization, neural networks, embeddings, attention, training tricks, efficient architectures, reinforcement learning, reasoning, multimodal models, and agents. In this final tutorial we put them together by writing the training loop for a real neural network.

We will use the PyTorch library, which is the most common framework for building and training neural networks. The code looks almost like math written in Python.

Core idea: training a network means defining a model, picking a loss, computing gradients, and updating weights. That same loop scales from this 3-weight toy to billion-parameter models.


Code

PyTorch code

Here is a complete network that learns AND from four examples. Two inputs, one output, logistic sigmoid, binary cross-entropy loss, and the Adam optimizer.

and_network.py
import torch
import torch.nn as nn

# Training data for AND
X = torch.tensor([[0,0], [0,1], [1,0], [1,1]], dtype=torch.float32)
y = torch.tensor([[0],     [0],     [0],     [1]],     dtype=torch.float32)

# One linear layer: 2 inputs -> 1 output
model = nn.Linear(2, 1)

# Binary cross-entropy loss with logits
criterion = nn.BCEWithLogitsLoss()

# Adam optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=0.1)

for epoch in range(200):
    optimizer.zero_grad()
    logits = model(X)
    loss = criterion(logits, y)
    loss.backward()
    optimizer.step()
    print(f"Epoch {epoch}: loss = {loss.item():.4f}")

After training, the model predicts close to 0 for (0,0), (0,1), and (1,0), and close to 1 for (1,1). The whole pipeline — data, model, loss, gradients, optimizer — is the same one used for ChatGPT, just with more layers, more data, and more compute.


Interactive

Train a tiny network

The network below learns the AND gate. Adjust the starting weights and bias, then click Train 100 steps to watch loss drop and predictions sharpen.

Input (x1, x2)TargetPrediction
Loss: --

Check yourself
?

Why do we call optimizer.zero_grad() before each step?

Think about what would happen if old gradients accumulated each time.

Gradients add up by default in PyTorch. If we did not zero them, each step would also include gradients from the previous step, sending the weights in the wrong direction. Zeroing makes each update only reflect the current batch.


Quick quiz

Three questions

1. What does loss.backward() do?

2. What does the optimizer do?

3. Why does the same training loop work for tiny AND models and giant LLMs?

You made it

You have now completed the AI Explained series. You understand how numbers become vectors, how models learn, how transformers reason over sequences, and how AI agents can act. If you want to go deeper, the next step is to write real code in Python and PyTorch on CodeHS.

Part of the AI Explained tutorial series.