import urllib.request
url = ("https://raw.githubusercontent.com/rasbt/"
"LLMs-from-scratch/main/ch02/01_main-chapter-code/"
"the-verdict.txt")
file_path = "the-verdict.txt"
urllib.request.urlretrieve(url, file_path)
('the-verdict.txt', <http.client.HTTPMessage at 0x7a3072aefd90>)
with open(file_path, 'r', encoding='utf8') as f:
raw_file = f.read()
print("Length of text:", len(raw_file))
print(raw_file[:99])
Length of text: 20479 I HAD always thought Jack Gisburn rather a cheap genius--though a good fellow enough--so it was no
# naive tokenization with regex splitting on space
import re
text = "Hello, world. This, is a test."
result = re.split(r'(\s)', text)
print(result)
['Hello,', ' ', 'world.', ' ', 'This,', ' ', 'is', ' ', 'a', ' ', 'test.']
# split on space, commas, periods
result = re.split(r'([,.\s])', text)
print(result)
['Hello', ',', '', ' ', 'world', '.', '', ' ', 'This', ',', '', ' ', 'is', ' ', 'a', ' ', 'test', '.', '']
# We don't actually want the whitespace, note that we can easily strip that out.
for item in result:
if item.strip():
print(item)
Hello , world . This , is a test .
# Strip out whitespace.
items = [item for item in result if item.strip()]
items
['Hello', ',', 'world', '.', 'This', ',', 'is', 'a', 'test', '.']
# Handle more characters and therefore more complex input text.
text = "Hello, world. Is this-- a test?"
result = re.split(r'([,.:;?_!"()\']|--|\s)', text)
tokens = [item for item in result if item.strip()]
tokens
['Hello', ',', 'world', '.', 'Is', 'this', '--', 'a', 'test', '?']
# Now apply it to our full sample text.
result = re.split(r'([,.:;?_!"()\']|--|\s)', raw_file)
tokens = [item for item in result if item.strip()]
print("# tokens:", len(tokens))
print("First 33 tokens:", tokens[:33])
# tokens: 4690 First 33 tokens: ['I', 'HAD', 'always', 'thought', 'Jack', 'Gisburn', 'rather', 'a', 'cheap', 'genius', '--', 'though', 'a', 'good', 'fellow', 'enough', '--', 'so', 'it', 'was', 'no', 'great', 'surprise', 'to', 'me', 'to', 'hear', 'that', ',', 'in', 'the', 'height', 'of']
# But how many *unique* tokens are there?
unique_tokens = sorted(set(tokens))
num_unique_tokens = len(unique_tokens)
print("# unique tokens:", num_unique_tokens)
print("First 10 unique tokens:", list(unique_tokens)[:10])
# unique tokens: 1130
First 10 unique tokens: ['!', '"', "'", '(', ')', ',', '--', '.', ':', ';']
# Now create a dict mapping integers to tokens.
vocab = {token:id for id, token in enumerate(unique_tokens)}
for token, id in vocab.items():
print(f'{token} - {id}')
if (id > 50):
break
! - 0 " - 1 ' - 2 ( - 3 ) - 4 , - 5 -- - 6 . - 7 : - 8 ; - 9 ? - 10 A - 11 Ah - 12 Among - 13 And - 14 Are - 15 Arrt - 16 As - 17 At - 18 Be - 19 Begin - 20 Burlington - 21 But - 22 By - 23 Carlo - 24 Chicago - 25 Claude - 26 Come - 27 Croft - 28 Destroyed - 29 Devonshire - 30 Don - 31 Dubarry - 32 Emperors - 33 Florence - 34 For - 35 Gallery - 36 Gideon - 37 Gisburn - 38 Gisburns - 39 Grafton - 40 Greek - 41 Grindle - 42 Grindles - 43 HAD - 44 Had - 45 Hang - 46 Has - 47 He - 48 Her - 49 Hermia - 50 His - 51
# Now make a basic tokenizer class.
class SimpleTokenizerV1:
def __init__(self, vocab):
self.str_to_int = vocab
self.int_to_str = {id:token for token, id in vocab.items()}
def encode(self, text):
tokens = re.split(r'([,.:;?_!"()\']|--|\s)', text)
tokens = [token.strip() for token in tokens if token.strip()]
ids = [self.str_to_int[token] for token in tokens]
return ids
def decode(self, ids):
tokens = [self.int_to_str[id] for id in ids]
text = " ".join(tokens)
text = re.sub(r'\s+([,.:;?_!"()\']|--)', r'\1', text)
return text
tokenizer = SimpleTokenizerV1(vocab)
text = """"It's the last he painted, you know,"
Mrs. Gisburn said with pardonable pride."""
ids = tokenizer.encode(text)
print(ids)
[1, 56, 2, 850, 988, 602, 533, 746, 5, 1126, 596, 5, 1, 67, 7, 38, 851, 1108, 754, 793, 7]
print(tokenizer.decode(ids))
" It' s the last he painted, you know," Mrs. Gisburn said with pardonable pride.
# It works, overlooking some minor issues with spaces in decoding.
# But it easily breaks on new vocab.
text = "Hello, do you like tea?"
#print(tokenizer.encode(text))
# This will obtain:
# KeyError: 'Hello'
# Let's handle unknown tokens and end of text.
unique_tokens.extend(["<|endoftext|>", "<|unk|>"])
vocab = {token:id for id, token in enumerate(unique_tokens)}
print(len(vocab))
1132
for token, id in list(vocab.items())[-5:]:
print(f"{token}, {id}")
younger, 1127 your, 1128 yourself, 1129 <|endoftext|>, 1130 <|unk|>, 1131
# Now enhance our tokenizer class to handle unknown words.
class SimpleTokenizerV2:
def __init__(self, vocab):
self.str_to_int = vocab
self.int_to_str = {id:token for token, id in vocab.items()}
def encode(self, text):
tokens = re.split(r'([,.:;?_!"()\']|--|\s)', text)
tokens = [token.strip() for token in tokens if token.strip()]
tokens = [token if token in self.str_to_int else "<|unk|>" for token in tokens]
ids = [self.str_to_int[token] for token in tokens]
return ids
def decode(self, ids):
tokens = [self.int_to_str[id] for id in ids]
text = " ".join(tokens)
text = re.sub(r'\s+([,.:;?_!"()\']|--)', r'\1', text)
return text
# Try the new tokenizer out.
text1 = "Hello, do you like tea?"
text2 = "In the sunlit terraces of the palace."
text = " <|endoftext|> ".join((text1, text2))
print(text)
Hello, do you like tea? <|endoftext|> In the sunlit terraces of the palace.
tokenizer = SimpleTokenizerV2(vocab)
print(tokenizer.encode(text))
[1131, 5, 355, 1126, 628, 975, 10, 1130, 55, 988, 956, 984, 722, 988, 1131, 7]
print(tokenizer.decode(tokenizer.encode(text)))
<|unk|>, do you like tea? <|endoftext|> In the sunlit terraces of the <|unk|>.
from importlib.metadata import version
import tiktoken
version("tiktoken") # should be > 0.7.0
'0.14.0'
# instantiate a byte-pair-encoding (BPE) tokenizer
tokenizer = tiktoken.get_encoding("gpt2")
# test out encoding
text = (
"Hello, do you like tea? <|endoftext|> In the sunlit terraces"
"of someunknownPlace."
)
integers = tokenizer.encode(text, allowed_special={"<|endoftext|>"})
print(integers)
[15496, 11, 466, 345, 588, 8887, 30, 220, 50256, 554, 262, 4252, 18250, 8812, 2114, 1659, 617, 34680, 27271, 13]
# now decoding
strings = tokenizer.decode(integers)
print(strings)
Hello, do you like tea? <|endoftext|> In the sunlit terracesof someunknownPlace.
Exercise 2.1 Byte pair encoding of unknown words¶
Try the BPE tokenizer from the tiktoken library on the unknown words “Akwirw ier” and print the individual token IDs. Then, call the decode function on each of the resulting integers in this list to reproduce the mapping shown in figure 2.11. Lastly, call the decode method on the token IDs to check whether it can reconstruct the original input, “Akwirw ier.”
text = "Akwirw ier"
integers = tokenizer.encode(text, allowed_special={"<|endoftext|>"})
print(integers)
strings = []
for integer in integers:
strings.append(tokenizer.decode([integer]))
print(strings)
for string, integer in zip(strings, integers):
print(f'{integer:5} = "{string}"')
print(tokenizer.decode(integers))
[33901, 86, 343, 86, 220, 959] ['Ak', 'w', 'ir', 'w', ' ', 'ier'] 33901 = "Ak" 86 = "w" 343 = "ir" 86 = "w" 220 = " " 959 = "ier" Akwirw ier
# Now load and encode the sample text
with open(file_path, 'r', encoding='utf8') as f:
raw_file = f.read()
tokens = tokenizer.encode(raw_file)
len(tokens)
5145
# demonstrate what next token prediction looks like
enc_sample = tokens[50:]
context_size = 4
x = enc_sample[:context_size]
y = enc_sample[1:context_size+1]
print(f'x: {x}')
print(f'y: {y}')
x: [290, 4920, 2241, 287] y: [4920, 2241, 287, 257]
# more generally
for i in range(1, context_size+1):
context = enc_sample[:i]
desired = enc_sample[i]
print(context, "->", desired)
[290] -> 4920 [290, 4920] -> 2241 [290, 4920, 2241] -> 287 [290, 4920, 2241, 287] -> 257
# as text
for i in range(1, context_size+1):
context = enc_sample[:i]
desired = enc_sample[i]
print(tokenizer.decode(context), "->", tokenizer.decode([desired]))
and -> established and established -> himself and established himself -> in and established himself in -> a
# Build a tokenizer dataset based on PyTorch datasets
import torch
from torch.utils.data import Dataset, DataLoader
class GPTDatasetV1(Dataset):
def __init__(self, txt, tokenizer, max_length, stride):
self.input_ids = []
self.target_ids = []
tokens = tokenizer.encode(txt)
self.num_tokens = len(tokens)
for i in range(1, self.num_tokens - max_length, stride):
input_batch = tokens[i-1:i-1+max_length]
target_batch = tokens[i:i+max_length]
self.input_ids.append(torch.tensor(input_batch))
self.target_ids.append(torch.tensor(target_batch))
def __len__(self):
return self.num_tokens
def __getitem__(self, idx):
return self.input_ids[idx], self.target_ids[idx]
ds = GPTDatasetV1(raw_file, tokenizer, 4, 2)
print("First batch:", ds[0])
print("Length:", len(ds))
First batch: (tensor([ 40, 367, 2885, 1464]), tensor([ 367, 2885, 1464, 1807])) Length: 5145
# create a PyTorch dataloader builder
def create_dataloader_v1(txt, batch_size=4, max_length=256,
stride=128, shuffle=True, drop_last=True,
num_workers=0):
tokenizer = tiktoken.get_encoding("gpt2")
dataset = GPTDatasetV1(txt, tokenizer, max_length, stride)
dataloader = DataLoader(
dataset=dataset,
batch_size=batch_size,
shuffle=shuffle,
drop_last=drop_last,
num_workers=num_workers
)
return dataloader
# uset the dataloader
with open('the-verdict.txt', 'r', encoding='utf-8') as f:
raw_text = f.read()
dataloader = create_dataloader_v1(raw_text, batch_size=1, max_length=4, stride=1, shuffle=False)
data_iter = iter(dataloader)
first_batch = next(data_iter)
print(first_batch)
[tensor([[ 40, 367, 2885, 1464]]), tensor([[ 367, 2885, 1464, 1807]])]
# observe the meaning of the `stride` parameter
second_batch = next(data_iter)
print(second_batch)
[tensor([[ 367, 2885, 1464, 1807]]), tensor([[2885, 1464, 1807, 3619]])]
Exercise 2.2 Data loaders with different strides and context sizes¶
To develop more intuition for how the data loader works, try to run it with different settings such as max_length=2 and stride=2, and max_length=8 and stride=2.
print('max_length=2 and stride=2')
dataloader = create_dataloader_v1(raw_text, batch_size=1, max_length=2, stride=2, shuffle=False)
data_iter = iter(dataloader)
first_batch = next(data_iter)
print(first_batch)
second_batch = next(data_iter)
print(second_batch)
max_length=2 and stride=2 [tensor([[ 40, 367]]), tensor([[ 367, 2885]])] [tensor([[2885, 1464]]), tensor([[1464, 1807]])]
print('max_length=8 and stride=8')
dataloader = create_dataloader_v1(raw_text, batch_size=1, max_length=8, stride=8, shuffle=False)
data_iter = iter(dataloader)
first_batch = next(data_iter)
print(first_batch)
second_batch = next(data_iter)
print(second_batch)
max_length=8 and stride=8 [tensor([[ 40, 367, 2885, 1464, 1807, 3619, 402, 271]]), tensor([[ 367, 2885, 1464, 1807, 3619, 402, 271, 10899]])] [tensor([[10899, 2138, 257, 7026, 15632, 438, 2016, 257]]), tensor([[ 2138, 257, 7026, 15632, 438, 2016, 257, 922]])]
# observe a batch size greater than 1, as is typical for real world use
dataloader = create_dataloader_v1(raw_text, batch_size=8, max_length=4, stride=4, shuffle=False)
data_iter = iter(dataloader)
inputs, targets = next(data_iter)
print(inputs)
print(targets)
tensor([[ 40, 367, 2885, 1464],
[ 1807, 3619, 402, 271],
[10899, 2138, 257, 7026],
[15632, 438, 2016, 257],
[ 922, 5891, 1576, 438],
[ 568, 340, 373, 645],
[ 1049, 5975, 284, 502],
[ 284, 3285, 326, 11]])
tensor([[ 367, 2885, 1464, 1807],
[ 3619, 402, 271, 10899],
[ 2138, 257, 7026, 15632],
[ 438, 2016, 257, 922],
[ 5891, 1576, 438, 568],
[ 340, 373, 645, 1049],
[ 5975, 284, 502, 284],
[ 3285, 326, 11, 287]])
# demonstrate token ID to embedding vector conversion
input_ids = torch.tensor([2, 3, 5, 1])
vocab_size = 6
output_dim = 3
torch.manual_seed(123)
embedding_layer = torch.nn.Embedding(vocab_size, output_dim)
embedding_layer.weight
# We will get a 6x3 matrix, one row per possible vocabulary term
# and a column for each embedding dimension
Parameter containing:
tensor([[ 0.3374, -0.1778, -0.1690],
[ 0.9178, 1.5810, 1.3010],
[ 1.2753, -0.2010, -0.1606],
[-0.4015, 0.9666, -1.1481],
[-1.1589, 0.3255, -0.6315],
[-2.8400, -0.7849, -1.4096]], requires_grad=True)
# Let's obtain an embedding vector.
print(torch.tensor([3]))
print(embedding_layer(torch.tensor([3])))
tensor([3]) tensor([[-0.4015, 0.9666, -1.1481]], grad_fn=<EmbeddingBackward0>)
# And all embeddings for our vocab:
print(embedding_layer(input_ids))
tensor([[ 1.2753, -0.2010, -0.1606],
[-0.4015, 0.9666, -1.1481],
[-2.8400, -0.7849, -1.4096],
[ 0.9178, 1.5810, 1.3010]], grad_fn=<EmbeddingBackward0>)
Ultimately this matrix will be part of the neural network which implements our language model. In the course of training that model to accurately predict the next token in the sequence, the embedding layer will tend to assume weights such that semantically similar token wind up closer together in the embedding space.
# Now a more realistic example
vocab_size = 50257 # The vocabulary size of the BPE tokenizer we use
output_dim = 256
token_embedding_layer = torch.nn.Embedding(vocab_size, output_dim)
# Instantiate a dataloader with 8 samples in a batch
# and up to 4 tokens per batch.
max_length = 4
dataloader = create_dataloader_v1(
raw_text, batch_size=8, max_length=max_length,
stride=max_length, shuffle=False)
data_iter = iter(dataloader)
inputs, targets = next(data_iter)
print("Input token ID's:\n", inputs)
print("Input shape:\n", inputs.shape)
# Prints an 8x4 matrix of (samples)x(tokens) for a batch.
# Each batch has eight text samples, and each text
# sample has four tokens.
Input token ID's:
tensor([[ 40, 367, 2885, 1464],
[ 1807, 3619, 402, 271],
[10899, 2138, 257, 7026],
[15632, 438, 2016, 257],
[ 922, 5891, 1576, 438],
[ 568, 340, 373, 645],
[ 1049, 5975, 284, 502],
[ 284, 3285, 326, 11]])
Input shape:
torch.Size([8, 4])
When we embed the preceding batch of tokens, we replace each cell in the matrix with a vector of 256 elements, corresponding to the appropriate row in the 50,257x256 embedding matrix.
token_embeddings = token_embedding_layer(inputs)
print("Batch embeddings shape:", token_embeddings.shape)
print("Sample embeddings shape:", token_embeddings[0].shape)
print("Token embeddings shape:", token_embeddings[0][0].shape)
Batch embeddings shape: torch.Size([8, 4, 256]) Sample embeddings shape: torch.Size([4, 256]) Token embeddings shape: torch.Size([256])
Now we need a way to account for token position within each sample. For this we will create a positional embedding layer with the same shape as a sample embedding: that is, the number of rows is the number of tokens, and the number of columns is the embedding dimension.
We can then retrieve the positional embedding vector that corresponds to the first token position, the second token position, and so on. Each token embedding can then be summed with its corresponding position embedding to produce a combined embedding that represents both a token and its position within the sample.
# The context length represents how much our model can handle,
# while the max_length represents the length of the raw input text.
# In the real world it's possible for max_length > context_length,
# and that has to be engineered around, but for our simple purposes
# here we will assume they are the same.
context_length = max_length
pos_embedding_layer = torch.nn.Embedding(context_length, output_dim)
seq = torch.arange(context_length)
print("Seq:", seq)
pos_embeddings = pos_embedding_layer(seq)
print(pos_embeddings)
print(pos_embeddings.shape)
Seq: tensor([0, 1, 2, 3])
tensor([[ 1.7375, -0.5620, -0.6303, ..., -0.2277, 1.5748, 1.0345],
[ 1.6423, -0.7201, 0.2062, ..., 0.4118, 0.1498, -0.4628],
[-0.4651, -0.7757, 0.5806, ..., 1.4335, -0.4963, 0.8579],
[-0.6754, -0.4628, 1.4323, ..., 0.8139, -0.7088, 0.4827]],
grad_fn=<EmbeddingBackward0>)
torch.Size([4, 256])
# Note that subsequent calls to pos_embedding_layer() with
# the same input produce the same results.
pos_embeddings = pos_embedding_layer(seq)
print(pos_embeddings)
print(pos_embeddings.shape)
tensor([[ 1.7375, -0.5620, -0.6303, ..., -0.2277, 1.5748, 1.0345],
[ 1.6423, -0.7201, 0.2062, ..., 0.4118, 0.1498, -0.4628],
[-0.4651, -0.7757, 0.5806, ..., 1.4335, -0.4963, 0.8579],
[-0.6754, -0.4628, 1.4323, ..., 0.8139, -0.7088, 0.4827]],
grad_fn=<EmbeddingBackward0>)
torch.Size([4, 256])
# Calls with different input produce different results.
seq = torch.tensor([1, 3, 2, 1, 2])
pos_embeddings = pos_embedding_layer(seq)
print(pos_embeddings)
print(pos_embeddings.shape)
tensor([[ 1.6423, -0.7201, 0.2062, ..., 0.4118, 0.1498, -0.4628],
[-0.6754, -0.4628, 1.4323, ..., 0.8139, -0.7088, 0.4827],
[-0.4651, -0.7757, 0.5806, ..., 1.4335, -0.4963, 0.8579],
[ 1.6423, -0.7201, 0.2062, ..., 0.4118, 0.1498, -0.4628],
[-0.4651, -0.7757, 0.5806, ..., 1.4335, -0.4963, 0.8579]],
grad_fn=<EmbeddingBackward0>)
torch.Size([5, 256])
# Trying to retrieve the embedding for something beyond the bounds
# of our embedding layer produces an error
seq = torch.tensor([4])
try:
pos_embeddings = pos_embedding_layer(seq)
print(pos_embeddings)
print(pos_embeddings.shape)
except Exception as e:
print("Error:", e)
Error: index out of range in self
# We can broadcast the position embeddings tensor to
# each row in the token_embeddings tensor because they have
# the same shape, which makes it convenient and efficient
# to produce the combined token + position embedding for each
# token, aka the input embedding.
seq = torch.arange(context_length)
pos_embeddings = pos_embedding_layer(seq)
print("Token embeddings shape:", token_embeddings.shape)
print("Position embeddings shape:", pos_embeddings.shape)
input_embeddings = token_embeddings + pos_embeddings
print("Input embeddings shape:", input_embeddings.shape)
Token embeddings shape: torch.Size([8, 4, 256]) Position embeddings shape: torch.Size([4, 256]) Input embeddings shape: torch.Size([8, 4, 256])
Why is it valid to just straight up add the token and position embeddings together? Intuitively, this makes more sense to me as an engineering thing than a math thing. We have input tokens with certain characteristics, and it just so happens that these tokens have both semantic meaning, and also their position is meaningful. Just as a low-resolution image devolves into pixel art while a high resolution image can be lifelike, if I embed these tokens into a low dimensional space, I probably will capture very little of both the semantic and positional information. But if I use a stupidly high dimensional embedding space, there will be more than enough room to store both pieces of information — and there will also be a lot of waste. So the trick is to find the sweet spot, and in practice that's a matter of enlightened trial-and-error.
Coming at it from a DSP angle: insufficient dimensionality in the embedding space is a lot like a too-low sampling rate, e.g. real-world recordings captured at 8khz are just inevitably going to alias like crazy. So with both embedding space dimensionality and sample rates, you want to crank things up high enough so that you don't have "aliasing" (information getting not just lost but garbled and bounced around in weird ways), but not so high that you're wasting resources.
What we call "aliasing" in the world of audio signals goes by the name "crosstalk" in neural networks, and they both represent the same essential phenomenon of "a system which can't accomodate its input information."