Neural Networks with PyTorch — From Numbers to Language

A progressive, hands-on introduction to neural networks with PyTorch. The same next-token prediction idea is applied four times at increasing scale:

  1. Setup — verify the PyTorch installation.
  2. Numbers — a minimal RNN learns a cyclic mapping: 1 → 2, 2 → 3, 3 → 1.
  3. Characters — a character-level RNN learns to continue "hello world".
  4. Language — a character-level language model trained on Portuguese proverbs (ditados populares) completes prompts with plausible text.

Each exercise introduces one building block — tensors, loss functions, embeddings, hidden state — that the next one reuses.

1. Setup — Testing Torch

Install PyTorch and confirm the version.

%pip install -q torch
import torch
 
torch.__version__

2. Simple Neural Network — Predicting Numbers

A minimal RNN learns a cyclic mapping from the training data: 1 → 2, 2 → 3, 3 → 1.

nn_learning_10steps.gif

Sample data

import torch
import torch.nn as nn

Fix the random seed first so weight initialisation — and therefore every result in this section — is reproducible across runs:

torch.manual_seed(50)
torch.__version__

Three inputs and their targets, shaped as tensors. unsqueeze(1) expands the shape from (3, 1) to (3, 1, 1) — the (batch, seq_len, features) layout that a batch_first RNN expects, so each number is treated as a one-step sequence:

Shape check

inputs: — three samples, one time step, one feature. targets: — one scalar per sample.

inputs = torch.tensor([[1.0], [2.0], [3.0]], dtype=torch.float32).unsqueeze(1)
targets = torch.tensor([[2.0], [3.0],[1.0]], dtype=torch.float32)
 
print('input', inputs.tolist())
print('output', targets.tolist())

Define the RNN model

The model stacks two layers:

  • nn.RNN — maps the input to a hidden state of 96 neurons. Because an RNN carries information across time steps, it can learn a sequence rule rather than a static lookup.
  • nn.Linear — maps the hidden state at the last time step (out[:, -1, :]) to a single output value.
class SimpleRNN(nn.Module):
 
    neurons  = 96
 
    def __init__(self):
        super(SimpleRNN, self).__init__()
        self.rnn = nn.RNN(input_size=1, hidden_size=self.neurons, batch_first=True)
        self.fc = nn.Linear(self.neurons, 1)
 
    def forward(self, x):
        out, _ = self.rnn(x)
        out = self.fc(out[:, -1, :])
        return out

Initialise model, loss and optimiser

Three components are needed for training:

ComponentRole
modelThe network whose weights are learned
criterion (nn.MSELoss)Mean squared error — measures how far predictions are from targets; the natural choice for regression on numbers
optimizer (Adam, lr=0.001)Updates the weights in the direction that reduces the loss; the learning rate controls the step size
model = SimpleRNN()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

Training

Train for 2000 epochs, printing the loss every 100 epochs. Each epoch runs the standard PyTorch training loop: optimizer.zero_grad() clears the gradients left by the previous step (otherwise they accumulate), loss.backward() computes new gradients by backpropagation, and optimizer.step() applies the weight update. The loss should fall steadily toward 0:

for epoch in range(2000):
    output = model(inputs)
    loss = criterion(output, targets)
 
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
 
    if (epoch + 1) % 100 == 0:
        print(f"Epoch {epoch+1}, Loss: {loss.item():.4f}")

Testing the model

with torch.no_grad() disables gradient tracking — inference needs no backpropagation, and skipping it saves memory and time. Expect predictions close to 2, 3 and 1:

with torch.no_grad():
    test_input = torch.tensor([[1.0]], dtype=torch.float32).unsqueeze(1)
    prediction = model(test_input).item()
    print(f"Input: 1 → Predicted: {prediction:.2f}")
 
    test_input = torch.tensor([[2.0]], dtype=torch.float32).unsqueeze(1)
    prediction = model(test_input).item()
    print(f"Input: 2 → Predicted: {prediction:.2f}")
 
    test_input = torch.tensor([[3.0]], dtype=torch.float32).unsqueeze(1)
    prediction = model(test_input).item()
    print(f"Input: 3 → Predicted: {prediction:.2f}")

Generalisation test

The model never saw 4 during training. If it truly learned the cyclic pattern, it should predict 2:

Memorisation or pattern?

A network can pass the first three tests by memorising the training pairs. Input 4 is the real test: an output near 2 suggests the model learned the rule add 1, wrapping around after 3 — that is, it generalised beyond the examples it saw.

with torch.no_grad():
    test_input = torch.tensor([[4.0]], dtype=torch.float32).unsqueeze(1)
    prediction = model(test_input).item()
    print(f"Input: 4 → Predicted: {prediction:.2f}")

3. Hello World — Predicting the Next Character

A character-level RNN that learns to predict the next letter in hello world. This next-token prediction is the same core idea behind the deep learning architectures (such as the Transformer) that power modern LLMs — here the “token” is a single character.

Sample text data

