Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions PROBLEMS.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Generated from the per-problem `problem.toml` manifests — do not edit by hand.
Run `python3 scripts/generate.py readme` to refresh.

**62 of 68 are auto-graded** (`pip install torchleet`). A ✅ in the
**63 of 68 are auto-graded** (`pip install torchleet`). A ✅ in the
Graded column means `check()` will verify your solution.

### Basics (23)
Expand All @@ -27,7 +27,7 @@ Graded column means `check()` will verify your solution.
| 💡 CNN Parameter Initialization | medium | | ✅ | [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Exorust/TorchLeet/blob/main/torch/medium/cnn-param-init/CNN_ParamInit.ipynb) | [Q](torch/medium/cnn-param-init/CNN_ParamInit.ipynb) / [S](torch/medium/cnn-param-init/CNN_ParamInit_SOLN.ipynb) |
| 💡 Implement a CNN from Scratch | medium | | ✅ | [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Exorust/TorchLeet/blob/main/torch/medium/cnn-scratch/CNN_scratch.ipynb) | [Q](torch/medium/cnn-scratch/CNN_scratch.ipynb) / [S](torch/medium/cnn-scratch/CNN_scratch_SOLN.ipynb) |
| 💡 Implement an LSTM from Scratch | medium | | ✅ | [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Exorust/TorchLeet/blob/main/torch/medium/lstm/LSTM.ipynb) | [Q](torch/medium/lstm/LSTM.ipynb) / [S](torch/medium/lstm/LSTM_SOLN.ipynb) |
| 💡 Implement RMS Norm | easy | | | [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Exorust/TorchLeet/blob/main/llm/RMS-Norm/rms-norm.ipynb) | [Q](llm/RMS-Norm/rms-norm.ipynb) |
| 💡 Implement RMS Norm | easy | | ✅ | [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Exorust/TorchLeet/blob/main/llm/RMS-Norm/rms-norm.ipynb) | [Q](llm/RMS-Norm/rms-norm.ipynb) / [S](llm/RMS-Norm/rms-norm_SOLN.ipynb) |
| 💡 Implement Byte Pair Encoding from Scratch | easy | | ✅ | [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Exorust/TorchLeet/blob/main/llm/Byte-Pair-Encoder/BPE-q3.ipynb) | [Q](llm/Byte-Pair-Encoder/BPE-q3.ipynb) / [S](llm/Byte-Pair-Encoder/BPE-q3-SOLN.ipynb) |
| 🔥 Implement Softmax from Scratch | easy | Apple, Meta, Google, Amazon | ✅ | [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Exorust/TorchLeet/blob/main/v3/classical-ml/softmax/softmax.ipynb) | [Q](v3/classical-ml/softmax/softmax.ipynb) / [S](v3/classical-ml/softmax/softmax_SOLN.ipynb) |
| 🔥 Implement K-Means Clustering in PyTorch | easy | Uber, LinkedIn, Google, Amazon | ✅ | [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Exorust/TorchLeet/blob/main/v3/classical-ml/kmeans/kmeans.ipynb) | [Q](v3/classical-ml/kmeans/kmeans.ipynb) / [S](v3/classical-ml/kmeans/kmeans_SOLN.ipynb) |
Expand All @@ -38,7 +38,7 @@ Graded column means `check()` will verify your solution.

