TorchLean API

NN.API.Models.Gpt2

Causal Transformer Models #

This module defines the model structure shared by TorchLean's causal language-model examples. It supports one-hot inputs and integer token tensors, with either an independent vocabulary head or a projection tied to the token-embedding table. Tokenization and checkpoint formats live in their respective API modules.

Configuration shared by TorchLean's GPT-style causal language models.

The model has the common GPT-2 “shape”:

embedding → learned positional embedding → (masked self-attention + FFN)×layers → LayerNorm → linear

The configuration is independent of how token ids enter the model. One-hot, integer-token, and pre-embedded constructors reuse the same Transformer width, depth, and output vocabulary.

  • batch :
  • seqLen :
  • vocab :
  • numHeads :
  • headDim :
  • ffnHidden :
  • layers :
  • activation : blocks.Activation

    Feed-forward activation used in every Transformer block.

  • dropout? : Option Float

    Dropout probability for attention and feed-forward outputs.

  • normFirst : Bool

    Use pre-normalized Transformer blocks.

  • attentionOutputBias : Bool

    Add a trainable bias after each attention output projection.

  • Shared initialization for embedding and projection weights. none keeps layer defaults.

  • residualProjectionInit? : Option Runtime.Autograd.Torch.Init.Scheme

    Initialization for projections whose outputs are added to residual streams.

    GPT-2 scales these weights by network depth. Keeping the setting explicit lets other causal Transformers use their own residual initialization without changing the block implementation.

  • seedStride :

    Seed stride used when initializing repeated blocks.

Instances For
    @[reducible, inline]

    Vocabulary-grid shape (batch × seqLen × vocab) used by one-hot inputs and output logits.

    Instances For
      @[reducible, inline]

      Embedded-token tensor shape (batch × seqLen × dModel).

      Instances For
        def TorchLean.nn.models.causalTransformerHiddenFromEmbeddings (cfg : CausalTransformerConfig) (h_seqLen : cfg.seqLen 0 := by decide) (h_dModel : cfg.dModel 0 := by decide) :

        Causal Transformer hidden-state stack after token embeddings have been computed.

        The stack adds learned positions, applies causally masked Transformer blocks, and finishes with LayerNorm. It deliberately has no vocabulary projection. Language models can therefore choose an independent output head or reuse their token-embedding matrix.

        Instances For
          def TorchLean.nn.models.causalTransformerFromEmbeddings (cfg : CausalTransformerConfig) (h_seqLen : cfg.seqLen 0 := by decide) (h_dModel : cfg.dModel 0 := by decide) :

          GPT-style causal Transformer body with an independent affine vocabulary head.

          Use causalTransformerHiddenFromEmbeddings when the caller needs hidden states or a tied token-embedding/output matrix.

          Instances For
            def TorchLean.nn.models.causalTransformerOneHot (cfg : CausalTransformerConfig) (h_seqLen : cfg.seqLen 0 := by decide) (h_dModel : cfg.dModel 0 := by decide) :

            Build a GPT-2-style causal language model over one-hot tokens.

            This is the shared constructor used by the runnable GPT-2 examples. It stays in nn.M so it composes with the rest of the API-layer model-building interface.

            Instances For
              @[reducible, inline]

              Flattened shape of one batch of token ids or row weights.

              Instances For
                @[reducible, inline]

                Parameter shapes for an indexed-token model with an independent vocabulary head.

                Instances For

                  Run indexed-token embedding and a causal Transformer body in any TorchLean backend.

                  Tokens remain Nat tensors throughout the call. Only the embedding table and Transformer parameters use the model scalar type, so the program cannot differentiate with respect to token ids or reinterpret them as floating-point data.

                  Instances For
                    @[reducible, inline]

                    Parameter shapes for an indexed-token model whose embedding and output projection are tied.

                    Instances For

                      Run a causal Transformer whose token lookup and vocabulary projection share one matrix.

                      The matrix has shape (vocab, dModel). The forward pass gathers its rows to construct the input embeddings, runs the hidden-state Transformer, and multiplies the final hidden states by its transpose. Consequently, gradients from both lookup and prediction accumulate into the same parameter.

                      Instances For

                        Scalar loss for causal language modeling with integer token ids.

                        The public one-hot constructor above is useful for small teaching examples because the input is an ordinary Float tensor. File-backed tokenized datasets use the representation found in language-model training systems: token ids are Nats, the embedding table is a trainable Float parameter, and the loss gathers the target classes directly instead of building one-hot targets.

                        tokens and targets are flattened (batch * seqLen) vectors. This matches the backend gather ops and keeps dataset storage simple; the embedding helper reshapes gathered rows back to (batch, seqLen, dModel) before running the Transformer body.

                        Instances For