Complete worked example
python
from bootstrap_lab import torch_setup
torch = torch_setup()
from torch import nn
def pooled_tokens(token_ids):
ids = torch.tensor(token_ids, dtype=torch.long)
if ids.ndim != 2 or ids.shape[1] == 0:
raise ValueError('padded token matrix required')
embedding = nn.Embedding(4, 2, padding_idx=0)
with torch.no_grad():
embedding.weight.copy_(torch.tensor([[0.,0.],[1.,2.],[3.,4.],[5.,6.]]))
vectors = embedding(ids)
mask = (ids != 0).unsqueeze(-1)
total = (vectors * mask).sum(dim=1)
count = mask.sum(dim=1).clamp_min(1)
return (total / count).tolist()- Reasoning
- The fixture defines a four-row, two-feature embedding with known values and padding id zero. It looks up vectors, builds a non-padding mask, sums real-token vectors and divides by the real-token count.