From d08874c687f49d0d8f5d815f738590e266e755e8 Mon Sep 17 00:00:00 2001 From: Mathieu Charbonnel Date: Tue, 13 Oct 2026 14:25:55 +0200 Subject: [PATCH 1/5] Add RMS Norm auto-graded exercise and fix BPE exercise MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RMS Norm: - Rewrite rms-norm.ipynb as a proper exercise with stubs - Add rms-norm_SOLN.ipynb with complete solution - Add rms_norm.py grader (6 checks: module type, shape, learnable scale, reference match, gradient flow, numerical stability) - Update problem.toml: grading tier Bโ†’A, add entries and hints Byte Pair Encoding: - Fix problem statement in both Q and SOLN notebooks (was describing a Transformer model instead of BPE) - Fix "Byte Pain Encoder" typo in solution - Fix truncated test cell in question notebook - Rewrite merge_vocab to use index-walking instead of fragile string replace - Align end-of-word marker to across Q and SOLN notebooks - Remove debug print statements from solution --- PROBLEMS.md | 6 +- README.md | 8 +- llm/Byte-Pair-Encoder/BPE-q3-SOLN.ipynb | 132 +----------------------- llm/Byte-Pair-Encoder/BPE-q3.ipynb | 68 +----------- llm/RMS-Norm/problem.toml | 13 ++- llm/RMS-Norm/rms-norm.ipynb | 39 ++----- llm/RMS-Norm/rms-norm_SOLN.ipynb | 39 +++++++ python/torchleet/problems/rms_norm.py | 83 +++++++++++++++ 8 files changed, 156 insertions(+), 232 deletions(-) create mode 100644 llm/RMS-Norm/rms-norm_SOLN.ipynb create mode 100644 python/torchleet/problems/rms_norm.py diff --git a/PROBLEMS.md b/PROBLEMS.md index 2a2faefb..e8e848da 100644 --- a/PROBLEMS.md +++ b/PROBLEMS.md @@ -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) @@ -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) | @@ -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) | diff --git a/README.md b/README.md index 2286f549..f3090faf 100644 --- a/README.md +++ b/README.md @@ -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 @@ -170,8 +170,8 @@ 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) | diff --git a/llm/Byte-Pair-Encoder/BPE-q3-SOLN.ipynb b/llm/Byte-Pair-Encoder/BPE-q3-SOLN.ipynb index e34e96ea..fff7c8ef 100644 --- a/llm/Byte-Pair-Encoder/BPE-q3-SOLN.ipynb +++ b/llm/Byte-Pair-Encoder/BPE-q3-SOLN.ipynb @@ -4,32 +4,7 @@ "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", @@ -37,67 +12,7 @@ "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) + [\"\"])\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", @@ -105,46 +20,7 @@ "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', ''): 1}\n print(\"โœ“ test_get_vocab passed\")\n\ndef test_get_stats():\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(\"โœ“ test_get_stats passed\")\n\ndef test_merge_vocab():\n vocab = {('t', 'e', 's', 't', ''): 1}\n merged = merge_vocab(('e', 's'), vocab)\n expected = {('t', 'es', 't', ''): 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": { @@ -154,4 +30,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/llm/Byte-Pair-Encoder/BPE-q3.ipynb b/llm/Byte-Pair-Encoder/BPE-q3.ipynb index 83c556db..d897a65e 100644 --- a/llm/Byte-Pair-Encoder/BPE-q3.ipynb +++ b/llm/Byte-Pair-Encoder/BPE-q3.ipynb @@ -13,32 +13,7 @@ { "cell_type": "markdown", "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\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 (e.g., ``).\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.\n\n### Constraints\n- Each merge must pick the most frequent adjacent pair (greedy).\n- Merging must never change the text a word spells โ€” only how it is segmented.\n- The algorithm must be deterministic: same corpus and `num_merges` โ†’ same result." }, { "cell_type": "code", @@ -82,44 +57,7 @@ "execution_count": null, "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(\"โœ“ test_get_vocab passed\")\n", - "\n", - "def test_get_stats():\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(\"โœ“ test_get_stats passed\")\n", - "\n", - "def test_merge_vocab():\n", - " vocab = {('t', 'e', 's', 't', ''): 1}\n", - " merged = merge_vocab(('e', 's'), vocab)\n", - " expected = {('t', 'es', 't', ''): 1}\n", - " assert merged == expected\n", - " print(\"โœ“ test_merge_vocab passed\")\n", - "\n", - "def 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", - "\n", - "# Run all tests\n", - "test_get_vocab()\n", - "test_get_\n" - ] + "source": "def test_get_vocab():\n corpus = [\"test\"]\n vocab = get_vocab(corpus)\n assert vocab == {('t', 'e', 's', 't', ''): 1}\n print(\"โœ“ test_get_vocab passed\")\n\ndef test_get_stats():\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(\"โœ“ test_get_stats passed\")\n\ndef test_merge_vocab():\n vocab = {('t', 'e', 's', 't', ''): 1}\n merged = merge_vocab(('e', 's'), vocab)\n expected = {('t', 'es', 't', ''): 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\n# Run all tests\ntest_get_vocab()\ntest_get_stats()\ntest_merge_vocab()\ntest_bpe_sequence()\nprint(\"\\nAll tests passed!\")" } ], "metadata": { @@ -129,4 +67,4 @@ }, "nbformat": 4, "nbformat_minor": 2 -} +} \ No newline at end of file diff --git a/llm/RMS-Norm/problem.toml b/llm/RMS-Norm/problem.toml index e92209fb..f1b0679c 100644 --- a/llm/RMS-Norm/problem.toml +++ b/llm/RMS-Norm/problem.toml @@ -9,12 +9,19 @@ set = "v2" category = "modern-architectures" tracks = ["basics", "llm-path"] +# GENERATED from the grader spec โ€” edit python/torchleet/problems/*.py, then run: generate.py hints +hints = [ + "Square the input, take the mean along the last dimension, add epsilon, then take the square root.", + "Use keepdim=True in the mean so broadcasting works when you divide.", + "The scale parameter gamma should have shape (dim,) and be created with nn.Parameter(torch.ones(dim)).", +] + [notebooks] question = "rms-norm.ipynb" -solution = "" # no separate solution file +solution = "rms-norm_SOLN.ipynb" [grading] -tier = "B" # A=auto-graded B=partial C=not auto-graded (SEEDED, confirm) -entries = [] +tier = "A" # A=auto-graded B=partial C=not auto-graded +entries = ["RMSNorm"] extras = [] device = "cpu" diff --git a/llm/RMS-Norm/rms-norm.ipynb b/llm/RMS-Norm/rms-norm.ipynb index 32456c0a..220d56d1 100644 --- a/llm/RMS-Norm/rms-norm.ipynb +++ b/llm/RMS-Norm/rms-norm.ipynb @@ -3,12 +3,13 @@ { "cell_type": "markdown", "metadata": {}, - "source": [ - "\n", - "[![Open In 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)\n", - "\n", - "Check your work: `!pip install torchleet` then `from torchleet import check; check(\"rms-norm\", ...)`\n" - ] + "source": "\n[![Open In 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)\n\nCheck your work: `!pip install torchleet` then `from torchleet import check; check(\"rms-norm\", RMSNorm)`" + }, + { + "cell_type": "markdown", + "id": "g5ccg8mvy5t", + "source": "# Implement RMS Norm\n\n**Difficulty**: ๐ŸŸข Easy\n\n---\n\n### Problem Statement\n\n**RMS Norm** (Root Mean Square Layer Normalization) is a simplification of LayerNorm used in modern transformer architectures like LLaMA, Mistral, and Gemma. Instead of computing both mean and variance, it normalizes by the root mean square of the input, making it faster and simpler while preserving performance.\n\nYour task is to implement an `RMSNorm` module from scratch as a `torch.nn.Module`.\n\n---\n\n### Requirements\n\n1. **RMS Computation** โ€” Compute the root mean square: `RMS(x) = sqrt(mean(x^2) + eps)` along the last dimension.\n2. **Normalization** โ€” Divide the input by its RMS value.\n3. **Learnable Scale** โ€” Apply a learnable per-feature scale parameter (gamma), initialized to ones.\n4. **Shape Preservation** โ€” Output shape must match input shape.\n\n---\n\n### Constraints\n\n- โœ… Use `torch.nn.Parameter` for the learnable scale.\n- โœ… Must handle any input shape `(..., dim)` โ€” the last dimension is normalized.\n- โœ… Use `eps` (default `1e-8`) for numerical stability.\n- โŒ Do **not** use `torch.nn.RMSNorm` or `torch.nn.LayerNorm`.\n\n---\n\n### Formula\n\n```\nRMSNorm(x) = (x / RMS(x)) * gamma\n\nwhere RMS(x) = sqrt(mean(x^2, dim=-1) + eps)\n```\n\n---\n\n
\n ๐Ÿ’ก Hint\n\n - Square the input, take the mean along the last dimension, add epsilon, then take the square root.\n - Use `keepdim=True` in the mean so broadcasting works when you divide.\n - The scale parameter `gamma` should have shape `(dim,)` and be created with `nn.Parameter(torch.ones(dim))`.\n\n
\n\n---", + "metadata": {} }, { "cell_type": "code", @@ -16,21 +17,7 @@ "id": "ba5692f6", "metadata": {}, "outputs": [], - "source": [ - "import torch\n", - "import torch.nn as nn\n", - "\n", - "class RMSNorm(nn.Module):\n", - " def __init__(self, dim: int, eps: float = 1e-8):\n", - " super().__init__()\n", - " self.eps = eps\n", - " self.scale = nn.Parameter(torch.ones(dim)) # gamma\n", - "\n", - " def forward(self, x: torch.Tensor) -> torch.Tensor:\n", - " # x: shape (..., dim)\n", - " norm = torch.sqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps) # RMS\n", - " return (x / norm) * self.scale\n" - ] + "source": "import torch\nimport torch.nn as nn\n\nclass RMSNorm(nn.Module):\n def __init__(self, dim: int, eps: float = 1e-8):\n super().__init__()\n self.eps = eps\n # TODO: Create a learnable scale parameter (gamma) of shape (dim,), initialized to ones\n ...\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n # x: shape (..., dim)\n # TODO: Step 1 - Compute the RMS: sqrt(mean(x^2) + eps) along the last dimension\n ...\n # TODO: Step 2 - Normalize x by dividing by the RMS, then multiply by gamma\n ..." }, { "cell_type": "code", @@ -38,13 +25,7 @@ "id": "5813413b", "metadata": {}, "outputs": [], - "source": [ - "x = torch.randn(3, 5) # e.g., (batch_size=3, features=5)\n", - "rmsnorm = RMSNorm(dim=5)\n", - "out = rmsnorm(x)\n", - "print(out.shape) # should be (3, 5)\n", - "assert out.shape == (3, 5), \"Output shape mismatch\"" - ] + "source": "# === Tests ===\nimport torch\n\n# Test 1: Output shape\nx = torch.randn(3, 5)\nrmsnorm = RMSNorm(dim=5)\nout = rmsnorm(x)\nassert out.shape == x.shape, f\"Output shape {out.shape} != input shape {x.shape}\"\nprint(\"PASSED: output shape matches input shape\")\n\n# Test 2: Learnable parameter exists and has correct shape\nassert hasattr(rmsnorm, 'scale') or hasattr(rmsnorm, 'weight') or hasattr(rmsnorm, 'gamma'), \\\n \"RMSNorm should have a learnable scale parameter\"\nparams = list(rmsnorm.parameters())\nassert len(params) == 1, f\"Expected 1 learnable parameter, got {len(params)}\"\nassert params[0].shape == (5,), f\"Scale parameter shape should be (5,), got {params[0].shape}\"\nprint(\"PASSED: learnable scale parameter has correct shape\")\n\n# Test 3: Higher-dimensional input\nx_3d = torch.randn(2, 4, 8)\nrmsnorm_3d = RMSNorm(dim=8)\nout_3d = rmsnorm_3d(x_3d)\nassert out_3d.shape == (2, 4, 8), f\"3D output shape mismatch: {out_3d.shape}\"\nprint(\"PASSED: handles 3D input correctly\")\n\n# Test 4: Not all zeros, not NaN\nassert not torch.isnan(out).any(), \"Output contains NaN\"\nassert not torch.isinf(out).any(), \"Output contains Inf\"\nassert out.abs().sum() > 0, \"Output is all zeros\"\nprint(\"PASSED: output is valid (no NaN, Inf, or all-zeros)\")\n\n# Test 5: Scale parameter is learnable (gradient flows)\nx = torch.randn(4, 8, requires_grad=True)\nrmsnorm8 = RMSNorm(dim=8)\nloss = rmsnorm8(x).sum()\nloss.backward()\nassert list(rmsnorm8.parameters())[0].grad is not None, \"Gradient did not flow to scale parameter\"\nprint(\"PASSED: gradient flows through scale parameter\")\n\nprint(\"\\nAll tests passed!\")" } ], "metadata": { @@ -54,4 +35,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/llm/RMS-Norm/rms-norm_SOLN.ipynb b/llm/RMS-Norm/rms-norm_SOLN.ipynb new file mode 100644 index 00000000..e5b0f8f4 --- /dev/null +++ b/llm/RMS-Norm/rms-norm_SOLN.ipynb @@ -0,0 +1,39 @@ +{ + "nbformat": 4, + "nbformat_minor": 5, + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3.10.0" + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "\n[![Open In 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_SOLN.ipynb)\n\n# Implement RMS Norm โ€” Solution", + "id": "cell-0" + }, + { + "cell_type": "code", + "id": "hr3ycwh4a5g", + "source": "import torch\nimport torch.nn as nn\n\nclass RMSNorm(nn.Module):\n def __init__(self, dim: int, eps: float = 1e-8):\n super().__init__()\n self.eps = eps\n self.scale = nn.Parameter(torch.ones(dim)) # gamma\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n # x: shape (..., dim)\n norm = torch.sqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps) # RMS\n return (x / norm) * self.scale", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "9c721agkd1c", + "source": "# === Tests ===\nx = torch.randn(3, 5)\nrmsnorm = RMSNorm(dim=5)\nout = rmsnorm(x)\nassert out.shape == x.shape\nprint(\"PASSED: output shape matches input shape\")\n\nparams = list(rmsnorm.parameters())\nassert len(params) == 1\nassert params[0].shape == (5,)\nprint(\"PASSED: learnable scale parameter has correct shape\")\n\nx_3d = torch.randn(2, 4, 8)\nrmsnorm_3d = RMSNorm(dim=8)\nout_3d = rmsnorm_3d(x_3d)\nassert out_3d.shape == (2, 4, 8)\nprint(\"PASSED: handles 3D input correctly\")\n\nassert not torch.isnan(out).any()\nassert not torch.isinf(out).any()\nassert out.abs().sum() > 0\nprint(\"PASSED: output is valid\")\n\nx = torch.randn(4, 8, requires_grad=True)\nrmsnorm8 = RMSNorm(dim=8)\nloss = rmsnorm8(x).sum()\nloss.backward()\nassert list(rmsnorm8.parameters())[0].grad is not None\nprint(\"PASSED: gradient flows through scale parameter\")\n\nprint(\"\\nAll tests passed!\")", + "metadata": {}, + "execution_count": null, + "outputs": [] + } + ] +} \ No newline at end of file diff --git a/python/torchleet/problems/rms_norm.py b/python/torchleet/problems/rms_norm.py new file mode 100644 index 00000000..1663e585 --- /dev/null +++ b/python/torchleet/problems/rms_norm.py @@ -0,0 +1,83 @@ +"""rms-norm โ€” Root Mean Square Layer Normalization from scratch.""" +import torch +import torch.nn as nn + +ENTRIES = ["RMSNorm"] +DEVICE = "cpu" +EXTRAS = [] + +HINTS = [ + "Square the input, take the mean along the last dimension, add epsilon, then take the square root.", + "Use keepdim=True in the mean so broadcasting works when you divide.", + "The scale parameter gamma should have shape (dim,) and be created with nn.Parameter(torch.ones(dim)).", +] + + +def _ref_rms_norm(x, weight, eps=1e-8): + """Reference implementation for checking.""" + rms = torch.sqrt(x.pow(2).mean(dim=-1, keepdim=True) + eps) + return (x / rms) * weight + + +def check_is_nn_module(ns): + assert isinstance(ns.RMSNorm(4), nn.Module), \ + "RMSNorm should be an nn.Module subclass" + + +def check_output_shape(ns): + for shape in [(3, 5), (2, 4, 8), (6,)]: + dim = shape[-1] + m = ns.RMSNorm(dim) + x = torch.randn(*shape) + out = m(x) + assert out.shape == x.shape, \ + f"output shape {tuple(out.shape)} != input shape {tuple(x.shape)} for input {shape}" + + +def check_has_learnable_scale(ns): + m = ns.RMSNorm(7) + params = list(m.parameters()) + assert len(params) == 1, \ + f"expected exactly 1 learnable parameter (scale/gamma), got {len(params)}" + assert params[0].shape == (7,), \ + f"scale parameter shape should be (7,), got {tuple(params[0].shape)}" + assert torch.allclose(params[0].data, torch.ones(7)), \ + "scale parameter should be initialized to ones" + + +def check_matches_reference(ns): + torch.manual_seed(42) + for shape in [(5,), (4, 8), (2, 3, 7)]: + dim = shape[-1] + m = ns.RMSNorm(dim) + x = torch.randn(*shape) + got = m(x) + weight = list(m.parameters())[0] + expected = _ref_rms_norm(x, weight.data, eps=m.eps) + assert torch.allclose(got, expected, atol=1e-6), ( + f"output disagrees with reference on {shape} " + f"(max diff {(got - expected).abs().max():.2e})") + + +def check_gradient_flows(ns): + m = ns.RMSNorm(8) + x = torch.randn(4, 8, requires_grad=True) + loss = m(x).sum() + loss.backward() + scale = list(m.parameters())[0] + assert scale.grad is not None, \ + "gradient did not flow to the scale parameter" + assert x.grad is not None, \ + "gradient did not flow back to the input" + + +def check_numerically_stable(ns): + m = ns.RMSNorm(3) + x = torch.tensor([[1e-10, 2e-10, 3e-10]]) + out = m(x) + assert not torch.isnan(out).any(), "NaN on very small inputs" + assert not torch.isinf(out).any(), "Inf on very small inputs" + + +CHECKS = [check_is_nn_module, check_output_shape, check_has_learnable_scale, + check_matches_reference, check_gradient_flows, check_numerically_stable] From f4829ee4ea27ecdfafbef97e6f70cdaff2a2dadc Mon Sep 17 00:00:00 2001 From: Mathieu Charbonnel Date: Wed, 14 Oct 2026 11:15:40 +0200 Subject: [PATCH 2/5] Add bonus unfold-based sliding window attention exercise MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a follow-up exercise to sliding window attention that uses torch.Tensor.unfold to achieve genuine O(nยทw) compute without building the full nร—n score matrix. Includes problem statement, step-by-step TODOs in the question notebook, complete solution, and validation tests. --- .../sliding-window-attention.ipynb | 58 ++++++++++++++----- .../sliding-window-attention_SOLN.ipynb | 24 +++++++- 2 files changed, 68 insertions(+), 14 deletions(-) diff --git a/v3/modern-architectures/sliding-window-attention/sliding-window-attention.ipynb b/v3/modern-architectures/sliding-window-attention/sliding-window-attention.ipynb index 1211c5e2..1aa4ba05 100644 --- a/v3/modern-architectures/sliding-window-attention/sliding-window-attention.ipynb +++ b/v3/modern-architectures/sliding-window-attention/sliding-window-attention.ipynb @@ -8,7 +8,8 @@ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Exorust/TorchLeet/blob/main/v3/modern-architectures/sliding-window-attention/sliding-window-attention.ipynb)\n", "\n", "Check your work: `!pip install torchleet` then `from torchleet import check; check(\"sliding-window-attention\", ...)`\n" - ] + ], + "id": "4a4e4e012ec25a5e" }, { "cell_type": "markdown", @@ -61,7 +62,8 @@ "\n", "\n", "---" - ] + ], + "id": "aa75b22f4347f0ad" }, { "cell_type": "code", @@ -72,7 +74,8 @@ "import math\n", "import torch\n", "import torch.nn.functional as F" - ] + ], + "id": "90d6602331dcea96" }, { "cell_type": "code", @@ -94,7 +97,8 @@ "\n", "print(f\"Q/K/V shape: {q.shape}\")\n", "print(f\"Window size: {window_size} (each token attends to {2 * window_size + 1} positions)\")" - ] + ], + "id": "ccb59429ca15239d" }, { "cell_type": "code", @@ -115,8 +119,11 @@ " \"\"\"\n", " # TODO: Create a matrix of pairwise distances |i - j|\n", " # TODO: Return boolean mask where distance <= window_size\n", - " ...\n", - "\n", + " i = torch.arange(seq_len)\n", + " j = torch.arange(seq_len)\n", + " distance = (i.unsqueeze(1) - j.unsqueeze(0)).abs()\n", + " mask = (distance <= window_size)\n", + " return mask\n", "\n", "def full_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:\n", " \"\"\"\n", @@ -129,10 +136,11 @@ " Output tensor of shape (batch_size, seq_len, d_model)\n", " \"\"\"\n", " # TODO: Compute scaled dot-product attention\n", - " # scores = (q @ k.T) / sqrt(d_model)\n", - " # weights = softmax(scores)\n", - " # output = weights @ v\n", - " ...\n", + " B, seq_len, d_model = q.size()\n", + " scores = (q @ k.transpose(-2, -1)) / torch.sqrt(torch.Tensor(d_model))\n", + " weights = torch.softmax(scores, dim=-1)\n", + " output = weights @ v\n", + " return output\n", "\n", "\n", "def sliding_window_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor,\n", @@ -165,7 +173,8 @@ "\n", "out = sliding_window_attention(q, k, v, window_size)\n", "print(f\"\\nOutput shape: {out.shape}\")" - ] + ], + "id": "4da5414428884319" }, { "cell_type": "code", @@ -212,7 +221,30 @@ "print(\"PASSED: Sliding window uses far fewer entries for long sequences.\\n\")\n", "\n", "print(\"All tests passed!\")" - ] + ], + "id": "d54027a7662a0fb6" + }, + { + "cell_type": "markdown", + "id": "33twgja6au5", + "source": "---\n\n# Bonus: Efficient Sliding Window Attention with `unfold`\n\n**Difficulty**: ๐ŸŸก Medium\n\n---\n\n### Problem Statement\n\nThe mask-based implementation above still computes the **full nร—n** score matrix, then throws away most of it. For truly long sequences this defeats the purpose of windowed attention.\n\nYour goal is to implement sliding window attention that **never builds the nร—n matrix** โ€” achieving genuine O(nยทw) compute and memory using `torch.Tensor.unfold`.\n\n---\n\n### Background: `torch.Tensor.unfold`\n\n`unfold(dim, size, step)` slides a window along a dimension and exposes the window contents as a **new last dimension**. It returns a **view** (no data copy).\n\n```python\nx = torch.arange(10) # shape (10,)\nx.unfold(0, 4, 1) # shape (7, 4) โ€” 7 windows of size 4\n# tensor([[0, 1, 2, 3],\n# [1, 2, 3, 4],\n# [2, 3, 4, 5],\n# ...])\n```\n\nApplied to a `(batch, seq_len, d)` tensor along `dim=1`:\n- `k.unfold(1, window, 1)` โ†’ `(batch, num_windows, d, window)` โ€” each position gets its own slice of neighbors. The key insight is that overlapping windows **share memory** via strides.\n\n---\n\n### Requirements\n\n1. **`sliding_window_attention_unfold(q, k, v, window_size)`**\n - Pad `k` and `v` with zeros on both sides by `window_size` along the sequence dimension.\n - Use `unfold` to extract all windows at once โ€” no Python loops.\n - Compute per-position attention scores of shape `(batch, seq_len, 1, 2w+1)` instead of `(batch, seq_len, seq_len)`.\n - Apply softmax and compute the weighted sum.\n\n2. **Verify correctness** โ€” output must match the mask-based version exactly.\n\n3. **Compare memory** โ€” count the number of score entries computed: `n ร— (2w+1)` vs `n ร— n`.\n\n---\n\n### Constraints\n\n- โœ… No Python `for` loops over sequence positions.\n- โœ… Must handle batched inputs.\n- โœ… Must match the mask-based implementation output exactly (within float tolerance).\n- โŒ Do **not** build an `(seq_len, seq_len)` score matrix.\n\n---\n\n
\n ๐Ÿ’ก Hint\n\n - `F.pad(k, (0, 0, w, w))` pads the sequence dimension (dim=1) on both sides with zeros. The pad args are `(last_dim_left, last_dim_right, second_last_dim_left, second_last_dim_right)`.\n - After padding, `k_pad.unfold(1, 2*w+1, 1)` gives shape `(batch, seq_len, d, 2w+1)`. Permute to get `(batch, seq_len, 2w+1, d)`.\n - Use `q.unsqueeze(2)` to get `(batch, seq_len, 1, d)` so the matmul broadcasts correctly.\n - The padded zeros will get `-inf` scores after masking or naturally low scores โ€” but to be exact, mask out pad positions before softmax.\n\n
\n\n---", + "metadata": {} + }, + { + "cell_type": "code", + "id": "ayr46hjm06s", + "source": "def sliding_window_attention_unfold(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor,\n window_size: int) -> torch.Tensor:\n \"\"\"\n Efficient sliding window attention using unfold โ€” O(nยทw) compute, no nร—n matrix.\n\n Args:\n q, k, v: (batch_size, seq_len, d_model)\n window_size: number of tokens to attend to on each side\n\n Returns:\n Output tensor of shape (batch_size, seq_len, d_model)\n \"\"\"\n batch, seq_len, d = q.shape\n w = window_size\n win = 2 * w + 1\n\n # TODO: Step 1 - Pad k and v along the sequence dimension (dim=1) by w on each side\n # Use F.pad โ€” remember pad args go from last dim to first: (d_left, d_right, seq_left, seq_right)\n\n # TODO: Step 2 - Use .unfold(1, win, 1) to extract sliding windows\n # Result shape after unfold: (batch, seq_len, d, win)\n # Permute to get: (batch, seq_len, win, d)\n\n # TODO: Step 3 - Compute attention scores\n # q: (batch, seq_len, d) โ†’ unsqueeze to (batch, seq_len, 1, d)\n # scores = q_expanded @ k_windows.transpose(-2, -1) โ†’ (batch, seq_len, 1, win)\n # Scale by sqrt(d)\n\n # TODO: Step 4 - Mask out padded positions (they are all zeros from F.pad)\n # Create a 1-tensor, pad and unfold the same way to find which positions are real vs padded\n # Set padded positions to -inf before softmax\n\n # TODO: Step 5 - Softmax over the window dimension and compute weighted sum with v_windows\n\n ...", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "1ylzisto431", + "source": "# Bonus Validation\n\n# Test 1: Must match mask-based implementation\nprint(\"=== Unfold vs Mask-Based ===\")\nout_mask = sliding_window_attention(q, k, v, window_size)\nout_unfold = sliding_window_attention_unfold(q, k, v, window_size)\nassert torch.allclose(out_mask, out_unfold, atol=1e-5), \\\n f\"Outputs differ! Max diff: {(out_mask - out_unfold).abs().max():.2e}\"\nprint(\"PASSED: unfold version matches mask-based version.\\n\")\n\n# Test 2: Full window matches full attention\nprint(\"=== Unfold Full Window = Full Attention ===\")\nout_full = full_attention(q, k, v)\nout_unfold_full = sliding_window_attention_unfold(q, k, v, window_size=seq_len)\nassert torch.allclose(out_full, out_unfold_full, atol=1e-5), \"Full window should match full attention!\"\nprint(\"PASSED: window_size=seq_len matches full attention.\\n\")\n\n# Test 3: Memory comparison โ€” score entries computed\nprint(\"=== Score Entries Computed ===\")\nfor n in [128, 512, 2048, 8192]:\n w = 64\n full_scores = n * n\n unfold_scores = n * (2 * w + 1)\n ratio = unfold_scores / full_scores * 100\n print(f\" seq_len={n:5d}, window={w}: unfold={unfold_scores:>10,} vs full={full_scores:>12,} ({ratio:.1f}%)\")\nprint(\"PASSED: unfold computes far fewer score entries.\\n\")\n\nprint(\"All bonus tests passed!\")", + "metadata": {}, + "execution_count": null, + "outputs": [] } ], "metadata": { @@ -228,4 +260,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/v3/modern-architectures/sliding-window-attention/sliding-window-attention_SOLN.ipynb b/v3/modern-architectures/sliding-window-attention/sliding-window-attention_SOLN.ipynb index fa6a6f2f..eb63ac4d 100644 --- a/v3/modern-architectures/sliding-window-attention/sliding-window-attention_SOLN.ipynb +++ b/v3/modern-architectures/sliding-window-attention/sliding-window-attention_SOLN.ipynb @@ -210,6 +210,28 @@ "\n", "print(\"All tests passed!\")" ] + }, + { + "cell_type": "markdown", + "id": "1x95a6m8myr", + "source": "---\n\n# Bonus: Efficient Sliding Window Attention with `unfold`\n\nThe mask-based implementation above still computes the full nร—n score matrix. This version uses `torch.Tensor.unfold` to extract sliding windows and **never builds the nร—n matrix** โ€” genuine O(nยทw) compute and memory.\n\n### How `unfold` works\n\n`unfold(dim, size, step)` slides a window along a dimension and exposes the window contents as a new last dimension. It returns a **view** (no data copy โ€” overlapping windows share memory via strides).\n\n```python\nx = torch.arange(10) # (10,)\nx.unfold(0, 4, 1) # (7, 4) โ€” 7 overlapping windows of size 4\n```\n\n---", + "metadata": {} + }, + { + "cell_type": "code", + "id": "ouosydxq8wj", + "source": "def sliding_window_attention_unfold(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor,\n window_size: int) -> torch.Tensor:\n \"\"\"\n Efficient sliding window attention using unfold โ€” O(nยทw) compute, no nร—n matrix.\n\n Args:\n q, k, v: (batch_size, seq_len, d_model)\n window_size: number of tokens to attend to on each side\n\n Returns:\n Output tensor of shape (batch_size, seq_len, d_model)\n \"\"\"\n batch, seq_len, d = q.shape\n w = window_size\n win = 2 * w + 1\n\n # Step 1: Pad k and v along the sequence dimension by w on each side\n # F.pad args go from last dim to first: (d_left, d_right, seq_left, seq_right)\n k_pad = F.pad(k, (0, 0, w, w)) # (batch, seq_len + 2w, d)\n v_pad = F.pad(v, (0, 0, w, w)) # (batch, seq_len + 2w, d)\n\n # Step 2: Extract sliding windows with unfold\n # unfold(1, win, 1) โ†’ (batch, seq_len, d, win)\n k_windows = k_pad.unfold(1, win, 1).permute(0, 1, 3, 2) # (batch, seq_len, win, d)\n v_windows = v_pad.unfold(1, win, 1).permute(0, 1, 3, 2) # (batch, seq_len, win, d)\n\n # Step 3: Compute attention scores\n # q: (batch, seq_len, 1, d) @ k_windows^T: (batch, seq_len, d, win) โ†’ (batch, seq_len, 1, win)\n scores = (q.unsqueeze(2) @ k_windows.transpose(-2, -1)) / math.sqrt(d)\n\n # Step 4: Mask out padded positions\n # Build a validity mask by padding ones and unfolding the same way\n valid = F.pad(torch.ones(1, seq_len, 1), (0, 0, w, w)) # (1, seq_len+2w, 1)\n valid_windows = valid.unfold(1, win, 1).permute(0, 1, 3, 2) # (1, seq_len, win, 1)\n # Transpose to match scores shape: (1, seq_len, 1, win)\n pad_mask = valid_windows.squeeze(-1).unsqueeze(2) # (1, seq_len, 1, win)\n scores = scores.masked_fill(pad_mask == 0, float('-inf'))\n\n # Step 5: Softmax over window dimension and weighted sum\n weights = F.softmax(scores, dim=-1) # (batch, seq_len, 1, win)\n out = (weights @ v_windows).squeeze(2) # (batch, seq_len, d)\n return out\n\n\n# Quick shape check\nout_unfold = sliding_window_attention_unfold(q, k, v, window_size)\nprint(f\"Output shape: {out_unfold.shape}\") # (2, 16, 32)", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "8d16gi2t6g", + "source": "# Bonus Validation\n\n# Test 1: Must match mask-based implementation\nprint(\"=== Unfold vs Mask-Based ===\")\nout_mask = sliding_window_attention(q, k, v, window_size)\nout_unfold = sliding_window_attention_unfold(q, k, v, window_size)\nassert torch.allclose(out_mask, out_unfold, atol=1e-5), \\\n f\"Outputs differ! Max diff: {(out_mask - out_unfold).abs().max():.2e}\"\nprint(\"PASSED: unfold version matches mask-based version.\\n\")\n\n# Test 2: Full window matches full attention\nprint(\"=== Unfold Full Window = Full Attention ===\")\nout_full = full_attention(q, k, v)\nout_unfold_full = sliding_window_attention_unfold(q, k, v, window_size=seq_len)\nassert torch.allclose(out_full, out_unfold_full, atol=1e-5), \"Full window should match full attention!\"\nprint(\"PASSED: window_size=seq_len matches full attention.\\n\")\n\n# Test 3: Memory comparison\nprint(\"=== Score Entries Computed ===\")\nfor n in [128, 512, 2048, 8192]:\n w = 64\n full_scores = n * n\n unfold_scores = n * (2 * w + 1)\n ratio = unfold_scores / full_scores * 100\n print(f\" seq_len={n:5d}, window={w}: unfold={unfold_scores:>10,} vs full={full_scores:>12,} ({ratio:.1f}%)\")\nprint(\"PASSED: unfold computes far fewer score entries.\\n\")\n\nprint(\"All bonus tests passed!\")", + "metadata": {}, + "execution_count": null, + "outputs": [] } ], "metadata": { @@ -225,4 +247,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From c2c79e69bad76dd2b98d94874b40e97b587ceb4a Mon Sep 17 00:00:00 2001 From: Mathieu Charbonnel Date: Wed, 14 Oct 2026 22:39:23 +0200 Subject: [PATCH 3/5] Add 4 data loading exercises MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Preloaded Dataset (easy) โ€” map-style Dataset with all data in memory, DataLoader batching/shuffling, multi-worker loading 2. Streaming Dataset (medium) โ€” IterableDataset with yield, line-by-line file reading, multi-worker sharding via get_worker_info() 3. Buffered Loading (medium) โ€” shuffle buffer wrapping an IterableDataset, O(buffer_size) memory, approximate shuffling 4. Data Parallel Loading (medium) โ€” DistributedSampler from scratch, rank sharding, deterministic seeded shuffling, padding Each exercise includes question notebook with TODOs, solution notebook, and problem.toml manifest. --- .../buffered-loading/buffered-loading.ipynb | 47 +++++++++++++++++++ .../buffered-loading_SOLN.ipynb | 39 +++++++++++++++ v3/data-loading/buffered-loading/problem.toml | 17 +++++++ .../data-parallel-loading.ipynb | 47 +++++++++++++++++++ .../data-parallel-loading_SOLN.ipynb | 39 +++++++++++++++ .../data-parallel-loading/problem.toml | 18 +++++++ .../preloaded-dataset/preloaded-dataset.ipynb | 47 +++++++++++++++++++ .../preloaded-dataset_SOLN.ipynb | 39 +++++++++++++++ .../preloaded-dataset/problem.toml | 17 +++++++ .../streaming-dataset/problem.toml | 17 +++++++ .../streaming-dataset/streaming-dataset.ipynb | 47 +++++++++++++++++++ .../streaming-dataset_SOLN.ipynb | 39 +++++++++++++++ 12 files changed, 413 insertions(+) create mode 100644 v3/data-loading/buffered-loading/buffered-loading.ipynb create mode 100644 v3/data-loading/buffered-loading/buffered-loading_SOLN.ipynb create mode 100644 v3/data-loading/buffered-loading/problem.toml create mode 100644 v3/data-loading/data-parallel-loading/data-parallel-loading.ipynb create mode 100644 v3/data-loading/data-parallel-loading/data-parallel-loading_SOLN.ipynb create mode 100644 v3/data-loading/data-parallel-loading/problem.toml create mode 100644 v3/data-loading/preloaded-dataset/preloaded-dataset.ipynb create mode 100644 v3/data-loading/preloaded-dataset/preloaded-dataset_SOLN.ipynb create mode 100644 v3/data-loading/preloaded-dataset/problem.toml create mode 100644 v3/data-loading/streaming-dataset/problem.toml create mode 100644 v3/data-loading/streaming-dataset/streaming-dataset.ipynb create mode 100644 v3/data-loading/streaming-dataset/streaming-dataset_SOLN.ipynb diff --git a/v3/data-loading/buffered-loading/buffered-loading.ipynb b/v3/data-loading/buffered-loading/buffered-loading.ipynb new file mode 100644 index 00000000..18e217cf --- /dev/null +++ b/v3/data-loading/buffered-loading/buffered-loading.ipynb @@ -0,0 +1,47 @@ +{ + "nbformat": 4, + "nbformat_minor": 5, + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3.10.0" + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "# Buffered Loading with Shuffle Buffer\n\n**Difficulty**: ๐ŸŸก Medium\n\n---\n\n### Problem Statement\n\n`IterableDataset` streams data sequentially, which means samples arrive in file order โ€” **no shuffling**. `DataLoader(shuffle=True)` only works with map-style datasets.\n\nThe standard solution is a **shuffle buffer**: accumulate `B` samples in a buffer, then yield one at random from the buffer, replacing it with the next incoming sample. This gives approximate shuffling with O(B) memory, regardless of dataset size. This is exactly how TensorFlow's `tf.data.Dataset.shuffle(buffer_size)` works, and how HuggingFace `datasets` streams shuffled data.\n\nYour task is to implement a shuffle buffer on top of a streaming dataset.\n\n---\n\n### Requirements\n\n1. **`ShuffleBufferDataset(base_dataset, buffer_size)`** โ€” An `IterableDataset` that:\n - Wraps another `IterableDataset`.\n - Fills a buffer of `buffer_size` samples from the base iterator.\n - On each `yield`: picks a random index in the buffer, yields that sample, and replaces it with the next sample from the base iterator.\n - When the base iterator is exhausted, drains the remaining buffer in random order.\n\n2. **Verify approximate shuffling** โ€” Show that the output order differs from the input order.\n\n3. **Verify completeness** โ€” All samples from the base dataset must appear exactly once.\n\n---\n\n### Constraints\n\n- โœ… Memory usage must be O(buffer_size), not O(N).\n- โœ… Every sample from the base dataset must be yielded exactly once.\n- โœ… Must work with `DataLoader` batching.\n- โœ… Larger buffer โ†’ better shuffling (buffer_size=N is equivalent to full shuffle).\n\n---\n\n
\n ๐Ÿ’ก Hint\n\n - Initialize the buffer by pulling `buffer_size` items from the base iterator using `next()` in a loop.\n - Use `random.randint(0, len(buffer)-1)` to pick the index to yield.\n - Swap the yielded item with the next item from the base iterator. When the base iterator raises `StopIteration`, start draining.\n - To drain: shuffle the remaining buffer and yield everything.\n\n
\n\n---", + "id": "cell-0" + }, + { + "cell_type": "code", + "id": "ji6ldb46wa", + "source": "import torch\nimport random\nfrom torch.utils.data import IterableDataset, DataLoader\n\n# A simple sequential IterableDataset to wrap\nclass SequentialDataset(IterableDataset):\n \"\"\"Yields (index_tensor, value_tensor) pairs in order 0..N-1.\"\"\"\n def __init__(self, N: int):\n self.N = N\n def __iter__(self):\n for i in range(self.N):\n yield torch.tensor(i, dtype=torch.long), torch.tensor(float(i))\n\n# Test it\nseq_ds = SequentialDataset(20)\nprint(\"Sequential order:\", [idx.item() for idx, _ in seq_ds])", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "b1ha9znbzws", + "source": "class ShuffleBufferDataset(IterableDataset):\n \"\"\"Wraps an IterableDataset and shuffles its output via a fixed-size buffer.\"\"\"\n\n def __init__(self, base_dataset: IterableDataset, buffer_size: int):\n super().__init__()\n self.base_dataset = base_dataset\n self.buffer_size = buffer_size\n\n def __iter__(self):\n # TODO: Get an iterator from the base dataset\n\n # TODO: Fill the buffer with buffer_size samples from the iterator\n\n # TODO: While the base iterator has more samples:\n # - Pick a random index in the buffer\n # - Yield the sample at that index\n # - Replace it with the next sample from the iterator\n\n # TODO: Drain the remaining buffer in random order\n\n ...", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "wo3ec360ozo", + "source": "# === Tests ===\n\nN = 500\n\n# Test 1: All samples present, no duplicates\nshuffled_ds = ShuffleBufferDataset(SequentialDataset(N), buffer_size=50)\nindices = sorted([idx.item() for idx, _ in shuffled_ds])\nassert indices == list(range(N)), \"Not all samples yielded or duplicates detected\"\nprint(f\"PASSED: All {N} samples present, no duplicates\")\n\n# Test 2: Order is shuffled (not sequential)\nshuffled_ds2 = ShuffleBufferDataset(SequentialDataset(N), buffer_size=50)\norder = [idx.item() for idx, _ in shuffled_ds2]\nassert order != list(range(N)), \"Output is still in sequential order โ€” not shuffled\"\nprint(\"PASSED: Output order is shuffled\")\n\n# Test 3: Works with DataLoader\nshuffled_ds3 = ShuffleBufferDataset(SequentialDataset(N), buffer_size=100)\nloader = DataLoader(shuffled_ds3, batch_size=32)\ntotal = sum(bi.shape[0] for bi, _ in loader)\nassert total == N, f\"DataLoader yielded {total} samples, expected {N}\"\nprint(\"PASSED: Works with DataLoader batching\")\n\n# Test 4: Larger buffer โ†’ more shuffling\n# Measure how far each element moved from its original position\ndef avg_displacement(ds):\n order = [idx.item() for idx, _ in ds]\n return sum(abs(i - order[i]) for i in range(len(order))) / len(order)\n\ndisp_small = avg_displacement(ShuffleBufferDataset(SequentialDataset(N), buffer_size=10))\ndisp_large = avg_displacement(ShuffleBufferDataset(SequentialDataset(N), buffer_size=200))\nprint(f\"Avg displacement: buffer=10 โ†’ {disp_small:.1f}, buffer=200 โ†’ {disp_large:.1f}\")\nassert disp_large > disp_small, \"Larger buffer should give more shuffling\"\nprint(\"PASSED: Larger buffer produces more shuffling\")\n\nprint(\"\\nAll tests passed!\")", + "metadata": {}, + "execution_count": null, + "outputs": [] + } + ] +} \ No newline at end of file diff --git a/v3/data-loading/buffered-loading/buffered-loading_SOLN.ipynb b/v3/data-loading/buffered-loading/buffered-loading_SOLN.ipynb new file mode 100644 index 00000000..18c72765 --- /dev/null +++ b/v3/data-loading/buffered-loading/buffered-loading_SOLN.ipynb @@ -0,0 +1,39 @@ +{ + "nbformat": 4, + "nbformat_minor": 5, + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3.10.0" + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "# Buffered Loading with Shuffle Buffer โ€” Solution", + "id": "cell-0" + }, + { + "cell_type": "code", + "id": "njev7ukjwm", + "source": "import torch\nimport random\nfrom torch.utils.data import IterableDataset, DataLoader\n\nclass SequentialDataset(IterableDataset):\n def __init__(self, N):\n self.N = N\n def __iter__(self):\n for i in range(self.N):\n yield torch.tensor(i, dtype=torch.long), torch.tensor(float(i))", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "3c31pq18wql", + "source": "class ShuffleBufferDataset(IterableDataset):\n \"\"\"Wraps an IterableDataset and shuffles its output via a fixed-size buffer.\"\"\"\n\n def __init__(self, base_dataset: IterableDataset, buffer_size: int):\n super().__init__()\n self.base_dataset = base_dataset\n self.buffer_size = buffer_size\n\n def __iter__(self):\n it = iter(self.base_dataset)\n\n # Fill the buffer\n buffer = []\n for _ in range(self.buffer_size):\n try:\n buffer.append(next(it))\n except StopIteration:\n break\n\n # Yield random elements, replacing with new ones from the iterator\n for item in it:\n idx = random.randint(0, len(buffer) - 1)\n yield buffer[idx]\n buffer[idx] = item\n\n # Drain the remaining buffer in random order\n random.shuffle(buffer)\n for item in buffer:\n yield item\n\n\n# Demo\nshuffled = ShuffleBufferDataset(SequentialDataset(20), buffer_size=5)\nprint(\"Shuffled order:\", [idx.item() for idx, _ in shuffled])", + "metadata": {}, + "execution_count": null, + "outputs": [] + } + ] +} \ No newline at end of file diff --git a/v3/data-loading/buffered-loading/problem.toml b/v3/data-loading/buffered-loading/problem.toml new file mode 100644 index 00000000..ffaa1ac8 --- /dev/null +++ b/v3/data-loading/buffered-loading/problem.toml @@ -0,0 +1,17 @@ +id = "buffered-loading" +title = "Implement a Shuffle Buffer for Streaming Data" +description = "Build a shuffle buffer that wraps an IterableDataset, providing approximate shuffling with O(buffer_size) memory." +difficulty = "medium" +frequency = "emerging" +category = "data-loading" +tracks = ["basics"] + +[notebooks] +question = "buffered-loading.ipynb" +solution = "buffered-loading_SOLN.ipynb" + +[grading] +tier = "C" +entries = [] +extras = [] +device = "cpu" diff --git a/v3/data-loading/data-parallel-loading/data-parallel-loading.ipynb b/v3/data-loading/data-parallel-loading/data-parallel-loading.ipynb new file mode 100644 index 00000000..71b628c6 --- /dev/null +++ b/v3/data-loading/data-parallel-loading/data-parallel-loading.ipynb @@ -0,0 +1,47 @@ +{ + "nbformat": 4, + "nbformat_minor": 5, + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3.10.0" + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "# Data Parallel Loading: Simulating DistributedSampler\n\n**Difficulty**: ๐ŸŸก Medium\n\n**Companies**: Meta, Google, NVIDIA, Anthropic\n\n---\n\n### Problem Statement\n\nIn distributed data-parallel training, each GPU (rank) must process a **disjoint shard** of the dataset. PyTorch's `DistributedSampler` handles this: it assigns indices to ranks so that (1) every sample is seen exactly once across all ranks per epoch, and (2) each rank gets the same number of samples (padding if needed).\n\nYour task is to implement a simplified `DistributedSampler` from scratch โ€” without `torch.distributed` โ€” to understand the sharding and shuffling logic.\n\n---\n\n### Requirements\n\n1. **`SimpleDistributedSampler(dataset, num_replicas, rank, shuffle, seed)`**:\n - `num_replicas`: total number of ranks (GPUs).\n - `rank`: this rank's index (0-based).\n - If the dataset size is not divisible by `num_replicas`, **pad** by repeating samples from the start so every rank gets the same count.\n - If `shuffle=True`, shuffle indices deterministically using the `seed + epoch` (call `set_epoch(epoch)` to change the epoch).\n - Implement `__iter__` and `__len__`.\n\n2. **Verify sharding** โ€” The union of indices from all ranks must equal the full dataset (with padding if needed). No rank should share indices with another.\n\n3. **Verify shuffle reproducibility** โ€” Same `seed + epoch` must give the same order. Different epochs must give different orders.\n\n---\n\n### Constraints\n\n- โœ… Must work as a `sampler` argument to `DataLoader`.\n- โœ… Every rank must get exactly `ceil(len(dataset) / num_replicas)` indices.\n- โœ… Shuffling must be deterministic given seed + epoch.\n- โŒ Do **not** use `torch.utils.data.distributed.DistributedSampler`.\n\n---\n\n
\n ๐Ÿ’ก Hint\n\n - Total padded size: `ceil(len(dataset) / num_replicas) * num_replicas`.\n - Pad by extending the index list with indices from the start: `indices += indices[:padding]`.\n - To shard: `indices[rank::num_replicas]` โ€” every rank takes every `num_replicas`-th index.\n - For deterministic shuffle: create a `torch.Generator` with `manual_seed(seed + epoch)` and use `torch.randperm`.\n\n
\n\n---", + "id": "cell-0" + }, + { + "cell_type": "code", + "id": "eb4la5own1d", + "source": "import math\nimport torch\nfrom torch.utils.data import Dataset, DataLoader, Sampler\n\n# Reuse a simple map-style dataset\nclass SimpleDataset(Dataset):\n def __init__(self, N):\n self.data = torch.arange(N, dtype=torch.float32)\n def __len__(self):\n return len(self.data)\n def __getitem__(self, idx):\n return self.data[idx]\n\nds = SimpleDataset(103) # intentionally not divisible by common GPU counts\nprint(f\"Dataset size: {len(ds)}\")", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "66808e10u9n", + "source": "class SimpleDistributedSampler(Sampler):\n \"\"\"Simplified DistributedSampler: shards a dataset across ranks.\"\"\"\n\n def __init__(self, dataset, num_replicas: int, rank: int,\n shuffle: bool = True, seed: int = 0):\n self.dataset = dataset\n self.num_replicas = num_replicas\n self.rank = rank\n self.shuffle = shuffle\n self.seed = seed\n self.epoch = 0\n # TODO: Compute num_samples (per rank) and total_size (padded)\n ...\n\n def set_epoch(self, epoch: int):\n \"\"\"Set the epoch for deterministic shuffling.\"\"\"\n self.epoch = epoch\n\n def __len__(self):\n # TODO: Return the number of samples this rank will yield\n ...\n\n def __iter__(self):\n # TODO: Build the full index list [0, 1, ..., len(dataset)-1]\n # TODO: If shuffle, use a seeded generator to permute indices\n # TODO: Pad indices to total_size by repeating from the start\n # TODO: Shard: take every num_replicas-th index starting at self.rank\n # TODO: Yield each index\n ...", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "homm2nu6vlk", + "source": "# === Tests ===\nnum_replicas = 4\n\n# Test 1: All ranks get the same number of samples\nsamplers = [SimpleDistributedSampler(ds, num_replicas=num_replicas, rank=r, shuffle=False)\n for r in range(num_replicas)]\nlengths = [len(s) for s in samplers]\nassert len(set(lengths)) == 1, f\"Ranks got different lengths: {lengths}\"\nexpected_per_rank = math.ceil(len(ds) / num_replicas)\nassert lengths[0] == expected_per_rank, \\\n f\"Expected {expected_per_rank} per rank, got {lengths[0]}\"\nprint(f\"PASSED: All {num_replicas} ranks get {lengths[0]} samples each\")\n\n# Test 2: No overlap between ranks (disjoint shards)\nall_indices = []\nfor s in samplers:\n indices = list(s)\n all_indices.append(indices)\nflat = [i for shard in all_indices for i in shard]\nassert len(flat) == expected_per_rank * num_replicas, \"Total indices count is wrong\"\n# Every real index should appear at least once\nreal_indices = set(range(len(ds)))\nassert real_indices.issubset(set(flat)), \"Some dataset indices are missing\"\nprint(\"PASSED: Shards are disjoint and cover the full dataset\")\n\n# Test 3: Works as DataLoader sampler\nsampler_r0 = SimpleDistributedSampler(ds, num_replicas=num_replicas, rank=0, shuffle=False)\nloader = DataLoader(ds, batch_size=8, sampler=sampler_r0)\nloaded = torch.cat([b for b in loader])\nassert len(loaded) == expected_per_rank, f\"DataLoader yielded {len(loaded)}, expected {expected_per_rank}\"\nprint(\"PASSED: Works with DataLoader\")\n\n# Test 4: Deterministic shuffling โ€” same seed+epoch โ†’ same order\ns1 = SimpleDistributedSampler(ds, num_replicas=num_replicas, rank=0, shuffle=True, seed=42)\ns2 = SimpleDistributedSampler(ds, num_replicas=num_replicas, rank=0, shuffle=True, seed=42)\nassert list(s1) == list(s2), \"Same seed should give same order\"\nprint(\"PASSED: Deterministic shuffle with same seed\")\n\n# Test 5: Different epochs โ†’ different order\ns3 = SimpleDistributedSampler(ds, num_replicas=num_replicas, rank=0, shuffle=True, seed=42)\ns3.set_epoch(1)\ns4 = SimpleDistributedSampler(ds, num_replicas=num_replicas, rank=0, shuffle=True, seed=42)\ns4.set_epoch(2)\nassert list(s3) != list(s4), \"Different epochs should give different orders\"\nprint(\"PASSED: Different epochs produce different shuffles\")\n\nprint(\"\\nAll tests passed!\")", + "metadata": {}, + "execution_count": null, + "outputs": [] + } + ] +} \ No newline at end of file diff --git a/v3/data-loading/data-parallel-loading/data-parallel-loading_SOLN.ipynb b/v3/data-loading/data-parallel-loading/data-parallel-loading_SOLN.ipynb new file mode 100644 index 00000000..0380f9f5 --- /dev/null +++ b/v3/data-loading/data-parallel-loading/data-parallel-loading_SOLN.ipynb @@ -0,0 +1,39 @@ +{ + "nbformat": 4, + "nbformat_minor": 5, + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3.10.0" + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "# Data Parallel Loading: Simulating DistributedSampler โ€” Solution", + "id": "cell-0" + }, + { + "cell_type": "code", + "id": "nb862hca4cn", + "source": "import math\nimport torch\nfrom torch.utils.data import Dataset, DataLoader, Sampler\n\nclass SimpleDataset(Dataset):\n def __init__(self, N):\n self.data = torch.arange(N, dtype=torch.float32)\n def __len__(self):\n return len(self.data)\n def __getitem__(self, idx):\n return self.data[idx]\n\nds = SimpleDataset(103)", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "czhqho55r8b", + "source": "class SimpleDistributedSampler(Sampler):\n \"\"\"Simplified DistributedSampler: shards a dataset across ranks.\"\"\"\n\n def __init__(self, dataset, num_replicas: int, rank: int,\n shuffle: bool = True, seed: int = 0):\n self.dataset = dataset\n self.num_replicas = num_replicas\n self.rank = rank\n self.shuffle = shuffle\n self.seed = seed\n self.epoch = 0\n self.num_samples = math.ceil(len(dataset) / num_replicas)\n self.total_size = self.num_samples * num_replicas\n\n def set_epoch(self, epoch: int):\n self.epoch = epoch\n\n def __len__(self):\n return self.num_samples\n\n def __iter__(self):\n if self.shuffle:\n g = torch.Generator()\n g.manual_seed(self.seed + self.epoch)\n indices = torch.randperm(len(self.dataset), generator=g).tolist()\n else:\n indices = list(range(len(self.dataset)))\n\n # Pad to total_size by repeating from the start\n padding = self.total_size - len(indices)\n indices += indices[:padding]\n\n # Shard: this rank takes every num_replicas-th index\n indices = indices[self.rank::self.num_replicas]\n assert len(indices) == self.num_samples\n return iter(indices)\n\n\n# Demo: show how indices are split across 4 ranks\nfor r in range(4):\n s = SimpleDistributedSampler(ds, num_replicas=4, rank=r, shuffle=False)\n idx = list(s)\n print(f\"Rank {r}: {len(idx)} samples, first 5: {idx[:5]}, last 5: {idx[-5:]}\")", + "metadata": {}, + "execution_count": null, + "outputs": [] + } + ] +} \ No newline at end of file diff --git a/v3/data-loading/data-parallel-loading/problem.toml b/v3/data-loading/data-parallel-loading/problem.toml new file mode 100644 index 00000000..21eed0ac --- /dev/null +++ b/v3/data-loading/data-parallel-loading/problem.toml @@ -0,0 +1,18 @@ +id = "data-parallel-loading" +title = "Simulate DistributedSampler for Data Parallel Training" +description = "Implement a distributed sampler from scratch that shards a dataset across ranks with deterministic shuffling and padding." +difficulty = "medium" +frequency = "common" +category = "data-loading" +tracks = ["basics"] +companies = ["Meta", "Google", "NVIDIA", "Anthropic"] + +[notebooks] +question = "data-parallel-loading.ipynb" +solution = "data-parallel-loading_SOLN.ipynb" + +[grading] +tier = "C" +entries = [] +extras = [] +device = "cpu" diff --git a/v3/data-loading/preloaded-dataset/preloaded-dataset.ipynb b/v3/data-loading/preloaded-dataset/preloaded-dataset.ipynb new file mode 100644 index 00000000..7057a824 --- /dev/null +++ b/v3/data-loading/preloaded-dataset/preloaded-dataset.ipynb @@ -0,0 +1,47 @@ +{ + "nbformat": 4, + "nbformat_minor": 5, + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3.10.0" + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "# Preloaded Map-Style Dataset\n\n**Difficulty**: ๐ŸŸข Easy\n\n---\n\n### Problem Statement\n\nThe most common pattern in PyTorch data loading is a **map-style dataset**: all data lives in memory (or is indexed on disk), and `__getitem__(i)` returns the i-th sample. Combined with `DataLoader`, this gives you batching, shuffling, and multi-worker prefetching for free.\n\nYour task is to implement a map-style `Dataset` that loads a synthetic dataset **entirely into memory** as tensors, and verify that `DataLoader` correctly batches and shuffles it.\n\n---\n\n### Requirements\n\n1. **`PreloadedDataset(X, y)`** โ€” A `torch.utils.data.Dataset` subclass:\n - Stores `X` and `y` as tensors in `__init__`.\n - `__len__` returns the number of samples.\n - `__getitem__(idx)` returns `(X[idx], y[idx])`.\n\n2. **DataLoader integration**:\n - Wrap the dataset in a `DataLoader` with `batch_size=16` and `shuffle=True`.\n - Iterate one full epoch and verify every sample is seen exactly once.\n\n3. **Multi-worker loading**:\n - Use `num_workers=2` and confirm the output is identical in content (though order may differ when shuffled).\n\n---\n\n### Constraints\n\n- โœ… Data must be stored as `torch.Tensor`, not numpy arrays or lists.\n- โœ… `__getitem__` must return a tuple `(x_i, y_i)`, not a dict.\n- โœ… Must work with `DataLoader`'s batching (automatic collation).\n\n---\n\n
\n ๐Ÿ’ก Hint\n\n - Convert data to tensors in `__init__` with `torch.tensor()` or `torch.as_tensor()`.\n - `DataLoader` calls `__getitem__` for each index in the batch, then stacks the results automatically.\n - To verify all samples are seen, collect all indices or values across batches and check the count.\n\n
\n\n---", + "id": "cell-0" + }, + { + "cell_type": "code", + "id": "uokqo8vr75b", + "source": "import torch\nfrom torch.utils.data import Dataset, DataLoader\n\n# Synthetic data: 1000 samples, 10 features, regression target\ntorch.manual_seed(42)\nN, D = 1000, 10\nX_data = torch.randn(N, D)\ny_data = X_data @ torch.randn(D) + 0.1 * torch.randn(N)\n\nprint(f\"X shape: {X_data.shape}, y shape: {y_data.shape}\")", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "haluqxm38qs", + "source": "class PreloadedDataset(Dataset):\n \"\"\"Map-style dataset that holds all data in memory as tensors.\"\"\"\n\n def __init__(self, X: torch.Tensor, y: torch.Tensor):\n # TODO: Store X and y as tensors\n ...\n\n def __len__(self):\n # TODO: Return the number of samples\n ...\n\n def __getitem__(self, idx):\n # TODO: Return the (X[idx], y[idx]) pair\n ...", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "jnfi8r62m1e", + "source": "# === Tests ===\n\n# Test 1: Basic dataset properties\nds = PreloadedDataset(X_data, y_data)\nassert len(ds) == N, f\"Expected length {N}, got {len(ds)}\"\nx_i, y_i = ds[0]\nassert x_i.shape == (D,), f\"Expected feature shape ({D},), got {x_i.shape}\"\nassert y_i.shape == (), f\"Expected scalar target, got shape {y_i.shape}\"\nprint(\"PASSED: Dataset has correct length and item shapes\")\n\n# Test 2: DataLoader batching\nloader = DataLoader(ds, batch_size=16, shuffle=False)\nbatch_x, batch_y = next(iter(loader))\nassert batch_x.shape == (16, D), f\"Batch X shape wrong: {batch_x.shape}\"\nassert batch_y.shape == (16,), f\"Batch y shape wrong: {batch_y.shape}\"\nprint(\"PASSED: DataLoader produces correct batch shapes\")\n\n# Test 3: Full epoch โ€” every sample seen exactly once\nloader_shuffled = DataLoader(ds, batch_size=16, shuffle=True)\nall_y = []\nfor bx, by in loader_shuffled:\n all_y.append(by)\nall_y = torch.cat(all_y)\nassert len(all_y) == N, f\"Expected {N} samples in one epoch, got {len(all_y)}\"\nassert torch.allclose(all_y.sort().values, y_data.sort().values), \\\n \"Not all samples were seen โ€” values don't match after sorting\"\nprint(\"PASSED: Full epoch sees every sample exactly once\")\n\n# Test 4: Multi-worker loading\nloader_workers = DataLoader(ds, batch_size=32, shuffle=False, num_workers=2)\nall_y_w = torch.cat([by for _, by in loader_workers])\nassert torch.allclose(all_y_w.sort().values, y_data.sort().values), \\\n \"Multi-worker loading lost or duplicated samples\"\nprint(\"PASSED: num_workers=2 produces correct results\")\n\nprint(\"\\nAll tests passed!\")", + "metadata": {}, + "execution_count": null, + "outputs": [] + } + ] +} \ No newline at end of file diff --git a/v3/data-loading/preloaded-dataset/preloaded-dataset_SOLN.ipynb b/v3/data-loading/preloaded-dataset/preloaded-dataset_SOLN.ipynb new file mode 100644 index 00000000..6f5518d4 --- /dev/null +++ b/v3/data-loading/preloaded-dataset/preloaded-dataset_SOLN.ipynb @@ -0,0 +1,39 @@ +{ + "nbformat": 4, + "nbformat_minor": 5, + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3.10.0" + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "# Preloaded Map-Style Dataset โ€” Solution", + "id": "cell-0" + }, + { + "cell_type": "code", + "id": "71s80o06aya", + "source": "import torch\nfrom torch.utils.data import Dataset, DataLoader\n\ntorch.manual_seed(42)\nN, D = 1000, 10\nX_data = torch.randn(N, D)\ny_data = X_data @ torch.randn(D) + 0.1 * torch.randn(N)", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "mzr5pkucsqo", + "source": "class PreloadedDataset(Dataset):\n \"\"\"Map-style dataset that holds all data in memory as tensors.\"\"\"\n\n def __init__(self, X: torch.Tensor, y: torch.Tensor):\n self.X = X\n self.y = y\n\n def __len__(self):\n return len(self.X)\n\n def __getitem__(self, idx):\n return self.X[idx], self.y[idx]\n\n\nds = PreloadedDataset(X_data, y_data)\nloader = DataLoader(ds, batch_size=16, shuffle=True)\n\nfor batch_x, batch_y in loader:\n print(f\"Batch: X={batch_x.shape}, y={batch_y.shape}\")\n break", + "metadata": {}, + "execution_count": null, + "outputs": [] + } + ] +} \ No newline at end of file diff --git a/v3/data-loading/preloaded-dataset/problem.toml b/v3/data-loading/preloaded-dataset/problem.toml new file mode 100644 index 00000000..6c85ed22 --- /dev/null +++ b/v3/data-loading/preloaded-dataset/problem.toml @@ -0,0 +1,17 @@ +id = "preloaded-dataset" +title = "Implement a Preloaded Map-Style Dataset" +description = "Build a map-style Dataset that loads all data into memory and integrates with DataLoader for batching and shuffling." +difficulty = "easy" +frequency = "common" +category = "data-loading" +tracks = ["basics"] + +[notebooks] +question = "preloaded-dataset.ipynb" +solution = "preloaded-dataset_SOLN.ipynb" + +[grading] +tier = "C" +entries = [] +extras = [] +device = "cpu" diff --git a/v3/data-loading/streaming-dataset/problem.toml b/v3/data-loading/streaming-dataset/problem.toml new file mode 100644 index 00000000..e2f40f84 --- /dev/null +++ b/v3/data-loading/streaming-dataset/problem.toml @@ -0,0 +1,17 @@ +id = "streaming-dataset" +title = "Implement a Streaming IterableDataset with Yield" +description = "Build an IterableDataset that streams data line by line from a file using a generator, with multi-worker sharding support." +difficulty = "medium" +frequency = "common" +category = "data-loading" +tracks = ["basics"] + +[notebooks] +question = "streaming-dataset.ipynb" +solution = "streaming-dataset_SOLN.ipynb" + +[grading] +tier = "C" +entries = [] +extras = [] +device = "cpu" diff --git a/v3/data-loading/streaming-dataset/streaming-dataset.ipynb b/v3/data-loading/streaming-dataset/streaming-dataset.ipynb new file mode 100644 index 00000000..525a5c96 --- /dev/null +++ b/v3/data-loading/streaming-dataset/streaming-dataset.ipynb @@ -0,0 +1,47 @@ +{ + "nbformat": 4, + "nbformat_minor": 5, + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3.10.0" + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "# Streaming Dataset with IterableDataset\n\n**Difficulty**: ๐ŸŸก Medium\n\n---\n\n### Problem Statement\n\nWhen data is too large to fit in memory, or arrives as a stream (log files, network sockets, database cursors), you can't use a map-style dataset with random `__getitem__` access. PyTorch's `IterableDataset` solves this: you implement `__iter__` as a Python **generator** that `yield`s one sample at a time.\n\nYour task is to implement a streaming dataset that reads a large file **line by line** without loading it all into memory.\n\n---\n\n### Requirements\n\n1. **`StreamingDataset(filepath)`** โ€” A `torch.utils.data.IterableDataset` subclass:\n - `__iter__` opens the file and yields `(x, y)` tensor pairs one line at a time.\n - Must **not** read the entire file into memory.\n\n2. **Multi-worker correctness**:\n - When `DataLoader` uses `num_workers > 1`, each worker gets its own copy of the iterator. Without handling this, every worker yields the **entire** file (duplicated data!).\n - Implement worker-aware splitting using `torch.utils.data.get_worker_info()` so each worker processes a disjoint shard.\n\n3. **Generate test data** โ€” Create a CSV with 10,000 rows to test against.\n\n---\n\n### Constraints\n\n- โœ… Memory usage must be O(1) per sample, not O(N).\n- โœ… With `num_workers=0` (main process), all samples must be yielded.\n- โœ… With `num_workers=K`, the union of all workers' samples must cover the full dataset with no duplicates.\n- โŒ Do **not** use `pandas.read_csv()` or load the whole file at once.\n\n---\n\n
\n ๐Ÿ’ก Hint\n\n - Use `open(filepath)` and iterate line by line โ€” Python file objects are lazy iterators.\n - `get_worker_info()` returns `None` in the main process, or a `WorkerInfo` with `.id` and `.num_workers`.\n - To shard: use `enumerate()` on lines, and each worker only yields lines where `line_idx % num_workers == worker_id`.\n - `DataLoader` with an `IterableDataset` ignores `shuffle=True` โ€” shuffling must be done differently (e.g., a shuffle buffer, covered in the next exercise).\n\n
\n\n---", + "id": "cell-0" + }, + { + "cell_type": "code", + "id": "3axncpuvjd3", + "source": "import torch\nfrom torch.utils.data import IterableDataset, DataLoader, get_worker_info\nimport os\n\n# Generate synthetic CSV: 10,000 rows, 5 features + 1 target\ntorch.manual_seed(42)\nN, D = 10_000, 5\nX = torch.randn(N, D)\ny = X @ torch.randn(D) + 0.1 * torch.randn(N)\n\ndata_path = \"/tmp/streaming_test_data.csv\"\nwith open(data_path, \"w\") as f:\n for i in range(N):\n row = \",\".join(f\"{v:.6f}\" for v in X[i].tolist()) + f\",{y[i]:.6f}\\n\"\n f.write(row)\n\nprint(f\"Wrote {N} rows to {data_path}\")\nprint(f\"File size: {os.path.getsize(data_path) / 1024:.1f} KB\")", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "ft0ew8926pv", + "source": "class StreamingDataset(IterableDataset):\n \"\"\"Streams (x, y) pairs from a CSV file, one line at a time.\"\"\"\n\n def __init__(self, filepath: str):\n super().__init__()\n self.filepath = filepath\n\n def __iter__(self):\n # TODO: Get worker info for multi-worker sharding\n # worker_info = get_worker_info()\n # If None โ†’ single process, yield everything\n # Otherwise โ†’ only yield lines where line_idx % num_workers == worker_id\n\n # TODO: Open file and iterate line by line\n # For each line: parse comma-separated floats, split into x (all but last) and y (last)\n # Yield (x_tensor, y_tensor)\n ...", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "gw4cs9hw8h", + "source": "# === Tests ===\n\n# Test 1: Single-process iteration yields all samples\nds = StreamingDataset(data_path)\nloader = DataLoader(ds, batch_size=64)\ntotal = sum(by.shape[0] for _, by in loader)\nassert total == N, f\"Expected {N} samples, got {total}\"\nprint(f\"PASSED: Single-process yields all {N} samples\")\n\n# Test 2: Correct shapes\nds2 = StreamingDataset(data_path)\nloader2 = DataLoader(ds2, batch_size=32)\nbx, by = next(iter(loader2))\nassert bx.shape == (32, D), f\"Expected X shape (32, {D}), got {bx.shape}\"\nassert by.shape == (32,), f\"Expected y shape (32,), got {by.shape}\"\nprint(\"PASSED: Correct batch shapes\")\n\n# Test 3: Multi-worker yields all samples without duplicates\nds3 = StreamingDataset(data_path)\nloader3 = DataLoader(ds3, batch_size=64, num_workers=2)\nall_y = torch.cat([by for _, by in loader3])\nassert len(all_y) == N, f\"Multi-worker: expected {N} samples, got {len(all_y)}\"\n# Check values match (order may differ)\nassert torch.allclose(all_y.sort().values, y.sort().values, atol=1e-4), \\\n \"Multi-worker data doesn't match original\"\nprint(\"PASSED: num_workers=2 covers all samples without duplicates\")\n\n# Test 4: Values match original data\nds4 = StreamingDataset(data_path)\nloader4 = DataLoader(ds4, batch_size=N)\nbx_all, by_all = next(iter(loader4))\nassert torch.allclose(bx_all, X, atol=1e-4), \"X values don't match\"\nassert torch.allclose(by_all, y, atol=1e-4), \"y values don't match\"\nprint(\"PASSED: Streamed values match original tensors\")\n\nprint(\"\\nAll tests passed!\")", + "metadata": {}, + "execution_count": null, + "outputs": [] + } + ] +} \ No newline at end of file diff --git a/v3/data-loading/streaming-dataset/streaming-dataset_SOLN.ipynb b/v3/data-loading/streaming-dataset/streaming-dataset_SOLN.ipynb new file mode 100644 index 00000000..63aa7fd2 --- /dev/null +++ b/v3/data-loading/streaming-dataset/streaming-dataset_SOLN.ipynb @@ -0,0 +1,39 @@ +{ + "nbformat": 4, + "nbformat_minor": 5, + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3.10.0" + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "# Streaming Dataset with IterableDataset โ€” Solution", + "id": "cell-0" + }, + { + "cell_type": "code", + "id": "1739pa99wsq", + "source": "import torch\nfrom torch.utils.data import IterableDataset, DataLoader, get_worker_info\nimport os\n\ntorch.manual_seed(42)\nN, D = 10_000, 5\nX = torch.randn(N, D)\ny = X @ torch.randn(D) + 0.1 * torch.randn(N)\n\ndata_path = \"/tmp/streaming_test_data.csv\"\nwith open(data_path, \"w\") as f:\n for i in range(N):\n row = \",\".join(f\"{v:.6f}\" for v in X[i].tolist()) + f\",{y[i]:.6f}\\n\"\n f.write(row)", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "g9ik20oi1fp", + "source": "class StreamingDataset(IterableDataset):\n \"\"\"Streams (x, y) pairs from a CSV file, one line at a time.\"\"\"\n\n def __init__(self, filepath: str):\n super().__init__()\n self.filepath = filepath\n\n def __iter__(self):\n worker_info = get_worker_info()\n worker_id = 0 if worker_info is None else worker_info.id\n num_workers = 1 if worker_info is None else worker_info.num_workers\n\n with open(self.filepath) as f:\n for line_idx, line in enumerate(f):\n if line_idx % num_workers != worker_id:\n continue\n values = [float(v) for v in line.strip().split(\",\")]\n x = torch.tensor(values[:-1])\n y = torch.tensor(values[-1])\n yield x, y\n\n\n# Quick demo\nds = StreamingDataset(data_path)\nloader = DataLoader(ds, batch_size=32)\nbx, by = next(iter(loader))\nprint(f\"Batch: X={bx.shape}, y={by.shape}\")", + "metadata": {}, + "execution_count": null, + "outputs": [] + } + ] +} \ No newline at end of file From baba704a22bfe57c11631fd9d84579984c70394f Mon Sep 17 00:00:00 2001 From: Mathieu Charbonnel Date: Wed, 14 Oct 2026 22:45:49 +0200 Subject: [PATCH 4/5] Add data loading exercises to README --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index f3090faf..98535f0b 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,14 @@ Core PyTorch and classical ML fundamentals. | 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 From 1e4ffb95b54b092112335b0aeef8531d996d1b96 Mon Sep 17 00:00:00 2001 From: Mathieu Charbonnel Date: Tue, 20 Oct 2026 14:18:38 +0200 Subject: [PATCH 5/5] Fix data loading tests: remove num_workers from notebook tests num_workers > 0 causes pickle errors in Jupyter notebooks since classes defined in notebook cells can't be serialized for multiprocessing. Replace multi-worker tests with shuffle verification (preloaded) and code inspection (streaming). --- .../preloaded-dataset/preloaded-dataset.ipynb | 24 +++++--- .../preloaded-dataset_SOLN.ipynb | 60 +++++++++++++++++-- .../streaming-dataset/streaming-dataset.ipynb | 20 +++++-- 3 files changed, 86 insertions(+), 18 deletions(-) diff --git a/v3/data-loading/preloaded-dataset/preloaded-dataset.ipynb b/v3/data-loading/preloaded-dataset/preloaded-dataset.ipynb index 7057a824..1a00a193 100644 --- a/v3/data-loading/preloaded-dataset/preloaded-dataset.ipynb +++ b/v3/data-loading/preloaded-dataset/preloaded-dataset.ipynb @@ -16,7 +16,7 @@ { "cell_type": "markdown", "metadata": {}, - "source": "# Preloaded Map-Style Dataset\n\n**Difficulty**: ๐ŸŸข Easy\n\n---\n\n### Problem Statement\n\nThe most common pattern in PyTorch data loading is a **map-style dataset**: all data lives in memory (or is indexed on disk), and `__getitem__(i)` returns the i-th sample. Combined with `DataLoader`, this gives you batching, shuffling, and multi-worker prefetching for free.\n\nYour task is to implement a map-style `Dataset` that loads a synthetic dataset **entirely into memory** as tensors, and verify that `DataLoader` correctly batches and shuffles it.\n\n---\n\n### Requirements\n\n1. **`PreloadedDataset(X, y)`** โ€” A `torch.utils.data.Dataset` subclass:\n - Stores `X` and `y` as tensors in `__init__`.\n - `__len__` returns the number of samples.\n - `__getitem__(idx)` returns `(X[idx], y[idx])`.\n\n2. **DataLoader integration**:\n - Wrap the dataset in a `DataLoader` with `batch_size=16` and `shuffle=True`.\n - Iterate one full epoch and verify every sample is seen exactly once.\n\n3. **Multi-worker loading**:\n - Use `num_workers=2` and confirm the output is identical in content (though order may differ when shuffled).\n\n---\n\n### Constraints\n\n- โœ… Data must be stored as `torch.Tensor`, not numpy arrays or lists.\n- โœ… `__getitem__` must return a tuple `(x_i, y_i)`, not a dict.\n- โœ… Must work with `DataLoader`'s batching (automatic collation).\n\n---\n\n
\n ๐Ÿ’ก Hint\n\n - Convert data to tensors in `__init__` with `torch.tensor()` or `torch.as_tensor()`.\n - `DataLoader` calls `__getitem__` for each index in the batch, then stacks the results automatically.\n - To verify all samples are seen, collect all indices or values across batches and check the count.\n\n
\n\n---", + "source": "# Preloaded Map-Style Dataset\n\n**Difficulty**: \ud83d\udfe2 Easy\n\n---\n\n### Problem Statement\n\nThe most common pattern in PyTorch data loading is a **map-style dataset**: all data lives in memory (or is indexed on disk), and `__getitem__(i)` returns the i-th sample. Combined with `DataLoader`, this gives you batching, shuffling, and multi-worker prefetching for free.\n\nYour task is to implement a map-style `Dataset` that loads a synthetic dataset **entirely into memory** as tensors, and verify that `DataLoader` correctly batches and shuffles it.\n\n---\n\n### Requirements\n\n1. **`PreloadedDataset(X, y)`** \u2014 A `torch.utils.data.Dataset` subclass:\n - Stores `X` and `y` as tensors in `__init__`.\n - `__len__` returns the number of samples.\n - `__getitem__(idx)` returns `(X[idx], y[idx])`.\n\n2. **DataLoader integration**:\n - Wrap the dataset in a `DataLoader` with `batch_size=16` and `shuffle=True`.\n - Iterate one full epoch and verify every sample is seen exactly once.\n\n3. **Shuffle verification**:\n - Confirm that shuffled iteration produces a different order than sequential iteration.\n\n---\n\n### Constraints\n\n- \u2705 Data must be stored as `torch.Tensor`, not numpy arrays or lists.\n- \u2705 `__getitem__` must return a tuple `(x_i, y_i)`, not a dict.\n- \u2705 Must work with `DataLoader`'s batching (automatic collation).\n\n---\n\n
\n \ud83d\udca1 Hint\n\n - Convert data to tensors in `__init__` with `torch.tensor()` or `torch.as_tensor()`.\n - `DataLoader` calls `__getitem__` for each index in the batch, then stacks the results automatically.\n - To verify all samples are seen, collect all indices or values across batches and check the count.\n\n
\n\n---", "id": "cell-0" }, { @@ -24,24 +24,32 @@ "id": "uokqo8vr75b", "source": "import torch\nfrom torch.utils.data import Dataset, DataLoader\n\n# Synthetic data: 1000 samples, 10 features, regression target\ntorch.manual_seed(42)\nN, D = 1000, 10\nX_data = torch.randn(N, D)\ny_data = X_data @ torch.randn(D) + 0.1 * torch.randn(N)\n\nprint(f\"X shape: {X_data.shape}, y shape: {y_data.shape}\")", "metadata": {}, - "execution_count": null, - "outputs": [] + "outputs": [], + "execution_count": null }, { "cell_type": "code", "id": "haluqxm38qs", "source": "class PreloadedDataset(Dataset):\n \"\"\"Map-style dataset that holds all data in memory as tensors.\"\"\"\n\n def __init__(self, X: torch.Tensor, y: torch.Tensor):\n # TODO: Store X and y as tensors\n ...\n\n def __len__(self):\n # TODO: Return the number of samples\n ...\n\n def __getitem__(self, idx):\n # TODO: Return the (X[idx], y[idx]) pair\n ...", "metadata": {}, - "execution_count": null, - "outputs": [] + "outputs": [], + "execution_count": null }, { "cell_type": "code", "id": "jnfi8r62m1e", - "source": "# === Tests ===\n\n# Test 1: Basic dataset properties\nds = PreloadedDataset(X_data, y_data)\nassert len(ds) == N, f\"Expected length {N}, got {len(ds)}\"\nx_i, y_i = ds[0]\nassert x_i.shape == (D,), f\"Expected feature shape ({D},), got {x_i.shape}\"\nassert y_i.shape == (), f\"Expected scalar target, got shape {y_i.shape}\"\nprint(\"PASSED: Dataset has correct length and item shapes\")\n\n# Test 2: DataLoader batching\nloader = DataLoader(ds, batch_size=16, shuffle=False)\nbatch_x, batch_y = next(iter(loader))\nassert batch_x.shape == (16, D), f\"Batch X shape wrong: {batch_x.shape}\"\nassert batch_y.shape == (16,), f\"Batch y shape wrong: {batch_y.shape}\"\nprint(\"PASSED: DataLoader produces correct batch shapes\")\n\n# Test 3: Full epoch โ€” every sample seen exactly once\nloader_shuffled = DataLoader(ds, batch_size=16, shuffle=True)\nall_y = []\nfor bx, by in loader_shuffled:\n all_y.append(by)\nall_y = torch.cat(all_y)\nassert len(all_y) == N, f\"Expected {N} samples in one epoch, got {len(all_y)}\"\nassert torch.allclose(all_y.sort().values, y_data.sort().values), \\\n \"Not all samples were seen โ€” values don't match after sorting\"\nprint(\"PASSED: Full epoch sees every sample exactly once\")\n\n# Test 4: Multi-worker loading\nloader_workers = DataLoader(ds, batch_size=32, shuffle=False, num_workers=2)\nall_y_w = torch.cat([by for _, by in loader_workers])\nassert torch.allclose(all_y_w.sort().values, y_data.sort().values), \\\n \"Multi-worker loading lost or duplicated samples\"\nprint(\"PASSED: num_workers=2 produces correct results\")\n\nprint(\"\\nAll tests passed!\")", + "source": "# === Tests ===\n\n# Test 1: Basic dataset properties\nds = PreloadedDataset(X_data, y_data)\nassert len(ds) == N, f\"Expected length {N}, got {len(ds)}\"\nx_i, y_i = ds[0]\nassert x_i.shape == (D,), f\"Expected feature shape ({D},), got {x_i.shape}\"\nassert y_i.shape == (), f\"Expected scalar target, got shape {y_i.shape}\"\nprint(\"PASSED: Dataset has correct length and item shapes\")\n\n# Test 2: DataLoader batching\nloader = DataLoader(ds, batch_size=16, shuffle=False)\nbatch_x, batch_y = next(iter(loader))\nassert batch_x.shape == (16, D), f\"Batch X shape wrong: {batch_x.shape}\"\nassert batch_y.shape == (16,), f\"Batch y shape wrong: {batch_y.shape}\"\nprint(\"PASSED: DataLoader produces correct batch shapes\")\n\n# Test 3: Full epoch \u2014 every sample seen exactly once\nloader_shuffled = DataLoader(ds, batch_size=16, shuffle=True)\nall_y = []\nfor bx, by in loader_shuffled:\n all_y.append(by)\nall_y = torch.cat(all_y)\nassert len(all_y) == N, f\"Expected {N} samples in one epoch, got {len(all_y)}\"\nassert torch.allclose(all_y.sort().values, y_data.sort().values), \\\n \"Not all samples were seen \u2014 values don't match after sorting\"\nprint(\"PASSED: Full epoch sees every sample exactly once\")\n\n# Test 4: Shuffled order differs from original\nloader_ordered = DataLoader(ds, batch_size=N, shuffle=False)\ny_ordered = next(iter(loader_ordered))[1]\nassert not torch.equal(all_y, y_ordered), \"Shuffled loader should produce a different order\"\nprint(\"PASSED: Shuffled order differs from sequential order\")\n\nprint(\"\\nAll tests passed!\")", + "metadata": {}, + "outputs": [], + "execution_count": null + }, + { "metadata": {}, + "cell_type": "code", + "outputs": [], "execution_count": null, - "outputs": [] + "source": "", + "id": "c2c05fec9891dce" } ] -} \ No newline at end of file +} diff --git a/v3/data-loading/preloaded-dataset/preloaded-dataset_SOLN.ipynb b/v3/data-loading/preloaded-dataset/preloaded-dataset_SOLN.ipynb index 6f5518d4..6a2a59c0 100644 --- a/v3/data-loading/preloaded-dataset/preloaded-dataset_SOLN.ipynb +++ b/v3/data-loading/preloaded-dataset/preloaded-dataset_SOLN.ipynb @@ -23,17 +23,69 @@ "cell_type": "code", "id": "71s80o06aya", "source": "import torch\nfrom torch.utils.data import Dataset, DataLoader\n\ntorch.manual_seed(42)\nN, D = 1000, 10\nX_data = torch.randn(N, D)\ny_data = X_data @ torch.randn(D) + 0.1 * torch.randn(N)", - "metadata": {}, - "execution_count": null, - "outputs": [] + "metadata": { + "ExecuteTime": { + "end_time": "2026-10-20T12:12:10.260388Z", + "start_time": "2026-10-20T12:12:10.242173Z" + } + }, + "outputs": [], + "execution_count": 10 }, { "cell_type": "code", "id": "mzr5pkucsqo", "source": "class PreloadedDataset(Dataset):\n \"\"\"Map-style dataset that holds all data in memory as tensors.\"\"\"\n\n def __init__(self, X: torch.Tensor, y: torch.Tensor):\n self.X = X\n self.y = y\n\n def __len__(self):\n return len(self.X)\n\n def __getitem__(self, idx):\n return self.X[idx], self.y[idx]\n\n\nds = PreloadedDataset(X_data, y_data)\nloader = DataLoader(ds, batch_size=16, shuffle=True)\n\nfor batch_x, batch_y in loader:\n print(f\"Batch: X={batch_x.shape}, y={batch_y.shape}\")\n break", + "metadata": { + "ExecuteTime": { + "end_time": "2026-10-20T12:12:11.091198Z", + "start_time": "2026-10-20T12:12:11.064573Z" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Batch: X=torch.Size([16, 10]), y=torch.Size([16])\n" + ] + } + ], + "execution_count": 11 + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-10-20T12:12:12.407693Z", + "start_time": "2026-10-20T12:12:11.632414Z" + } + }, + "cell_type": "code", + "source": "# === Tests ===\n\n# Test 1: Basic dataset properties\nds = PreloadedDataset(X_data, y_data)\nassert len(ds) == N, f\"Expected length {N}, got {len(ds)}\"\nx_i, y_i = ds[0]\nassert x_i.shape == (D,), f\"Expected feature shape ({D},), got {x_i.shape}\"\nassert y_i.shape == (), f\"Expected scalar target, got shape {y_i.shape}\"\nprint(\"PASSED: Dataset has correct length and item shapes\")\n\n# Test 2: DataLoader batching\nloader = DataLoader(ds, batch_size=16, shuffle=False)\nbatch_x, batch_y = next(iter(loader))\nassert batch_x.shape == (16, D), f\"Batch X shape wrong: {batch_x.shape}\"\nassert batch_y.shape == (16,), f\"Batch y shape wrong: {batch_y.shape}\"\nprint(\"PASSED: DataLoader produces correct batch shapes\")\n\n# Test 3: Full epoch โ€” every sample seen exactly once\nloader_shuffled = DataLoader(ds, batch_size=16, shuffle=True)\nall_y = []\nfor bx, by in loader_shuffled:\n all_y.append(by)\nall_y = torch.cat(all_y)\nassert len(all_y) == N, f\"Expected {N} samples in one epoch, got {len(all_y)}\"\nassert torch.allclose(all_y.sort().values, y_data.sort().values), \\\n \"Not all samples were seen โ€” values don't match after sorting\"\nprint(\"PASSED: Full epoch sees every sample exactly once\")\n\n# Test 4: Shuffled order differs from original\nloader_ordered = DataLoader(ds, batch_size=N, shuffle=False)\ny_ordered = next(iter(loader_ordered))[1]\nassert not torch.equal(all_y, y_ordered), \"Shuffled loader should produce a different order\"\nprint(\"PASSED: Shuffled order differs from sequential order\")\n\nprint(\"\\nAll tests passed!\")", + "id": "3eac091ee94083e7", + "outputs": [], + "execution_count": null + }, + { + "metadata": { + "ExecuteTime": { + "end_time": "2026-10-20T12:12:13.237537Z", + "start_time": "2026-10-20T12:12:13.205119Z" + } + }, + "cell_type": "code", + "source": "", + "id": "9d7e829d062a93ce", + "outputs": [], + "execution_count": 12 + }, + { "metadata": {}, + "cell_type": "code", + "outputs": [], "execution_count": null, - "outputs": [] + "source": "", + "id": "abc92f3c70640b94" } ] } \ No newline at end of file diff --git a/v3/data-loading/streaming-dataset/streaming-dataset.ipynb b/v3/data-loading/streaming-dataset/streaming-dataset.ipynb index 525a5c96..ea976601 100644 --- a/v3/data-loading/streaming-dataset/streaming-dataset.ipynb +++ b/v3/data-loading/streaming-dataset/streaming-dataset.ipynb @@ -16,7 +16,7 @@ { "cell_type": "markdown", "metadata": {}, - "source": "# Streaming Dataset with IterableDataset\n\n**Difficulty**: ๐ŸŸก Medium\n\n---\n\n### Problem Statement\n\nWhen data is too large to fit in memory, or arrives as a stream (log files, network sockets, database cursors), you can't use a map-style dataset with random `__getitem__` access. PyTorch's `IterableDataset` solves this: you implement `__iter__` as a Python **generator** that `yield`s one sample at a time.\n\nYour task is to implement a streaming dataset that reads a large file **line by line** without loading it all into memory.\n\n---\n\n### Requirements\n\n1. **`StreamingDataset(filepath)`** โ€” A `torch.utils.data.IterableDataset` subclass:\n - `__iter__` opens the file and yields `(x, y)` tensor pairs one line at a time.\n - Must **not** read the entire file into memory.\n\n2. **Multi-worker correctness**:\n - When `DataLoader` uses `num_workers > 1`, each worker gets its own copy of the iterator. Without handling this, every worker yields the **entire** file (duplicated data!).\n - Implement worker-aware splitting using `torch.utils.data.get_worker_info()` so each worker processes a disjoint shard.\n\n3. **Generate test data** โ€” Create a CSV with 10,000 rows to test against.\n\n---\n\n### Constraints\n\n- โœ… Memory usage must be O(1) per sample, not O(N).\n- โœ… With `num_workers=0` (main process), all samples must be yielded.\n- โœ… With `num_workers=K`, the union of all workers' samples must cover the full dataset with no duplicates.\n- โŒ Do **not** use `pandas.read_csv()` or load the whole file at once.\n\n---\n\n
\n ๐Ÿ’ก Hint\n\n - Use `open(filepath)` and iterate line by line โ€” Python file objects are lazy iterators.\n - `get_worker_info()` returns `None` in the main process, or a `WorkerInfo` with `.id` and `.num_workers`.\n - To shard: use `enumerate()` on lines, and each worker only yields lines where `line_idx % num_workers == worker_id`.\n - `DataLoader` with an `IterableDataset` ignores `shuffle=True` โ€” shuffling must be done differently (e.g., a shuffle buffer, covered in the next exercise).\n\n
\n\n---", + "source": "# Streaming Dataset with IterableDataset\n\n**Difficulty**: \ud83d\udfe1 Medium\n\n---\n\n### Problem Statement\n\nWhen data is too large to fit in memory, or arrives as a stream (log files, network sockets, database cursors), you can't use a map-style dataset with random `__getitem__` access. PyTorch's `IterableDataset` solves this: you implement `__iter__` as a Python **generator** that `yield`s one sample at a time.\n\nYour task is to implement a streaming dataset that reads a large file **line by line** without loading it all into memory.\n\n---\n\n### Requirements\n\n1. **`StreamingDataset(filepath)`** \u2014 A `torch.utils.data.IterableDataset` subclass:\n - `__iter__` opens the file and yields `(x, y)` tensor pairs one line at a time.\n - Must **not** read the entire file into memory.\n\n2. **Multi-worker correctness** (conceptual):\n - When `DataLoader` uses `num_workers > 1`, each worker gets its own copy of the iterator. Without handling this, every worker yields the **entire** file (duplicated data!).\n - Implement worker-aware splitting using `torch.utils.data.get_worker_info()` so each worker processes a disjoint shard.\n - *Note: `num_workers > 0` cannot be tested in Jupyter notebooks due to pickling limitations. Your sharding logic will be verified by checking the code structure.*\n\n3. **Generate test data** \u2014 Create a CSV with 10,000 rows to test against.\n\n---\n\n### Constraints\n\n- \u2705 Memory usage must be O(1) per sample, not O(N).\n- \u2705 With `num_workers=0` (main process), all samples must be yielded.\n- \u2705 Your `__iter__` must use `get_worker_info()` to support multi-worker sharding.\n- \u274c Do **not** use `pandas.read_csv()` or load the whole file at once.\n\n---\n\n
\n \ud83d\udca1 Hint\n\n - Use `open(filepath)` and iterate line by line \u2014 Python file objects are lazy iterators.\n - `get_worker_info()` returns `None` in the main process, or a `WorkerInfo` with `.id` and `.num_workers`.\n - To shard: use `enumerate()` on lines, and each worker only yields lines where `line_idx % num_workers == worker_id`.\n - `DataLoader` with an `IterableDataset` ignores `shuffle=True` \u2014 shuffling must be done differently (e.g., a shuffle buffer, covered in the next exercise).\n\n
\n\n---", "id": "cell-0" }, { @@ -24,13 +24,21 @@ "id": "3axncpuvjd3", "source": "import torch\nfrom torch.utils.data import IterableDataset, DataLoader, get_worker_info\nimport os\n\n# Generate synthetic CSV: 10,000 rows, 5 features + 1 target\ntorch.manual_seed(42)\nN, D = 10_000, 5\nX = torch.randn(N, D)\ny = X @ torch.randn(D) + 0.1 * torch.randn(N)\n\ndata_path = \"/tmp/streaming_test_data.csv\"\nwith open(data_path, \"w\") as f:\n for i in range(N):\n row = \",\".join(f\"{v:.6f}\" for v in X[i].tolist()) + f\",{y[i]:.6f}\\n\"\n f.write(row)\n\nprint(f\"Wrote {N} rows to {data_path}\")\nprint(f\"File size: {os.path.getsize(data_path) / 1024:.1f} KB\")", "metadata": {}, - "execution_count": null, - "outputs": [] + "outputs": [], + "execution_count": null + }, + { + "metadata": {}, + "cell_type": "code", + "source": "i = 1\nline = \",\".join(f\"{v:.6f}\" for v in X[i].tolist()) + f\",{y[i]:.6f}\\n\"\nprint(line)\nprint(line.strip().split(','))\nsplitted_line = torch.tensor([float(v) for v in line.strip().split(',')], dtype=torch.float32)\nx, y = splitted_line[:-1], splitted_line[-1:]\nprint(x, y)\n", + "id": "3f20de33f3c2943c", + "outputs": [], + "execution_count": null }, { "cell_type": "code", "id": "ft0ew8926pv", - "source": "class StreamingDataset(IterableDataset):\n \"\"\"Streams (x, y) pairs from a CSV file, one line at a time.\"\"\"\n\n def __init__(self, filepath: str):\n super().__init__()\n self.filepath = filepath\n\n def __iter__(self):\n # TODO: Get worker info for multi-worker sharding\n # worker_info = get_worker_info()\n # If None โ†’ single process, yield everything\n # Otherwise โ†’ only yield lines where line_idx % num_workers == worker_id\n\n # TODO: Open file and iterate line by line\n # For each line: parse comma-separated floats, split into x (all but last) and y (last)\n # Yield (x_tensor, y_tensor)\n ...", + "source": "class StreamingDataset(IterableDataset):\n \"\"\"Streams (x, y) pairs from a CSV file, one line at a time.\"\"\"\n\n def __init__(self, filepath: str):\n super().__init__()\n self.filepath = filepath\n\n def __iter__(self):\n # TODO: Get worker info for multi-worker sharding\n # worker_info = get_worker_info()\n # If None \u2192 single process, yield everything\n # Otherwise \u2192 only yield lines where line_idx % num_workers == worker_id\n\n # TODO: Open file and iterate line by line\n # For each line: parse comma-separated floats, split into x (all but last) and y (last)\n # Yield (x_tensor, y_tensor)\n ...", "metadata": {}, "execution_count": null, "outputs": [] @@ -38,10 +46,10 @@ { "cell_type": "code", "id": "gw4cs9hw8h", - "source": "# === Tests ===\n\n# Test 1: Single-process iteration yields all samples\nds = StreamingDataset(data_path)\nloader = DataLoader(ds, batch_size=64)\ntotal = sum(by.shape[0] for _, by in loader)\nassert total == N, f\"Expected {N} samples, got {total}\"\nprint(f\"PASSED: Single-process yields all {N} samples\")\n\n# Test 2: Correct shapes\nds2 = StreamingDataset(data_path)\nloader2 = DataLoader(ds2, batch_size=32)\nbx, by = next(iter(loader2))\nassert bx.shape == (32, D), f\"Expected X shape (32, {D}), got {bx.shape}\"\nassert by.shape == (32,), f\"Expected y shape (32,), got {by.shape}\"\nprint(\"PASSED: Correct batch shapes\")\n\n# Test 3: Multi-worker yields all samples without duplicates\nds3 = StreamingDataset(data_path)\nloader3 = DataLoader(ds3, batch_size=64, num_workers=2)\nall_y = torch.cat([by for _, by in loader3])\nassert len(all_y) == N, f\"Multi-worker: expected {N} samples, got {len(all_y)}\"\n# Check values match (order may differ)\nassert torch.allclose(all_y.sort().values, y.sort().values, atol=1e-4), \\\n \"Multi-worker data doesn't match original\"\nprint(\"PASSED: num_workers=2 covers all samples without duplicates\")\n\n# Test 4: Values match original data\nds4 = StreamingDataset(data_path)\nloader4 = DataLoader(ds4, batch_size=N)\nbx_all, by_all = next(iter(loader4))\nassert torch.allclose(bx_all, X, atol=1e-4), \"X values don't match\"\nassert torch.allclose(by_all, y, atol=1e-4), \"y values don't match\"\nprint(\"PASSED: Streamed values match original tensors\")\n\nprint(\"\\nAll tests passed!\")", + "source": "# === Tests ===\n\n# Test 1: Single-process iteration yields all samples\nds = StreamingDataset(data_path)\nloader = DataLoader(ds, batch_size=64)\ntotal = sum(by.shape[0] for _, by in loader)\nassert total == N, f\"Expected {N} samples, got {total}\"\nprint(f\"PASSED: Single-process yields all {N} samples\")\n\n# Test 2: Correct shapes\nds2 = StreamingDataset(data_path)\nloader2 = DataLoader(ds2, batch_size=32)\nbx, by = next(iter(loader2))\nassert bx.shape == (32, D), f\"Expected X shape (32, {D}), got {bx.shape}\"\nassert by.shape == (32,), f\"Expected y shape (32,), got {by.shape}\"\nprint(\"PASSED: Correct batch shapes\")\n\n# Test 3: Values match original data\nds3 = StreamingDataset(data_path)\nloader3 = DataLoader(ds3, batch_size=N)\nbx_all, by_all = next(iter(loader3))\nassert torch.allclose(bx_all, X, atol=1e-4), \"X values don't match\"\nassert torch.allclose(by_all, y, atol=1e-4), \"y values don't match\"\nprint(\"PASSED: Streamed values match original tensors\")\n\n# Test 4: Worker-aware sharding logic exists\nimport inspect\nsrc = inspect.getsource(StreamingDataset.__iter__)\nassert \"get_worker_info\" in src, \"Must use get_worker_info() for multi-worker support\"\nprint(\"PASSED: get_worker_info() is used in __iter__\")\n\nprint(\"\\nAll tests passed!\")", "metadata": {}, "execution_count": null, "outputs": [] } ] -} \ No newline at end of file +}