import torch
import torch.nn as nn
weight = torch.FloatTensor([[1, 2, 3], [4, 5, 6]])
embedding_sum = nn.EmbeddingBag.from_pretrained(weight, mode='sum')
print(embedding_sum.weight)
""" output
Parameter containing:
tensor([[1., 2., 3.],
[4., 5., 6.]])
"""
input = torch.LongTensor([0, 1])
offsets = torch.LongTensor([0, 1, 2, 1])
According to these offsets you will get the following samples
"""
sample_1: input[0:1] # tensor([0])
sample_2: input[1:2] # tensor([1])
sample_3: input[2:1] # tensor([])
sample_4: input[1:] # tensor([1])
"""
Embedding the samples above
# tensor([0]) => lookup 0 => embedding_sum.weight[0] => [1., 2., 3.]
# tensor([1]) => lookup 1 => embedding_sum.weight[1] => [4., 5., 6.]
# tensor([]) => empty bag => [0., 0., 0.]
# tensor([1]) => lookup 1 => embedding_sum.weight[1] => [4., 5., 6.]
print(embedding_sum(input, offsets))
""" output
tensor([[1., 2., 3.],
[4., 5., 6.],
[0., 0., 0.],
[4., 5., 6.]])
"""
One more example:
input = torch.LongTensor([0, 1])
offsets = torch.LongTensor([0, 1, 0])
According to these offsets you will get the following samples
"""
sample_1: input[0:1] # tensor([0])
sample_2: input[1:0] # tensor([])
sample_3: input[0:] # tensor([0, 1])
"""
Embedding the samples above
# tensor([0]) => lookup 0 => embedding_sum.weight[0] => [1., 2., 3.]
# tensor([]) => empty bag => [0., 0., 0.]
# tensor([0, 1]) => lookup 0 and 1 then reduce by sum
# => embedding_sum.weight[0] + embedding_sum.weight[1] => [5., 7., 9.]
print(embedding_sum(input, offsets))
""" output
tensor([[1., 2., 3.],
[0., 0., 0.],
[5., 7., 9.]])
"""