RNN predict function predicting the unknown token as the next character for all characters

Lost_Wanderer: <p>Hello PyTorch users,</p>
<p>I have been trying to solve Exercise 3, Chapter 8.5 from Dive into Deep Learning book. I got stuck on that exercise and I was hoping you can help me. I will explain the exercise below.</p>
<p>Exercise goes as follows:</p>
<blockquote>
<p>Modify the prediction function such as to use sampling rather than picking the most likely next character.</p>
<pre><code>What happens?
</code></pre>
</blockquote>
<p>I tried to do that. Below is the original code from the book, which works as expected (the training goes well). I separated every code cell in its code block.</p>
<pre><code class="lang-auto">%matplotlib inline
import math
import torch
from torch import nn
from torch.nn import functional as F
from d2l import torch as d2l
</code></pre>
<pre><code class="lang-auto">batch_size, num_steps = 32, 35
train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps)
</code></pre>
<pre><code class="lang-auto">def get_params(vocab_size, num_hiddens, device):
    num_inputs = num_outputs = vocab_size

    def normal(shape):
        return torch.randn(size=shape, device=device) * 0.01

    # Hidden layer parameters
    W_xh = normal((num_inputs, num_hiddens))
    W_hh = normal((num_hiddens, num_hiddens))
    b_h = torch.zeros(num_hiddens, device=device)
    # Output layer parameters
    W_hq = normal((num_hiddens, num_outputs))
    b_q = torch.zeros(num_outputs, device=device)
    # Attach gradients
    params = [W_xh, W_hh, b_h, W_hq, b_q]
    for param in params:
        param.requires_grad_(True)
    return params
</code></pre>
<pre><code class="lang-auto">def init_rnn_state(batch_size, num_hiddens, device):
    return (torch.zeros((batch_size, num_hiddens), device=device),)
</code></pre>
<pre><code class="lang-auto">def rnn(inputs, state, params):
    # Here `inputs` shape: (`num_steps`, `batch_size`, `vocab_size`)
    W_xh, W_hh, b_h, W_hq, b_q = params
    H, = state
    outputs = []
    # Shape of `X`: (`batch_size`, `vocab_size`)
    for X in inputs:
        H = torch.tanh(torch.mm(X, W_xh) + torch.mm(H, W_hh) + b_h)
        Y = torch.mm(H, W_hq) + b_q
        outputs.append(Y)
    return torch.cat(outputs, dim=0), (H,)
</code></pre>
<pre><code class="lang-auto">class RNNModelScratch:  #@save
    """A RNN Model implemented from scratch."""
    def __init__(self, vocab_size, num_hiddens, device, get_params,
                 init_state, forward_fn):
        self.vocab_size, self.num_hiddens = vocab_size, num_hiddens
        self.params = get_params(vocab_size, num_hiddens, device)
        self.init_state, self.forward_fn = init_state, forward_fn

    def __call__(self, X, state):
        X = F.one_hot(X.T, self.vocab_size).type(torch.float32)
        return self.forward_fn(X, state, self.params)

    def begin_state(self, batch_size, device):
        return self.init_state(batch_size, self.num_hiddens, device)
</code></pre>
<pre><code class="lang-auto">def predict_ch8(prefix, num_preds, net, vocab, device):  #@save
    """Generate new characters following the `prefix`."""
    state = net.begin_state(batch_size=1, device=device)
    outputs = [vocab[prefix[0]]]
    get_input = lambda: torch.tensor([outputs[-1]], device=device).reshape(
        (1, 1))
    for y in prefix[1:]:  # Warm-up period
        _, state = net(get_input(), state)
        outputs.append(vocab[y])
    for _ in range(num_preds):  # Predict `num_preds` steps
        y, state = net(get_input(), state)
        print("int(y.argmax(dim=1).reshape(1)):")
        print(int(y.argmax(dim=1).reshape(1)))
        outputs.append(int(y.argmax(dim=1).reshape(1)))
    return ''.join([vocab.idx_to_token[i] for i in outputs])
