Introduction to Artificial Intelligence - Homework Assignment 08 (5 pts.)¶

  • Name:
  • NETID:

A Message in the Letters Due November 23, 2026.

This assignment covers:

  • Text as counts: bags of words and characters and cosine similarity, used to identify the cipher
  • Token IDs, padding, and one-hot targets for batches of phrases (supplied this week)
  • The layers of a recurrent network: a linear layer, an embedding layer built on it, and tanh
  • The recurrent block: one shared cell applied at every position, with its hidden states cached for next week
  • The same network in PyTorch (nn.Embedding, nn.RNN, nn.Linear), checked against yours
Task Description Points
00 Open the corrected transcription 0
01 Which cipher? Bags of words, bags of characters, and cosine similarity 0.875
02 Our own training phrases, as token batches (supplied) 0.125
03 The layers: linear, embedding, and tanh 0.75
04 The recurrent block and the network 2.00
05 The same network in PyTorch, and the untrained reading 0.75
06 Report the results to Caulfield 0.50
07 Export the notebook 0
Total 5.00

Run the cells in order and answer the written questions. Like HW06, this assignment builds a network but does not train it: every model this week keeps its random starting weights. HW09 teaches it to decode.

Story Progression¶

The forensics lab sent back the cut-out letters with a few corrections in red pencil. Your CNN had read about four letters in five correctly; the lab fixed the rest. Caulfield now has a clean, checked transcription of all four pages.

It still makes no sense: "v ybirq zheqrevat ze gurvfrasyblq ng gur rfgngr…"

Caulfield spreads the pages across his desk. The words have the right lengths for English, the spaces fall in natural places, and there's even a number, 69, sitting in the middle of the third page. Somebody has encoded the message, letter by letter. The department's cipher unit has a shortlist of five ciphers it has seen in cases like this one.

This week we'll test that hunch with a few measurements, then start building a model that can learn to translate an encoded message from examples: a recurrent neural network, which reads a sequence one character at a time and carries a memory of what it has seen so far. Our network will start untrained, so its first translation will be nonsense. HW09 will teach it.

Evidence 1: Caulfield studies the checked transcription while the lab's computer tallies its letters.
Evidence 1: Caulfield studies the checked transcription while the lab's computer tallies its letters.

Task 00: Open the Corrected Transcription¶

Task 00-1: Description (0 pts.)¶

The Evidence for This Week¶

File Contents Used in
cipher_note.txt The lab's checked transcription of all four pages, in lowercase, as one line Every task

That's the only file. There's no training data in the evidence folder: until we know how the note was encoded, we couldn't make examples of it anyway. Task 01 finds out which cipher was used, and Task 02 builds training data to match.

Nothing to implement here: run the cell and read the printed summary.

Task 00-1: Code (0 pts.)¶

In [ ]:
import os
import shutil
import subprocess
from pathlib import Path

REPO_URL = 'https://github.com/wtheisen/nd-cse-30124-homeworks.git'

try:
    import google.colab
except ImportError:
    # Reuse a local checkout, including when launched from a homework subfolder.
    DATA_ROOT = next((p for p in [Path.cwd(), *Path.cwd().parents]
                      if (p / '.git').exists() and (p / 'evidence').is_dir()), None)
    if DATA_ROOT is None:
        DATA_ROOT = Path.cwd() / 'nd-cse-30124-homeworks'
else:
    # Leave the old checkout before deleting it, including on a setup-cell rerun.
    os.chdir('/content')
    DATA_ROOT = Path('/content/nd-cse-30124-homeworks')
    # Fetch fresh evidence every time this cell runs in Colab.
    if DATA_ROOT.exists():
        shutil.rmtree(DATA_ROOT)

if not DATA_ROOT.exists():
    subprocess.run(['git', 'clone', REPO_URL, str(DATA_ROOT)], check=True)

if not (DATA_ROOT / '.git').exists():
    raise RuntimeError(f'{DATA_ROOT} exists but is not a Git checkout. Choose a different clone location.')

# All later relative paths now start at the homework repository root.
os.chdir(DATA_ROOT)
DATA_ROOT = Path.cwd()

import json
import math
import random
import nltk
import sys
import warnings
import string
import codecs
from collections import Counter, namedtuple
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import Dataset, DataLoader

with warnings.catch_warnings():
    warnings.simplefilter('ignore', SyntaxWarning)   # pycipher has an old regex escape
    try:
        import pycipher
    except ImportError:   # not preinstalled on Colab
        subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', 'pycipher'], check=True)
    from pycipher import Caesar, Vigenere, Affine, SimpleSubstitution

torch.set_num_threads(2)
torch.manual_seed(42)

EVIDENCE_DIR = DATA_ROOT / 'evidence' / 'homework08'
required = ['cipher_note.txt']
if any(not (EVIDENCE_DIR / name).is_file() for name in required):
    raise FileNotFoundError('HW08 evidence is missing. Rerun the setup cell with an internet connection, or check that your local repository contains the evidence/homework08 files.')
os.chdir(EVIDENCE_DIR)

letter_text = Path('cipher_note.txt').read_text().strip()

print('Note length:', len(letter_text), 'characters,', len(letter_text.split()), 'words')
print('Note begins:', letter_text[:59])

Task 00-1: Expected Output (0 pts.)¶

Note length: 262 characters, 49 words
Note begins: v ybirq zheqrevat ze gurvfrasyblq ng gur rfgngr gur tnf jnf

Task 01: Which Cipher Is It?¶

Task 01-1: Description (0 pts.)¶

The forensics unit has identified 5 possible ciphers that could have been used to generate the text in the note.

Five candidate ciphers from the pycipher library, each with a fixed key. Caesar(3): hello becomes KHOOR. Caesar(13), ROT13, its own inverse: URYYB. Vigenere with key clue: the shift cycles through the key, JPFPQ, so the two ls become different letters and counts are blurred. Affine(5, 8): x becomes (5x + 8) mod 26, RCLLA. SimpleSubstitution: a fixed scrambled alphabet, ITSSG. All but Vigenere rename letters consistently. encipher returns capitals and drops spaces, digits and punctuation. The test: encode an English sample with each candidate, compare its word and character bags with the note, and score BoW + BoC. The keys are fixed, so a low score rules out that key, not the whole family.

