{"id":13408337,"url":"https://github.com/rasbt/LLMs-from-scratch","last_synced_at":"2025-03-14T13:30:48.829Z","repository":{"id":183291756,"uuid":"669879380","full_name":"rasbt/LLMs-from-scratch","owner":"rasbt","description":"Implementing a ChatGPT-like LLM in PyTorch from scratch, step by step","archived":false,"fork":false,"pushed_at":"2024-10-24T23:23:53.000Z","size":12167,"stargazers_count":29935,"open_issues_count":0,"forks_count":3489,"subscribers_count":320,"default_branch":"main","last_synced_at":"2024-10-25T03:53:48.777Z","etag":null,"topics":["chatgpt","gpt","large-language-models","llm","python","pytorch"],"latest_commit_sha":null,"homepage":"https://mng.bz/orYv","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rasbt.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-07-23T18:15:57.000Z","updated_at":"2024-10-25T03:47:42.000Z","dependencies_parsed_at":"2023-07-23T20:36:44.281Z","dependency_job_id":"b17f8409-8f4f-4326-b663-9473161619f7","html_url":"https://github.com/rasbt/LLMs-from-scratch","commit_stats":{"total_commits":647,"total_committers":28,"mean_commits":"23.107142857142858","dds":"0.15455950540958274","last_synced_commit":"1f61aeb7c4396b12e75f7994de0657d257329b0b"},"previous_names":["rasbt/llms-from-scratch"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rasbt%2FLLMs-from-scratch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rasbt%2FLLMs-from-scratch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rasbt%2FLLMs-from-scratch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rasbt%2FLLMs-from-scratch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rasbt","download_url":"https://codeload.github.com/rasbt/LLMs-from-scratch/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243584102,"owners_count":20314700,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["chatgpt","gpt","large-language-models","llm","python","pytorch"],"created_at":"2024-07-30T20:00:52.241Z","updated_at":"2025-03-14T13:30:48.813Z","avatar_url":"https://github.com/rasbt.png","language":"Jupyter Notebook","readme":"# Build a Large Language Model (From Scratch)\n\nThis repository contains the code for developing, pretraining, and finetuning a GPT-like LLM and is the official code repository for the book [Build a Large Language Model (From Scratch)](https://amzn.to/4fqvn0D).\n\n\u003cbr\u003e\n\u003cbr\u003e\n\n\u003ca href=\"https://amzn.to/4fqvn0D\"\u003e\u003cimg src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/cover.jpg?123\" width=\"250px\"\u003e\u003c/a\u003e\n\n\u003cbr\u003e\n\nIn [*Build a Large Language Model (From Scratch)*](http://mng.bz/orYv), you'll learn and understand how large language models (LLMs) work from the inside out by coding them from the ground up, step by step. In this book, I'll guide you through creating your own LLM, explaining each stage with clear text, diagrams, and examples.\n\nThe method described in this book for training and developing your own small-but-functional model for educational purposes mirrors the approach used in creating large-scale foundational models such as those behind ChatGPT. In addition, this book includes code for loading the weights of larger pretrained models for finetuning.\n\n- Link to the official [source code repository](https://github.com/rasbt/LLMs-from-scratch)\n- [Link to the book at Manning (the publisher's website)](http://mng.bz/orYv)\n- [Link to the book page on Amazon.com](https://www.amazon.com/gp/product/1633437167)\n- ISBN 9781633437166\n\n\u003ca href=\"http://mng.bz/orYv#reviews\"\u003e\u003cimg src=\"https://sebastianraschka.com//images/LLMs-from-scratch-images/other/reviews.png\" width=\"220px\"\u003e\u003c/a\u003e\n\n\n\u003cbr\u003e\n\u003cbr\u003e\n\nTo download a copy of this repository, click on the [Download ZIP](https://github.com/rasbt/LLMs-from-scratch/archive/refs/heads/main.zip) button or execute the following command in your terminal:\n\n```bash\ngit clone --depth 1 https://github.com/rasbt/LLMs-from-scratch.git\n```\n\n\u003cbr\u003e\n\n(If you downloaded the code bundle from the Manning website, please consider visiting the official code repository on GitHub at [https://github.com/rasbt/LLMs-from-scratch](https://github.com/rasbt/LLMs-from-scratch) for the latest updates.)\n\n\u003cbr\u003e\n\u003cbr\u003e\n\n\n# Table of Contents\n\nPlease note that this `README.md` file is a Markdown (`.md`) file. If you have downloaded this code bundle from the Manning website and are viewing it on your local computer, I recommend using a Markdown editor or previewer for proper viewing. If you haven't installed a Markdown editor yet, [MarkText](https://www.marktext.cc) is a good free option.\n\nYou can alternatively view this and other files on GitHub at [https://github.com/rasbt/LLMs-from-scratch](https://github.com/rasbt/LLMs-from-scratch) in your browser, which renders Markdown automatically.\n\n\u003cbr\u003e\n\u003cbr\u003e\n\u003c!--  --\u003e\n\n\u003e **Tip:**\n\u003e If you're seeking guidance on installing Python and Python packages and setting up your code environment, I suggest reading the [README.md](setup/README.md) file located in the [setup](setup) directory.\n\n\u003cbr\u003e\n\u003cbr\u003e\n\n[![Code tests Linux](https://github.com/rasbt/LLMs-from-scratch/actions/workflows/basic-tests-linux-uv.yml/badge.svg)](https://github.com/rasbt/LLMs-from-scratch/actions/workflows/basic-tests-linux-uv.yml)\n[![Code tests Windows](https://github.com/rasbt/LLMs-from-scratch/actions/workflows/basic-tests-windows-uv-pip.yml/badge.svg)](https://github.com/rasbt/LLMs-from-scratch/actions/workflows/basic-tests-windows-uv-pip.yml)\n[![Code tests macOS](https://github.com/rasbt/LLMs-from-scratch/actions/workflows/basic-tests-macos-uv.yml/badge.svg)](https://github.com/rasbt/LLMs-from-scratch/actions/workflows/basic-tests-macos-uv.yml)\n\n\n\n\n\u003cbr\u003e\n\n| Chapter Title                                              | Main Code (for Quick Access)                                                                                                    | All Code + Supplementary      |\n|------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------|-------------------------------|\n| [Setup recommendations](setup)                             | -                                                                                                                               | -                             |\n| Ch 1: Understanding Large Language Models                  | No code                                                                                                                         | -                             |\n| Ch 2: Working with Text Data                               | - [ch02.ipynb](ch02/01_main-chapter-code/ch02.ipynb)\u003cbr/\u003e- [dataloader.ipynb](ch02/01_main-chapter-code/dataloader.ipynb) (summary)\u003cbr/\u003e- [exercise-solutions.ipynb](ch02/01_main-chapter-code/exercise-solutions.ipynb)               | [./ch02](./ch02)            |\n| Ch 3: Coding Attention Mechanisms                          | - [ch03.ipynb](ch03/01_main-chapter-code/ch03.ipynb)\u003cbr/\u003e- [multihead-attention.ipynb](ch03/01_main-chapter-code/multihead-attention.ipynb) (summary) \u003cbr/\u003e- [exercise-solutions.ipynb](ch03/01_main-chapter-code/exercise-solutions.ipynb)| [./ch03](./ch03)             |\n| Ch 4: Implementing a GPT Model from Scratch                | - [ch04.ipynb](ch04/01_main-chapter-code/ch04.ipynb)\u003cbr/\u003e- [gpt.py](ch04/01_main-chapter-code/gpt.py) (summary)\u003cbr/\u003e- [exercise-solutions.ipynb](ch04/01_main-chapter-code/exercise-solutions.ipynb) | [./ch04](./ch04)           |\n| Ch 5: Pretraining on Unlabeled Data                        | - [ch05.ipynb](ch05/01_main-chapter-code/ch05.ipynb)\u003cbr/\u003e- [gpt_train.py](ch05/01_main-chapter-code/gpt_train.py) (summary) \u003cbr/\u003e- [gpt_generate.py](ch05/01_main-chapter-code/gpt_generate.py) (summary) \u003cbr/\u003e- [exercise-solutions.ipynb](ch05/01_main-chapter-code/exercise-solutions.ipynb) | [./ch05](./ch05)              |\n| Ch 6: Finetuning for Text Classification                   | - [ch06.ipynb](ch06/01_main-chapter-code/ch06.ipynb)  \u003cbr/\u003e- [gpt_class_finetune.py](ch06/01_main-chapter-code/gpt_class_finetune.py)  \u003cbr/\u003e- [exercise-solutions.ipynb](ch06/01_main-chapter-code/exercise-solutions.ipynb) | [./ch06](./ch06)              |\n| Ch 7: Finetuning to Follow Instructions                    | - [ch07.ipynb](ch07/01_main-chapter-code/ch07.ipynb)\u003cbr/\u003e- [gpt_instruction_finetuning.py](ch07/01_main-chapter-code/gpt_instruction_finetuning.py) (summary)\u003cbr/\u003e- [ollama_evaluate.py](ch07/01_main-chapter-code/ollama_evaluate.py) (summary)\u003cbr/\u003e- [exercise-solutions.ipynb](ch07/01_main-chapter-code/exercise-solutions.ipynb) | [./ch07](./ch07)  |\n| Appendix A: Introduction to PyTorch                        | - [code-part1.ipynb](appendix-A/01_main-chapter-code/code-part1.ipynb)\u003cbr/\u003e- [code-part2.ipynb](appendix-A/01_main-chapter-code/code-part2.ipynb)\u003cbr/\u003e- [DDP-script.py](appendix-A/01_main-chapter-code/DDP-script.py)\u003cbr/\u003e- [exercise-solutions.ipynb](appendix-A/01_main-chapter-code/exercise-solutions.ipynb) | [./appendix-A](./appendix-A) |\n| Appendix B: References and Further Reading                 | No code                                                                                                                         | -                             |\n| Appendix C: Exercise Solutions                             | No code                                                                                                                         | -                             |\n| Appendix D: Adding Bells and Whistles to the Training Loop | - [appendix-D.ipynb](appendix-D/01_main-chapter-code/appendix-D.ipynb)                                                          | [./appendix-D](./appendix-D)  |\n| Appendix E: Parameter-efficient Finetuning with LoRA       | - [appendix-E.ipynb](appendix-E/01_main-chapter-code/appendix-E.ipynb)                                                          | [./appendix-E](./appendix-E) |\n\n\u003cbr\u003e\n\u0026nbsp;\n\nThe mental model below summarizes the contents covered in this book.\n\n\u003cimg src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/mental-model.jpg\" width=\"650px\"\u003e\n\n\u003cbr\u003e\n\u0026nbsp;\n\n## Hardware Requirements\n\nThe code in the main chapters of this book is designed to run on conventional laptops within a reasonable timeframe and does not require specialized hardware. This approach ensures that a wide audience can engage with the material. Additionally, the code automatically utilizes GPUs if they are available. (Please see the [setup](https://github.com/rasbt/LLMs-from-scratch/blob/main/setup/README.md) doc for additional recommendations.)\n\n\u0026nbsp;\n## Bonus Material\n\nSeveral folders contain optional materials as a bonus for interested readers:\n\n- **Setup**\n  - [Python Setup Tips](setup/01_optional-python-setup-preferences)\n  - [Installing Python Packages and Libraries Used In This Book](setup/02_installing-python-libraries)\n  - [Docker Environment Setup Guide](setup/03_optional-docker-environment)\n- **Chapter 2: Working with text data**\n  - [Byte Pair Encoding (BPE) Tokenizer From Scratch](ch02/05_bpe-from-scratch/bpe-from-scratch.ipynb)\n  - [Comparing Various Byte Pair Encoding (BPE) Implementations](ch02/02_bonus_bytepair-encoder)\n  - [Understanding the Difference Between Embedding Layers and Linear Layers](ch02/03_bonus_embedding-vs-matmul)\n  - [Dataloader Intuition with Simple Numbers](ch02/04_bonus_dataloader-intuition)\n- **Chapter 3: Coding attention mechanisms**\n  - [Comparing Efficient Multi-Head Attention Implementations](ch03/02_bonus_efficient-multihead-attention/mha-implementations.ipynb)\n  - [Understanding PyTorch Buffers](ch03/03_understanding-buffers/understanding-buffers.ipynb)\n- **Chapter 4: Implementing a GPT model from scratch**\n  - [FLOPS Analysis](ch04/02_performance-analysis/flops-analysis.ipynb)\n- **Chapter 5: Pretraining on unlabeled data:**\n  - [Alternative Weight Loading from Hugging Face Model Hub using Transformers](ch05/02_alternative_weight_loading/weight-loading-hf-transformers.ipynb)\n  - [Pretraining GPT on the Project Gutenberg Dataset](ch05/03_bonus_pretraining_on_gutenberg)\n  - [Adding Bells and Whistles to the Training Loop](ch05/04_learning_rate_schedulers)\n  - [Optimizing Hyperparameters for Pretraining](ch05/05_bonus_hparam_tuning)\n  - [Building a User Interface to Interact With the Pretrained LLM](ch05/06_user_interface)\n  - [Converting GPT to Llama](ch05/07_gpt_to_llama)\n  - [Llama 3.2 From Scratch](ch05/07_gpt_to_llama/standalone-llama32.ipynb)\n  - [Memory-efficient Model Weight Loading](ch05/08_memory_efficient_weight_loading/memory-efficient-state-dict.ipynb)\n  - [Extending the Tiktoken BPE Tokenizer with New Tokens](ch05/09_extending-tokenizers/extend-tiktoken.ipynb)\n  - [PyTorch Performance Tips for Faster LLM Training](ch05/10_llm-training-speed)\n- **Chapter 6: Finetuning for classification**\n  - [Additional experiments finetuning different layers and using larger models](ch06/02_bonus_additional-experiments)\n  - [Finetuning different models on 50k IMDB movie review dataset](ch06/03_bonus_imdb-classification)\n  - [Building a User Interface to Interact With the GPT-based Spam Classifier](ch06/04_user_interface)\n- **Chapter 7: Finetuning to follow instructions**\n  - [Dataset Utilities for Finding Near Duplicates and Creating Passive Voice Entries](ch07/02_dataset-utilities)\n  - [Evaluating Instruction Responses Using the OpenAI API and Ollama](ch07/03_model-evaluation)\n  - [Generating a Dataset for Instruction Finetuning](ch07/05_dataset-generation/llama3-ollama.ipynb)\n  - [Improving a Dataset for Instruction Finetuning](ch07/05_dataset-generation/reflection-gpt4.ipynb)\n  - [Generating a Preference Dataset with Llama 3.1 70B and Ollama](ch07/04_preference-tuning-with-dpo/create-preference-data-ollama.ipynb)\n  - [Direct Preference Optimization (DPO) for LLM Alignment](ch07/04_preference-tuning-with-dpo/dpo-from-scratch.ipynb)\n  - [Building a User Interface to Interact With the Instruction Finetuned GPT Model](ch07/06_user_interface)\n\n\u003cbr\u003e\n\u0026nbsp;\n\n## Questions, Feedback, and Contributing to This Repository\n\n\nI welcome all sorts of feedback, best shared via the [Manning Forum](https://livebook.manning.com/forum?product=raschka\u0026page=1) or [GitHub Discussions](https://github.com/rasbt/LLMs-from-scratch/discussions). Likewise, if you have any questions or just want to bounce ideas off others, please don't hesitate to post these in the forum as well.\n\nPlease note that since this repository contains the code corresponding to a print book, I currently cannot accept contributions that would extend the contents of the main chapter code, as it would introduce deviations from the physical book. Keeping it consistent helps ensure a smooth experience for everyone.\n\n\n\u0026nbsp;\n## Citation\n\nIf you find this book or code useful for your research, please consider citing it.\n\nChicago-style citation:\n\n\u003e Raschka, Sebastian. *Build A Large Language Model (From Scratch)*. Manning, 2024. ISBN: 978-1633437166.\n\nBibTeX entry:\n\n```\n@book{build-llms-from-scratch-book,\n  author       = {Sebastian Raschka},\n  title        = {Build A Large Language Model (From Scratch)},\n  publisher    = {Manning},\n  year         = {2024},\n  isbn         = {978-1633437166},\n  url          = {https://www.manning.com/books/build-a-large-language-model-from-scratch},\n  github       = {https://github.com/rasbt/LLMs-from-scratch}\n}\n```\n","funding_links":[],"categories":["Jupyter Notebook","书籍 Book","By Language","A01_文本生成_文本对话","HarmonyOS","Large Language Models (LLMs)","[🔤 pedagogy](https://github.com/stars/ketsapiwiq/lists/pedagogy)","Learning Resources","Summary","4. 算法","Repos","LLMs \u0026 Transformsers","Documentation and examples","🤖 Machine Learning \u0026 AI","LLM Courses / Education","Tutorials","Artificial Intelligence \u0026 Data Science"],"sub_categories":["Data Science","大语言对话模型及数据","Windows Manager","Contribute to our Repository","Tutorials","4.1 指令微调（SFT）","Documentation, lists, guides, or examples","Resources","Machine Learning \u0026 Neural Networks"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frasbt%2FLLMs-from-scratch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frasbt%2FLLMs-from-scratch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frasbt%2FLLMs-from-scratch/lists"}