First, encode characters as integers. The vocabulary is the sorted set of unique characters in the text — 11 here, including the space. Two dictionaries make the mapping reversible: char2idx for encoding, idx2char for decoding.

import torch
import torch.nn as nn
text = "hello world"
chars = sorted(list(set(text)))
char2idx = {c: i for i, c in enumerate(chars)}
idx2char = {i: c for i, c in enumerate(chars)}
vocab_size = len(chars)
print(idx2char)

Prepare training data

Use a sliding window: 4 characters as input, the next character as target. Sliding one character at a time over the 11-character text produces 7 training pairs:

Input (4 chars)Target
hello
ello␣
llo␣w
……
seq_length = 4
X = []
y = []
for i in range(len(text) - seq_length):
    input_seq = [char2idx[c] for c in text[i:i + seq_length]]
    target = char2idx[text[i + seq_length]]
    X.append(input_seq)
    y.append(target)
print('X=', X)
print('Y=', y)

Convert to tensors

Both inputs and targets become integer tensors. CrossEntropyLoss expects the target as a class index, so no one-hot encoding is needed:

X = torch.tensor(X, dtype=torch.long)
y = torch.tensor(y, dtype=torch.long)
X

Define the model

The pipeline has three stages:

  1. Embedding — nn.Embedding turns each character id into a dense 64-dim vector that is learned during training, a much richer representation than one-hot encoding.
  2. RNN — reads the vector sequence and produces a hidden state for each time step.
  3. Linear — maps the last hidden state to a score (logit) for every character in the vocabulary; the highest score is the model’s prediction.

With 11 possible answers, this is a classification problem — hence nn.CrossEntropyLoss here instead of the MSE used in section 2:

class CharRNN(nn.Module):
    def __init__(self, vocab_size, hidden_size=64):
        super().__init__()
        self.embed = nn.Embedding(vocab_size, hidden_size)
        self.rnn = nn.RNN(hidden_size, hidden_size, batch_first=True)
        self.fc = nn.Linear(hidden_size, vocab_size)
 
    def forward(self, x):
        x = self.embed(x)
        out, _ = self.rnn(x)
        out = self.fc(out[:, -1, :])
        return out
 
model = CharRNN(vocab_size)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
loss_fn = nn.CrossEntropyLoss()

Training

The loop structure is identical to section 2; only the loss differs. With just 7 training samples the model fits the text within a few hundred epochs:

for epoch in range(200):
    model.train()
    optimizer.zero_grad()
    output = model(X)
    loss = loss_fn(output, y)
    loss.backward()
    optimizer.step()
    if (epoch + 1) % 50 == 0:
        print(f"Epoch {epoch+1}, Loss: {loss.item():.4f}")

Predicting the next letter

predict_next_letter encodes the last seq_length characters of the seed, runs one forward pass, and picks the character with the highest logit via argmax. Always taking the most likely option is called greedy decoding:

def predict_next_letter(seed):
    model.eval()
    result = seed
    input_seq = [char2idx[c] for c in seed[-seq_length:]]
    x = torch.tensor([input_seq], dtype=torch.long)
    with torch.no_grad():
            output = model(x)
            next_idx = torch.argmax(output, dim=1).item()
            next_char = idx2char[next_idx]
            result += next_char
            seed += next_char
    return result
predict_next_letter('hell')

Text generation

Feed each predicted character back into the model and keep generating until the text reaches the target length. Each iteration keeps only the last 4 characters (seed[-seq_length:]) as context, so a single starting letter is enough — the window fills up as generation proceeds:

def generate_text(seed, length=len(text)):
    model.eval()
    result = seed
    length -= len(seed)
    for _ in range(length):
        input_seq = [char2idx[c] for c in seed[-seq_length:]]
        x = torch.tensor([input_seq], dtype=torch.long)
        with torch.no_grad():
            output = model(x)
            next_idx = torch.argmax(output, dim=1).item()
            next_char = idx2char[next_idx]
            result += next_char
            seed += next_char
    return result
generate_text("h")

4. A Tiny Language Model — Portuguese Proverbs

Scale up the same idea: a character-level language model trained on a corpus of Portuguese proverbs (ditados populares) that completes prompts with plausible text. The model, loss and generation loop are the same as in section 3 — only the data pipeline and the size of the model change.

Configuration

import torch
import torch.nn as nn
import torch.optim as optim
import random
ParameterValueMeaning
SEQ_LENGTH100Characters per training sequence
HIDDEN_SIZE128RNN hidden state dimension
NUM_LAYERS1Stacked RNN layers
NUM_EPOCHS3000Training iterations
LR0.001Learning rate
SEQ_LENGTH = 100
HIDDEN_SIZE = 128
NUM_LAYERS = 1
NUM_EPOCHS = 3000
LR = 0.001

Load and preprocess the text

Requires ditados_populares.txt in the same folder as the notebook.

ditados_populares.txt