We can generate examples of text encoded with the 5 candidate ciphers, and then using NLP techniques compare them to the encoded note and see if any match as the likely cipher! We can compare them using two techniques: Bag of Words and Bag of Characters.

Two bags. A bag of words splits on spaces and counts each word: the cat saw the dog gives the 2, cat 1, saw 1, dog 1, the same bag as the dog saw the cat. A bag of characters counts each letter and digit and skips spaces and punctuation: the cat gives t 2, h 1, e 1, c 1, a 1. In a cipher, a word matches only if it was encoded exactly the same way and the spaces survived; a consistent letter renaming moves each letter's count to a new letter, so the sample encoded with the note's cipher has its counts on the same letters as the note. Cosine similarity turns the comparison into one number.

Cosine similarity is one of the most common ways to compare things in NLP tasks.

Cosine similarity compares the directions of two count vectors and ignores their lengths: cos theta = a dot b over the product of their lengths. a = [1, 2] and b = [2, 4] point the same way: dot product 10, lengths root 5 and root 20, cosine 1. a and c = [3, 1] are 45 degrees apart: 5 over root 50 = 0.707. [1, 0] and [0, 1] share nothing: cosine 0. hello and hellohello have counts [1, 1, 2, 1] and [2, 2, 4, 2], about 2.65 apart but cosine exactly 1. For counts, the cosine is between 0 and 1. Worked example: character bags of hello and yellow over e, h, l, o, w, y are [1,1,2,1,0,0] and [1,0,2,1,1,1]; dot product 6, norms root 7 and root 8, cosine 6 over root 56 = 0.802. hello and its ROT13 encoding uryyb share no letters, so their letter-by-letter cosine is 0, but their sorted counts are both [2,1,1,1], so the sorted-profile cosine is 1.

Your Task¶

The bag functions (words and characters) and the encoded samples are supplied. The five ciphers come from the pycipher library, which the setup cell installs and imports. Complete the cell:

  1. cosine(vec1, vec2): the cosine similarity of two bags (Counters). Their dot product sums vec1[k] * vec2[k] over every key in either bag (a missing key counts as 0); each magnitude is the square root of the bag's squared counts. If either bag is empty, return 0.0.
  2. In the loop, for each candidate compute bow, the cosine between the word bags of the encoded sample and the note (letter_text), and boc, the same for the character bags.
  3. Score each candidate by bow + boc. If its score is the best so far, store the cipher's name in best_name and its score in best_score.

Python Help¶

words('the cat the')                       # Counter({'the': 2, 'cat': 1})
characters('Cat 9!')                       # Counter({'c': 1, 'a': 1, 't': 1, '9': 1})
bag = words('a b b')
bag['b'], bag['z']                         # (2, 0): a missing key counts as 0
set(words('a b')) | set(words('b c'))      # {'a', 'b', 'c'}: every key in either bag
math.sqrt(sum(v * v for v in bag.values()))   # sqrt(1 + 4): the bag's magnitude
cosine(words('a b'), words('b c'))         # 0.5 once your cosine works
for name, encoded_sample in candidates.items():   # each cipher's name and its encoded sample
    ...
Caesar(13).encipher('hello, 69 world')    # 'URYYBJBEYQ': capitals, no spaces, digits or punctuation

Useful Links¶

  • Cosine similarity (Wikipedia) · Caesar cipher and ROT13 (Wikipedia) · Vigenère cipher (Wikipedia) · Affine cipher (Wikipedia) · Substitution cipher (Wikipedia)

Task 01-1: Code (0.75 pts.)¶

In [ ]:
def words(text):
    return Counter(text.lower().split())

def characters(text):
    return Counter(ch for ch in text.lower() if ch.isalnum())

# Supplied: a paragraph of ordinary English to encode with each candidate.
SAMPLE = ('the detective reached the old house at the end of a long day. the door was open and the lamp '
          'in the hall was still lit. he walked through every room and wrote down what he saw: a broken '
          'clock, a letter on the desk, and a cold cup of tea by the window. it was clear that someone '
          'had left in a hurry, and that they had not wanted to be found.')

# Supplied: the five candidate ciphers, each with a fixed key, applied to the sample.
candidates = {
    'Caesar (shift 3)': Caesar(3).encipher(SAMPLE),
    'ROT13': Caesar(13).encipher(SAMPLE),
    'Vigenere (key clue)': Vigenere('clue').encipher(SAMPLE),
    'Affine (a=5, b=8)': Affine(5, 8).encipher(SAMPLE),
    'Substitution': SimpleSubstitution('qwertyuiopasdfghjklzxcvbnm').encipher(SAMPLE),
}
print('Sample begins:          ', SAMPLE[:36])
for name, encoded in candidates.items():
    print(f'{name + ":":24}', encoded[:36])

# TODO: Calculate the cosine similarity of two bags
def cosine(vec1, vec2):
    """Cosine similarity of two bags (Counters): their dot product over the product of their magnitudes."""
    dot_product = None
    mag1 = None
    mag2 = None
    return None

print()
print(f"{'Cipher':22}{'BoW':>8}{'BoC':>8}")
best_name, best_score = None, -1.0

for name, encoded_sample in candidates.items():
    # TODO: Compare the encoded sample with the note (letter_text): word cosine and character cosine.
    bow = None
    boc = None

    print(f'{name:22}{bow:8.4f}{boc:8.4f}')

    # TODO: If this cipher's score (bow + boc) is the best so far, remember its name and score.
    pass

print('Most likely cipher:', best_name)

Task 01-1: Expected Output (0 pts.)¶

Sample begins:           the detective reached the old house
Caesar (shift 3):        WKHGHWHFWLYHUHDFKHGWKHROGKRXVHDWWKHH
ROT13:                   GURQRGRPGVIRERNPURQGURBYQUBHFRNGGURR
Vigenere (key clue):     VSYHGEYGVTPITPUGJPXXJPIPFSIYUPUXVSYI
Affine (a=5, b=8):       ZRCXCZCSZWJCPCISRCXZRCALXRAEUCIZZRCC
Substitution:            ZITRTZTEZOCTKTQEITRZITGSRIGXLTQZZITT

