Multi Threads Transformer Model

Can we train Transformer model using 2 threads?
first thread on GPU-1
second threads on GPU-2?

Is it possible?

What you are describing sounds like a typical distributed data parallel set up, which works with transformer models indeed. You can look it up for more information.

BramVanroy,

I experimented with nn.DataParallel(model), For example, if I want to use 2 GPU
but in this method, the entire model copy is copied on both GPUs

I would like to do, half data should be trained on one GPU and another half data on another GPU, eventually I can complete training in less time.

I wonder that is it possible to nn.DataParallel(model) ?

Not DataParallel, but DistributedDataParallel, which does what you require.

ok, I will try with DistributedDataParallel

Thanks BramVanroy

1 Like

Since I am a beginner, understanding these frameoworks.

How to wrap the below code with DistributedDataParallel?

class TransformerModel(nn.Module):
def init(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5):
super(TransformerModel, self).init()
from torch.nn import TransformerEncoder, TransformerEncoderLayer
self.model_type = ‘Transformer’
self.src_mask = None
self.pos_encoder = PositionalEncoding(ninp, dropout)
encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid, dropout)
self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers)
self.encoder = nn.Embedding(ntoken, ninp)
self.ninp = ninp
self.decoder = nn.Linear(ninp, ntoken)
self.init_weights()
def generate_square_subsequent_mask(self, sz):
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
mask = mask.float().masked_fill(mask == 0, float(’-inf’)).masked_fill(mask == 1, float(0.0))
return mask
def init_weights(self):
initrange = 0.1
self.encoder.weight.data.uniform
(-initrange, initrange)
self.decoder.bias.data.zero_()
self.decoder.weight.data.uniform_(-initrange, initrange)
def forward(self, src):
if self.src_mask is None or self.src_mask.size(0) != len(src):
device = src.device
mask = self._generate_square_subsequent_mask(len(src)).to(device)
self.src_mask = mask
src = self.encoder(src) * math.sqrt(self.ninp)
src = self.pos_encoder(src)
output = self.transformer_encoder(src, self.src_mask)
output = self.decoder(output)
return F.log_softmax(output, dim=-1)

class PositionalEncoding(nn.Module):
def init(self, d_model, dropout=0.1, max_len=5000):
super(PositionalEncoding, self).init()
self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0).transpose(0, 1)
self.register_buffer(‘pe’, pe)
def forward(self, x):
x = x + self.pe[:x.size(0), :]
return self.dropout(x)

I believe that DistributedDataParallel does not work with Transformer model,