Reshaping output to fit In CTC loss

jojojo: <p>Hi fellows,</p>
<p>I have a doubt. I am working on 2D Cnn network for OCR. After my 6th CNN layer output, tensor shape will be (B, C, H, W). I have to pass this output to linear layer to map to number of classes(76) required to have for CTC loss. Now how should i reshape my CNN output tensor to pass to linear layer. Also after linear layer I have to pass to softmax and CTC which requires 3d tensor. how should I reshape from linear layer output to pass to CTC.<br>
CNN output:(64, 512, 1, 28). Now this tensor I have to pass to linear layer. at the end output channels shold be 76 in my case. If I flatten it using view (B, -1), then it should look like (64, 28<em>512</em>28), and the end output will look like (64, 76), now how should I pass to CTC because I have no time steps information. Please help.</p>

ptrblck: <p>There are multiple possible approaches and it depends how the activation shape is interpreted.<br>
E.g. using <code>[64, 512, 1, 28]</code> you could <code>squeeze</code> dim3 and use dim4 as the “sequence” dimension (it’s one of the spatial dimension).<br>
In this case, you could permute the activation so that the linear layer will be applied on each time step and permute it back to the expected shape for <code>CTCLoss</code>.<br>
Something like this could work:</p>
<pre><code class="lang-python">B, C, H, W = 64, 512, 1, 28
x = torch.randn(B, C, H, W)

x = x.squeeze(2) # remove H dim
x = x.permute(0, 2, 1).contiguous() # permute to [B, H, C=T]
T = x.size(1)

linear = nn.Linear(C, 76)
out = linear(x) # will be applied on each timestep (same as looping over dim1)
print(out.shape)
# &gt; torch.Size([64, 28, 76]) # corresponds to [B, T, out_features]

criterion = nn.CTCLoss() # expects an input in [T, N=B, C]
out = out.permute(1, 0, 2).contiguous() # permute to [T, B, C]
out = F.log_softmax(out, dim=2) # create log probabilities

# create random target and lengths
target = torch.randint(1, C, size=(B, 10))
input_lengths = torch.full((B,), T, dtype=torch.long)
target_lengths = torch.randint(1, 10, (B,))

# calculate loss
loss = criterion(out, target, input_lengths, target_lengths)
loss.backward()
</code></pre>

jojojo: <p>Hello, Thanks for your answer. I have some doubts still.<br>
What was the motivation to choose this interpretation and choosing dim 4 as sequence dimension?<br>
In Line 4, after you have squeezed H dimension in line 3, it is still mentioned in the comment, also, why C = T? Shouldn’t it be W = T?<br>
Also, shouldn’t input to linear layer be in shape of 2D tensor? Shouldn’t we flatten it? You have passed a 3D tensor to linear layer. Will it work?</p>

ptrblck: <aside class="quote no-group" data-username="jojojo" data-post="3" data-topic="139459">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/jojojo/48/43645_2.png" class="avatar"> jojojo:</div>
<blockquote>
<p>What was the motivation to choose this interpretation and choosing dim 4 as sequence dimension?</p>
</blockquote>
</aside>
<p>One idea could be that the spatial dimensions are comparable to a temporal dimension in that both are encoding a sequential information (i.e. neighboring values might be correlated).</p>
<aside class="quote no-group" data-username="jojojo" data-post="3" data-topic="139459">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/jojojo/48/43645_2.png" class="avatar"> jojojo:</div>
<blockquote>
<p>Shouldn’t it be W = T?</p>
</blockquote>
</aside>
<p>Yes, you are right. My comments are wrong, <code>T = x.size(1)</code> should still work as it would assign <code>W</code> to <code>T</code>.</p>
<aside class="quote no-group" data-username="jojojo" data-post="3" data-topic="139459">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/jojojo/48/43645_2.png" class="avatar"> jojojo:</div>
<blockquote>
<p>Also, shouldn’t input to linear layer be in shape of 2D tensor? Shouldn’t we flatten it? You have passed a 3D tensor to linear layer. Will it work?</p>
</blockquote>
</aside>
<p>Yes, it will work as described in the <a href="https://pytorch.org/docs/stable/generated/torch.nn.Linear.html?highlight=linear#torch.nn.Linear">docs</a>. Linear layers accept an input of <code>[batch_size, *, in_features]</code> where <code>*</code> denotes additional dimensions. They will be applied on each sample in the additional dimensions as if you were using a for loop.</p>