Cipher                     BoW     BoC
Caesar (shift 3)        0.0000  0.5429
ROT13                   0.0000  0.9360
Vigenere (key clue)     0.0000  0.6830
Affine (a=5, b=8)       0.0000  0.5577
Substitution            0.0000  0.5958
Most likely cipher: ROT13

Task 01-2: Written Response (0.125 pts.)¶

  1. In your Task 01-1 table, the word (BoW) cosine is exactly 0 for every cipher, ROT13 included. Look at what encipher returned. Why can no encoded word ever match a word in the note, and what, then, is the character (BoC) cosine measuring that lets ROT13 win anyway?
    • [ANSWER]
  2. ROT13 wins clearly, but the test tried only one key for each cipher and one sample paragraph. Why is a high score evidence that the note uses ROT13 rather than proof? Name one way the wrong cipher could win, or the right one could lose.
    • [ANSWER]

Story Progression¶

ROT13 wins by a wide margin: encoded the same way, the sample's letter counts line up with the note's. Caulfield is fairly sure he could decode it with a pencil. Even the intern might be able to do it.

The department has other plans. There's a huge push for everyone to stick AI algorithms in places they don't belong. ROT13 is the perfect training ground: simple, well understood, and with an exact answer to check our model against. Better still, now that we know the cipher, we can make as many examples as we like: string random words from a dictionary into phrases, and encode each one with ROT13. Our model will learn from those, never from the note itself.

First, though, the pages have to become numbers.

Evidence 2: The cipher unit's training phrases, character by character.
Evidence 2: The cipher unit's training phrases, character by character.

Task 02: Our Own Training Phrases (Supplied)¶

Task 02-1: Description (0 pts.)¶

Now that we know the note was encoded with ROT13, we don't need anyone to hand us training data. We can make as much as we like.

NLTK, the Natural Language Toolkit, is one of the most widely used Python libraries for working with text: tokenizers, stemmers, taggers, and dozens of ready-made corpora. We use one of them, words: about 236,000 English words.

Rot13Dataset makes its own training data from that list: 2,000 phrases. Each phrase is 3 to 12 random words, now and then a number in place of a word (the note has one), encoded with codecs.encode(phrase, 'rot_13'): Task 01's answer. Two properties matter all through HW08–HW10:

  • The same seed always makes the same phrases, so everyone's data, and every reference output, is the same.
  • The note itself is never one of the phrases. We never train on the evidence we want to read.

Each encoded phrase lines up with its plain phrase character for character, which makes this a particular kind of task, and not the one most people picture when they hear "language model":

The task is aligned translation: the encoded input u r y y b space 6 9 EOS lines up position by position with the plain target h e l l o space 6 9 EOS, one output character for every input character, with every real position scored, EOS included. It is not next-character prediction, where a language model reads h e l l and is scored on e l l o (the input shifted by one), and not general translation, where le chat noir becomes the black cat with different lengths and reordered words, needing an encoder-decoder. Because the sequences line up, the network answers position t as soon as it has read position t: one forward pass, one prediction per position.

A network can't do anything with letters though, only numbers, so every character gets an integer ID from a fixed vocabulary:

Vocabulary of V = 41 tokens: 0 PAD, 1 EOS, 2 UNK, 3 SOS (unused), 4 space, 5 to 30 letters a to z, 31 to 40 digits 0 to 9. Token IDs are category labels. encode hello 69 gives [12, 9, 16, 16, 19, 4, 37, 40, 1]. decode stops at the first EOS, skips PAD, and shows other special tokens as ?.

Our phrases are all different lengths, but a batch has to be one rectangular tensor, so the shorter phrases get padded out to the longest one:

Padding: append PAD (ID 0) so a batch of B phrases becomes a (B, T) tensor. Sources [[25, 22, 29, 29, 6, 1], [37, 40, 1, 0, 0, 0]] and targets [[12, 9, 16, 16, 19, 1], [37, 40, 1, 0, 0, 0]]. ROT13 keeps lengths equal, so positions align. Losses and accuracies ignore PAD positions.

The dataset hands its pairs to a DataLoader, which uses the dataset's collate function to turn a list of pairs into one padded batch:

From pairs to batches: the training Rot13Dataset holds 2,000 (source, target) pairs; the DataLoader picks 64 and passes them to the supplied collate, which returns X of shape (64, T) and one-hot targets Y of shape (64, T, 41). zip(*batch) unzips the pairs; pad_sequence pads each group; F.one_hot turns the target IDs into one-hot vectors. T changes from batch to batch, and the last batch has only 16 pairs.

Supplied¶

The dataset also owns the vocabulary and turns each pair into token IDs. Its collate pads each batch and returns the targets one-hot, shape (B, T, 41), which is what next week's loss expects. device picks a GPU when one is available, and every layer you write this week takes it as an argument.

There's no code to write: read the cell, run it, and check the output.

Useful Links¶

  • NLTK corpora · random.Random · Dataset and DataLoader · pad_sequence · F.one_hot

Task 02-1: Code (0 pts.)¶