</code></pre>
<p>Now take a look at the next code cell and its output right after it (again, this is the code from the book):</p>
<p><code>predict_ch8('time traveller ', 10, net, vocab, d2l.try_gpu())</code></p>
<pre><code class="lang-auto">int(y.argmax(dim=1).reshape(1)):
16
int(y.argmax(dim=1).reshape(1)):
9
int(y.argmax(dim=1).reshape(1)):
27
int(y.argmax(dim=1).reshape(1)):
7
int(y.argmax(dim=1).reshape(1)):
18
int(y.argmax(dim=1).reshape(1)):
20
int(y.argmax(dim=1).reshape(1)):
12
int(y.argmax(dim=1).reshape(1)):
1
int(y.argmax(dim=1).reshape(1)):
16
int(y.argmax(dim=1).reshape(1)):
9

'time traveller autovkurho'
</code></pre>
<p>The non-sensical output is expected, but note that there are different letters present in the output. Now follows the rest of the code from the book:</p>
<pre><code class="lang-auto">def grad_clipping(net, theta):  #@save
    """Clip the gradient."""
    if isinstance(net, nn.Module):
        params = [p for p in net.parameters() if p.requires_grad]
    else:
        params = net.params
    norm = torch.sqrt(sum(torch.sum((p.grad**2)) for p in params))
    if norm &gt; theta:
        for param in params:
            param.grad[:] *= theta / norm
</code></pre>
<pre><code class="lang-auto">#@save
def train_epoch_ch8(net, train_iter, loss, updater, device, use_random_iter):
    """Train a net within one epoch (defined in Chapter 8)."""
    state, timer = None, d2l.Timer()
    metric = d2l.Accumulator(2)  # Sum of training loss, no. of tokens
    for X, Y in train_iter:
        if state is None or use_random_iter:
            # Initialize `state` when either it is the first iteration or
            # using random sampling
            state = net.begin_state(batch_size=X.shape[0], device=device)
        else:
            if isinstance(net, nn.Module) and not isinstance(state, tuple):
                # `state` is a tensor for `nn.GRU`
                state.detach_()
            else:
                # `state` is a tuple of tensors for `nn.LSTM` and
                # for our custom scratch implementation
                for s in state:
                    s.detach_()
        y = Y.T.reshape(-1)
        X, y = X.to(device), y.to(device)
        y_hat, state = net(X, state)
        l = loss(y_hat, y.long()).mean()
        if isinstance(updater, torch.optim.Optimizer):
            updater.zero_grad()
            l.backward()
            grad_clipping(net, 1)
            updater.step()
        else:
            l.backward()
            grad_clipping(net, 1)
            # Since the `mean` function has been invoked
            updater(batch_size=1)
        metric.add(l * y.numel(), y.numel())
    return math.exp(metric[0] / metric[1]), metric[1] / timer.stop()
</code></pre>
<pre><code class="lang-auto">#@save
def train_ch8(net, train_iter, vocab, lr, num_epochs, device,
              use_random_iter=False):
    """Train a model (defined in Chapter 8)."""
    loss = nn.CrossEntropyLoss()
    animator = d2l.Animator(xlabel='epoch', ylabel='perplexity',
                            legend=['train'], xlim=[10, num_epochs])
    # Initialize
    if isinstance(net, nn.Module):
        updater = torch.optim.SGD(net.parameters(), lr)
    else:
        updater = lambda batch_size: d2l.sgd(net.params, lr, batch_size)
    predict = lambda prefix: predict_ch8(prefix, 50, net, vocab, device)
    # Train and predict
    for epoch in range(num_epochs):
        ppl, speed = train_epoch_ch8(net, train_iter, loss, updater, device,
                                     use_random_iter)
        if (epoch + 1) % 10 == 0:
            print(predict('time traveller'))
            animator.add(epoch + 1, [ppl])
    print(f'perplexity {ppl:.1f}, {speed:.1f} tokens/sec on {str(device)}')
    print(predict('time traveller'))
    print(predict('traveller'))
</code></pre>
<p>What follows is the code I modified:</p>
<pre><code class="lang-auto">import numpy as np

def predict_ch8(prefix, num_preds, net, vocab, device): #@save
    """Generate new characters following the `prefix`."""
    state = net.begin_state(batch_size=1, device=device)
    outputs = [vocab[prefix[0]]]
    get_input = lambda: torch.tensor([outputs[-1]], device=device).reshape(
        (1, 1))
    for y in prefix[1:]:  # Warm-up period
        _, state = net(get_input(), state)
        outputs.append(vocab[y])
    for _ in range(num_preds):  # Predict `num_preds` steps
        y, state = net(get_input(), state)
        print("int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)):")
        print(int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)))
        outputs.append(int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1))) # here is the modification
    return ''.join([vocab.idx_to_token[i] for i in outputs])
