LSTM DataParallel hidden state not split between workers

username: arvindmohan
cooked: <p>Hello all,<br>
I am trying to run a LSTM in DataParallel, and there have been several threads[1,2] which have mentioned that batch_first=True has to be enforced since Pytorch splits the data in first dimension.</p>
<ol>
<li>The problem is that the hidden state dimensions are still ( num_layers * num_directions x batch_size x hidden_size)</li>
<li>This means it has to be manually permuted into ( batch_size x num_layers * num_directions x hidden_size) at initialization so that its split among workers along the batch dimension, and reshaped back to ( num_layers * num_directions x batch_size x hidden_size) as input to forward(), to keep the hidden state dimensions consistent with LSTM documentation.</li>
</ol>
<p>This has been discussed in quite a few threads, and it does not seem to have any clear, clean resolution as of now</p>
<p>[1] <a href="https://discuss.pytorch.org/t/multi-layer-rnn-with-dataparallel/4450/3" class="inline-onebox">Multi layer RNN with DataParallel</a><br>
[2] <a href="https://discuss.pytorch.org/t/dataparallel-lstm-gru-wrong-hidden-batch-size-8-gpus/6701/15" class="inline-onebox">DataParallel LSTM/GRU wrong hidden batch size (8 GPUs)</a></p>
<p>Going by the strategies in these threads, I have implemented the code as below - BUT Pytorch does not split the hidden state at all, regardless of the dimensions.</p>
<pre><code class="lang-auto">
class LSTM(nn.Module):

    def __init__(self,input_size,hiddensize,batch,output_size,nlayers):
        super(LSTM, self).__init__()
        self.input_size= input_size
        self.hiddensize= hiddensize
        self.batch= batch
        self.output_size= output_size
        self.nlayers= nlayers

        #Define LSTM layers
        self.lstm= nn.LSTM(self.input_size, self.hiddensize, self.nlayers, batch_first=True)
        #Define Output layer
        self.linear= nn.Linear(self.hiddensize,self.output_size)

    def init_hidden(self):
        h0= torch.randn(self.batch, self.nlayers, self.hiddensize).cuda() #batch_first= True
        c0= torch.randn(self.batch, self.nlayers, self.hiddensize).cuda()
        return (h0,c0)

    def forward(self,input_tensor):
        hiddenvecs= self.init_hidden()
        hiddenvecs = tuple([h.permute(1,0,2).contiguous() for h in hiddenvecs])
        lstm_out, hiddenvecs = self.lstm(input_tensor, hiddenvecs)
        #output layer
        pred= self.linear(lstm_out)
        return pred

#LSTM params
nlayers=3
hiddensize= 40
input_size=1
output_size=input_size
batch=8
epochs= 1000000
k=10 #sequence length

# load batches and ensure nbatches is divisible by batch size
x = data[:,:-1,:]
y = data[:,1:,:]
nbatch_idx = int(x.size(1)/batch)*batch
x = x[:,:nbatch_idx,:]
y = y[:,:nbatch_idx,:]
x = torch.reshape(x, (x.size(1),k,input_size)) #batch first=True
y = torch.reshape(y, (y.size(1),k,input_size))
# Create dataloader pipeline
train_dataset = torch.utils.data.TensorDataset(x,y)
trainloader = DataLoader(train_dataset, batch_size=batch, shuffle=False, num_workers=0)
print(len(trainloader))


model= LSTM(input_size,hiddensize,batch,output_size,nlayers)
if torch.cuda.device_count() &gt; 1:
    print('Using', torch.cuda.device_count(), 'GPUs')
    model = nn.DataParallel(model)
model.cuda()

print('Start training...')
PATH = 'checkpoints'
loss_history=[]
for ep in range(epochs):
    print('Epoch', ep)
    for local_x, local_y in tqdm(trainloader, total=len(trainloader)):
        local_x, local_y = local_x.cuda(), local_y.cuda()
        output = model(local_x.type(torch.cuda.FloatTensor)).cuda()
        loss = criterion(output, local_y.type(torch.cuda.FloatTensor))
        # #backward
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        loss_history.append(loss.item())

</code></pre>
<p>size of input_tensor and target i.e. x and y, are (batch x sequence_length X input_size). I have init the hidden state with batch first, and permuted them to batch second, for LSTM forward. Here is the error message I get</p>
<pre><code class="lang-auto">RuntimeError: Expected hidden[0] size (3, 2, 40), got (3, 8, 40)
</code></pre>
<p>So the hidden state of dimension (8,3,40) should have been split into (2,3,40) - I am using 4 GPUs (so 2 x 4 = 8), followed by my permute operation should have given (3,2,40) - which is exactly what the network needs. But the error above says the split never happened.</p>
<p>Regardless of how I reshape the hidden state (batch first or second) , the batch dimension does not get split among the workers. I would really appreciate any help with whats going on. Thank you!</p>