In [ ]:
device = torch.device('cuda' if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")

# NLTK's English word list: about 236,000 words, lowercased, letters only
nltk.download('words', quiet=True)
from nltk.corpus import words
word_list = [w.lower() for w in words.words() if w.isalpha()]

class Rot13Dataset(Dataset):
    def __init__(self, word_list, num_phrases, seed, device="cpu", one_hot_targets=True):
        # ---- vocab (owned by the dataset) ----
        self.vocab = ('<PAD>', '<EOS>', '<UNK>', '<SOS>', ' ') + tuple(string.ascii_lowercase + string.digits)  # 41
        self.vocab_size = len(self.vocab)
        self.char2idx = {ch: i for i, ch in enumerate(self.vocab)}
        self.idx2char = {i: ch for i, ch in enumerate(self.vocab)}
        self.padding_idx = self.char2idx['<PAD>']
        self.eos_idx = self.char2idx['<EOS>']

        self.device = device
        self.one_hot_targets = one_hot_targets

        # ---- synthetic phrases: 3 to 12 random words, now and then a number, then ROT13 ----
        rng = random.Random(seed)   # the same seed always makes the same phrases
        self.phrases = []
        for _ in range(num_phrases):
            phrase_words = rng.choices(word_list, k=rng.randint(3, 12))
            phrase_words = [str(rng.randint(0, 99)) if rng.random() < 0.15 else word for word in phrase_words]
            self.phrases.append(' '.join(phrase_words))
        self.data = [(self.encode(codecs.encode(phrase, 'rot_13')), self.encode(phrase)) for phrase in self.phrases]

    # ---------- helpers ----------
    def encode(self, s):  # string -> 1D LongTensor, ending in <EOS>
        return torch.tensor([self.char2idx.get(c, self.char2idx['<UNK>']) for c in s.lower()] + [self.eos_idx], dtype=torch.long)

    def decode(self, idxs):  # 1D LongTensor -> string: stop at <EOS>, skip <PAD>, '?' for other special tokens
        text = []
        for i in idxs:
            i = int(i)
            if i == self.eos_idx:
                break
            if i == self.padding_idx:
                continue
            ch = self.idx2char[i]
            text.append(ch if len(ch) == 1 else '?')
        return ''.join(text)

    # ---------- Dataset API ----------
    def __len__(self): return len(self.data)
    def __getitem__(self, i): return self.data[i]  # (T,), (T,)

    # ---------- Collate (pad, one-hot targets, move to device) ----------
    def collate(self, batch):
        X_list, Y_list = zip(*batch)  # tuples of 1D tensors
        X = pad_sequence(X_list, batch_first=True, padding_value=self.padding_idx)        # (B,T)
        Y_idx = pad_sequence(Y_list, batch_first=True, padding_value=self.padding_idx)    # (B,T)
        if not self.one_hot_targets:
            return X.to(self.device), Y_idx.to(self.device)

        Y = F.one_hot(Y_idx.clamp_min(0), num_classes=self.vocab_size).float()        # (B,T,V)
        return X.to(self.device), Y.to(self.device)

# 2,000 training phrases from a fixed seed
dataset = Rot13Dataset(word_list, 2000, seed=1, device=device)
train_loader = DataLoader(dataset, batch_size=64, shuffle=True, collate_fn=dataset.collate,
                          generator=torch.Generator().manual_seed(42))

print('Words in the list:', len(word_list))
print('First training pair:', codecs.encode(dataset.phrases[0], 'rot_13'), '->', dataset.phrases[0])
print('Vocabulary size:', dataset.vocab_size)
print('encode("hello 69"):', dataset.encode('hello 69').tolist())
print('decode(encode("Hello 69!")):', dataset.decode(dataset.encode('Hello 69!')))
x_toy, y_toy = dataset.collate([(dataset.encode('uryyb'), dataset.encode('hello')), (dataset.encode('69'), dataset.encode('69'))])
print('Toy batch: X', tuple(x_toy.shape), '| Y', tuple(y_toy.shape))
print('X (token IDs):', x_toy.tolist())
print('Y as IDs again:', y_toy.argmax(dim=-1).tolist())
print('Training phrases:', len(dataset))
print('Training batches per epoch:', len(train_loader))

Task 02-1: Expected Output (0 pts.)¶

Words in the list: 236734
First training pair: birerzcgl fgveevat nflyn ohgpurevat fureelzbbe -> overempty stirring asyla butchering sherrymoor
Vocabulary size: 41
encode("hello 69"): [12, 9, 16, 16, 19, 4, 37, 40, 1]
decode(encode("Hello 69!")): hello 69?
Toy batch: X (2, 6) | Y (2, 6, 41)
X (token IDs): [[25, 22, 29, 29, 6, 1], [37, 40, 1, 0, 0, 0]]
Y as IDs again: [[12, 9, 16, 16, 19, 1], [37, 40, 1, 0, 0, 0]]
Training phrases: 2000
Training batches per epoch: 32

Task 02-2: Written Response (0.125 pts.)¶

Every phrase gets an <EOS> token, but <PAD> only fills out shorter phrases. Explain the different job each one does. Why should a model be scored on predicting <EOS> but never on predicting <PAD>?

  • [ANSWER]

Task 03: The Layers: Linear, Embedding, and tanh¶

Task 03-1: Description (0 pts.)¶

Our network has three layers. An embedding layer turns each character's ID into a vector, a recurrent block reads those vectors one position at a time, and an output layer turns what the block has read back into a guess at each character. Every layer is built the way HW07's were: a class with a forward method (and next week, backward and update). Two of them are linear layers underneath, so we start with one you've already written.

Your Task¶

Fill in the LinearLayer stub in the cell below with your Homework 07 code, with two small changes:

  1. Its constructor takes a device argument, __init__(self, input_dim, output_dim, device='cpu'), and creates W and b on that device.
  2. Its forward must work on 3-D input (B, T, input_dim) as well as 2-D. X @ self.W.T + self.b already does: @ multiplies along the last dimension.

Its backward will need changes for 3-D input next week; leave it as it was in HW07 for now.

Python Help¶

torch.randn(3, 4, device=device)          # created directly on the chosen device
torch.zeros(2, 6, 4) @ torch.zeros(3, 4).T  # (2, 6, 3): the last dimension is multiplied

Task 03-1: Code (0 pts.)¶

In [ ]:
# TODO: Implement the LinearLayer class (Consider copying from Homework 07)
class LinearLayer:
    """
    A fully connected (dense) layer that performs a linear transformation.

    Attributes:
        W (torch.Tensor): Weight matrix with shape (output_dim, input_dim).
        b (torch.Tensor): Bias vector with shape (output_dim,).
        X (torch.Tensor): Cached input used during the forward pass.
    """
    def __init__(self, input_dim, output_dim, device='cpu'):
        self.device = device
        # TODO: Initialize W and b as in Homework 07, created on self.device.
        self.W = None
        self.b = None

    def forward(self, X):
        # TODO: Cache the input and return the layer's output.
        return None

    def backward(self, dY):
        # TODO: Store the weight and bias gradients, then return the gradient for the layer below.
        self.dW = None
        self.db = None
        return None

    def update(self, lr):
        # TODO: Take one gradient-descent step on W and b.
        pass

layer = LinearLayer(4, 3, device=device)
print('2-D input (5, 4) ->', tuple(layer.forward(torch.zeros(5, 4, device=device)).shape))
print('3-D input (2, 6, 4) ->', tuple(layer.forward(torch.zeros(2, 6, 4, device=device)).shape))

Task 03-1: Expected Output (0 pts.)¶

2-D input (5, 4) -> (5, 3)
3-D input (2, 6, 4) -> (2, 6, 3)

Task 03-2: Description (0 pts.)¶

A token ID is just a label, so we can't hand it to the network as a number (z, ID 30, isn't six times a, ID 5). Instead, every token gets its own vector of numbers, which the network will learn next week:

