TorchLean API

NN.Examples.Models.Sequence.CharGpt

Char-GPT (minGPT-style) Example #

This example follows the character-level Transformer from Andrej Karpathy's "Let's build GPT: from scratch, in code, spelled out" lecture:

The karpathy preset follows the lecture configuration: batch size 64, context length 256, width 384, six attention heads, six pre-normalized Transformer blocks, ReLU feed-forward layers, dropout 0.2, AdamW, and 5,000 updates. The CUDA command executes the numerical path in float32. TorchLean applies dropout to the attention and feed-forward sublayer outputs; unlike the lecture code, it does not yet apply a second dropout to the attention weights themselves. All dimensions remain command-line choices.

Training draws a fresh deterministic batch of corpus windows at every step. The windows are built on demand, so a long run does not retain thousands of large one-hot tensors in host memory.

Unlike the introductory model examples, this file intentionally uses the low-level Module API. The indexed objective receives token IDs while the model parameters and loss use floating-point storage, so it crosses a mixed-dtype boundary that the homogeneous Trainer interface does not express. Ordinary floating-point models should use Trainer.new and trainer.train.

Quick check:

lake -R -K cuda=true build torchlean:exe
lake -R -K cuda=true exe torchlean chargpt --device cuda --tiny-shakespeare --preset smoke

Full lecture experiment:

lake -R -K cuda=true exe torchlean chargpt --device cuda --tiny-shakespeare --preset karpathy

Reference: https://github.com/karpathy/ng-video-lecture/blob/master/gpt.py.

CLI subcommand name used in terminal banners and error messages.

Instances For

    Parse corpus flags and return the UTF-8 training text plus remaining CLI arguments.

    Instances For

      Build a deterministic character alphabet from the corpus.

      Instances For

        Default JSON loss-curve path for this command.

        Instances For

          Architecture and evaluation controls independent of the corpus and runtime device.

          • modelWidth :
          • attentionHeads :
          • transformerLayers :
          • dropoutProbability : Float
          • trainingSteps :
          • batchSize :
          • contextLength :
          • learningRate : Float
          • evalEvery :
          • evaluationBatches :
          • generationLength :
          Instances For

            Fast configuration used to validate the complete training and generation path.

            Instances For

              Hyperparameters from Karpathy's final Tiny Shakespeare lecture model.

              Instances For

                Resolve a --preset name. smoke is the fast configuration used in CI; karpathy reproduces the hyperparameters from the nanoGPT character-level Shakespeare run.

                Instances For

                  Help text for character-level GPT training.

                  Instances For

                    Command-local controls for CharGPT training, checkpointing, and generation.

                    Instances For

                      Parse training controls after the experiment preset has supplied defaults.

                      Instances For

                        Decode token ids for terminal output with control characters escaped.

                        Instances For

                          Printable-ASCII generation filter used by --ascii-only.

                          Instances For
                            @[reducible, inline]
                            abbrev NN.Examples.Models.Sequence.CharGpt.Predictor (α : Type) (batchSize contextLength vocabularySize : ) :

                            Fitted predictor for a runtime-sized character GPT model.

                            Instances For
                              def NN.Examples.Models.Sequence.CharGpt.generateSampledFromIds {α : Type} {promptLength : } (toFloat : αFloat) (batchSize contextLength vocabularySize : ) [NeZero vocabularySize] (predict : Predictor α batchSize contextLength vocabularySize) (promptTokens : TorchLean.Tensor (Fin vocabularySize) [promptLength]) (steps : ) (temperature : Float) (topK seed repeatWindow : ) (repeatPenalty : Float) (allowToken : Fin vocabularySizeBool := fun (x : Fin vocabularySize) => true) (paddingTokenId : Fin vocabularySize := 0) :
                              IO (TorchLean.Tensor (Fin vocabularySize) [promptLength + steps])

                              Autoregressively extend character token ids using a trained CharGPT model.

                              Instances For

                                CLI entrypoint for character-level GPT training and sampling.

                                Instances For