Embedding
_PaddedTableEmbedding(num_embeddings: int, embedding_dim: int, padding_idx: int | None = None, max_norm: float | None = None, norm_type: float = 2.0, scale_grad_by_freq: bool = False, sparse: bool = False, _weight: Tensor | None = None, _freeze: bool = False, device: DeviceLike = None, dtype: DTypeLike = None)Implementing kernel
C++ engine symbols that back this Python API.Learnable dense lookup table that maps integer token indices to vectors.
An embedding table is a matrix
where = num_embeddings (vocabulary size) and
= embedding_dim. The forward pass is a simple index
operation:
Each row is the dense representation (embedding vector) of token . Because indexing is not differentiable with respect to the integer indices themselves, gradients flow only into the rows of that were selected during the forward pass.
Padding index. When padding_idx is set, the corresponding
row is initialised to zero and its gradient is masked to zero during
backpropagation. This is the standard way to mark a special
<PAD> token whose embedding should never influence the model.
Max-norm renormalisation. When max_norm is set, every row
looked up whose -norm exceeds max_norm is rescaled
in place at each forward call before the lookup:
Parameters
num_ embeddingsintembedding_ dimintpadding_ idxint or None= Nonepadding_idx + num_embeddings. Default: None.max_ normfloat or None= NoneNone.norm_ typefloat= 2.0max_norm.
Default: 2.0.scale_ grad_ by_ freqbool= Falsebackward() are each scaled by their own. Default: False.sparsebool= FalseTrue raises
NotImplementedError at the first forward. Default: False.deviceDeviceLike= NonedtypeDTypeLike= NoneAttributes
weightParameter, shape (num_embeddings, embedding_dim)padding_idx is set, that
row is zeroed immediately after initialisation.Notes
- Input
x:(*)— integer tensor of arbitrary shape with values in[0, num_embeddings). - Output:
(*, embedding_dim)— the input shape with an extra trailing dimension of sizeembedding_dim.
The weight matrix is initialised from a standard normal distribution , which gives each embedding a unit-order magnitude. For downstream layers that are sensitive to input scale (e.g. transformers), consider dividing by after construction.
An index outside [0, num_embeddings) differs by device. On
the CPU it raises IndexError. On Metal the index is never read
back (that would stall every step), so the row it names reads as NaN
and the loss turns NaN far from its cause. Set the environment
variable LUCID_STRICT_INDEX=1 (before the call, or in
os.environ) to have Metal raise the same IndexError; it costs a
host read of the index on every lookup, so it is meant for finding a
bad label, not for the training loop. Unset, or 0, Metal behaves
as before and pays nothing.
Embedding is commonly used in natural-language processing (token embeddings, position encodings), recommendation systems (item / user embeddings), and any domain where discrete categorical inputs must be projected into a continuous representation space.
Examples
Simple token embedding for a vocabulary of 100 with 16-dim vectors:
>>> import lucid, lucid.nn as nn
>>> emb = nn.Embedding(num_embeddings=100, embedding_dim=16)
>>> idx = lucid.tensor([[1, 5, 3], [0, 2, 7]], dtype=lucid.int64)
>>> y = emb(idx)
>>> y.shape # (2, 3, 16)
(2, 3, 16)
Using padding_idx to mark a <PAD> token (index 0):
>>> emb_pad = nn.Embedding(50, 8, padding_idx=0)
>>> # Row 0 is always zero and never updated
>>> import lucid.linalg
>>> float(lucid.linalg.norm(emb_pad.weight[0])) == 0.0
True
>>> idx2 = lucid.tensor([0, 3, 0, 7], dtype=lucid.int64)
>>> emb_pad(idx2).shape
(4, 8)See Also
EmbeddingBag—Efficient embedding lookup with per-bag reduction.
Used by 1
Constructors
1__init__
→None__init__(num_embeddings: int, embedding_dim: int, padding_idx: int | None = None, max_norm: float | None = None, norm_type: float = 2.0, scale_grad_by_freq: bool = False, sparse: bool = False, _weight: Tensor | None = None, _freeze: bool = False, device: DeviceLike = None, dtype: DTypeLike = None)Initialise the Embedding module. See the class docstring for parameter semantics.
Class methods
1from_pretrained(embeddings: Tensor, freeze: bool = True, padding_idx: int | None = None, max_norm: float | None = None, norm_type: float = 2.0, scale_grad_by_freq: bool = False, sparse: bool = False)Build an Embedding whose table is embeddings.
Parameters
embeddingsTensor(num_embeddings, embedding_dim). The table is bound without
a copy, so an in-place write through either is seen by both.freezebool= TrueTrue keeps the table out of training
(weight.requires_grad = False). Default: True.padding_ idxint or None= Noneembeddings; it only stops gradient reaching that row.max_ normfloat or None= NoneNone.norm_ typefloat= 2.02.0.scale_ grad_ by_ freqbool= FalseFalse.sparsebool= FalseFalse.Returns
EmbeddingThe module.
Raises
ValueErrorembeddings is not 2-D.Examples
>>> import lucid, lucid.nn as nn
>>> weight = lucid.tensor([[1.0, 2.3, 3.0], [4.0, 5.1, 6.3]])
>>> emb = nn.Embedding.from_pretrained(weight)
>>> emb(lucid.tensor([1], dtype=lucid.int64))
tensor([[4., 5.1, 6.3]])
>>> emb.weight.requires_grad
FalseInstance methods
3Return a string representation of the layer's configuration.
Re-draw weight from N(0, 1) and zero the padding row.