Why not feed the IDs directly: a linear layer treats an ID as an amount, so b (6) looks almost the same as a (5), z (30) sits next to the digit 0 (31), and z pushes the weights six times as hard as a. One-hot vectors make every pair of tokens equally different but use 41 inputs, 40 of them zero. A one-hot vector times a matrix just selects one row. An embedding is a linear layer on one-hot inputs.

It turns out an embedding layer is just a linear layer applied to one-hot vectors, so we can inherit almost everything from LinearLayer and only rewrite forward:

An embedding layer is a LinearLayer with no bias applied to one-hot vectors. Its weight W has shape (E, V), one column per token, and onehot(i) times W transpose is column i of W. Example W = [[0, 1, 3], [0, 2, 4]]: tokens [2, 1, 2] give [[3, 4], [1, 2], [3, 4]]. (B, T) IDs become (B, T, V) one-hot vectors and then (B, T, E) embeddings; E = 32.

Your Task¶

Complete EmbeddingLayer.forward(X_idx). The layer is a LinearLayer from vocabulary size to embedding size (it inherits the constructor), applied to one-hot vectors with no bias:

  1. Turn the (B, T) token IDs into one-hot vectors with F.one_hot, as floats, and store them in self.X (next week's backward needs them).
  2. Return self.X @ self.W.T, shape (B, T, E).

Python Help¶

F.one_hot(torch.tensor([[2, 0]]), num_classes=3)          # tensor([[[0, 0, 1], [1, 0, 0]]])
F.one_hot(torch.tensor([[2, 0]]), num_classes=3).float()  # the same, as floats for matrix products

Useful Links¶

  • F.one_hot · nn.Embedding

Task 03-2: Code (0.5 pts.)¶

In [ ]:
class EmbeddingLayer(LinearLayer):
    """
    An embedding layer

    Attributes:
        W (torch.Tensor): Weight matrix with shape (embed_dim, vocab_size): one column per token.
        vocab_size (int): Size of the vocabulary
        X (torch.Tensor): Cached one-hot input used during the forward pass.
    """
    def __init__(self, vocab_size, embed_dim, device="cpu"):
        """
        Initialize the EmbeddingLayer using the constructor from the LinearLayer

        Args:
            vocab_size (int): Number of tokens in the vocab
            embed_dim (int): Size of the token embedding
        """

        # call the LinearLayer constructor
        super().__init__(input_dim=vocab_size, output_dim=embed_dim, device=device)
        self.vocab_size = vocab_size

    def forward(self, X_idx):
        """
        Compute the forward pass of the embedding layer.

        Args:
            X_idx (torch.Tensor): Token IDs with shape (batch_size, sequence_length)

        Returns:
            torch.Tensor: Linear output with shape (batch_size, sequence_length, embedding_dim)

        Notes:
            The bias is disabled as it is not used in the embedding layer.
        """
        # TODO: Implement the forward pass for the embedding layer

toy = EmbeddingLayer(3, 2, device=device)
toy.W = torch.tensor([[0., 1., 3.], [0., 2., 4.]], device=device)   # column i is token i's vector
print('Worked example:', toy.forward(torch.tensor([[2, 1, 2]], device=device)).tolist())

embedding = EmbeddingLayer(dataset.vocab_size, 32, device=device)
print('Token IDs', tuple(x_toy.shape), '-> one-hot', tuple(F.one_hot(x_toy, dataset.vocab_size).shape),
      '-> embeddings', tuple(embedding.forward(x_toy).shape))
print('Same as looking up columns of W:', torch.allclose(embedding.forward(x_toy), embedding.W.T[x_toy]))

Task 03-2: Expected Output (0 pts.)¶

Worked example: [[[3.0, 4.0], [1.0, 2.0], [3.0, 4.0]]]
Token IDs (2, 6) -> one-hot (2, 6, 41) -> embeddings (2, 6, 32)
Same as looking up columns of W: True

Task 03-3: Description (0 pts.)¶

The recurrent block feeds its own output back in at every position, so it needs an activation that keeps those numbers from running away. We'll use tanh:

tanh(a) = (e^a - e^-a) / (e^a + e^-a) maps any number into (-1, 1) and is centered on zero, unlike sigmoid. Slope 1 - tanh(a)^2. Worked example: tanh(1) = (2.718 - 0.368) / (2.718 + 0.368) = 2.350 / 3.086 = 0.7616; tanh(-1) = -0.7616; tanh(3) = 0.9951.

Here's why the bound matters, on a network with a single number for a hidden state:

Why a bounded activation: the one-number recurrence c_t = f(1.5 c_(t-1) + 0.5) from c_0 = 0 grows 0.5, 1.25, 2.375, 4.06, ..., 24.6 after 8 steps with ReLU but settles at 0.959 with tanh. tanh is centered on zero, unlike sigmoid.

Your Task¶

Complete Tanh.forward(X): return the tanh of every element. Next week this class gets a backward method too.

Python Help¶

torch.tanh(torch.tensor([0., 1.]))   # tensor([0.0000, 0.7616])

Task 03-3: Code (0.25 pts.)¶

In [ ]:
class Tanh:
    """
    The tanh activation function

    Attributes:
       None
    """
    def forward(self, X):
        """
        Compute the forward pass of the tanh activation function

        Args:
            X (torch.Tensor): Input data with shape (batch_size, hidden_size)

        Returns:
            torch.Tensor: the tanh of the input X
        """
        # TODO: Return the tanh activation

values = torch.tensor([-3., -1., 0., 1., 3.], device=device)
print('tanh at', values.tolist(), '=', [round(v, 4) for v in Tanh().forward(values).tolist()])

Task 03-3: Expected Output (0 pts.)¶

tanh at [-3.0, -1.0, 0.0, 1.0, 3.0] = [-0.9951, -0.7616, 0.0, 0.7616, 0.9951]

Story Progression¶

The intern has volunteered to memorize the embedding table. Caulfield gently points out that the table has 1,312 entries, that every one of them is a random number, and that next week training will change all of them anyway. The intern says he'll wait until next week.

We now have every ingredient: characters become IDs, IDs become vectors, and tanh keeps numbers in bounds. Time to connect them into a network that reads.

Evidence 3: The intern attempts to memorize 41 random vectors.
Evidence 3: The intern attempts to memorize 41 random vectors.

Task 04: The Recurrent Block and the Network¶

Task 04-1: Description (0 pts.)¶

With the layers built, we can write the part that makes this a recurrent network. At each position the block combines the current character's vector with a summary of everything it has read so far (the hidden state, c for context), and passes the new summary on to the next position:

One recurrent step: c_t = tanh(x_t Wx^T + c_(t-1) Wc^T + b), c for context. Shapes: x_t (B, 32), c (B, 64), Wx (64, 32), Wc (64, 64), b (64,). c_0 = 0. Example: x = [1, 0], c_prev = [0.5, -0.5], Wx = I, Wc = 0.5 I, b = [0, 0.1] gives z = [1.25, -0.15] and c_t = [0.8483, -0.1489].

Running that same step at every position, with the same weights each time, is called unrolling the network. Notice that it also keeps every hidden state along the way, which HW09 will need:

Unrolling: the same step at every position with shared weights Wx and Wc. The output layer turns each hidden state into 41 logits, so (B, T) token IDs become (B, T, 41) logits. At each timestep X[:, timestep, :] has shape (B, 32). hidden_states caches a Grad_Info(x, c, c_prev) for every step plus the zero start: T + 1 entries, used by backpropagation in HW09.

Your Task¶

Complete the loop body in RecurrentBlock.forward(X). The constructor, the zero starting state and the stacking are supplied. For each timestep:

  1. Get the previous hidden state from the last entry of self.hidden_states.
  2. Compute z_at_timestep = x_at_timestep @ self.Wx.t() + c_prev_at_timestep @ self.Wc.t() + self.b, then c_at_timestep with self.activation.forward.
  3. Append a Grad_Info with this step's input, new hidden state, and previous hidden state to self.hidden_states. HW09's backpropagation through time reads them.

Python Help¶

Grad_Info = namedtuple('Grad_Info', ['x_at_timestep', 'c_at_timestep', 'c_prev_at_timestep'])
info = Grad_Info(x_at_timestep=x, c_at_timestep=c, c_prev_at_timestep=c_prev)
info.c_at_timestep           # read a field by name
states[-1]                   # the last item of a list

Useful Links¶

  • collections.namedtuple

Task 04-1: Code (1.0 pts.)¶

In [ ]:
class RecurrentBlock:
    """
    A Recurrent Block

    Attributes:
        Wx (torch.Tensor): Input Weight matrix with shape (hidden_size, input_dim).
        Wc (torch.Tensor): Hidden-state (context) Weight matrix with shape (hidden_size, hidden_size).
        b (torch.Tensor): Bias vector with shape (hidden_size).
        Grad_Info (namedtuple): Cached hidden state info using the Grad_Info tuple made in forward and used in backward
    """

    Grad_Info = namedtuple('Grad_Info', ['x_at_timestep', 'c_at_timestep', 'c_prev_at_timestep'])

    def __init__(self, input_dim, hidden_size, device='cpu'):
        self.input_dim = input_dim      # This should match the embedding size.
        self.hidden_size = hidden_size
        self.device = device

        self.Wx = torch.randn(hidden_size, input_dim, device=self.device) * math.sqrt(2.0 / input_dim)
        self.Wc = torch.randn(hidden_size, hidden_size, device=self.device) * math.sqrt(2.0 / input_dim)
        self.b = torch.zeros(hidden_size, device=self.device)

        self.activation = Tanh()
        self.hidden_states = []

    def forward(self, X):
        """
        Compute the forward pass of the recurrent block over the entire input sequence

        Args:
            X (torch.Tensor): embedded input with shape: (batch_size, sequence_len, input_dim)

        Returns:
            self.outputs (torch.Tensor): matrix containing the hidden state at each timestep with shape: (batch_size, sequence_len, hidden_size)
        """
        batch_size, seq_len, _ = X.shape

        outputs = []
        self.hidden_states = [self.Grad_Info(
            x_at_timestep=None,
            c_at_timestep=torch.zeros((batch_size, self.hidden_size), device=self.device),
            c_prev_at_timestep=None
        )]

        for timestep in range(seq_len):
            x_at_timestep = X[:, timestep, :]

            # TODO: Compute the forward pass for each item in the sequence

            outputs.append(c_at_timestep)

        # Stack outputs along the time-axis: (batch_size, seq_len, hidden_size)
        self.outputs = torch.stack(outputs, dim=1)
        return self.outputs

block = RecurrentBlock(2, 2, device=device)
block.Wx = torch.eye(2, device=device)
block.Wc = 0.5 * torch.eye(2, device=device)
block.b = torch.tensor([0., 0.1], device=device)
c = block.forward(torch.tensor([[[1., 0.], [0., 1.]]], device=device))
print('Worked example, two steps:', [[round(v, 4) for v in step] for step in c[0].tolist()])
print('Cached entries (T + 1):', len(block.hidden_states), '| first is the zero start:', bool((block.hidden_states[0].c_at_timestep == 0).all()))

block = RecurrentBlock(32, 64, device=device)
states = block.forward(embedding.forward(x_toy))
print('Embeddings (2, 6, 32) -> hidden states', tuple(states.shape), '| every value inside (-1, 1):', bool(states.abs().max() < 1))

Task 04-1: Expected Output (0 pts.)¶

Worked example, two steps: [[0.7616, 0.0997], [0.3634, 0.8177]]
Cached entries (T + 1): 3 | first is the zero start: True
Embeddings (2, 6, 32) -> hidden states (2, 6, 64) | every value inside (-1, 1): True

Task 04-2: Description (0 pts.)¶

Now we can stack the three layers into one network, the same way our HW07 network chained its layers. Here is every shape along the way for the toy batch from Task 02, along with the mistakes that usually break it:

Inside the forward pass for the toy batch (B = 2, T = 6): token IDs (2, 6); one-hot (2, 6, 41); embeddings (2, 6, 32); at each timestep x (2, 32), c_prev (2, 64), z and c (2, 64); hidden_states holds 7 entries; outputs stack to (2, 6, 64); the output layer gives logits (2, 6, 41). Common mistakes: X[timestep] instead of X[:, timestep, :]; using the zero start at every step; calling layer.forward(X) without X = ; stacking with dim=0.

Because every position shares the same weights, the number of parameters doesn't depend on how long the phrase is:

Parameters: embedding W 32 x 41 = 1,312, recurrent Wx 64 x 32 = 2,048, Wc 64 x 64 = 4,096, b 64, output W 41 x 64 = 2,624, output b 41: 10,185 in all, independent of sequence length. The embedding layer also inherits an unused bias from LinearLayer.

Your Task¶

  1. In RecurrentNeuralNetwork.__init__, create the three layers and keep them, in order, in self.layers: an EmbeddingLayer from the vocabulary to embed_size, a RecurrentBlock from embed_size to hidden_size, and an output LinearLayer from hidden_size back to the vocabulary. Pass device=device to each.
  2. In forward, pass X through every layer in order. Each layer's output is the next layer's input.

The supplied code builds the network with embed_size=32 and hidden_size=64, runs the toy batch, and counts the parameters.

Python Help¶

for layer in self.layers:   # embedding, recurrent block, output layer
    ...

Task 04-2: Code (0.875 pts.)¶

In [ ]:
class RecurrentNeuralNetwork:
    def __init__(self, vocab_size, embed_size, hidden_size, padding_idx=0, device='cpu'):
        self.vocab_size = vocab_size
        self.embed_size = embed_size
        self.hidden_size = hidden_size
        self.padding_idx = padding_idx
        self.device = device

        # TODO: Initialize the 3 components of the RNN

    def forward(self, X, eval=False):
        """
        Args:
          X: (batch_size, seq_len) with integer token indices.
        Returns:
          logits: (batch_size, seq_len, vocab_size)
        """
        # TODO: Calculate the output of the network

        return X if not eval else self.softmax(X)   # softmax arrives in HW09

torch.manual_seed(42)
model = RecurrentNeuralNetwork(vocab_size=dataset.vocab_size, embed_size=32, hidden_size=64, padding_idx=dataset.padding_idx, device=device)
logits = model.forward(x_toy)
embedding_layer, recurrent_block, output_layer = model.layers
print('Layers:', [type(layer).__name__ for layer in model.layers])
print('Token IDs', tuple(x_toy.shape), '-> logits', tuple(logits.shape), '| cached hidden states:', len(recurrent_block.hidden_states))
used = [embedding_layer.W, recurrent_block.Wx, recurrent_block.Wc, recurrent_block.b, output_layer.W, output_layer.b]
print('Parameters used by the forward pass:', sum(p.numel() for p in used))

Task 04-2: Expected Output (0 pts.)¶

Layers: ['EmbeddingLayer', 'RecurrentBlock', 'LinearLayer']
Token IDs (2, 6) -> logits (2, 6, 41) | cached hidden states: 7
Parameters used by the forward pass: 10185

Task 04-3: Written Response (0.125 pts.)¶

  1. In RecurrentBlock, what job does Wx do, and what job does Wc do? Why does the RNN need both?
    • [ANSWER]
  2. ROT13 replaces each letter with a fixed partner, no matter what comes before it. Does decoding ROT13 actually need the hidden state's memory? What does that tell you about how impressive it would be for an RNN to learn it?
    • [ANSWER]

Task 05: The Same Network in PyTorch¶

Task 05-1: Description (0 pts.)¶

As in HW07, we'll check our scratch network against PyTorch's version of the same thing. PyTorch has a module for each of our three layers:

PyTorch version: nn.Embedding(V, 32) for the embedding layer, whose weight is our W transposed; nn.RNN(input_size=32, hidden_size=64, batch_first=True) for the recurrent block, with weight_ih_l0 = Wx, weight_hh_l0 = Wc, and bias_ih_l0 + bias_hh_l0 = b; nn.Linear(64, V) for the output layer.

Lined up side by side, the two are nearly identical (the only real differences are a transpose on the embedding and an extra bias), which is what lets us copy our weights straight across:

Scratch and library side by side: the embedding, the recurrent loop, and the output layer each map to one PyTorch module. nn.RNN returns all hidden states (B, T, 64), without c_0, and the final state (1, B, 64). Only the embedding needs a transpose when copying. PyTorch keeps two recurrent biases for its gated relative, the GRU, and for cuDNN compatibility.

Your Task¶

  1. In CharRNN.__init__, create self.embed (nn.Embedding), self.rnn (nn.RNN with batch_first=True), and self.fc (nn.Linear) to match the table. Use these three names: the supplied check below copies parameters into them.
  2. In forward, embed x, run the RNN (passing c0), and apply self.fc to the hidden state at every position. Return the logits.

The supplied code then copies your scratch model's parameters into the PyTorch model and checks that the two forward passes agree.

Python Help¶

rnn = nn.RNN(input_size=32, hidden_size=64, batch_first=True)
all_states, final_state = rnn(torch.zeros(2, 6, 32))   # (2, 6, 64) and (1, 2, 64)

Useful Links¶

  • nn.Embedding · nn.RNN: see the formula and the "Variables" section · nn.Linear

Task 05-1: Code (0.75 pts.)¶

In [ ]:
vocab_size = dataset.vocab_size
embed_size = 32
hidden_size = 64

class CharRNN(nn.Module):
    def __init__(self, vocab_size, embed_size, hidden_size):
        super().__init__()
        # TODO: Instantiate the embedding, RNN, and linear layers

    def forward(self, x, c0=None):
        # TODO: Implement the forward pass
        pass

rnn_model = CharRNN(vocab_size, embed_size, hidden_size).to(device)
print('PyTorch logits:', tuple(rnn_model(x_toy).shape))

# Supplied: give the PyTorch model the scratch model's parameters, then compare the two forward passes.
with torch.no_grad():
    before = (model.forward(x_toy) - rnn_model(x_toy)).abs().max()
    rnn_model.embed.weight.copy_(embedding_layer.W.T)          # nn.Embedding stores one ROW per token
    rnn_model.rnn.weight_ih_l0.copy_(recurrent_block.Wx)
    rnn_model.rnn.weight_hh_l0.copy_(recurrent_block.Wc)
    rnn_model.rnn.bias_ih_l0.copy_(recurrent_block.b)
    rnn_model.rnn.bias_hh_l0.zero_()                            # PyTorch adds a second bias; ours has one
    rnn_model.fc.weight.copy_(output_layer.W)
    rnn_model.fc.bias.copy_(output_layer.b.reshape(-1))
    after = (model.forward(x_toy) - rnn_model(x_toy)).abs().max()
print(f'Largest logit difference before copying: {float(before):.2f}')
print('Largest logit difference after copying is below 1e-5:', bool(after < 1e-5))

Task 05-1: Reference Output (0 pts.)¶

The difference before copying depends on the random starting weights; it should be well above zero. The other lines are exact.

PyTorch logits: (2, 6, 41)
Largest logit difference before copying: 3.40
Largest logit difference after copying is below 1e-5: True

Task 05-2: Description (0 pts.)¶

Both networks still have their random starting weights. The supplied cell asks them to read the note: expect nonsense, and expect the two networks to produce the same nonsense at the start of the note, since they now share their parameters. HW09 trains them.

Task 05-2: Code (0 pts.)¶

In [ ]:
# Supplied: read the note with the untrained networks (every predicted token, special tokens included, as in SP26's test_on_letter).
with torch.no_grad():
    x = dataset.encode(letter_text).unsqueeze(0).to(device)    # (1, T)
    scratch_logits, torch_logits = model.forward(x), rnn_model(x)
scratch_reading = "".join(dataset.idx2char[int(i)] for i in scratch_logits.argmax(dim=-1)[0])
torch_reading = "".join(dataset.idx2char[int(i)] for i in torch_logits.argmax(dim=-1)[0])
print('Note (ROT13):     ', letter_text[:60])
print('Untrained scratch:', scratch_reading[:60])
print('Untrained PyTorch:', torch_reading[:60])
print('Same first 60 characters:', scratch_reading[:60] == torch_reading[:60])

Task 05-2: Reference Output (0 pts.)¶

The untrained readings depend on the random starting weights, but the two networks should agree with each other over the first 60 characters.

Note (ROT13):      v ybirq zheqrevat ze gurvfrasyblq ng gur rfgngr gur tnf jnf
Untrained scratch: <PAD><PAD>emxau0448<EOS>8fa8 8u8<EOS><EOS>rljll720rjt5i6r1<S
Untrained PyTorch: <PAD><PAD>emxau0448<EOS>8fa8 8u8<EOS><EOS>rljll720rjt5i6r1<S
Same first 60 characters: True

Task 06: Report the Results to Caulfield¶

Task 06-1: Written Response (0.5 pts.)¶

  1. Summarize the evidence from Task 01 that the note is English encoded with a letter-substitution cipher, and say what that evidence cannot establish on its own.
    • [ANSWER]
  2. Your scratch network and your CharRNN produced the same logits once they shared parameters. What did that comparison verify, and what didn't it?
    • [ANSWER]
  3. The untrained network turned the note into gibberish. In two or three sentences, explain to Caulfield what will have to change for it to produce a real translation, and which data it will learn from (and which it must not).
    • [ANSWER]

Story Progression¶

Your report goes on Caulfield's board next to the cipher table. The verdict: the note is almost certainly English encoded letter for letter, the network that will learn to undo it is built and verified, and right now that network translates the confession into something that looks like a cat walked across a keyboard.

The intern asks why we don't just shift every letter by 13 and be done with it. Caulfield admits the intern has a point, for this note. But the next message might use a different cipher, and the department wants a reader that learns from examples. Besides, the exact shift gives us something rare in machine learning: a perfect answer key to check the network against.

In HW09, we'll teach the network: send the error backward through every step of the unrolled sequence, adjust all 10,185 numbers, and see what the note really says.

Evidence 4: The team maps out the recurrent network on the evidence board. Next week: training.
Evidence 4: The team maps out the recurrent network on the evidence board. Next week: training.

Task 07: Export the Completed Notebook (0 pts.)¶

  1. Complete your code and written responses, and run the cells above in order. Compare your results with the expected and reference outputs.
  2. Save your notebook, including its outputs. Set GENERATE = True below when you are ready to export.
  3. In Colab, the cell captures the current notebook and its outputs. Locally, it reads the saved notebook at NOTEBOOK_PATH; adjust that path if you saved your copy elsewhere.
  4. Download homework08.html and open it in a browser. Check that your name, NETID, code, written answers, and outputs appear.

Submit only homework08.html on Canvas. The exporter does not rerun your code.

Task 07-1: Code (0 pts.)¶

In [ ]:
GENERATE = False
NOTEBOOK_PATH = DATA_ROOT / 'homeworks' / 'homework08' / 'homework08.ipynb'

if GENERATE:
    import json
    import nbformat
    from nbconvert import HTMLExporter
    from pathlib import Path

    try:
        from google.colab import _message, files
    except ImportError:
        current = nbformat.read(NOTEBOOK_PATH, as_version=4)
        html_path = NOTEBOOK_PATH.with_name('homework08.html')
        in_colab = False
    else:
        captured = _message.blocking_request('get_ipynb', timeout_sec=10)
        current = nbformat.reads(json.dumps(captured['ipynb']), as_version=4)
        html_path = Path('/content/homework08.html')
        in_colab = True

    exporter = HTMLExporter()
    exporter.embed_images = True
    report_html, _ = exporter.from_notebook_node(current)
    html_path.write_text(report_html, encoding='utf-8')
    print(f'Exported {html_path.name}. Open it in a browser before submitting.')

    if in_colab:
        files.download(str(html_path))
    else:
        print(f'Saved to: {html_path}')
else:
    print('Export disabled. Set GENERATE = True when ready.')

Task 07-1: Expected Output (0 pts.)¶

Export disabled. Set GENERATE = True when ready.