</code></pre>
<p>Now look at the following code cells and their outputs:</p>
<p><code>predict_ch8('time traveller ', 10, net, vocab, d2l.try_gpu())</code></p>
<pre><code class="lang-auto">int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)):
0
int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)):
0
int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)):
0
int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)):
0
int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)):
0
int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)):
0
int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)):
0
int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)):
0
int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)):
0
int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)):
0

'time traveller &lt;unk&gt;&lt;unk&gt;&lt;unk&gt;&lt;unk&gt;&lt;unk&gt;&lt;unk&gt;&lt;unk&gt;&lt;unk&gt;&lt;unk&gt;&lt;unk&gt;'
</code></pre>
<p>Note how my outputs are all 0. I don’t know why is that.</p>
<p>When I try to train the model, I get the following:</p>
<pre><code class="lang-auto">num_epochs, lr = 500, 1
train_ch8(net, train_iter, vocab, lr, num_epochs, d2l.try_gpu())
</code></pre>
<pre><code class="lang-auto">int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)):
0
int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)):

/pytorch/aten/src/ATen/native/cuda/ScatterGatherKernel.cu:312: operator(): block: [0,0,0], thread: [0,0,0] Assertion `idx_dim &gt;= 0 &amp;&amp; idx_dim &lt; index_size &amp;&amp; "index out of bounds"` failed.

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
/tmp/ipykernel_28343/3385443296.py in &lt;module&gt;
      1 num_epochs, lr = 500, 1
----&gt; 2 train_ch8(net, train_iter, vocab, lr, num_epochs, d2l.try_gpu())

/tmp/ipykernel_28343/636485725.py in train_ch8(net, train_iter, vocab, lr, num_epochs, device, use_random_iter)
     17                                      use_random_iter)
     18         if (epoch + 1) % 10 == 0:
---&gt; 19             print(predict('time traveller'))
     20             animator.add(epoch + 1, [ppl])
     21     print(f'perplexity {ppl:.1f}, {speed:.1f} tokens/sec on {str(device)}')

/tmp/ipykernel_28343/636485725.py in &lt;lambda&gt;(prefix)
     11     else:
     12         updater = lambda batch_size: d2l.sgd(net.params, lr, batch_size)
---&gt; 13     predict = lambda prefix: predict_ch8(prefix, 50, net, vocab, device)
     14     # Train and predict
     15     for epoch in range(num_epochs):

/tmp/ipykernel_28343/2030242475.py in predict_ch8(prefix, num_preds, net, vocab, device)
     13         y, state = net(get_input(), state)
     14         print("int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)):")
---&gt; 15         print(int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)))
     16         outputs.append(int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1))) # here is the modification
     17     return ''.join([vocab.idx_to_token[i] for i in outputs])

RuntimeError: CUDA error: device-side assert triggered
CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1.
</code></pre>
<p>I tried re-defning the <code>train_epoch_ch8</code> and <code>train_ch8</code> functions after the redefining the <code>predict_ch8</code> function. The only difference is that besides the <code>0</code>’s I sometimes get <code>-2</code>’s as outputs.</p>
<p>Can someone please tell me what is going on here? All I changed was the line in <code>predict_ch8</code> that was:</p>
<p><code>outputs.append(int(y.argmax(dim=1).reshape(1)))</code></p>
<p>to:</p>
<p><code>outputs.append(int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1))) # here is the modification</code></p>
<p>I don’t know what went wrong. The entire <code>.cpu().detach().numpy().ravel()</code> chain is due to getting errors that I have to move the tensor to the CPU.</p>
<p><strong>Can someone tell me what is going on here?</strong></p>
<p>Thank you in advance!</p>

ptrblck: <p>Based on the error message you are running into a device <code>assert</code> so you could either run the script via <code>CUDA_LAUNCH_BLOCKING=1 python script.py args</code> from the terminal to isolate the failing operation or run it on the CPU.</p>

Lost_Wanderer: <p>After doing what you suggested, I found the error. I was supposed to write:</p>
<p><code>outputs.append(int(np.random.choice(len(y.cpu().detach().numpy().ravel()), size=1).reshape(1)))</code></p>
<p>instead of</p>
<p><code>outputs.append(int(np.random.choice(y.cpu().detach().numpy().ravel(), size=1).reshape(1)))</code></p>
<p>note the <code>len()</code>, since I’m looking for class indicies.</p>
<p>Thank you for the help!</p>