StannisLaw: <p>Hello! Recently I ran several experiments on OCR with CTC for my own research, and I would suggest you to try the following:</p>
<p>Instead of compressing some of the cnn output dimensions to one, in your case H is squeezed to 1, I would recommend to change CNN’s kernel_size to get wider dimension - thus you can use some pooling/attention operation over it:</p>
<pre><code class="lang-auto"># let input image size is (b, c, h, w) = (16, 3, 64, 1024)
# let cnn output size is (16, 2048, 128, 512)
# then

pooling =  nn.AdaptiveAvgPool2d((512, 512))

out = out.view(16, 2048, 128*512)
out = pooling(out)
</code></pre>
<p>Of course you can use classical maxPooling, or some custom self-attention, but in my experiments with IAM/Bentham I found the averagePooling best.</p>
<p>You can also try to use different dimension to multiply, for example (16, 2048*128, 512), etc.<br>
Try to find your best.</p>
<p>Speaking about some background behind this, well, I think that we getting much wider feature map by keeping dimension not-equal-to-one, and by aggregation we can reduce the overall size, but also extract valuable feats.</p>

jojojo: <p>Thank you I will try this for sure. You do this avgPool after the last layer before passing to CTC? Not between every CNN layers right? My network right now doesnt have any pooling layers. Its pure CNN network and after that 1 fc layer before CTC</p>

jojojo: <p>Hi. I want an advice. My mentor said to change the ways i feed the cnn outputs to CTC.  He said :- For each of the 100 timestamps of CTC, feed three spatial coumns from CNN ouputs, instead of 1 so that each CTC timestamp sees three spatial neighboring columns instead of one. I think CTC accepts the whole CNN ouputs. Is slicing can be done to cnn outputs to feed to CTC? What’d you guys think?</p>

StannisLaw: <p>Aggregation was made once after the cnn before passing to dense layer.</p>

jojojo: <p>Hi Stannis,<br>
My input size is 64, 1, 32, 100</p>
<p>Let say by increasing padding and decreasing kernel size to 2 from 3, uplift my dinesions to 64, 1, 64, 128. and then doing adaptive avg pooling with kernel size(256, 256). Will this be alright?</p>
<aside class="quote no-group quote-modified" data-username="StannisLaw" data-post="5" data-topic="139459" data-full="true">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/c89c15/48.png" class="avatar"> StannisLaw:</div>
<blockquote>
<h1>let input image size is (b, c, h, w) = (16, 3, 64, 1024)</h1>
<h1>let cnn output size is (16, 2048, 128, 512)</h1>
<h1>then</h1>
<p>pooling =  nn.AdaptiveAvgPool2d((512, 512))</p>
<p>out = out.view(16, 2048, 128*512)<br>
out = pooling(out)</p>
<pre><code class="lang-auto"></code></pre>
</blockquote>
</aside>
<p>Also Why did you multilpy ypur spatial dimesnsions before feeding to pooling. Cant it be done without multiplying?</p>
<p>Thanks</p>

StannisLaw: <p>Hello there, the model flow could be presented as follows:</p>
<p>CNN → multiply → pooling → linear → log_softmax</p>
<p>Speaking about multiplying: referring to the docs (<a href="https://pytorch.org/docs/stable/generated/torch.nn.AdaptiveAvgPool2d.html" rel="noopener nofollow ugc">link</a>), pooling input could be 4d or 3d, but hence the <a href="https://pytorch.org/docs/stable/generated/torch.nn.CTCLoss.html" rel="noopener nofollow ugc">ctc loss</a> input has to be 3D, its better to first multiply dimensions, and then apply pooling to them - thus the relatively rough multiplication operation will be ‘smoothed’ by pooling.</p>