username: robd2
cooked: <p>I “might” have found a workaround for this issue, or maybe its the actual correct way to implement. According to the torch.nn.LSTM docs<br>
<em>“If (h_0, c_0) is not provided, both  <strong>h_0</strong>  and  <strong>c_0</strong>  default to zero.”</em></p>
<p>So the workaround is basically to allow nn.LSTM to initialize itself rather than have separate init_hidden logic. Some might say this is the correct way to initialize the hidden. Thoughts? I see better results initializing the RNN hidden with zeros anyway.</p>

username: robd2
cooked: <p>No need to even init hidden as the LSTM will do it automatically. Your forward should look something like this:</p>
<p>def forward(self, x):<br>
out, hidden = self.lstm(x)<br>
out = self.fc(out)<br>
return out</p>

username: arvindmohan
cooked: <p>Thanks for the response  - but I do want to explicitly define the hidden states (I plan to develop a custom LSTM based architecture) and initialize them every time, and thats when the dataparallel doesn’t split along the batch. Is there a way to force Pytorch to do this?</p>

username: marchinidavide
cooked: <aside class="quote no-group" data-username="arvindmohan" data-post="4" data-topic="43630">
<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/arvindmohan/48/6841_2.png" class="avatar"> arvindmohan:</div>
<blockquote>
<p>but I do want to explicitly define the hidden states</p>
</blockquote>
</aside>
<p>I need to do exactly the same. Any update from other threads?<br>
My code is getting kind of messy dealing with batch_first in the RNN instance, <code>dim=1</code> in the <code>nn.DataParallel</code> and all the functions to have the <code>batch</code> dimension of every object in the same position …</p>

username: arvindmohan
cooked: <p>Hi Davide,<br>
I ended up implementing LSTM from scratch in Pytorch as it gave me greater flexibility to try various modifications and not mess with the Pytorch internals. It didn’t take much time though.</p>
<p>But once you have an implementation, you can still automatically run it in parallel/distributed mode using Pytorch’s built in modules. Then, to explicitly define hidden states at every call, have the LSTM call the init method like this:</p>
<pre><code class="lang-auto">    def init_states(self, hiddensize, distbatchsize):
        """ Initialize h and c LSTMCell states """
        h = torch.randn(distbatchsize, hiddensize, self.input_dim[0], self.input_dim[1]).cuda()
        c = torch.randn(distbatchsize, hiddensize, self.input_dim[0], self.input_dim[1]).cuda()
        states = (h,c)
        return states

</code></pre>
<p>In data parallel mode, there is a <em>separate network on each GPU</em>, so this function is called locally on each GPU which has its <em>local batch size</em>. In that case, the hidden states should then be initialized with that local batch size.</p>
<p>The “distbatchsize” here does exactly that.  It is the batch size  <em>local to the GPU</em> after the full batch size has been scattered by the distributed module. So if your full batchsize = 8 and num_gpus = 4, then distbatchsize = 8/4 = 2. Pytorch automatically computes this and splits your input tensors into that size and sends it to all GPUs (Check the all_scatter module in MPI for more details). So How do you find the distbatchsize? The snippet below is from the LSTM forward method. The first dimension is the local batch size = 2. If you were running this on only 1 GPU, the distbatchsize = 8 i.e. the global batch size.</p>
<pre><code class="lang-auto">    def forward(self, input_tensor):
        """ Forward Pass """

        # Find the local batch size
        distbatchsize = input_tensor.size(0)

       # continue with init_states and forward pass

</code></pre>
<p>Not a clean solution, but it serves me well. Let me know if you have any comments!</p>

username: marchinidavide
cooked: <aside class="quote no-group" data-username="arvindmohan" data-post="6" data-topic="43630">
<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/arvindmohan/48/6841_2.png" class="avatar"> arvindmohan:</div>
<blockquote>
<p>I ended up implementing LSTM from scratch in Pytorch as it gave me greater flexibility to try various modifications and not mess with the Pytorch internals. It didn’t take much time though.</p>
</blockquote>
</aside>
<p>Thank you Arvind!<br>
It’s a great solution, will try it out soon!<br>
I need to initialise hidden states querying a big tensor that I would avoid coping to each gpu.<br>
Although pretty inefficient I think I have to send the query vector to where the big tensor is, extracting the query and then call <code>.cuda()</code> again. Not sure if autograd can track these device changes… hope to give a feedback soon</p>