To load the pretrained embedded vectors generated from genesis to torch text, you need to:

Save embedded vectors by “word2vec” format,

model = gensim.models.Word2Vec(...)
model.wv.save_word2vec_format(path_to_embeddings_file)


Then load the “word2vec” format by “Vectors” from torch text,

from torchtext.vocab import Vectors
vectors = Vectors(name=model_name, cache=path) # model_name + path = path_to_embeddings_file


You can either provide the embedded vectors when you call build_vocab function or set them later,

# provide the embedded vectors when you call build_vocab function
TEXT = data.Field(
            pad_first=True,
            batch_first=True
        ) 
TEXT.build_vocab(
            self.trn,
            max_size=self.config.vocab_maxsize,
            min_freq=self.config.vocab_minfreq,
            vectors=vectors
)

#set embedded vectors later
TEXT.build_vocab(
            self.trn,
            max_size=self.config.vocab_maxsize,
            min_freq=self.config.vocab_minfreq)
TEXT.vocab.set_vectors(vectors.stoi, vectors.vectors, vectors.dim)


Initialise nn.Embedding variable with the embedded vectors

embedding = nn.Embedding(n_embed, embed_dim).from_pretrained(TEXT.vocab.vectors)

That’s it. The torchtext vocab index will be aligned to your pretrained vectors’ index.