Skip to content
Medium End-to-End

Word Embedding Model

An embedding table stores one vector per vocabulary item. To represent a sequence with a single vector, look up its embeddings and average them, coordinate by coordinate. This is called mean pooling.

Your task

Implement embed_and_average(embedding_table, indices).

  • embedding_table is a floating-point tensor of shape (vocab_size, embed_dim).
  • indices has shape (seq_len,), with seq_len >= 1. Each value is a valid vocabulary ID in 0 <= id < vocab_size. The runtime supplies integer-valued floats, so convert them to an integer dtype before indexing.
  • Return a floating-point vector of shape (embed_dim,), preserving the table's dtype. Leave both inputs unchanged.
output[d] = sum(embedding_table[indices[t], d] for t in the sequence) / seq_len

Average over sequence positions, not embedding coordinates or all vocabulary rows. Repeated IDs contribute once per occurrence. There is no padding mask or special ID to skip: every supplied position counts in the denominator.

For example, with table [[2, -1], [8, 5]] and IDs [0, 0, 1], average [2, -1], [2, -1] and [8, 5] to get [4, 1]. For one ID, return that row as a vector, without a leading size-1 dimension.

The table is supplied, so this exercise does not train embeddings, tokenize text or apply a classifier. Mean pooling also discards word order: rearranging the same IDs leaves the mathematical average unchanged. Sequences with different word orders can therefore receive the same representation.