Skip to content

← Neural Network Layers step 5 of 9

Easy Primitives

Implement Embedding Lookup

An embedding table stores one vector per item, such as a token in a vocabulary. An integer ID selects a row of that table. A lookup retrieves the stored numbers; it does not compute a new vector from the ID itself.

For the table [[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]] and IDs [2, 0, 2], return [[0.5, 0.6], [0.1, 0.2], [0.5, 0.6]]. Preserve the requested order and repeat a row whenever its ID appears again.

Your task

Implement embedding_lookup(weight, indices):

  • weight is a floating-point table of shape (V, D), with positive vocabulary size V and embedding dimension D.
  • indices is a 1D integer tensor of shape (S,). Every ID is in [0, V - 1]; no handling for negative or out-of-range IDs is required.
  • Return a tensor of shape (S, D), with output row i equal to weight[indices[i]].

Use tensor indexing rather than a built-in embedding layer. Do not sort, deduplicate, sum, or average the selected vectors. Keep both output axes, even when S=1 or D=1. An empty index vector returns shape (0, D). The supplied table is already populated; you do not initialize or train it.