Skip the Multiplication

Sequential DataEasy+10 XP+10

Skip the Multiplication

A colleague's pipeline one-hot encodes every token before it reaches the embedding layer. A sentence of nnn tokens arrives as an n×Vn \times Vn×V matrix XXX — one row per token, where VVV is the vocabulary size — and the layer multiplies it by the V×dV \times dV×d embedding table EEE:

(XE)ij=∑k=0V−1Xik Ekj(XE)_{ij} = \sum_{k=0}^{V-1} X_{ik}\, E_{kj}(XE)ij​=k=0∑V−1​Xik​Ekj​

With VVV in the tens of thousands, that sum is enormous for every single entry of the result, and almost every term in it is zero.

Task: write embed(one_hot_rows, table) that returns exactly the n×dn \times dn×d matrix XEXEXE — without carrying out the multiplication.

  • one_hot_rows is XXX, as a list of rows. A token's row has a single 1 and zeros everywhere else.
  • Padding slots arrive as a row of all zeros (that is how this pipeline encodes <PAD>). Your output for them must still be whatever XEXEXE gives.
  • table is EEE, as a list of VVV rows — one row per vocabulary entry, each of length ddd.

Return a list of nnn lists, with every entry rounded to 4 decimal places.

0.70
0.20
-0.40
0.60

The embedding layer is nothing but a lookup table — one row per vocabulary entry. Feeding in a word ID just reads that row.

Examples

one_hot_rows = [[0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 1, 0]]
table = [[0.12, -0.5], [0.8, 0.31], [-0.27, 0.66], [0.05, 0.9]]
returns [[-0.27, 0.66], [0.12, -0.5], [-0.27, 0.66]]
one_hot_rows = [[0, 1, 0], [0, 0, 1]]
table = [[1.5, -0.25, 0.75], [0.0, 2.0, -1.0], [-0.6, 0.4, 0.2]]
returns [[0.0, 2.0, -1.0], [-0.6, 0.4, 0.2]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run