fairseq icon indicating copy to clipboard operation
fairseq copied to clipboard

loss increasing with larger input range

Open Zrachel opened this issue 9 years ago • 6 comments

When I multiply the input by sqrt(512), loss always increases, on the order of magnitude of 1e2~1e3 from the beginning of training. i.e., Only change fconv.py:

def Embedding(num_embeddings, embedding_dim, padding_idx):
    m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
    m.weight.data.normal_(0, 0.1)
    m.weight.data.mul_(math.sqrt(embedding_dim))  # I add it here
    return m

I thought the operation above only change the input's magnitude from 1e-4 to 1e-2, can you tell me why loss exploding? PS: I'm sure loss decreases normally without mul_.


Here is part of the log:

| epoch 001:   0%|                                         | 13/14254 [00:19<5:38:48,  1.43s/it, loss=1075.60 (897.77), wps=4021, wpb=5703, bsz=131, lr=0.25, clip=100%, gnorm=1689590071670.1538]
| epoch 001:   1%|3                                      | 114/14254 [02:44<5:46:16,  1.47s/it, loss=1859.97 (1038.92), wps=3977, wpb=5695, bsz=169, lr=0.25, clip=100%, gnorm=7599585518747.3330]

Zrachel avatar Oct 31 '17 06:10 Zrachel

为什么要乘这个数?

xvshiting avatar Oct 31 '17 09:10 xvshiting

That multiple may enlarge the value of both words and positional embedding Matrix.

xvshiting avatar Oct 31 '17 09:10 xvshiting

这大哥。。。我还以为author不睡觉回复这么快。。。 我知道会enlarge值域,但是后面应该怎么调呢?我想知道该加layer_norm还是咋地。

About why multiply sqrt(512).

Explain: I'm testing position encoding from transformer on fairseq-py. Here is my result:

Experiment 1: x = embed(tokens) * sqrt(512) + position encoding ---- loss exploding Experiment 2: x = embed(tokens) + position encoding/sqrt(512) ---- loss decreases normal Experiment 3: x = embed(tokens) * sqrt(512)----loss exploding Experiment 4: x = embed(tokens) + position encoding ---- loss exploding

It's obviously the range problem.

Zrachel avatar Oct 31 '17 09:10 Zrachel

Yes, you are changing the range of the embeddings which is the problem. If you want a fixed encoding for the positions, then try to set it so that the range of the position encoding is similar to how nn.Embedding is initialized, i.e., similar to normal(0, 0.1). Also, you may want to use a custom layer instead of nn.Embedding which simply outputs those fixed position features.

michaelauli avatar Oct 31 '17 23:10 michaelauli

Thank you. Is there any explanation on why input should be in a small range (normal(0, 0.1)) instead of normal(0, 1)?

Zrachel avatar Nov 01 '17 11:11 Zrachel

Those values worked well based on cross validation experiments.

michaelauli avatar Nov 05 '17 01:11 michaelauli