What is the right way to apply pruning to LSTMs?

username: K0mp0t
cooked: <p>Hello everyone!</p>
<p>I’m currently studying model optimization methods and trying out pruning right now. I’ve chosen CRNN for my experiments because it has different types of layers following each other.</p>
<p><a href="https://imgur.com/a/jBgjcxE" rel="noopener nofollow ugc">Net architecture, if this helps</a></p>
<p>I prune layers by iteratively selecting channel indices with the least L1 norm:</p>
<ol>
<li>Calculate the L1 norm channel-wise.</li>
<li>Select n% least L1 norm channel indices.</li>
<li>Modify the current layer’s weights by removing OUT channels with indices from step 2.</li>
<li>Modify the next layer’s weights by removing IN channels with indices from step 2.</li>
<li>Loop over every layer.</li>
</ol>
<p>This scheme works correctly with the convolutional part of the net, though when I apply it to the whole net, it starts to produce nans. My assumption here is that something is wrong with my LSTM weights processing (nans occur right after the LSTM). However, I’m able to correctly prune the first LSTM layer’s IN channels (so there is no shape conflict).</p>
<p>Here’s part of my code that processes the output part of LSTM weights (output for ih and input and output for hh weights, actually).</p>
<pre><code class="lang-auto">elif isinstance(layer, nn.LSTM):
  prev_layer_output_size = layer.hidden_size

  for attr in dir(layer):
    if attr.startswith('weight_ih'):
      weight = getattr(layer, attr).view(layer.hidden_size, 4, -1)
      l1 = torch.sum(torch.abs(weight), dim=(1, 2))
      sorted_indices = torch.argsort(l1)[int(fraction*layer.hidden_size):]
      sorted_indices = torch.sort(sorted_indices).values

      bias_name = attr.replace('weight', 'bias')
      setattr(layer, attr, torch.nn.Parameter(weight[sorted_indices].view(-1, weight.shape[-1])))
      setattr(layer, bias_name, torch.nn.Parameter(getattr(layer, bias_name)[sorted_indices]))

  for attr in dir(layer):
    if attr.startswith('weight_hh'):
      weight = getattr(layer, attr)[:, sorted_indices].view(layer.hidden_size, 4, -1)
      l1 = torch.sum(torch.abs(weight), dim=(1, 2))
      sorted_indices = torch.argsort(l1)[int(fraction*layer.hidden_size):]
      sorted_indices = torch.sort(sorted_indices).values

      bias_name = attr.replace('weight', 'bias')
      setattr(layer, attr, torch.nn.Parameter(weight[sorted_indices].view(-1, weight.shape[-1])))
      setattr(layer, bias_name, torch.nn.Parameter(getattr(layer, bias_name)[sorted_indices]))

  layer.hidden_size = len(sorted_indices)
</code></pre>
<p>I’ve read the docs and LSTM impl, though, wasn’t able to fix the error.<br>
Finally, some observations that might help:</p>
<ol>
<li>I’ve checked model weights for nans, and there weren’t any.</li>
<li>The model produces nans randomly. I use torchinfo.summary(…) or my own validation function to check for nans, so there could be a lot of randomness in the data. Some torchinfo.summary(…) or validation iterations didn’t return nans for some reason.</li>
</ol>
<p>Thanks in advance. I would really appreciate your help.</p>

username: K0mp0t
cooked: <p>Hello again.</p>
<p>I decided to give pruning another chance and found the error in the question code:</p>
<pre><code class="lang-auto">bias_name = attr.replace('weight', 'bias')
setattr(layer, attr, torch.nn.Parameter(weight[sorted_indices].view(-1, weight.shape[-1])))
setattr(layer, bias_name, torch.nn.Parameter(getattr(layer, bias_name)[sorted_indices]))  # &lt;--- HERE
</code></pre>
<p>When reindexing bias, I forgot that bias has to be chunked before reindexing. Bias has (hidden_size*4,) shape, while my sorted_indices variable was meant to index tensors of shape (hidden_size,).</p>
<p>So I simply chunk the bias tensor ((hidden_size*4,) → (hidden_size, 4)), reindex it over 0th dim, and reshape it back to 1d tesnor:</p>
<pre><code class="lang-auto">bias_name = attr.replace('weight', 'bias')
setattr(layer, attr, torch.nn.Parameter(weight[sorted_indices].view(-1, weight.shape[-1])))
setattr(layer, bias_name, torch.nn.Parameter(getattr(layer, bias_name).view(-1, 4)[sorted_indices].view(-1)))
</code></pre>
<p>And that’s it; no nans were produced.</p>
<p>Though my pruning RNNs pruning method is completely incorrect: pruning the hidden size of RNN stresses the net so much that it loses all of its capacity, which results in ~20x loss rise (and ~20x metric drop). So net has to be totally retrained. For example, when I pruned only the convolution part, there wasn’t any significant metric drop (though loss rose ~1.5x).</p>