TorchLean API

NN.Spec.Layers.Embedding

Embeddings #

An embedding is a table whose rows are indexed by a finite vocabulary. The primary definition in this file uses Fin vocab, so an invalid token id cannot be supplied to the mathematical model. The one-hot presentation is retained as a differentiable linear map and is useful when comparing an indexed lookup with matrix multiplication.

References / analogies:

structure Spec.Embedding (vocab embedDim : ℕ) (α : Type) [TorchLean.Storage α] :

A trainable table with vocab rows of width embedDim.

  • weight : TorchLean.Tensor α [vocab, embedDim]

    Embedding table, stored row-major by executable backends.

Instances For
    def Spec.Embedding.lookup {α : Type} [TorchLean.Storage α] {vocab embedDim : ℕ} (embedding : Embedding vocab embedDim α) {shape : Shape} :
    TorchLean.Tensor (Fin vocab) shape → TorchLean.Tensor α (shape.appendDim embedDim)

    Look up every finite index in a tensor and append the embedding dimension to its shape.

    The index type is Fin vocab, rather than Nat, so this specification has no out-of-range case. File and tokenizer boundaries may begin with natural-number identifiers, but executable APIs must validate them before interpreting them as indices into this table.

    Instances For
      def Spec.Embedding.oneHot {α : Type} [TorchLean.Storage α] [Add α] [Mul α] [Zero α] {vocab embedDim seqLen : ℕ} (embedding : Embedding vocab embedDim α) (oneHot : TorchLean.Tensor α [seqLen, vocab]) :
      TorchLean.Tensor α [seqLen, embedDim]

      Embed a batch/sequence of one-hot vectors:

      oneHot : (seqLen × vocab) and W : (vocab × embedDim) gives (seqLen × embedDim).

      Instances For

        Gradients #

        Embedding.oneHot is matrix multiplication:

        Y = oneHot @ weight.

        So the reverse-mode derivatives are the standard ones:

        Even though "true" one-hot tensors are often treated as non-differentiable in practice, having a named VJP is useful for:

        def Spec.Embedding.oneHotVjp {α : Type} [TorchLean.Storage α] [Add α] [Mul α] [Zero α] {vocab embedDim seqLen : ℕ} (embedding : Embedding vocab embedDim α) (oneHot : TorchLean.Tensor α [seqLen, vocab]) (dY : TorchLean.Tensor α [seqLen, embedDim]) :
        TorchLean.Tensor α [seqLen, vocab] × TorchLean.Tensor α [vocab, embedDim]

        VJP for Embedding.oneHot, returning gradients for the input and table.

        Instances For