Training loss is decreasing while validation loss is NaN

fan_percy: <p>Hi all, I’m training a neural network with both CNN and RNN, but I found that although the training loss is consistently decreasing, the validation loss remains as NaN.</p>
<p>Here is an example:<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/a/a743fc7db37fa32d5b1e78d3bc65d2cfc56190c1.jpeg" data-download-href="https://discuss.pytorch.org/uploads/default/a743fc7db37fa32d5b1e78d3bc65d2cfc56190c1" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/2X/a/a743fc7db37fa32d5b1e78d3bc65d2cfc56190c1_2_341x500.jpeg" alt="image" data-base62-sha1="nRHoE5AM455aM2RKyxbbZBrlz4l" width="341" height="500" srcset="https://discuss.pytorch.org/uploads/default/optimized/2X/a/a743fc7db37fa32d5b1e78d3bc65d2cfc56190c1_2_341x500.jpeg, https://discuss.pytorch.org/uploads/default/optimized/2X/a/a743fc7db37fa32d5b1e78d3bc65d2cfc56190c1_2_511x750.jpeg 1.5x, https://discuss.pytorch.org/uploads/default/optimized/2X/a/a743fc7db37fa32d5b1e78d3bc65d2cfc56190c1_2_682x1000.jpeg 2x" data-dominant-color="EAEBEA"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">761×1113 418 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>Any idea why?</p>
<pre><code class="lang-auto">&gt; 
&gt; models = [model1, model2, model3]
&gt; for epoch in range(epochs):
&gt;     [model.train() for model in models]
&gt;     for i, (data, label) in enumerate(dataloader_train):
&gt;         data = Variable(data).cuda().float()
&gt;         label = torch.squeeze(label)
&gt;         label = Variable(label).cuda().float()
&gt;         # CNN + RNN
&gt;         batch_size, timesteps, C, H, W = data.size()
&gt;         c_in = data.view(batch_size * timesteps, C, H, W)
&gt;         c_out = model1(c_in)
&gt;         _, C, H, W = c_out.size()
&gt;         c_out = c_out.view(batch_size, timesteps, C, H, W)
&gt;         r_out = model2(c_out)
&gt;         pred = model3(r_out)
&gt;         pred = torch.sigmoid(pred)
&gt;         # training loss update
&gt;         loss = criterion(pred, label)
&gt;         optimizer.zero_grad()
&gt;         loss.backward()
&gt;         optimizer.step()
&gt;         train_losses.append(loss.item())
&gt;         if (i + 1) % 10 == 0:
&gt;             print('Epoch:', epoch, 'Iter', i, 'Loss:', loss.item())

&gt;     [model.eval() for model in models]
&gt;     with torch.no_grad():
&gt;         for i, (data, label) in enumerate(dataloader_valid):
&gt;             data = Variable(data).cuda().float()
&gt;             label = torch.squeeze(label)
&gt;             label = Variable(label).cuda().float()
&gt;             # CNN + RNN
&gt;             batch_size, timesteps, C, H, W = data.size()
&gt;             c_in = data.view(batch_size * timesteps, C, H, W)
&gt;             c_out = model1(c_in)
&gt;             _, C, H, W = c_out.size()
&gt;             c_out = c_out.view(batch_size, timesteps, C, H, W)
&gt;             r_out = model2(c_out)
&gt;             pred = model3(r_out)
&gt;             pred = torch.sigmoid(pred)
&gt;             # validation loss update
&gt;             loss = criterion(pred, label)
&gt;             valid_losses.append(loss.item())
</code></pre>
<p>Here is a snippet of training and validation, I’m using a combined CNN+RNN network, model 1,2,3 are encoder, RNN, decoder respectively.</p>

JuanFMontesinos: <p>Could you check you are not introducing nans as input?</p>

fan_percy: <p>Actually I randomly split the data into training and validation set, so I don’t think it is the problem with the input, since the training loss is decreasing.</p>

charan_Vjy: <p>Can you post a code snippet of the Training and Validation?</p>

fan_percy: <p>Hi, I’ve posted a snippet, please take a look.</p>

charan_Vjy: <p>The code looks good.</p>
<ol>
<li>Since the code for train and test is the exact same, the bug had to be introduced during the data preprocessing or splitting. Do you keep a fixed random state while splitting your data? Can you show the code for how you have split the data, trainloader and testloader?</li>
</ol>

fan_percy: <pre><code class="lang-auto">input_list = sorted(glob.glob(os.path.join(dataset_dir, "input/*.npy")))
output_list = sorted(glob.glob(os.path.join(dataset_dir, "output/*.npy")))

X_train, X_valid, y_train, y_valid = train_test_split(input_list, output_list, test_size=0.3, random_state=42)
scaler = pickle.load(open(scaler_path, 'rb'))

X_train, X_valid, y_train, y_valid = train_test_split(input_list, output_list, test_size=0.3, random_state=42)
scaler = pickle.load(open(scaler_path, 'rb'))

train_dataset = RFFullDataset3d(X_train, y_train, scaler)
valid_dataset = RFFullDataset3d(X_valid, y_valid, scaler)

dataloader_train = DataLoader(train_dataset, 32, shuffle=True)
dataloader_valid = DataLoader(valid_dataset, 32, shuffle=True)
</code></pre>
<p>Here is how I split and load the train/valid data, I tried different random state and they all have the same issue.</p>

charan_Vjy: <p>Give the test inputs as random inputs and then give all zeros as inputs and see if you get Nan as the loss in both the cases. This will help localize the error.</p>

fan_percy: <p>Thank you very much for your advice,  I will check it.</p>

charan_Vjy: <p>Do let me know what the error is, if you find it.</p>

fan_percy: <p>Sure, of course.<img src="https://discuss.pytorch.org/images/emoji/apple/grinning.png?v=9" title=":grinning:" class="emoji" alt=":grinning:"></p>

fan_percy: <p>I tried different data patterns and the problem didn’t occur anymore. I also tried to clip the gradient in the RNN and found that it worked. So I guess it is probably a explosive gradient problem, but I couldn’t figure out why only the valid loss is NaN…</p>

JuanFMontesinos: <p>There are no gradients on validation… It’s better you to find which sample equals NaN and check why rather than randomly changing stuff</p>

charan_Vjy: <p>Would have to agree with Juan. There are no gradients during validation. I still feel it is something to do with the specific test data that you put in.</p>

SivaHemanth24: <p>i too faced the same issue in LSTM while working with text input. Turns out my sequence length is too much and input is very small. so it is actually skipping the validation calculation steps</p>

prat: <p>Hi, for me, Test inputs of 0 are also giving nan output. What does this signify then? I am having the same problem with CNN + RNN, only the validation loss is nan and not train loss. Training proceeds normally. Even with the lstm layer removed I get nan as output.</p>

yfflood: <p>Similar issue for me lol, setting a batch size too large may lead to the same problem</p>