A straightforward method for training your LLM, from downloading data to generating text.
Added typing hints
FareedKhan-dev3f3a8dbdaa46
diff --git a/data_loader/data_loader.py b/data_loader/data_loader.pyindex 6e1938c..4375928 100644--- a/data_loader/data_loader.py+++ b/data_loader/data_loader.py@@ -1,8 +1,9 @@import torchimport numpy as npimport h5py+from typing import Iterator, Tuple-def get_batch_iterator(data_path, batch_size, context_length, device="cpu"):+def get_batch_iterator(data_path: str, batch_size: int, context_length: int, device: str = "cpu") -> Iterator[Tuple[torch.Tensor, torch.Tensor]]:"""Creates an iterator for generating batches of data from an HDF5 file.diff --git a/scripts/data_download.py b/scripts/data_download.pyindex a95537d..992cf7b 100644--- a/scripts/data_download.py+++ b/scripts/data_download.py@@ -2,13 +2,14 @@ import osimport argparseimport requestsfrom tqdm import tqdm+from typing import List# Base URL for the dataset filesBASE_URL = "https://huggingface.co/datasets/monology/pile-uncopyrighted/resolve/main"VAL_URL = f"{BASE_URL}/val.jsonl.zst" # URL for the validation datasetTRAIN_URLS = [f"{BASE_URL}/train/{i:02d}.jsonl.zst" for i in range(65)] # URLs for 65 training files (adjust the range if needed)-def download_file(url, file_name):+def download_file(url: str, file_name: str) -> None:"""Downloads a file from the given URL and saves it with the specified file name.Displays a progress bar using tqdm.@@ -25,7 +26,7 @@ def download_file(url, file_name):for chunk in tqdm(response.iter_content(block_size), total=total_size // block_size, desc="Downloading", leave=True):f.write(chunk) # Write each chunk to the file-def download_dataset(val_url, train_urls, val_dir, train_dir, max_train_files):+def download_dataset(val_url: str, train_urls: List[str], val_dir: str, train_dir: str, max_train_files: int) -> None:"""Manages downloading of the dataset, including both validation and training files.@@ -54,7 +55,7 @@ def download_dataset(val_url, train_urls, val_dir, train_dir, max_train_files):else:print(f"Training file {file_name} already present. Skipping download.")-def main():+def main() -> None:"""Main function to parse arguments and orchestrate the dataset download process."""diff --git a/scripts/data_preprocess.py b/scripts/data_preprocess.pyindex e6541d7..7ae9a48 100644--- a/scripts/data_preprocess.py+++ b/scripts/data_preprocess.py@@ -5,8 +5,9 @@ import tiktokenimport h5pyfrom tqdm import tqdmimport argparse+from typing import Optional-def process_files(input_dir, output_file, tokenizer_name, max_data=None):+def process_files(input_dir: str, output_file: str, tokenizer_name: str, max_data: Optional[int] = None) -> None:"""Process a specified number of lines from each .jsonl.zst file in the input directoryand save encoded tokens to an HDF5 file.diff --git a/scripts/generate_text.py b/scripts/generate_text.pyindex 51d0625..e160c79 100644--- a/scripts/generate_text.py+++ b/scripts/generate_text.py@@ -4,7 +4,7 @@ import argparsefrom config.config import default_config as configfrom src.models.transformer import Transformer # Assuming your Transformer class is in this module-def generate_text(model_path, input_text, max_new_tokens=100, device='cuda'):+def generate_text(model_path: str, input_text: str, max_new_tokens: int = 100, device: str = 'cuda') -> str:"""Generates text using a pre-trained Transformer model.@@ -46,7 +46,7 @@ def generate_text(model_path, input_text, max_new_tokens=100, device='cuda'):return output_text-def main():+def main() -> None:parser = argparse.ArgumentParser(description="Generate text using a pre-trained Transformer model.")parser.add_argument('--model_path', type=str, help='Path to the saved model checkpoint.')parser.add_argument('--input_text', type=str, help='The initial text to start generation from.')diff --git a/scripts/train_transformer.py b/scripts/train_transformer.pyindex d1341de..8cbb14a 100644--- a/scripts/train_transformer.py+++ b/scripts/train_transformer.py@@ -6,6 +6,7 @@ import numpy as npfrom config.config import default_config as configfrom src.models.transformer import Transformerfrom data_loader.data_loader import get_batch_iterator+from typing import Dict# --- Initialize the Model and Print Parameters ---@@ -34,7 +35,7 @@ AVG_WINDOW = 64# Helper function to estimate the average loss for training and development data.@torch.no_grad()-def estimate_loss(steps):+def estimate_loss(steps: int) -> Dict[str, float]:"""Evaluate the model on training and development datasets and calculate average loss.diff --git a/src/models/attention.py b/src/models/attention.pyindex 608c42a..c0f9c8f 100644--- a/src/models/attention.py+++ b/src/models/attention.py@@ -16,7 +16,7 @@ class Head(nn.Module):n_embed (int): The dimensionality of the input embedding.context_length (int): The maximum length of the input sequence, used for causal masking."""- def __init__(self, head_size, n_embed, context_length):+ def __init__(self, head_size: int, n_embed: int, context_length: int) -> None:"""Initializes the attention head.@@ -32,7 +32,7 @@ class Head(nn.Module):# Lower triangular matrix for causal maskingself.register_buffer('tril', torch.tril(torch.ones(context_length, context_length)))- def forward(self, x):+ def forward(self, x: torch.Tensor) -> torch.Tensor:"""Forward pass through the attention head.@@ -68,7 +68,7 @@ class MultiHeadAttention(nn.Module):n_embed (int): The dimensionality of the input embedding.context_length (int): The maximum length of the input sequence."""- def __init__(self, n_head, n_embed, context_length):+ def __init__(self, n_head: int, n_embed: int, context_length: int) -> None:"""Initializes the multi-head attention module.@@ -80,7 +80,7 @@ class MultiHeadAttention(nn.Module):super().__init__()self.heads = nn.ModuleList([Head(n_embed // n_head, n_embed, context_length) for _ in range(n_head)])- def forward(self, x):+ def forward(self, x: torch.Tensor) -> torch.Tensor:"""Forward pass through the multi-head attention.diff --git a/src/models/mlp.py b/src/models/mlp.pyindex c45f89a..c7baa79 100644--- a/src/models/mlp.py+++ b/src/models/mlp.py@@ -1,5 +1,6 @@import torchimport torch.nn as nn+from torch import Tensorclass MLP(nn.Module):"""@@ -12,7 +13,7 @@ class MLP(nn.Module):Args:n_embed (int): The dimensionality of the input embedding."""- def __init__(self, n_embed):+ def __init__(self, n_embed: int) -> None:"""Initializes the MLP module.@@ -24,7 +25,7 @@ class MLP(nn.Module):self.relu = nn.ReLU() # ReLU activation functionself.proj = nn.Linear(4 * n_embed, n_embed) # Linear layer to project back to original size- def forward(self, x):+ def forward(self, x: Tensor) -> Tensor:"""Forward pass through the MLP.@@ -39,7 +40,7 @@ class MLP(nn.Module):x = self.project_embedding(x)return x- def forward_embedding(self, x):+ def forward_embedding(self, x: Tensor) -> Tensor:"""Applies the hidden linear layer followed by ReLU activation.@@ -52,7 +53,7 @@ class MLP(nn.Module):x = self.relu(self.hidden(x))return x- def project_embedding(self, x):+ def project_embedding(self, x: Tensor) -> Tensor:"""Applies the projection linear layer.diff --git a/src/models/transformer.py b/src/models/transformer.pyindex 64d1515..4650753 100644--- a/src/models/transformer.py+++ b/src/models/transformer.py@@ -17,7 +17,7 @@ class Transformer(nn.Module):vocab_size (int): The size of the vocabulary.N_BLOCKS (int): The number of transformer blocks in the model."""- def __init__(self, n_head, n_embed, context_length, vocab_size, N_BLOCKS):+ def __init__(self, n_head: int, n_embed: int, context_length: int, vocab_size: int, N_BLOCKS: int) -> None:"""Initializes the Transformer model.@@ -38,7 +38,7 @@ class Transformer(nn.Module):self.lm_head = nn.Linear(n_embed, vocab_size)self.register_buffer('pos_idxs', torch.arange(context_length))- def _pre_attn_pass(self, idx):+ def _pre_attn_pass(self, idx: torch.Tensor) -> torch.Tensor:"""Combines token and position embeddings.@@ -53,7 +53,7 @@ class Transformer(nn.Module):pos_embedding = self.position_embed(self.pos_idxs[:T])return tok_embedding + pos_embedding- def forward(self, idx, targets=None):+ def forward(self, idx: torch.Tensor, targets: torch.Tensor = None) -> tuple[torch.Tensor, torch.Tensor | None]:"""Forward pass through the Transformer.@@ -77,7 +77,7 @@ class Transformer(nn.Module):loss = F.cross_entropy(flat_logits, targets)return logits, loss- def forward_embedding(self, idx):+ def forward_embedding(self, idx: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:"""Forward pass focusing on the embedding and attention blocks.@@ -93,7 +93,7 @@ class Transformer(nn.Module):x, residual = block.forward_embedding(x)return x, residual- def generate(self, idx, max_new_tokens):+ def generate(self, idx: torch.Tensor, max_new_tokens: int) -> torch.Tensor:"""Generates new tokens given a starting sequence.diff --git a/src/models/transformer_block.py b/src/models/transformer_block.pyindex de00b74..b6cfd29 100644--- a/src/models/transformer_block.py+++ b/src/models/transformer_block.py@@ -15,7 +15,7 @@ class Block(nn.Module):n_embed (int): The dimensionality of the input embedding.context_length (int): The maximum length of the input sequence."""- def __init__(self, n_head, n_embed, context_length):+ def __init__(self, n_head: int, n_embed: int, context_length: int) -> None:"""Initializes the Transformer block.@@ -30,7 +30,7 @@ class Block(nn.Module):self.ln2 = nn.LayerNorm(n_embed)self.mlp = MLP(n_embed)- def forward(self, x):+ def forward(self, x: torch.Tensor) -> torch.Tensor:"""Forward pass through the Transformer block.@@ -46,7 +46,7 @@ class Block(nn.Module):x = x + self.mlp(self.ln2(x))return x- def forward_embedding(self, x):+ def forward_embedding(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:"""Forward pass focusing on the embedding and attention parts.