minGPT README

The project's README from github.com/karpathy/minGPT. As one markdown file: README.md.

minGPT

mingpt

A PyTorch re-implementation of GPT, both training and inference. minGPT tries to be small, clean, interpretable and educational, as most of the currently available GPT model implementations can a bit sprawling. GPT is not a complicated model and this implementation is appropriately about 300 lines of code (see mingpt/model.py). All that's going on is that a sequence of indices feeds into a Transformer, and a probability distribution over the next index in the sequence comes out. The majority of the complexity is just being clever with batching (both across examples and over sequence length) for efficiency.

note (Jan 2023): though I may continue to accept and change some details, minGPT is in a semi-archived state. For more recent developments see my rewrite nanoGPT. Basically, minGPT became referenced across a wide variety of places (notebooks, blogs, courses, books, etc.) which made me less willing to make the bigger changes I wanted to make to move the code forward. I also wanted to change the direction a bit, from a sole focus on education to something that is still simple and hackable but has teeth (reproduces medium-sized industry benchmarks, accepts some tradeoffs to gain runtime efficiency, etc).

The minGPT library is three files: mingpt/model.py contains the actual Transformer model definition, mingpt/bpe.py contains a mildly refactored Byte Pair Encoder that translates between text and sequences of integers exactly like OpenAI did in GPT, mingpt/trainer.py is (GPT-independent) PyTorch boilerplate code that trains the model. Then there are a number of demos and projects that use the library in the projects folder:

Library Installation

If you want to import mingpt into your project:

git clone https://github.com/karpathy/minGPT.git
cd minGPT
pip install -e .

Usage

Here's how you'd instantiate a GPT-2 (124M param version):

from mingpt.model import GPT
model_config = GPT.get_default_config()
model_config.model_type = 'gpt2'
model_config.vocab_size = 50257 # openai's model vocabulary
model_config.block_size = 1024  # openai's model block_size (i.e. input context length)
model = GPT(model_config)

And here's how you'd train it:

# your subclass of torch.utils.data.Dataset that emits example
# torch LongTensor of lengths up to 1024, with integers from [0,50257)
train_dataset = YourDataset()

from mingpt.trainer import Trainer
train_config = Trainer.get_default_config()
train_config.learning_rate = 5e-4 # many possible options, see the file
train_config.max_iters = 1000
train_config.batch_size = 32
trainer = Trainer(train_config, model, train_dataset)
trainer.run()

See demo.ipynb for a more concrete example.

Unit tests

Coverage is not super amazing just yet but:

python -m unittest discover tests

todos

References

Code:

Papers + some implementation notes:

Improving Language Understanding by Generative Pre-Training (GPT-1)

Language Models are Unsupervised Multitask Learners (GPT-2)

Language Models are Few-Shot Learners (GPT-3)

Generative Pretraining from Pixels (Image GPT)

License

MIT

minGPT (karpathy/minGPT)

Searching Database…

25K ·GitHub
Что это такое?minGPT — минимальная переписанная на PyTorch реализация GPT от OpenAI, которая охватывает и обучение, и инференс. Её написали компактной и easy-to-read, а не оптимизированной для продакшена.
Это полноценный фреймворк или маленькая эталонная библиотека?Это небольшая библиотека из трёх файлов: mingpt/model.py (трансформер), mingpt/bpe.py (токенизатор) и mingpt/trainer.py (цикл обучения), а также демонстрационные скрипты и блокноты в папке projects.
Как добавить это в свой проект?Клонируйте репозиторий и установите mingpt в свой проект по инструкции из раздела 'Library Installation', затем создайте модель GPT и Trainer, как показано в demo.ipynb.
Мне нужно что-то помимо Python?Нужен PyTorch, чтобы построить и обучить трансформер. Примечательно, что автор сам признаёт: в репозитории пока даже нет файла requirements.txt.
Этот проект всё ещё активно развивается?Нет. С января 2023 года minGPT находится в полуархивном состоянии: на него широко ссылаются в блокнотах, блогах и курсах, поэтому автор не хочет вносить крупные изменения. Для нового кода он рекомендует свою переработку nanoGPT.
Что такое nanoGPT и как он связан с minGPT?nanoGPT — это переписанная преемница minGPT от karpathy. Он появился после того, как автор решил выйти за рамки чисто учебного проекта: получился код, который остаётся простым, но воспроизводит средние по размеру отраслевые эталонные тесты и работает эффективнее.
Какие демонстрационные проекты есть в minGPT?projects/adder обучает GPT с нуля складывать числа, projects/chargpt обучает посимвольную языковую модель на входном текстовом файле, а demo.ipynb и generate.ipynb показывают базовое использование в блокнотах, в том числе загрузку предобученной GPT-2.
Как minGPT работает с токенизацией?mingpt/bpe.py заново реализует Byte Pair Encoder от OpenAI и преобразует текст в последовательности целых чисел и обратно точно так же, как это делает исходный код GPT-2.
Можно ли генерировать текст с предобученной GPT-2, а не обучать модель с нуля?Да, generate.ipynb показывает, как загрузить предобученную модель GPT-2 и генерировать продолжения текста по заданному промпту.
Creator
karpathy
Size
1.5 MB
Stars
25K
Updated
CommitJan 08
Age
6y
Commits · 90 Days