ml-engineering README

The project's README from github.com/stas00/ml-engineering. As one markdown file: README.md.

Machine Learning Engineering Open Book

This is an open collection of methodologies, tools and step by step instructions to help with successful training and fine-tuning of large language models and multi-modal models and their inference.

This is a technical material suitable for LLM/VLM training engineers and operators. That is the content here contains lots of scripts and copy-n-paste commands to enable you to quickly address your needs.

This repo is an ongoing brain dump of my experiences training Large Language Models (LLM) (and VLMs); a lot of the know-how I acquired while training the open-source BLOOM-176B model in 2022 and IDEFICS-80B multi-modal model in 2023, and RAG models at Contextual.AI in 2024.

I've been compiling this information mostly for myself so that I could quickly find solutions I have already researched in the past and which have worked, but as usual I'm happy to share these notes with the wider ML community.

Table of Contents

Part 1. Insights

  1. The AI Battlefield Engineering - what you need to know in order to succeed.

  2. How to Choose a Cloud Provider - these questions will empower you to have a successful compute cloud experience.

  3. When Is It Worth Upgrading GPUs? - a practical framework for deciding whether a GPU generation upgrade is worth its cost, worked through on a real H200 → B200 benchmark.

Part 2. Hardware

  1. Compute - accelerators, CPUs, CPU memory.

  2. Storage - local, distributed and shared file systems.

  3. Network - intra- and inter-node networking.

Part 3. Orchestration

  1. Orchestration Systems - managing containers and resources
  2. SLURM - Simple Linux Utility for Resource Management

Part 4. Training

  1. Training - model training-related guides

Part 5. Inference

  1. Inference - model inference insights

Part 6. Development

  1. Debugging and Troubleshooting - how to debug easy and difficult issues

  2. And more debugging

  3. Testing - numerous tips and tools to make test writing enjoyable

Part 7. Miscellaneous

  1. Resources - LLM/VLM chronicles

Updates

I announce any significant updates on my twitter channel https://twitter.com/StasBekman.

Ebook versions of the book

You can download various ebook formats of this book:

I will try to rebuild these once in a few weeks or so, but if you want the latest ebook versions, the instructions for building are here.

Thanks to HuggingFace for giving me permission to host my book's ebook formats at the HF hub.

SKILL.md for AI agents

I maintain a SKILL.md file that you can use to teach your AI agent to train and operate large-scale ML models better.

See also the companion skills: The Art of Debugging and Stas' Python Cookbook.

Courses

Lectures/Talks

Discussions

If you want to discuss something related to ML engineering this repo has the community discussions available - so please don't hesitate to share your experience or start a new discussion about something you're passionate about.

Key comparison tables

High end accelerators:

Networks:

Shortcuts

Things that you are likely to need to find quickly and often.

Tools:

Guides:

Gratitude

None of this would have been possible without me being entrusted with doing the specific LLM/VLM trainings I have learned the initial know-how from. This is a privilege that only a few enjoy due to the prohibitively expensive cost of renting huge ML compute clusters. So hopefully the rest of the ML community will vicariously learn from these notes.

Special thanks go to Thom Wolf who proposed that I lead the BLOOM-176B training back when I didn't know anything about large scale training. This was the project that catapulted me into the intense learning process. And, of course, HuggingFace for giving me the opportunity to work full time on BLOOM-176B and later on IDEFICS-80B trainings.

Recently, I continued expanding my knowledge and experience while training models and building scalable training/inference systems at Contextual.AI and I'm grateful for that opportunity to Aman and Douwe.

I'd also like to thank the numerous contributors who have been making this text awesome and error-free.

Contributing

If you found a bug, typo or would like to propose an improvement please don't hesitate to open an Issue or contribute a PR.

License

The content of this site is distributed under Attribution-ShareAlike 4.0 International.

Citation