| Problem | Difficulty | Companies | Graded | Run | Links |
|---|---|---|---|---|---|
| 💡 Implement RMS Norm | easy | | | [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Exorust/TorchLeet/blob/main/llm/RMS-Norm/rms-norm.ipynb) | [Q](llm/RMS-Norm/rms-norm.ipynb) |
| 💡 Implement RMS Norm | easy | | ✅ | [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Exorust/TorchLeet/blob/main/llm/RMS-Norm/rms-norm.ipynb) | [Q](llm/RMS-Norm/rms-norm.ipynb) / [S](llm/RMS-Norm/rms-norm_SOLN.ipynb) |
| 💡 Implement Byte Pair Encoding from Scratch | easy | | ✅ | [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Exorust/TorchLeet/blob/main/llm/Byte-Pair-Encoder/BPE-q3.ipynb) | [Q](llm/Byte-Pair-Encoder/BPE-q3.ipynb) / [S](llm/Byte-Pair-Encoder/BPE-q3-SOLN.ipynb) |
| 💡 Implement Attention from Scratch | medium | | ✅ | [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Exorust/TorchLeet/blob/main/llm/Implement-Attention-from-Scratch/attention-q4-Question.ipynb) | [Q](llm/Implement-Attention-from-Scratch/attention-q4-Question.ipynb) / [S](llm/Implement-Attention-from-Scratch/attention-q4.ipynb) |
| 💡 Implement Multi-Head Attention from Scratch | medium | | ✅ | [![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Exorust/TorchLeet/blob/main/llm/Multi-Head-Attention/multi-head-attention-q5-Question.ipynb) | [Q](llm/Multi-Head-Attention/multi-head-attention-q5-Question.ipynb) / [S](llm/Multi-Head-Attention/multi-head-attention-q5.ipynb) |
Expand Down
16 changes: 12 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,10 @@ Build an LLM from scratch, one question at a time. Recommended order:
### 1. Foundations
| Problem | Links |
|---------|-------|
| Implement Byte Pair Encoding from Scratch | [Q](llm/Byte-Pair-Encoder/BPE-q3.ipynb) |
| Implement Byte Pair Encoding from Scratch | [Q](llm/Byte-Pair-Encoder/BPE-q3.ipynb) / [S](llm/Byte-Pair-Encoder/BPE-q3-SOLN.ipynb) |
| Implement Sinusoidal Embeddings | [Q](llm/Sinusoidal-Positional-Embedding/sinusoidal-q7-Question.ipynb) / [S](llm/Sinusoidal-Positional-Embedding/sinusoidal-q7.ipynb) |
| Implement ROPE Embeddings | [Q](llm/Rotary-Positional-Embedding/rope-q8-Question.ipynb) / [S](llm/Rotary-Positional-Embedding/rope-q8.ipynb) |
| Implement RMS Norm | |
| Implement RMS Norm | [Q](llm/RMS-Norm/rms-norm.ipynb) / [S](llm/RMS-Norm/rms-norm_SOLN.ipynb) |
| Implement Attention from Scratch | [Q](llm/Implement-Attention-from-Scratch/attention-q4-Question.ipynb) / [S](llm/Implement-Attention-from-Scratch/attention-q4.ipynb) |

### 2. Core Transformer
Expand Down Expand Up @@ -170,12 +170,20 @@ Core PyTorch and classical ML fundamentals.
| Implement KNN in PyTorch | Easy | [Q](v3/classical-ml/knn/knn.ipynb) / [S](v3/classical-ml/knn/knn_SOLN.ipynb) |
| Implement Logistic Regression | Easy | [Q](v3/classical-ml/logistic-regression/logistic-regression.ipynb) / [S](v3/classical-ml/logistic-regression/logistic-regression_SOLN.ipynb) |
| KL Divergence Loss | Easy | |
| RMS Norm | Easy | |
| Byte Pair Encoding | Easy | [Q](llm/Byte-Pair-Encoder/BPE-q3.ipynb) |
| RMS Norm | Easy | [Q](llm/RMS-Norm/rms-norm.ipynb) / [S](llm/RMS-Norm/rms-norm_SOLN.ipynb) |
| Byte Pair Encoding | Easy | [Q](llm/Byte-Pair-Encoder/BPE-q3.ipynb) / [S](llm/Byte-Pair-Encoder/BPE-q3-SOLN.ipynb) |
| CNN Parameter Initialization | Medium | [Q](torch/medium/cnn-param-init/CNN_ParamInit.ipynb) / [S](torch/medium/cnn-param-init/CNN_ParamInit_SOLN.ipynb) |
| Implement a CNN from Scratch | Medium | [Q](torch/medium/cnn-scratch/CNN_scratch.ipynb) / [S](torch/medium/cnn-scratch/CNN_scratch_SOLN.ipynb) |
| Implement an LSTM from Scratch | Medium | [Q](torch/medium/lstm/LSTM.ipynb) / [S](torch/medium/lstm/LSTM_SOLN.ipynb) |

### Data Loading
| Problem | Difficulty | Links |
|---------|------------|-------|
| Preloaded Map-Style Dataset | Easy | [Q](v3/data-loading/preloaded-dataset/preloaded-dataset.ipynb) / [S](v3/data-loading/preloaded-dataset/preloaded-dataset_SOLN.ipynb) |
| Streaming IterableDataset with Yield | Medium | [Q](v3/data-loading/streaming-dataset/streaming-dataset.ipynb) / [S](v3/data-loading/streaming-dataset/streaming-dataset_SOLN.ipynb) |
| Shuffle Buffer for Streaming Data | Medium | [Q](v3/data-loading/buffered-loading/buffered-loading.ipynb) / [S](v3/data-loading/buffered-loading/buffered-loading_SOLN.ipynb) |
| Simulate DistributedSampler for Data Parallel | Medium | [Q](v3/data-loading/data-parallel-loading/data-parallel-loading.ipynb) / [S](v3/data-loading/data-parallel-loading/data-parallel-loading_SOLN.ipynb) |

---

## Advanced
Expand Down
132 changes: 4 additions & 128 deletions llm/Byte-Pair-Encoder/BPE-q3-SOLN.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -4,147 +4,23 @@
"cell_type": "markdown",
"id": "081a9dd1",
"metadata": {},
"source": [
"## Problem: Write a Byte Pain Encoder in Python\n",
"\n",
"### Problem Statement\n",
"Implement a **Transformer model** in PyTorch by completing the required sections. The model should consist of an embedding layer, a Transformer encoder, and an output layer for sequence processing and prediction.\n",
"\n",
"### Requirements\n",
"1. **Define the Transformer Model Architecture**:\n",
" - **Embedding Layer**:\n",
" - Implement a layer to transform input data into a higher-dimensional space.\n",
" - Use a `torch.nn.Linear` or `torch.nn.Embedding` layer to create embeddings from the input.\n",
" - **Transformer Encoder**:\n",
" - Use `torch.nn.TransformerEncoder` or `torch.nn.Transformer` to process sequences with attention.\n",
" - Configure parameters such as the number of attention heads and encoder layers.\n",
" - **Output Layer**:\n",
" - Add a fully connected (linear) layer to reduce the transformer's sequence output into the desired output dimension.\n",
"\n",
"2. **Implement the Forward Method**:\n",
" - Map the input to the higher-dimensional space using the embedding layer.\n",
" - Pass the transformed input through the Transformer encoder.\n",
" - Use the output layer to convert the encoded sequence into predictions.\n",
"\n",
"### Constraints\n",
"- Handle input padding correctly for variable-length sequences.\n",
"- Ensure compatibility with batch processing by correctly shaping input and output tensors.\n"
]
"source": "## Problem: Write a Byte Pair Encoder in Python — Solution\n\n### Problem Statement\nImplement the **Byte Pair Encoding (BPE)** algorithm in Python. BPE is a subword tokenization method used in modern NLP models (GPT, LLaMA, etc.) that iteratively merges the most frequent pair of adjacent symbols in a vocabulary to build a compact subword vocabulary from a corpus of words.\n\n### Requirements\n1. **`get_vocab(corpus)`** — Build an initial vocabulary from a list of words:\n - Split each word into individual characters plus a special end-of-word token.\n - Count how many times each word appears in the corpus.\n\n2. **`get_stats(vocab)`** — Count adjacent symbol pairs:\n - For each word in the vocabulary, count every pair of adjacent symbols.\n - Weight each pair's count by the word's frequency.\n\n3. **`merge_vocab(pair, vocab)`** — Apply a merge operation:\n - Find every occurrence of the given pair of adjacent symbols in the vocabulary.\n - Replace the pair with a single merged symbol (concatenation of the two).\n - The merged vocabulary must spell the same words as before — only the chunking changes.\n\n4. **`byte_pair_encoding(corpus, num_merges=10)`** — Run the full BPE loop:\n - Build the initial vocabulary, then repeatedly find and merge the most frequent pair.\n - Return the final vocabulary and the list of merge operations performed."
},
{
"cell_type": "code",
"execution_count": null,
"id": "89f09999",
"metadata": {},
"outputs": [],
"source": [
"from collections import defaultdict, Counter\n",
"\n",
"def get_vocab(corpus):\n",
" \"\"\"Creates a vocabulary with words split into characters and a special end of word token.\"\"\"\n",
" vocab = Counter()\n",
" for word in corpus:\n",
" tokens = list(word) + [\"\"]\n",
" vocab[tuple(tokens)]+=1\n",
" return vocab\n",
"\n",
"def get_stats(vocab):\n",
" \"\"\"Counts frequency of adjacent symbol pairs.\"\"\"\n",
" pairs = defaultdict(int)\n",
" for word,freq in vocab.items():\n",
" for i in range(len(word)-1):\n",
" pairs[(word[i], word[i+1])] +=freq\n",
" return pairs\n",
"\n",
"def merge_vocab(pair, vocab):\n",
" \"\"\"Merges the most frequent pair into a single symbol.\"\"\"\n",
" new_vocab = {}\n",
" bigram = ' '.join(pair)\n",
" replacement = ''.join(pair)\n",
" print(f\"Bigram: {bigram}\")\n",
" for word,freq in vocab.items():\n",
" word_str = ' '.join(word)\n",
" #Replace bigram with merged symbol\n",
" new_word_str=word_str.replace(bigram, replacement)\n",
" #Preserve the trailing empty string token if the original word ended with it\n",
" tokens = new_word_str.split()\n",
" if word[-1] == \"\":\n",
" tokens.append(\"\")\n",
" new_vocab[tuple(tokens)]=freq\n",
" return new_vocab\n",
"\n",
"\n",
"def byte_pair_encoding(corpus, num_merges=10):\n",
" \"\"\"Performs BPE on a corpus.\"\"\"\n",
" vocab = get_vocab(corpus)\n",
" merges = []\n",
" for _ in range(num_merges):\n",
" pairs = get_stats(vocab)\n",
" if not pairs:\n",
" break\n",
" best = max(pairs, key=pairs.get)\n",
" vocab = merge_vocab(best, vocab)\n",
" merges.append(best)\n",
" print(f\"Merge {_ + 1}: {best}\")\n",
" return vocab, merges\n",
"\n",
"corpus = [\"low\", \"lowest\", \"newer\", \"wider\", \"owl\", \"LOW\"]\n",
"final_vocab , merge_operations = byte_pair_encoding(corpus, num_merges=10)\n",
"# vocab = get_vocab(corpus)\n",
"# pairs = get_stats(vocab)\n",
"# print(pairs)\n",
"# new_vocab = merge_vocab(pairs, vocab)\n",
"print(\"\\nFinal Vocabulary:\")\n",
"for word in final_vocab:\n",
" print(\"\".join(word), \":\", final_vocab[word])"
]
"source": "from collections import defaultdict, Counter\n\ndef get_vocab(corpus):\n \"\"\"Creates a vocabulary with words split into characters and a special end-of-word token.\"\"\"\n vocab = Counter()\n for word in corpus:\n tokens = tuple(list(word) + [\"</w>\"])\n vocab[tokens] += 1\n return dict(vocab)\n\ndef get_stats(vocab):\n \"\"\"Counts frequency of adjacent symbol pairs.\"\"\"\n pairs = defaultdict(int)\n for word, freq in vocab.items():\n for i in range(len(word) - 1):\n pairs[(word[i], word[i + 1])] += freq\n return dict(pairs)\n\ndef merge_vocab(pair, vocab):\n \"\"\"Merges the most frequent pair into a single symbol.\"\"\"\n new_vocab = {}\n bigram = pair\n replacement = ''.join(pair)\n for word, freq in vocab.items():\n new_word = []\n i = 0\n while i < len(word):\n if i < len(word) - 1 and (word[i], word[i + 1]) == bigram:\n new_word.append(replacement)\n i += 2\n else:\n new_word.append(word[i])\n i += 1\n new_vocab[tuple(new_word)] = freq\n return new_vocab\n\ndef byte_pair_encoding(corpus, num_merges=10):\n \"\"\"Performs BPE on a corpus.\"\"\"\n vocab = get_vocab(corpus)\n merges = []\n for i in range(num_merges):\n pairs = get_stats(vocab)\n if not pairs:\n break\n best = max(pairs, key=pairs.get)\n vocab = merge_vocab(best, vocab)\n merges.append(best)\n return vocab, merges\n\n# Example usage\ncorpus = [\"low\", \"lowest\", \"newer\", \"wider\"]\nfinal_vocab, merge_operations = byte_pair_encoding(corpus, num_merges=10)\n\nprint(\"Final Vocabulary:\")\nfor word in final_vocab:\n print(' '.join(word), \":\", final_vocab[word])"
},
{
"cell_type": "code",
"execution_count": null,
"id": "9e4638a1",
"metadata": {},
"outputs": [],
"source": [
"def test_get_vocab():\n",
" corpus = ['test']\n",
" vocab = get_vocab(corpus)\n",
" assert vocab == {(\"t\", \"e\", \"s\", \"t\", \"\"):1}\n",
" print(\"✓\")\n",
"\n",
"def test_get_status():\n",
" vocab = {('t', 'e', 's', 't', '' ):1}\n",
" stats = get_stats(vocab)\n",
" expected = {\n",
" ('t', 'e'): 1,\n",
" ('e', 's'): 1,\n",
" ('s', 't'): 1,\n",
" ('t', ''): 1\n",
" }\n",
" assert stats == expected\n",
" print(\"✓✓\")\n",
"\n",
"def test_merge_vocab():\n",
" vocab = {('t', 'e', 's', 't', '' ):1}\n",
" merged = merge_vocab((\"e\", \"s\"),vocab)\n",
" print(merged)\n",
" expected = {(\"t\", \"es\", 't', ''):1}\n",
" assert merged == expected\n",
" print(\"✓✓✓\")\n",
"\n",
"def test_bpe_sequence():\n",
" corpus = ['low', 'lower', 'lower', 'newest', 'wildest']\n",
" final_vocab, merges = byte_pair_encoding(corpus, num_merges=5)\n",
" assert isinstance(final_vocab, dict)\n",
" assert all(isinstance(pair, tuple) for pair in merges)\n",
" assert len(merges) == 5\n",
" print(\"✓✓✓✓\")\n",
"\n",
"test_get_vocab()\n",
"test_get_status()\n",
"test_merge_vocab()\n",
"test_bpe_sequence()"
]
"source": "def test_get_vocab():\n corpus = ['test']\n vocab = get_vocab(corpus)\n assert vocab == {('t', 'e', 's', 't', '</w>'): 1}\n print(\"✓ test_get_vocab passed\")\n\ndef test_get_stats():\n vocab = {('t', 'e', 's', 't', '</w>'): 1}\n stats = get_stats(vocab)\n expected = {\n ('t', 'e'): 1,\n ('e', 's'): 1,\n ('s', 't'): 1,\n ('t', '</w>'): 1\n }\n assert stats == expected\n print(\"✓ test_get_stats passed\")\n\ndef test_merge_vocab():\n vocab = {('t', 'e', 's', 't', '</w>'): 1}\n merged = merge_vocab(('e', 's'), vocab)\n expected = {('t', 'es', 't', '</w>'): 1}\n assert merged == expected\n print(\"✓ test_merge_vocab passed\")\n\ndef test_bpe_sequence():\n corpus = ['low', 'lower', 'newest', 'widest']\n final_vocab, merges = byte_pair_encoding(corpus, num_merges=5)\n assert isinstance(final_vocab, dict)\n assert all(isinstance(pair, tuple) for pair in merges)\n assert len(merges) == 5\n print(\"✓ test_bpe_sequence passed\")\n\ntest_get_vocab()\ntest_get_stats()\ntest_merge_vocab()\ntest_bpe_sequence()\nprint(\"\\nAll tests passed!\")"
}
],
"metadata": {
Expand All @@ -154,4 +30,4 @@
},
"nbformat": 4,
"nbformat_minor": 5
}
}
Loading