Skip to content

[已解決][PyTorch] return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse) RuntimeError: index out of range: Tried to access index 5 out of table with 4 rows. at /pytorch/aten/src/TH/generic/THTensorEvenMoreMath.cpp:237

今天我在使用 PyTorch 當中的 nn.Embedding 時,由於我誤會了 nn.Embedding 的使用方法,故出現了以下報錯:

return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse) 
RuntimeError: index out of range: Tried to access index 5 out of table with 4 rows.
at /pytorch/aten/src/TH/generic/THTensorEvenMoreMath.cpp:237

花費了我好一番功夫,我才終於搞明白自己錯在哪 —— 這算是我在學習 PyTorch 的過程中,數一數二沒有頭緒的報錯。不過讓我為自己小小辯解一下,我昨天只有睡兩個小時,著實很累,哈哈哈。

根據我的經驗,我自己紀錄下來的 PyTorch 報錯解決方法,通常我自己一定會再來查看第二遍,有點可撥。不過如果真的是我很熟知要怎麼解決的問題,那我想我根本不會有想要紀錄下來的衝動就是了,哈哈哈。

話題扯遠了,以下就來看看這個報錯發生的過程吧。


問題描述

我的問題發生得非常簡單,簡單來說,就是我在測試以下這樣的程式碼:

embedding = nn.Embedding(5, 3, padding_idx=0)
inputs = torch.tensor([1, 2, 3, 4, 5])
print(embedding(inputs))



正當我志得意滿、滿心以為接下來我就會得到一串形狀為 [5, 3] 的向量的時候,我反而得到了以下報錯:

return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse) 
RuntimeError: index out of range: Tried to access index 5 out of table with 4 rows.
at /pytorch/aten/src/TH/generic/THTensorEvenMoreMath.cpp:237

查了老半天,我才終於發現自己的問題所在。

看看官方的文檔,在輸入文字的時候,我應該要事先『詞彙』轉換成『數值』,這很明確,可是我搞錯了 “num_embeddings” 的意思。直覺上,我以為 num_embeddings 是指我輸入的字串應該要有的詞量維度,比方說我的輸入為:

Today is a nice day

那麼我的輸入就是 5 個詞。轉換成數值之後可能為:

[1, 2, 3, 4, 5]

輸入 embedding 之後,就會出現錯誤了!

其實,問題真的很單純:num_embedding 並不是指當前輸入的字串長度,而是所有相異字的 Index 應有的數量,而且是從 0 開始編號 —— 所以,如果是以下 embedding:

embedding = nn.Embedding(5, 3, padding_idx=0)

那麼,輸入的 Index 就只能在 [0, 4] 之間了。

強烈建議,在使用 nn.Embedding() 前,先確認自己字典的維度。


References


Read More

2 thoughts on “[已解決][PyTorch] return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse) RuntimeError: index out of range: Tried to access index 5 out of table with 4 rows. at /pytorch/aten/src/TH/generic/THTensorEvenMoreMath.cpp:237”

Leave a Reply