unk_init not used when passed to Vocab
Vocab takes an optional unk_init callback that should be used for initializing words that are not in the Vocabulary, but this is not actually called when e.g.:
TEXT.build_vocab(train, vectors=GloVe(name='6B', dim=300), unk_init=lambda x: torch.rand(x))
The Field object does pass the unk_init to the Vocab object, but it is not used there.
For a temporary fix, you can also do this:
def init_emb(vocab, init="randn", num_special_toks=2):
# mode="unk"|"all", all means initialize everything
emb_vectors = vocab.vectors
sweep_range = len(vocab)
running_norm = 0.
num_non_zero = 0
total_words = 0
for i in range(num_special_toks, sweep_range):
if len(emb_vectors[i, :].nonzero()) == 0:
# std = 0.5 is based on the norm of average GloVE word vectors
if init == "randn":
torch.nn.init.normal(emb_vectors[i], mean=0, std=0.5)
else:
num_non_zero += 1
running_norm += torch.norm(emb_vectors[i])
total_words += 1
print("average GloVE norm is {}, number of known words are {}, total number of words are {}".format(
running_norm / num_non_zero, num_non_zero, total_words))
I find it a bit weird that unk_init is passed around various functions and constructors as an argument. In the above example, one could pass unk_init to the GloVe constructor and everything should work (see my reference above). However, consider the following:
TEXT.build_vocab(train,
vectors=GloVe(name='6B', dim=300, unk_init=lambda x: torch.rand(x)),
unk_init=lambda x: torch.uniform(x))
Which unk_init instance should have the precedence over the other? It's not quite clear. I think that it should be possible to set unk_init only through the constructor of Vectors, i.e., I'd keep Vocab out of this. I would love to hear other opinions on this.
Ran in to this problem as well. I agree that it is unclear what should happen in the case described by @domaala in https://github.com/pytorch/text/issues/263#issuecomment-386735588 but a solution to the problem originally described could be to after the line:
https://github.com/pytorch/text/blob/28fc0556f56fb1e4e68302ec7f18d80698078fe6/torchtext/vocab.py#L158
set the value of the self.vectors.unk_init to the passed in unk_init function.