@misc{bekman2024mlengineering,
  author = {Bekman, Stas},
  title = {Machine Learning Engineering Open Book},
  year = {2023-2026},
  publisher = {Stasosphere Online Inc.},
  journal = {GitHub repository},
  url = {https://github.com/stas00/ml-engineering}
}

My repositories map

✔ Books: Machine Learning Engineering | The Art of Debugging | Stas' Python Cookbook

✔ Applications: ipyexperiments

✔ Tools and Cheatsheets: bash | conda | git | jupyter-notebook | make | python | tensorboard | unix

✔ Other Machine Learning: ML ways | Porting

ml-engineering (stas00/ml-engineering)

Searching Database…

Что это такое?Открытая книга по ML-инжинирингу: методологии, инструменты и пошаговые инструкции по обучению, дообучению (fine-tuning) и запуску инференса больших языковых моделей и мультимодальных моделей (VLM), написанная инженером, который руководил обучением BLOOM-176B.
Это книга, которую читают, или программа, которую устанавливают?Это книга, а не пакет: читайте её бесплатно на GitHub или скачайте версии в PDF и EPUB, а текст полон скриптов и готовых команд, которые вы копируете и запускаете на своих машинах.
С чего начать?Просто читайте на GitHub или скачайте PDF/EPUB с хаба HuggingFace. Есть ещё сопроводительный курс «Lessons Learned from Training LLMs», где сначала даются сжатые выводы, а углубляться можно там, где нужно.
Нужен ли мне свой GPU-кластер, чтобы получить от неё пользу?Читать бесплатно, но практическая часть — инструменты вроде torch-distributed-gpu-test.py и тесты производительности сети — рассчитана на запуск на GPU-машинах, на которых вы обучаете модели, так что один ноутбук не покроет большую её часть.
Это законченный, выверенный учебник?Нет — автор называет её постоянно пополняемым конспектом мыслей (brain dump): электронные версии пересобираются лишь раз в несколько недель, обновления анонсируются в его Twitter-канале, поэтому некоторые разделы более сырые, чем в аккуратном учебнике.
Это для новичков или для тех, кто уже запускает большие обучения?Для практикующих инженеров и операторов обучения LLM/VLM, а не для новичков в ML: книга исходит из того, что вы работаете с реальными GPU-задачами, и делится рецептами, добытыми при обучении BLOOM-176B и IDEFICS-80B, а не вводной теорией.
Могу ли я повторно использовать или распространять содержимое?Да, под лицензией CC BY-SA 4.0: можно делиться и адаптировать при условии указания авторства и распространения на тех же условиях — типично для открытой книги, но отличается от разрешительных лицензий на код, к которым вы, возможно, привыкли.
О чём на самом деле эта книга?Семь частей: инсайты (выбор облачного провайдера, когда обновлять GPU), железо (вычисления, хранилище, сеть), оркестрация включая SLURM, обучение, инференс, отладка и тестирование, плюс глава с ресурсами.
Там есть готовые к запуску инструменты?Да: allreducebench.py для бенчмаркинга пропускной способности сети проще, чем nccl-tests, torch-distributed-gpu-test.py для проверки связности между узлами и mamf-finder.py для измерения реально достижимых TFLOPS, а также шпаргалки по отладке PyTorch и по SLURM.
Можно ли использовать её, чтобы обучить мой AI-агент для кодинга?Да — в репозитории есть SKILL.md, предназначенный для обучения AI-агентов лучшему обучению и эксплуатации крупномасштабных ML-моделей, а также сопутствующие навыки: The Art of Debugging и Stas' Python Cookbook.
Поможет ли она решить, какое железо арендовать или покупать?В ней ведутся ключевые сравнительные таблицы TFLOPS ускорителей, объёма и скорости памяти, скорости сети между узлами и внутри узла, а также разбирается реальный бенчмарк H200 против B200, чтобы понять, когда апгрейд GPU окупает себя.
What are similar projects?verl, ColossalAI, transformers, halo, skypilot, airllm, EvoVLM, ms-swift
Creator
stas00
Size
27.9 MB
Stars
19.5K
Updated
CommitOct 16
Age
6y
Commits · 90 Days