aguas passadas nao movem moinhos.
amigo nao empata amigo.
agua mole em pedra dura tanto da ate que fura.
a ocasiao faz o ladrao.
a cavalo dado nao se olha a dente.
antes so do que mal acompanhado.
a preguica e mae de todos os vicios.
a pensar morreu um burro.
antes so que mal acompanhado.

Newlines are removed and the text is lowercased. Lowercasing shrinks the vocabulary (no separate A/a entries means fewer parameters to learn), and removing newlines lets training sequences flow continuously across line boundaries:

with open("ditados_populares.txt", "r", encoding="utf-8") as f:
    text = f.read().replace('\n', '').lower()
text

Character mappings

The same vocabulary logic as section 3, now computed over the whole corpus:

# Create character mappings
chars = sorted(list(set(text)))
char2idx = {ch: i for i, ch in enumerate(chars)}
idx2char = {i: ch for ch, i in char2idx.items()}
vocab_size = len(chars)
idx2char

Prepare sequences

Sample random chunks of text: the input is the chunk without its last character, the target is the chunk without its first. For a chunk abcde, the input is abcd and the target is bcde — every position is a training example, so one chunk of length 101 yields 100 next-character predictions.

Two differences from section 3:

  • The window is much longer: SEQ_LENGTH = 100 characters of context instead of 4.
  • Chunks start at a random offset each epoch instead of covering every position — a lightweight form of stochastic training.
def char_tensor(string):
    tensor = torch.zeros(len(string)).long()
    for c in range(len(string)):
        tensor[c] = char2idx[string[c]]
    return tensor
 
def get_batch(seq_length=SEQ_LENGTH):
    start_index = random.randint(0, len(text) - seq_length - 1)
    end_index = start_index + seq_length + 1
    chunk = text[start_index:end_index]
    input_seq = char_tensor(chunk[:-1])
    target_seq = char_tensor(chunk[1:])
    return input_seq, target_seq

RNN model

Compared with the previous models, this one keeps the hidden state outside the forward pass: init_hidden() creates the zero initial state and the caller passes it back in on every step. The output is flattened to (batch × seq_len, vocab_size) so that every position can be scored against its target character by CrossEntropyLoss:

class CharRNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(CharRNN, self).__init__()
        self.rnn = nn.RNN(input_size, hidden_size, NUM_LAYERS, batch_first=True)
        self.fc = nn.Linear(hidden_size, output_size)
        self.hidden_size = hidden_size
        self.embedding = nn.Embedding(input_size, input_size)
 
    def forward(self, x, hidden):
        x = self.embedding(x)
        out, hidden = self.rnn(x, hidden)
        out = self.fc(out.reshape(out.size(0)*out.size(1), out.size(2)))
        return out, hidden
 
    def init_hidden(self):
        return torch.zeros(NUM_LAYERS, 1, self.hidden_size)
 
# Initialize model
model = CharRNN(vocab_size, HIDDEN_SIZE, vocab_size)
optimizer = optim.Adam(model.parameters(), lr=LR)
loss_fn = nn.CrossEntropyLoss()

Training

One random batch per epoch — a single gradient update on one random excerpt of the corpus, repeated NUM_EPOCHS = 3000 times. The hidden state starts fresh (init_hidden()) for every batch:

print("Training...")
for epoch in range(NUM_EPOCHS):
    inputs, targets = get_batch()
    inputs = inputs.unsqueeze(0)
    targets = targets.view(-1)
 
    hidden = model.init_hidden()
    optimizer.zero_grad()
    output, hidden = model(inputs, hidden)
    loss = loss_fn(output, targets)
    loss.backward()
    optimizer.step()
 
    if (epoch+1) % 50 == 0:
        print(f"Epoch {epoch+1}/{NUM_EPOCHS}, Loss: {loss.item():.4f}")

Text generation

Generate greedily (always the most likely next character) until a . ends the answer or max_len is reached. Unlike generate_text in section 3, the prompt is fed in once and only the last predicted character is appended on each step — the hidden state carries the context, so no sliding window is needed:

Greedy vs sampling

topk(logits, 1) always takes the single most likely character, which makes the output deterministic but prone to repetition. Replacing it with a random draw from the logits (temperature sampling) adds variety — a good follow-up exercise.

def generate_answer(prompt, max_len=72):
    model.eval()
    with torch.no_grad():
        input_seq = char_tensor(prompt.lower()).unsqueeze(0)
        hidden = model.init_hidden()
        output_chars = list(prompt)
 
        for i in range(max_len):
            output, hidden = model(input_seq, hidden)
            last_char_logits = output[-1]
            _, top_idx = torch.topk(last_char_logits, 1)
            predicted_char = idx2char[top_idx.item()]
            output_chars.append(predicted_char)
            input_seq = char_tensor(predicted_char).unsqueeze(0)
            if predicted_char == '.':
                break
        return ''.join(output_chars)

Ask questions

Prompts are lowercased inside generate_answer, matching how the training text was preprocessed:

question = 'aguas'
answer = generate_answer(question)
print(answer)
question = 'Completa o ditado amigo nao'
answer = generate_answer(question)
print(answer)