id
stringlengths
3
8
text
stringlengths
1
115k
st84968
Is there a single function for this: t = torch.rand(3) #tensor m = t.mean() #mean print(t) print(m) ma = (t-m) # mean absolute print(ma) ama = ma.abs() # make it absolute print(ama) mama = ama.mean() # take the mean print(mama) # tensor([0.3468, 0.4841, 0.3940]) # tensor(0.4083) # tensor([-0.0615, 0.0758, -0.0143]) # tensor([0.0615, 0.0758, 0.0143]) # tensor(0.0505)
st84969
I have a learning algorithm that tries to reconstruct the input data using a particular model. My forward problem is to reconstruct the 10 input data, and compute the sum of the losses between reconstructions and inputs. I would like the 10 reconstructions to be done in parallel on the CPU, with 10 processes. I don’t know if it’s even possible, meaning if autograd can be used in different processes. I have tried so many approaches, mainly with torch.multiprocessing.spawn and there always seems to be a problem with different things. What is the best way to do this ? Here is the single-process code: import numpy as np import torch def forward_routine(leaf): xi = lambda x: apply_kernel(leaf,x,extra_param) err = np.zeros([S,L]) for j in range(S): # S = 10 # xi is a function that uses the leaf variable, so what it returns requires grad. # The function 'reconstruct' uses xi many times. # rec is the reconstruction, that requires grad. # P is a parameter that is constant for each reconstruction # err is a numpy array. rec, err[j] = reconstruct(P, w[j], xi) loss_cur = loss_func(rec, obs[j]) loss = loss + loss_cur return loss if __name__ == "__main__": # x0 is a numpy array, let's say of size (D,N) # I give this functor to the scipy's LBFGS routine. def torch_func(x0): leaf = torch.from_numpy(x0, requires_grad=True) loss = forward_routine(leaf) loss.backward() grad = leaf.grad return loss.numpy(), grad.numpy() # Read input data # Run LBFGS, with torch_func as the function to minimize. I know that lambda functions can’t be pickled so I wrote a function object for xi, but I didn’t add it to be short.
st84970
This is probably very silly question. However, I could not find an answer for it. given that I have Matrix A (with the size of NxN), and Kernel K (with the size of MxM) how I can get the output B, where: B = A*K? where * is the 2d-convolution sign P.S. I did looked at torch.nn.functional.conv2d, but im not sure how we can define the kernel in that. I am not even sure if it is doing what I need…
st84971
I’m not sure if conv2d is what you’re looking for, but here’s how to adapt it to take your inputs. Try this: import torch import torch.nn.functional as F from torch.autograd import Variable N = 4 M = 3 A = Variable(torch.randn(1, 1, N, N)) M = Variable(torch.ones(1, 1, M, M)) output = F.conv2d(A, M) You can set A to be any N x N matrix with A[0,0,:] = A2, where A2 is N x N. Same with M[0, 0, :] = M2 where M2 is M by M.
st84972
Yeah, Can you please tell me how would you do 2d convolution in pytorch if you dont want to use conv2d? or if you wanna use another way other than conv2… I mean is there any other way to do it here in pytorch? Thanks
st84973
sorry for retrieving this question. lets say i wanna do convolution with a specific filter on tensors. e.g. my kernel is: H = torch.Tensor([[1 ,0, -1],[2, 0 ,-2], [1, 0 ,-1]]), so it is 3x3 originally, but i can expand it in a size that is needed. If my tensor T, has size of BxCxDxD, What should be the size and shape of my kernel so i can do conv2d(T,H) and get the output of BxCxDxD
st84974
I have an autoencoder deep network, and I notice that when I use nn.Sequential , the generalization performance is better than when I don’t use it (i.e. explicitly pass the inputs through layers). Has anyone else noticed this behavior, or can provide an explanation as to why this is? Does Pytorch handle regularization differently in a sequential block?
st84975
Solved by ptrblck in post #4 Thanks for the code. The difference is indeed in the usage of the batch norm layers. While you are initializing two different nn.BatchNorm1d layers in your sequential approach, you are reusing the same in your manual approach. Could you create two separate batch norm layers and run the test again…
st84976
There shouldn’t be a difference, if you just reimplemented the sequential model using your custom one. Did you run the code a few times and checked for small variations in the loss/accuracy? Would it be possible to post both model codes so that we can have a look?
st84977
Thanks for the response. Here is a code snippet; I’ve attached the full code at the end for your reference. I am toggling between using nn.Sequential and not using it with the variable use_sequential. I find that when I don’t use the sequential module, my test accuracy is always worse than if I do use it. class Net(nn.Module): def __init__(self, hidden_dim, in_dim, use_sequential): super(Net, self).__init__() self.use_sequential = use_sequential self.in_dim = in_dim self.hidden_dim = hidden_dim self.sig = nn.Sigmoid() self.encoder = nn.Sequential( nn.Linear(in_dim, in_dim), nn.BatchNorm1d(in_dim), nn.Linear(in_dim, hidden_dim) ) self.decoder = nn.Sequential( nn.Linear(hidden_dim, in_dim), nn.BatchNorm1d(in_dim), nn.Linear(in_dim, in_dim) ) def encode(self, x): if self.use_sequential: x = self.encoder(x) else: x = self.lin1(x) x = self.batchnorm(x) x = self.lin2(x) return x def decode(self, x): if self.use_sequential: x = self.decoder(x) else: x = self.lin3(x) x = self.batchnorm(x) x = self.lin4(x) return x def forward(self, x): x = self.encode(x) x = self.decode(x) x = self.sig(x) # Sigmoid for BCELoss return x Here’s the output of the script, which I have pasted in full at the very end for reference. As you can see, the test accuracy/loss is worse as the models train, even though their train accuracy/loss remain similar (I initialize all weights myself, see full code at the end): SEQUENTIAL TRAIN, Epoch 0: loss=0.7185, acc=0.51 NONSEQUENTIAL TRAIN, Epoch 0: loss=0.7185, acc=0.51 ---> SEQUENTIAL TEST: Epoch 0: loss=0.7240, acc=0.50080 ---> NONSEQUENTIAL TEST: Epoch 0: loss=0.7240, acc=0.50080 SEQUENTIAL TRAIN, Epoch 1: loss=0.7192, acc=0.49 NONSEQUENTIAL TRAIN, Epoch 1: loss=0.7192, acc=0.49 ---> SEQUENTIAL TEST: Epoch 1: loss=0.7226, acc=0.49920 ---> NONSEQUENTIAL TEST: Epoch 1: loss=0.7221, acc=0.49920 SEQUENTIAL TRAIN, Epoch 2: loss=0.7207, acc=0.50 NONSEQUENTIAL TRAIN, Epoch 2: loss=0.7208, acc=0.50 ---> SEQUENTIAL TEST: Epoch 2: loss=0.7183, acc=0.56120 ---> NONSEQUENTIAL TEST: Epoch 2: loss=0.7186, acc=0.49920 SEQUENTIAL TRAIN, Epoch 3: loss=0.7032, acc=0.54 NONSEQUENTIAL TRAIN, Epoch 3: loss=0.7033, acc=0.54 ---> SEQUENTIAL TEST: Epoch 3: loss=0.7104, acc=0.56120 ---> NONSEQUENTIAL TEST: Epoch 3: loss=0.7153, acc=0.49920 SEQUENTIAL TRAIN, Epoch 4: loss=0.7002, acc=0.56 NONSEQUENTIAL TRAIN, Epoch 4: loss=0.7002, acc=0.56 ---> SEQUENTIAL TEST: Epoch 4: loss=0.7006, acc=0.56120 ---> NONSEQUENTIAL TEST: Epoch 4: loss=0.7119, acc=0.49920 SEQUENTIAL TRAIN, Epoch 5: loss=0.6906, acc=0.55 NONSEQUENTIAL TRAIN, Epoch 5: loss=0.6907, acc=0.55 ---> SEQUENTIAL TEST: Epoch 5: loss=0.6903, acc=0.56120 ---> NONSEQUENTIAL TEST: Epoch 5: loss=0.7088, acc=0.49920 SEQUENTIAL TRAIN, Epoch 6: loss=0.6807, acc=0.54 NONSEQUENTIAL TRAIN, Epoch 6: loss=0.6811, acc=0.54 ---> SEQUENTIAL TEST: Epoch 6: loss=0.6815, acc=0.56120 ---> NONSEQUENTIAL TEST: Epoch 6: loss=0.7058, acc=0.49920 SEQUENTIAL TRAIN, Epoch 7: loss=0.6698, acc=0.52 NONSEQUENTIAL TRAIN, Epoch 7: loss=0.6702, acc=0.52 ---> SEQUENTIAL TEST: Epoch 7: loss=0.6729, acc=0.56120 ---> NONSEQUENTIAL TEST: Epoch 7: loss=0.7033, acc=0.49920 SEQUENTIAL TRAIN, Epoch 8: loss=0.6710, acc=0.67 NONSEQUENTIAL TRAIN, Epoch 8: loss=0.6722, acc=0.60 ---> SEQUENTIAL TEST: Epoch 8: loss=0.6643, acc=0.56120 ---> NONSEQUENTIAL TEST: Epoch 8: loss=0.7014, acc=0.49920 SEQUENTIAL TRAIN, Epoch 9: loss=0.6642, acc=0.71 NONSEQUENTIAL TRAIN, Epoch 9: loss=0.6659, acc=0.65 ---> SEQUENTIAL TEST: Epoch 9: loss=0.6612, acc=0.68860 ---> NONSEQUENTIAL TEST: Epoch 9: loss=0.6999, acc=0.49920 SEQUENTIAL TRAIN, Epoch 10: loss=0.6593, acc=0.68 NONSEQUENTIAL TRAIN, Epoch 10: loss=0.6613, acc=0.68 ---> SEQUENTIAL TEST: Epoch 10: loss=0.6570, acc=0.68860 ---> NONSEQUENTIAL TEST: Epoch 10: loss=0.6988, acc=0.49920 SEQUENTIAL TRAIN, Epoch 11: loss=0.6522, acc=0.68 NONSEQUENTIAL TRAIN, Epoch 11: loss=0.6541, acc=0.68 ---> SEQUENTIAL TEST: Epoch 11: loss=0.6540, acc=0.68860 ---> NONSEQUENTIAL TEST: Epoch 11: loss=0.6978, acc=0.49920 SEQUENTIAL TRAIN, Epoch 12: loss=0.6651, acc=0.67 NONSEQUENTIAL TRAIN, Epoch 12: loss=0.6679, acc=0.67 ---> SEQUENTIAL TEST: Epoch 12: loss=0.6511, acc=0.68860 ---> NONSEQUENTIAL TEST: Epoch 12: loss=0.6971, acc=0.49920 SEQUENTIAL TRAIN, Epoch 13: loss=0.6617, acc=0.67 NONSEQUENTIAL TRAIN, Epoch 13: loss=0.6640, acc=0.67 ---> SEQUENTIAL TEST: Epoch 13: loss=0.6494, acc=0.68860 ---> NONSEQUENTIAL TEST: Epoch 13: loss=0.6964, acc=0.49920 SEQUENTIAL TRAIN, Epoch 14: loss=0.6506, acc=0.67 NONSEQUENTIAL TRAIN, Epoch 14: loss=0.6527, acc=0.67 ---> SEQUENTIAL TEST: Epoch 14: loss=0.6470, acc=0.68860 ---> NONSEQUENTIAL TEST: Epoch 14: loss=0.6961, acc=0.49920 SEQUENTIAL TRAIN, Epoch 15: loss=0.6479, acc=0.69 NONSEQUENTIAL TRAIN, Epoch 15: loss=0.6500, acc=0.69 ---> SEQUENTIAL TEST: Epoch 15: loss=0.6453, acc=0.68860 ---> NONSEQUENTIAL TEST: Epoch 15: loss=0.6954, acc=0.49920 SEQUENTIAL TRAIN, Epoch 16: loss=0.6441, acc=0.70 NONSEQUENTIAL TRAIN, Epoch 16: loss=0.6461, acc=0.70 ---> SEQUENTIAL TEST: Epoch 16: loss=0.6445, acc=0.68860 ---> NONSEQUENTIAL TEST: Epoch 16: loss=0.6950, acc=0.49920 ... I’ve found that the issue lies in the BatchNorm1d layer, because when I take it out of the model the issue disappears. Is there a difference between BatchNorm1d in a sequential block? Or have I made a mistake I am overlooking? Thank you in advance for any help! Here’s the full code: import torch from torch.utils import data from torch.optim import Adam from tqdm import tqdm class Dataset(data.Dataset): 'Characterizes a dataset for PyTorch' def __init__(self, data, labels): self.labels = labels self.data = data def __len__(self): 'Denotes the total number of samples' return len(self.labels) def __getitem__(self, index): 'Generates one sample of data' # Load data and get label X = self.data[index] y = self.labels[index] return X, y class Net(nn.Module): def __init__(self, hidden_dim, in_dim, use_sequential): super(Net, self).__init__() self.use_sequential = use_sequential self.in_dim = in_dim self.hidden_dim = hidden_dim self.sig = nn.Sigmoid() self.encoder = nn.Sequential( nn.Linear(in_dim, in_dim), nn.BatchNorm1d(in_dim), nn.Linear(in_dim, hidden_dim) ) self.decoder = nn.Sequential( nn.Linear(hidden_dim, in_dim), nn.BatchNorm1d(in_dim), nn.Linear(in_dim, in_dim) ) self.lin1 = nn.Linear(in_dim, in_dim) self.lin1.weight.data.fill_(0.01) self.lin1.bias.data.fill_(0.01) self.batchnorm = nn.BatchNorm1d(in_dim) self.batchnorm.weight.data.fill_(0.01) self.batchnorm.bias.data.fill_(0.01) self.lin2 = nn.Linear(in_dim, hidden_dim) self.lin2.weight.data.fill_(0.01) self.lin2.bias.data.fill_(0.01) self.lin3 = nn.Linear(hidden_dim, in_dim) self.lin3.weight.data.fill_(0.01) self.lin3.bias.data.fill_(0.01) self.lin4 = nn.Linear(in_dim, in_dim) self.lin4.weight.data.fill_(0.01) self.lin4.bias.data.fill_(0.01) def encode(self, x): if self.use_sequential: x = self.encoder(x) else: x = self.lin1(x) x = self.batchnorm(x) x = self.lin2(x) return x def decode(self, x): if self.use_sequential: x = self.decoder(x) else: x = self.lin3(x) x = self.batchnorm(x) x = self.lin4(x) return x def forward(self, x): x = self.encode(x) x = self.decode(x) x = self.sig(x) # Sigmoid for BCELoss return x def accuracy(preds, labels): acc2 = 1 - torch.sum(torch.abs(preds-labels)).item() / (list(preds.size())[0]*list(preds.size())[1]) return acc2 def generate_data(block_size): train_data = torch.randint(2, (10000, block_size)).float() test_data = torch.randint(2, (2500, block_size)).float() train_labels = train_data test_labels = test_data return train_data, train_labels, test_data, test_labels def init_weights(m): if type(m) == nn.Linear or type(m) == nn.BatchNorm1d: m.weight.data.fill_(0.01) m.bias.data.fill_(0.01) if type(m) == nn.PReLU: m.weight.data.fill_(0.01) ########################## Train code #################### IN_DIM = 4 HIDDEN_DIM = 32 EPOCHS = 200 BATCH_SIZE = 256 # Generate data train_data, train_labels, test_data, test_labels = generate_data(IN_DIM) # Data loading params = {'batch_size': BATCH_SIZE, 'shuffle': True, 'num_workers': 8} training_set = Dataset(train_data, train_labels) training_loader = torch.utils.data.DataLoader(training_set, **params) # Sequential and non-sequential models model_seq = Net(hidden_dim=HIDDEN_DIM, in_dim=IN_DIM, use_sequential=True) model_non = Net(hidden_dim=HIDDEN_DIM, in_dim=IN_DIM, use_sequential=False) model_seq.apply(init_weights) model_non.apply(init_weights) loss_fn = nn.BCEWithLogitsLoss() optimizer_seq = Adam(model_seq.parameters(), lr=0.001) optimizer_non = Adam(model_non.parameters(), lr=0.001) # Training for epoch in range(EPOCHS): model_seq.train() model_non.train() for batch_idx, (batch, labels) in enumerate(training_loader): # Testing sequential model output_seq = model_seq(batch) loss_seq = loss_fn(output_seq, labels) optimizer_seq.zero_grad() loss_seq.backward() optimizer_seq.step() # Testing non-sequential model output_non = model_non(batch) loss_non = loss_fn(output_non, labels) optimizer_non.zero_grad() loss_non.backward() optimizer_non.step() if batch_idx % (BATCH_SIZE-1) == 0: pred_seq = torch.round(output_seq) acc_seq = accuracy(pred_seq, labels) print('SEQUENTIAL TRAIN, Epoch %2d: loss=%.4f, acc=%.2f' % (epoch, loss_seq.item(), acc_seq)) pred_non = torch.round(output_non) acc_non = accuracy(pred_non, labels) print('NONSEQUENTIAL TRAIN, Epoch %2d: loss=%.4f, acc=%.2f' % (epoch, loss_non.item(), acc_non)) # Sequential Validation model_seq.eval() val_output_seq = model_seq(test_data) val_loss_seq = loss_fn(val_output_seq, test_labels) val_pred_seq = torch.round(val_output_seq) val_acc_seq = accuracy(val_pred_seq, test_labels) print('---> SEQUENTIAL TEST: Epoch %2d: loss=%.4f, acc=%.5f' % (epoch, val_loss_seq.item(), val_acc_seq)) model_seq.train() # Nonsequential Validation model_non.eval() val_output_non = model_non(test_data) val_loss_non = loss_fn(val_output_non, test_labels) val_pred_non = torch.round(val_output_non) val_acc_non = accuracy(val_pred_non, test_labels) print('---> NONSEQUENTIAL TEST: Epoch %2d: loss=%.4f, acc=%.5f' % (epoch, val_loss_non.item(), val_acc_non)) model_non.train() print('\n')
st84978
Thanks for the code. The difference is indeed in the usage of the batch norm layers. While you are initializing two different nn.BatchNorm1d layers in your sequential approach, you are reusing the same in your manual approach. Could you create two separate batch norm layers and run the test again?
st84979
Hello, I have DQN training that I’m doing, and I’ve messed around with the hyperparameters a lot and the best results I have so far, it learns a bit until around 10k-20k episodes, then it stagnates, and the average top return it gets starts to stay the same. The settings I have are: Batch size = 128 gamma = 0.999 eps start = 0.99 eps end = 0.05 eps decay = 100000 target update = 500 Learning rate = 0.0005 I’ve tried many settings, decaying till later, different learning rates, keeping exploration rate constant. I realize the exploration rate is still low at 10k episodes if it decays at 100k, however it is weird that after around 10k and 20k, suddenly, it stays same and the average scores keep start to go up and down a lot, here’s a screenshot: 500 target update.png1920×1023 104 KB Any ideas? So it seems to me like it already starts converging into something very quick even though it has high exploration rate still
st84980
Morning all, I am hoping that someone will be able to help me as I am at the end of my tether… I am trying to write the autoencoder for my network. having hit a problem i started experiementing with a know working decoder (shown below): class Decoder(nn.Module): def __init__(self, z_dim): super(Decoder, self).__init__() self.fc1 = nn.Linear(z_dim, 672) self.conv1 = nn.ConvTranspose1d(32, 32, 8, 2, padding=3) self.conv2 = nn.ConvTranspose1d(32, 32, 8, 2, padding=3) self.conv3 = nn.ConvTranspose1d(32, 16, 8, 2, padding=3) self.conv4 = nn.ConvTranspose1d(16, 16, 8, 2, padding=3) self.conv5 = nn.ConvTranspose1d(16, 1, 7, 1, padding=3) self.bn1 = nn.BatchNorm1d(32) self.bn2 = nn.BatchNorm1d(32) self.bn3 = nn.BatchNorm1d(16) self.bn4 = nn.BatchNorm1d(16) self.relu = nn.ReLU() def forward(self, z): z = self.relu(self.fc1(z)) print(z) print(z.shape) #z = F.dropout(z, 0.3) z = z.view(-1, 32, 21) z = self.relu(self.conv1(z)) z = self.bn1(z) #z = F.dropout(z, 0.3) z = self.relu(self.conv2(z)) z = self.bn2(z) #z = F.dropout(z, 0.3) z = self.relu(self.conv3(z)) z = self.bn3(z) #z = F.dropout(z, 0.3) z = self.relu(self.conv4(z)) z = self.bn4(z) #z = F.dropout(z, 0.3) z = self.conv5(z) recon = torch.sigmoid(z) return recon summary(vae.decoder, (1, 2)) this gives the following results: **tensor([[[0.0000, 0.3415, 0.6484, ..., 0.2840, 0.0000, 0.3873]],** ** [[0.0000, 0.4126, 0.6034, ..., 0.2224, 0.0000, 0.3813]]],** ** device='cuda:0', grad_fn=<ReluBackward0>)** **torch.Size([2, 1, 672])** **----------------------------------------------------------------** ** Layer (type) Output Shape Param #** **================================================================** ** Linear-1 [-1, 1, 672] 2,016** ** ReLU-2 [-1, 1, 672] 0** ** ConvTranspose1d-3 [-1, 32, 42] 8,224** ** ReLU-4 [-1, 32, 42] 0** ** BatchNorm1d-5 [-1, 32, 42] 64** ** ConvTranspose1d-6 [-1, 32, 84] 8,224** ** ReLU-7 [-1, 32, 84] 0** ** BatchNorm1d-8 [-1, 32, 84] 64** ** ConvTranspose1d-9 [-1, 16, 168] 4,112** ** ReLU-10 [-1, 16, 168] 0** ** BatchNorm1d-11 [-1, 16, 168] 32** ** ConvTranspose1d-12 [-1, 16, 336] 2,064** ** ReLU-13 [-1, 16, 336] 0** ** BatchNorm1d-14 [-1, 16, 336] 32** ** ConvTranspose1d-15 [-1, 1, 336] 113** **================================================================** **Total params: 24,945** **Trainable params: 24,945** **Non-trainable params: 0** **----------------------------------------------------------------** **Input size (MB): 0.00** **Forward/backward pass size (MB): 0.29** **Params size (MB): 0.10** **Estimated Total Size (MB): 0.38** **----------------------------------------------------------------** **which is expected.** however changing the decoder to be included in a nn.sequential module the summary no longer works (see below). class Decoder(nn.Module): def __init__(self, z_dim): super(Decoder, self).__init__() self.decode = nn.Sequential(OrderedDict([ ('fc1',nn.Linear(z_dim, 672)), ('conv1',nn.ConvTranspose1d(32, 32, 8, 2, padding=3)), ('conv2',nn.ConvTranspose1d(32, 32, 8, 2, padding=3)), ('conv3',nn.ConvTranspose1d(32, 16, 8, 2, padding=3)), ('conv4',nn.ConvTranspose1d(16, 16, 8, 2, padding=3)), ('conv5',nn.ConvTranspose1d(16, 1, 7, 1, padding=3)), ('bn1',nn.BatchNorm1d(32)), ('bn2',nn.BatchNorm1d(32)), ('bn3',nn.BatchNorm1d(16)), ('bn4',nn.BatchNorm1d(16)), ('relu',nn.ReLU()) ])) def forward(self, z): z = self.decode.relu(self.decode.fc1(z)) print(z) print(z.shape) z = z.view(-1, 32, 31) z = self.decode(z) #z = self.relu(self.fc1(z)) #z = F.dropout(z, 0.3) recon = torch.sigmoid(z) return recon summary(vae.decoder, (1, 2)) This gives the following error: tensor([[[0.6222, 0.0000, 0.0000, ..., 0.0180, 0.3997, 0.3615]], [[0.7606, 0.0000, 0.0000, ..., 0.0000, 0.2021, 0.2654]]], device='cuda:0', grad_fn=<ReluBackward0>) torch.Size([2, 1, 672]) Traceback (most recent call last): File "G:/decoder-test.py", line 30, in forward z = z.view(-1, 32, 31) RuntimeError: shape '[-1, 32, 31]' is invalid for input of size 1344 I know I have done something silly, but I cannot for the life of me see what (removing the z = self.decode.relu(self.decode.fc1(z)) line just changes the size from 1344 to 4)… I’m hopng that someone can point me in the correct direction… Chaslie
st84981
Solved by chaslie in post #8 Oli, thanks for this you are a life saver. I tried putting the fc1 layer into a another sequential slot but that didn’t work. Your solution is neat and works… Chaslie
st84982
chaslie: z = z.view(-1, 32, 31) Did you mean to do z = z.view(-1, 32, 21)? But, I’m not sure the code will work on the next line where you do z = self.decode(z) anyways. But one step at a time
st84983
hi Olaf, thanks for spotting that, yes i did mean z.view(-1,32,21), but know i haave the following error output = input.matmul(weight.t()) RuntimeError: size mismatch, m1: [64 x 21], m2: [2 x 672] at C:/w/1/s/tmp_conda_3.7_044431/conda/conda-bld/pytorch_1556686009173/work/aten/src\THC/generic/THCTensorMathBlas.cu:268 commenting out “z = self.decode.relu(self.decode.fc1(z))” (as i am double accounting) gives this error File “G:/decoder-test.py”, line 30, in forward z = z.view(-1, 32, 21) RuntimeError: shape ‘[-1, 32, 21]’ is invalid for input of size 4
st84984
I think you should look further into how the nn.Sequential model works. From my understanding it is used when you want a series of layers to always execute after one another, but it has to be put into the sequential in that order. Honestly, I think your first code was fine. Why did you want to put it into sequential in the first place? Example of sequential, but without the dropout (which you should probably not use if you use batchnorm) self.decode = nn.Sequential(OrderedDict([ ('conv1',nn.ConvTranspose1d(32, 32, 8, 2, padding=3)), ('bn1',nn.BatchNorm1d(32)), ('conv2',nn.ConvTranspose1d(32, 32, 8, 2, padding=3)), ('bn2',nn.BatchNorm1d(32)), ... ]))
st84985
Hi Olaf, Sorry for the delay. The reason I chose to use sequential is that i understood that it ran quicker and was more efficient… I’m just trying your suggestion know, I will let you know if solves the problem. chaslie
st84986
hi Olaf, thanks for the suggestion but that didn’t get over the error. self.decode = nn.Sequential(OrderedDict([ ('fc1',nn.Linear(z_dim, 672)), ('relu1',nn.ReLU()), ('conv1',nn.ConvTranspose1d(32, 32, 8, 2, padding=3)), ('bn1',nn.BatchNorm1d(32)), ('conv2',nn.ConvTranspose1d(32, 32, 8, 2, padding=3)), ('bn2',nn.BatchNorm1d(32)), ('conv3',nn.ConvTranspose1d(32, 16, 8, 2, padding=3)), ('bn3',nn.BatchNorm1d(32)), ('conv4',nn.ConvTranspose1d(16, 16, 8, 2, padding=3)), ('bn4',nn.BatchNorm1d(32)), ('conv5',nn.ConvTranspose1d(16, 1, 7, 1, padding=3)), ])) def forward(self, z): z = self.decode.relu1(self.decode.fc1(z)) print(z) print(z.shape) z = z.view(-1, 32, 21) print(z) print(z.shape) z = self.decode(z) print(z) print(z.shape) #z = self.relu(self.fc1(z)) #z = F.dropout(z, 0.3) recon = torch.sigmoid(z) return recon gives the following error: tensor([[[0.3054, 0.0000, 0.0000, ..., 0.0000, 0.4342, 0.0000]], [[0.4361, 0.0000, 0.0000, ..., 0.0206, 0.5194, 0.0000]]], device='cuda:0', grad_fn=<ReluBackward0>) torch.Size([2, 1, 672]) tensor([[[0.3054, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000], [0.4938, 0.0000, 0.0000, ..., 0.0000, 0.2481, 0.9124], [0.5702, 0.0000, 0.0000, ..., 0.4131, 0.1147, 0.0842], ..., [0.0000, 0.1210, 0.5313, ..., 0.6218, 0.3895, 0.0000], [0.0000, 0.0000, 0.0000, ..., 0.0850, 0.5332, 0.1528], [0.2276, 0.0021, 0.0000, ..., 0.0000, 0.4342, 0.0000]], [[0.4361, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000], [0.3129, 0.0000, 0.0000, ..., 0.0000, 0.3701, 1.3570], [0.8684, 0.0000, 0.0000, ..., 0.2555, 0.4145, 0.0000], ..., [0.0000, 0.4524, 0.8189, ..., 0.8206, 0.2301, 0.0000], [0.0000, 0.0000, 0.0000, ..., 0.4690, 0.3480, 0.0000], [0.0000, 0.0000, 0.0000, ..., 0.0206, 0.5194, 0.0000]]], device='cuda:0', grad_fn=<ViewBackward>) torch.Size([2, 32, 21]) Traceback (most recent call last): RuntimeError: size mismatch, m1: [64 x 21], m2: [2 x 672] at C:/w/1/s/tmp_conda_3.7_044431/conda/conda-bld/pytorch_1556686009173/work/aten/src\THC/generic/THCTensorMathBlas.cu:268
st84987
I don’t think you can include a view into your sequential. Saw a post where they tried to make it into a layer but I wouldn’t bother. You’re not going to see that much speedup anyways. I suggest that you do something like this import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict class MyModel(nn.Module): def __init__(self, zdim): super().__init__() self.fc1 = nn.Linear(zdim, 672) self.decode = nn.Sequential(OrderedDict([ ('conv1',nn.ConvTranspose1d(32, 32, 8, 2, padding=3)), ('relu1',nn.ReLU()), ('bn1',nn.BatchNorm1d(32)), ('conv2',nn.ConvTranspose1d(32, 32, 8, 2, padding=3)), ('relu2',nn.ReLU()), ('bn2',nn.BatchNorm1d(32)), ('conv3',nn.ConvTranspose1d(32, 16, 8, 2, padding=3)), ('relu3',nn.ReLU()), ('bn3',nn.BatchNorm1d(16)), ])) def forward(self, z): z = F.relu(self.fc1(z)) print(z) print(z.shape) z = z.view(-1, 32, 21) z = self.decode(z) print(z.shape) zdim = 10 model = MyModel(zdim) inputs = torch.randn(2, zdim) outputs = model(inputs)
st84988
Oli, thanks for this you are a life saver. I tried putting the fc1 layer into a another sequential slot but that didn’t work. Your solution is neat and works… Chaslie
st84989
This is my data, id label tweet 0 1 0 @user when a father is dysfunctional and is so selfish he drags his kids into his dysfunction. #run which is in text format, I have pre-processed it and then I want to fit a PyTorch LSTM model in it. To fit the model I have to split the dataset into train and test set, and as PyTorch has a very interesting module called DataLoader to load the dataset, so we could use it. But as soon as I do this - train_data = TensorDataset(torch.from_numpy(np.array(train_x)), torch.from_numpy(np.array(train_y))) valid_data = TensorDataset(torch.from_numpy(np.array(valid_x)), torch.from_numpy(np.array(valid_y))) test_data = TensorDataset(torch.from_numpy(np.array(test_x)), torch.from_numpy(np.array(test_y))) It throws an error that TypeError: can't convert np.ndarray of type numpy.object_. The only supported types are: float64, float32, float16, int64, int32, int16, int8, and uint8. in the line of ----> 4 train_data = TensorDataset(torch.from_numpy(np.array(train_x)),torch.from_numpy(np.array(train_y))) I have also printed the shape and type of the splitted datasets, print('shape of training set: {}' .format(train_x.shape)) print('shape of valid set: {}' .format(valid_x.shape)) print('shape of test set: {}' .format(test_x.shape)) shape of training set: (32979,) shape of valid set: (2910,) shape of test set: (2910,) print(train_x.dtype) object How can I solve this error? I have tried solutions like converting the object type to string or float, neither of them worked. I am not getting any solutions. Any help appriciated.
st84990
I would suggest to encode the words as some indices similar to the Lang class in the Seq2Seq Tutorial 136.
st84991
So, here I am encoding my sorted words using this - reviews_int = [] for review in combi['tidy_tweet']: r = [vocab_to_int[w] for w in review.split()] reviews_int.append(r) print(reviews_int[0:3]) OUTPUT: [[38, 4, 86, 10, 14869, 6, 10, 22, 4161, 71, 9356, 97, 332, 245, 97, 14870, 1301], [170, 8, 11409, 2355, 3, 33, 18, 424, 625, 59, 70, 18, 1651, 14871, 14872, 7, 14873, 22887, 14874], [76, 25, 4162]] Then I convert it to np.array like this - reviews_int = np.array(reviews_int) Still when I try to print the dtype of the reviews_int, it shows - print(reviews_int.dtype) object How can I do this now? Is Seq2Seq is the only way? My approach is wrong?
st84992
I’m not sure, how you’ve processed the text, but the methods from the seq2seq tutorial seem to work for your example tweet: text = '@user when a father is dysfunctional and is so selfish he drags his kids into his dysfunction. #run' text = normalizeString(text) input_lang = Lang('tweet') input_lang.addSentence(text) encoded = [input_lang.word2index[w] for w in text.split(' ')] input = torch.tensor(encoded) print(input.type()) > torch.LongTensor
st84993
ptrblck: normalizeString So, do I need apply those two methods? normalizeString and Lang? Also, what does it input_lang = Lang('tweet') mean? why aren’t we passing text file there?
st84994
You don’t need the exact same class Lang, but could have a look at the underlying operations and how to transform each word to an index. Also, zou don’t necessarily need normalizeString, but it might help cleaning the tweets. The passed argument to Lang is just the name of the language, which I called “tweet”. The most important part is, that using the input_lang.word2index dict, you’ll get valid word indices, which can be used to train a model.
st84995
Hi all, I was able to implement Resnet34 using the class as follows class Resnet34(nn.Module): def __init__(self, num_classes = 10): super(Resnet34,self).__init__() original_model = models.resnet34(pretrained=True) self.features = nn.Sequential(*list(original_model.children())[:-1]) self.classifier = nn.Sequential(nn.Linear(512, num_classes)) def forward(self, x): f = self.features(x) f = f.view(f.size(0), -1) y = self.classifier(f) return f,y But when i try similar approach for densenet. class Densenet161(nn.Module): def __init__(self, num_classes = 2): super(Densenet161,self).__init__() original_model = models.densenet161(pretrained=True) self.features = nn.Sequential(*list(original_model.children())[:-1]) self.classifier = (nn.Linear(2208, num_classes)) def forward(self, x): f = self.features(x) f = f.view(f.size(0), -1) y = self.classifier(f) return f,y I get the following error RuntimeError: size mismatch at /py/conda-bld/pytorch_1493676237139/work/torch/lib/THC/generic/THCTensorMathBlas.cu:243 I am using the same code used in Pytorch transfer learning fine tuning example. Please suggest a method to sort the issue
st84996
It is best to read the model definitions first, otherwise you wont know what’s wrong. Densenet has average pooling before the classifier stage: github.com pytorch/vision/blob/master/torchvision/models/densenet.py#L158-L159 98 if isinstance(m, nn.Conv2d): nn.init.kaiming_normal(m.weight.data) Here’s a corrected version: import torch import torch.nn as nn from torch.autograd import Variable import torchvision.models as models import torch.nn.functional as F class Densenet161(nn.Module): def __init__(self, num_classes = 2): super(Densenet161,self).__init__() original_model = models.densenet161() self.features = nn.Sequential(*list(original_model.children())[:-1]) self.classifier = (nn.Linear(2208, num_classes)) def forward(self, x): f = self.features(x) f = F.relu(f, inplace=True) f = F.avg_pool2d(f, kernel_size=7).view(f.size(0), -1) y = self.classifier(f) return f,y x = Densenet161() inp = Variable(torch.randn(4, 3, 224, 224)) out = x(inp)
st84997
Thanks @smth … I downloaded the densenet code from the pytorch git and I modified the model as per my need. Its working good. Thanks
st84998
Here is the correct code for Transfer learning with densenet dset_classes_number = len(class_names) model_ft = models.densenet121(pretrained=True) model_ft.classifier = nn.Linear(1024, dset_classes_number)
st84999
I have this tensor: tensor([[425.0000, 625.0000], [550.0000, 566.6667], [700.0000, 600.0000]]) and I want to obtain something like this: tensor([[425.0000, 425.0000, 625.0000, 625.0000], [550.0000, 550.0000, 566.6667, 566.6667], [700.0000, 700.0000, 600.0000, 600.0000] Is there anyway to do this efficiently?
st30000
To debug the training loop, you might want to check that your model can overfit a small training set (a few examples).
st30001
def train(model,dataloader,validloader,criterion,optimizer,epochs=50): max_valid_acc = 0 train_acc,val_acc = 0,0 for e in range(epochs): train_loss = 0.0 model.train() # Optional when not using Model Specific layer for data, labels in dataloader: # print(labels.shape[0]) data, labels = data.to(device), labels.to(device) # print(data.shape) optimizer.zero_grad() target = model(data) # print(target.shape) loss = criterion(target.float(),labels.long()) loss.backward() optimizer.step() train_loss = loss.item() * data.size(0) train_acc += torch.sum((torch.max(target, 1)[1] == labels.data),0) valid_loss = 0.0 model.eval() # Optional when not using Model Specific layer for data, labels in validloader: data, labels = data.to(device), labels.to(device) target = model(data) loss = criterion(target.float(),labels.long()) valid_loss = loss.item() * data.size(0) val_acc += torch.sum((torch.max(target, 1)[1] == labels.data),0) print(f'Epoch {e+1} \t\t Training Loss: {train_loss / len(dataloader)} \t\t Validation Loss: {valid_loss / len(validloader)}') print("Validation Accuracy ... :",val_acc/(len(validloader))) print("Train Accuracy ... :",train_acc/(len(X_train_tensor))) if val_acc > max_valid_acc: print(f'Validation Acc Increased({max_valid_acc:.6f}--->{val_acc:.6f}) \t Saving The Model') max_valid_acc = val_acc # Saving State Dict torch.save(model.state_dict(), 'saved_model.pth') train_acc = 0 val_acc = 0 return model How can I check that a few examples are overfitting? I’m beginner
st30002
I’m getting this… Epoch 18 Training Loss: 0.004407357424497604 Validation Loss: 8.263123961403024e-08 Validation Accuracy … : tensor(0.4572, device=‘cuda:0’) Train Accuracy … : tensor(0.9526, device=‘cuda:0’) I’m using optimizer = optim.SGD(net.parameters(), lr = 0.0001,momentum = 0.92) and net.fc = nn.Sequential(nn.Linear(2048,512,bias = True), nn.ReLU(inplace=True), nn.Linear(512,6), ) in Resnet50. @eqy
st30003
For example, you can just load the first batch in the dataloader (then break from the loading loop) and verify that the loss goes down to basically zero after many epochs (you might want to tweak your learning rate schedule, if you have one for this experiment as the epochs have fewer examples now).
st30004
I have 28,000 training example so do I need to do for all the batches of let’s say 128 images manually train?
st30005
Yes, training for 128 images manually would work. Actually, you may want to just use the first epoch to get 128 (shuffled images) and then just reuse this first batch over and over.
st30006
But if I got the data which is overfitting how can I drop that from trainloader? But I have one question that if validation loss is decreasing then why the validation accuracy doesn’t increase and decrease for some epoch and behaves wrong.
st30007
The purpose of this test is not to improve the model but to simply verify that the basic training loop is working properly. If it works, then it makes sense to revert the changes and start looking at other potential issues. The issue of loss going down without accuracy increasing is possible; for example if the model makes the same incorrect predictions but with lower confidence between epochs this will cause the loss to decrease without an actual increase in performance.
st30008
Hey, It is well known that a model works better if the data is standardized. Here is how I deal with this in the context of regression based on tabular data: df_train, df_test, df_val = get_data(config) if config['scaler'] is not None: scaler = config['scaler'] else: scaler = StandardScaler().fit(df[config['columns']], df[target]) # I only scale some numerical columns df_train, df_test, df_val = scaler.transform(df_train), scaler.transform(df_test), scaler.transform(df_val) best_model, test_predictions = train(df_train, df_test, df_val, config) target_std, target_mean = get_scaler_coeffs(scaler) test_predictions['y_hat'] = test_predictions['y_hat'] * target_std + target_mean store_results(test_predictions, best_model, scaler, config) In short, I use StandardScaler from sklearn to scale values (target included) and pandas for operating with csv files. After training, I store the best model along with its scaler and its results. I think that this approach is not elegant at all, but I can’t figure out how should I change the code. What is the “standard” way of dealing with scalling and reverse scalling in pytorch? (preferably for regression purposes)
st30009
I converted a PyTorch Tensor into a NumPy ndarray, and as it’s shown below ‘a’ and ‘b’ both have different ids so they point to different memory locations. I know in PyTorch underscore indicates in-place operation so a.add_(1) does not change the memory location of a, but why does it change the content of the array b (due to the difference in id)? import torch a = torch.ones(5) b = a.numpy() a.add_(1) print(id(a), id(b)) print(a) print(b) Results: 139851293933696 139851293925904 tensor([2., 2., 2., 2., 2.]) [2. 2. 2. 2. 2.] PyTorch documentation: Converting a torch Tensor to a NumPy array and vice versa is a breeze. The torch Tensor and NumPy array will share their underlying memory locations, and changing one will change the other. But why? (They have different IDs so must be independent)
st30010
Solved by googlebot in post #2 id() is inappropriate because python objects are not value objects, i.e. they link to other objects, and you just have multiple links here (see .storage().data_ptr() to reason about address identities)
st30011
id() is inappropriate because python objects are not value objects, i.e. they link to other objects, and you just have multiple links here (see .storage().data_ptr() to reason about address identities)
st30012
Hello! I would want to compute the training accuracy of my neural network, but I want it to be IOU. I found something on the internet but mostly are for binary classification only, can anyone help me? by the way this is my script so far: def display_segmentation(): model = ESNet(classes=6) path = F"/content/drive/MyDrive/Thesis_QuilangCastillano/Models/ESNET_5250.37-checkpoint.pt" checkpoint = torch.load(path) model.load_state_dict(checkpoint['state_dict']) total = 0 correct = 0 torch.set_printoptions(edgeitems=128) with torch.no_grad(): model.eval() for i in tqdm(range(1)): net_out = model(img[100].view(-1, 3, 384, 512)) segmentation_label = torch.argmax(net_out.squeeze(), dim= 0) segmented_image = decode_segmap(segmentation_label) label = np.unique(segmentation_label) groundtruth = np.unique(mask[100]) alpha = 0.3 # how much transparency to apply beta = 1 - alpha # alpha + beta should equal 1 gamma = 0 # scalar added to each sum image = np.array(img[100].view(384, 512, 3)) prediction = cv2.addWeighted(segmented_image, alpha, image, beta, gamma, image, dtype=cv2.CV_64F) Sub = f"Prediction: {label}, Groundtruth: {groundtruth}" plt.imshow(prediction) plt.title(Sub) plt.show() display_segmentation() this script outputs this one: image1303×551 58.9 KB the groundtruth array contains the class number of what class should be present in an image, the prediction array contains the class number of what the neural net thinks the image is composed of
st30013
I would recommend you don’t start from vanilla PyTorch as there are multiple decent libraries built on top of it that simplify building models. You could try lightning bolts 1 for baseline model architecture + training procedure (you just need to replace the provided dataset with your own. For IoU implementation you can use torchmetrics 4.
st30014
Hi everyone, I’m in a pickle here. I have a problem where I get streaming data and a Pytorch model which is to be continuously trained on the said streaming data (in batches of 16 multi-feature data points). Now I have been trying to come up with a class/code structure which would facilitate this, but I have been unable to come up with a solution. My model is initialized through a class. I tried something like this: def train(model, data, batch_size): # Get data in appropriate format train_data = TensorDataset(torch.from_numpy(np.array(data)), torch.from_numpy(np.array(data))) train_loader = DataLoader(train_data, shuffle=False, batch_size=batch_size) model = model.double() # Model Hyperparameters criterion = nn.MSELoss() optimizer = optim.RMSprop(model.parameters()) # Keep track of training loss train_loss = 0. # Train the model model.train() for data, label in train_loader: data = data.double() label = label.double() # Clear gradients of all optimized variables optimizer.zero_grad() # Convert data to appropriate format of : (batch_size, seq_len, input_dimensions) data = data.view(batch_size, 1, data.size(1)) # Forward pass output = model(data) # Calcualte batch loss loss = criterion(output.squeeze(), label) # Backward pass loss.backward() # Perform a single optimization step optimizer.step() return model, loss And then calling the function on each collected batch individually, such as: model, loss = train(model, data[:16], 16) But this is a very stupid approach in my mind and there has got to be a better approach. Moreover, this does not give me the right losses anyway (I want to get losses per batch as an output) as the losses are calculated as if the model is re-tranied from scratch at every call (I thought that passing back the model would ensure that its weights after each update are maintained, but I seem to be wrong). Any help would e appreciated. P.S.: I am not a software engineer but more of a domain expert data scientist and so please forgive me if I made any naive mistake.
st30015
It seems IterableDataset 294 would be suitable for streaming data: For example, such a dataset, when called iter(dataset) , could return a stream of data reading from a database, a remote server, or even logs generated in real time.
st30016
hello, is there any tutorial or example explaining carefully how to stream temporally coherent batches? i did this github here: https://github.com/etienne87/pytorch-streamloader 187 to explain precisely what I would like from pytorch. (well i did it and it works but perhaps it can be done in 3 lines of code in pytorch ^^).
st30017
Hi there, since so many people clicked there, i just wanted to say that i simplified a bit the code, and that, in fact, the easiest for people who train networks with memory could be to just use an IterableDataset where you yield the worker’s id at the same time as your data. Otherwise, I did a wrapper around Pytorch DataLoader that just concatenates the data from different FIFOs indexed by the worker’s id.
st30018
Hello! I am working on textual entailment. Can anyone please help on how to visualize the premise and hypothesis of activated neurons? similarly like this: Best Regards
st30019
Hello! I am new to PyTorch and I am trying to implement a Bidirectional LSTM model with input sequences of varied length. I wanted to mask the inputs to avoid influencing the gradient calculation with the padding information. Is this the right way to proceed? class Bi_RNN(nn.Module): def __init__(self, input_dim1, input_dim2, hidden_dim, batch_size, output_dim, num_layers=2, rnn_type='LSTM'): super(Bi_RNN, self).__init__() self.input_dim1 = input_dim1 self.input_dim2 = input_dim2 self.hidden_dim = hidden_dim self.batch_size = batch_size self.num_layers = num_layers #Define the initial linear hidden layer self.init_linear1 = nn.Linear(self.input_dim1, self.input_dim1) self.init_linear2 = nn.Linear(self.input_dim2, self.input_dim2) # Define the LSTM layer self.lstm1 = eval('nn.' + rnn_type)(self.input_dim1, self.hidden_dim, self.num_layers, batch_first=True, bidirectional=True) self.lstm2 = eval('nn.' + rnn_type)(self.input_dim2, self.hidden_dim, self.num_layers, batch_first=True, bidirectional=True) self.lstm3 = eval('nn.' + rnn_type)(self.hidden_dim *4, self.hidden_dim, self.num_layers, batch_first=True, bidirectional=True) # Define the output layer self.linear = nn.Linear(self.hidden_dim * 2 , output_dim) self.log_softmax = nn.LogSoftmax(dim=1) def init_hidden(self): # This is what we'll initialise our hidden state as return (torch.zeros(self.num_layers, self.batch_size, self.hidden_dim), torch.zeros(self.num_layers, self.batch_size, self.hidden_dim)) def forward(self, input1, input2, x_lens): x1_packed = pack_padded_sequence(input1, x_lens, batch_first=True, enforce_sorted=False) x2_packed = pack_padded_sequence(input2, x_lens, batch_first=True, enforce_sorted=False) # Forward pass through LSTM layer lstm_out1, self.hidden1 = self.lstm1(x1_packed) lstm_out1_padded, output1_lengths = pad_packed_sequence(lstm_out1, batch_first=True) lstm_out2, self.hidden2 = self.lstm2(x2_packed) lstm_out2_padded, output2_lengths = pad_packed_sequence(lstm_out2, batch_first=True) lstm_out3 = torch.cat((lstm_out1_padded, lstm_out2_padded), 2) lstm_out, self.hidden3 = self.lstm3(lstm_out3) y_pred = self.log_softmax(self.linear(lstm_out)) return y_pred
st30020
I am using the torch.Distribution package inside of my Module. However, since the distribution classes do not inherit from torch.Module, they won’t be saved when calling my_module.state_dict(). Is there an easy way to save the distributions? import torch class GmmNet(torch.nn.Module): def __init__(self): super(GmmNet, self).__init__() # Example, random parameters self.gmm = D.MixtureSameFamily(D.Categorical(torch.nn.parameter.Parameter(torch.ones(5,))), D.Normal(torch.randn(5,),(torch.rand(5,)))) def forward(self, x): return self.gmm.log_prob(x) print(GmmNet().state_dict()) # --> OrderedDict()
st30021
Solved by googlebot in post #2 bigger issue is that Distribution objects are immutable, so you can’t push nn.Parameters inside them in __init__. Keep parameters in modules, create transient Distribution objects in forward, then saving & training will work correctly.
st30022
bigger issue is that Distribution objects are immutable, so you can’t push nn.Parameters inside them in __init__. Keep parameters in modules, create transient Distribution objects in forward, then saving & training will work correctly.
st30023
Thanks! For anyone else, this is the working code: import torch class GmmNet(torch.nn.Module): def __init__(self): super(GmmNet, self).__init__() self.cat = torch.nn.parameter.Parameter(torch.ones(5,)) self.cov = torch.nn.parameter.Parameter(torch.ones(5,)) def forward(self, x): gmm = D.MixtureSameFamily(D.Categorical(self.cat), D.Normal(self.cov, self.cov)) return gmm.log_prob(x) print(GmmNet().state_dict()) # --> OrderedDict([('cat', tensor([1., 1., 1., 1., 1.])), ('cov', tensor([1., 1., 1., 1., 1.]))])
st30024
I have a PyTorch model and I want to deploy it in TensorRT. I want to know what are the best practices to carry out before moving the model to ONNX (should I train it in fp32 or fp16 using AMP), what are the best practices to do while the model is in ONNX(use anything from the ONNX optimization toolkit), and what are the best practices to carry out while the model is in TensorRT? The goal is to maximize inference time in the deployment stage. Since, there are so many different articles and methods to optimize a PyTorch model, include PyTorch JIT and torchscript, I am confused about which steps to carry out and which to not. The goal is to maximize inference time in the deployment stage.
st30025
Hi, I have model in the model of forward, as follows. model2 = torchvision.models.video.r3d_18(pretrained=False).to('cuda') class model1(torch.nn.Module): def __init__(self): super(model1, self).__init__() self.ReLU = ReLU(400, 128, 1) self.QoS = nn.Linear(128, 1) def forward(self, pixel): pixel = model2(pixel.cuda()) pixel = self.ReLU(pixel) pixel = self.QoS(pixel) return pixel Now, I’m training model1 by loss.backward() However, the model2, located in the model1’s forward, is trained? If not, How can I train the model 2? My model 1 train code is as follows. for idx, (raw_data, len_frame, true_mos) in enumerate(train_module): raw_data = raw_data.to(device).float() true_mos = true_mos.to(device).float() optimizer.zero_grad() outputs = model1(raw_data) loss = criterion(outputs, true_mos) loss.backward() optimizer.step() Thanks.
st30026
Solved by Ali1234 in post #2 I had similar case. When I checked the loss value of inner model’s output after each epoch, it was different (decreasing). This means that the model weights are changing which implies the model is training. So, as far as you don’t use detach() the model2 is training. To verify, you can also return t…
st30027
I had similar case. When I checked the loss value of inner model’s output after each epoch, it was different (decreasing). This means that the model weights are changing which implies the model is training. So, as far as you don’t use detach() the model2 is training. To verify, you can also return the output of model2() and check the loss value (or the vectors themselves) after each epoch. Something like the following: class model1(torch.nn.Module): def __init__(self): super(model1, self).__init__() self.ReLU = ReLU(400, 128, 1) self.QoS = nn.Linear(128, 1) def forward(self, pixel): model2_out = model2(pixel.cuda()) pixel = self.ReLU(model2_out) pixel = self.QoS(pixel) return model2_out, pixel for idx, (raw_data, len_frame, true_mos) in enumerate(train_module): raw_data = raw_data.to(device).float() true_mos = true_mos.to(device).float() optimizer.zero_grad() model2_out, outputs = model1(raw_data) if (idx == 0): print("model2_out: ", model2_out) loss = criterion(outputs, true_mos) loss.backward() optimizer.step() but if you have the ground truth data for model2 output, you can check loss value instead of the tensor values. Hope this helps
st30028
I think so. And it’s easily verifiable, you can proceed as @Ali1234 says, but it can also be done without the need to calculate an intermediate loss. For example you can check the following quantity before and after optimizer.step() : norm_check = (sum([p.norm(p=2).item() ** 2 for p in model2.parameters()]) ** 0.5 Or after loss.backward() you can check the gradient of one of the parameters of ``model2``` next(model2.parameters()).grad There are some that are certainly more efficient…
st30029
My code is running fine but the model is not training regardless of the hyperparameters I use. I am not sure where it is going wrong. I am facing the same issue with a different model while using CTC Loss. Am I not understanding CTCLOss() correctly? Here is my model: class Bi_RNN(nn.Module): def __init__(self, input_dim1, input_dim2, hidden_dim, batch_size, output_dim=35, num_layers=2, rnn_type='LSTM'): super(Bi_RNN, self).__init__() self.input_dim1 = input_dim1 self.input_dim2 = input_dim2 self.hidden_dim = hidden_dim self.batch_size = batch_size self.num_layers = num_layers #Define the initial linear hidden layer self.init_linear1 = nn.Linear(self.input_dim1, self.input_dim1) self.init_linear2 = nn.Linear(self.input_dim2, self.input_dim2) # Define the LSTM layer self.lstm1 = eval('nn.' + rnn_type)(self.input_dim1, self.hidden_dim, self.num_layers, batch_first=True, bidirectional=True) self.lstm2 = eval('nn.' + rnn_type)(self.input_dim2, self.hidden_dim, self.num_layers, batch_first=True, bidirectional=True) self.lstm3 = eval('nn.' + rnn_type)(self.hidden_dim *2 *2, self.hidden_dim, self.num_layers, batch_first=True, bidirectional=True) # Define the output layer self.linear = nn.Linear(self.hidden_dim * 2 , output_dim) self.log_softmax = nn.LogSoftmax(dim=1) def init_hidden(self): # This is what we'll initialise our hidden state as return (torch.zeros(self.num_layers, self.batch_size, self.hidden_dim), torch.zeros(self.num_layers, self.batch_size, self.hidden_dim)) def forward(self, input1, input2): #Forward pass through initial hidden layer linear_input1 = self.init_linear1(input1) linear_input2 = self.init_linear2(input2) # Forward pass through LSTM layer # shape of lstm_out: [batch_size, input_size ,hidden_dim] # shape of self.hidden: (a, b), where a and b both # have shape (batch_size, num_layers, hidden_dim). lstm_out1, self.hidden1 = self.lstm1(linear_input1) lstm_out2, self.hidden2 = self.lstm2(linear_input2) # Can pass on the entirety of lstm_out to the next layer if it is a seq2seq prediction lstm_out3 = torch.cat((lstm_out1, lstm_out2), 2) lstm_out, self.hidden3 = self.lstm3(lstm_out3) y_pred = self.log_softmax(self.linear(lstm_out)) return y_pred I am using Adam Optimizer and CTC Loss model = Bi_RNN(input_dim1, input_dim2, hidden_dim, num_layers, num_classes).to(device) criterion = nn.CTCLoss(blank=0, reduction='mean') optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE) This is my training loop for e in tqdm(range(1, EPOCHS+1)): # TRAINING train_epoch_loss = 0 train_epoch_acc = 0 model.train() for X1_train_batch, X2_train_batch, y_train_batch, X_train_lens, y_train_lens in train_loader: X1_train_batch, X2_train_batch, y_train_batch, X_train_lens, y_train_lens = X1_train_batch.to(device), X2_train_batch.to(device), y_train_batch.to(device), X_train_lens.to(device), y_train_lens.to(device) y_train_pred = model(X1_train_batch, X2_train_batch) y_train_batch = torch.squeeze(y_train_batch) T = MAX_SEQ_LEN N = BATCH_SIZE C = num_classes pred_len = torch.full((N,), T, dtype=torch.long) y_train_pred_trans = y_train_pred.permute(1, 0, 2) train_loss = criterion(y_train_pred_trans, y_train_batch, pred_len, y_train_lens) train_acc = multi_acc(y_train_pred, y_train_batch, y_train_lens) optimizer.zero_grad() train_loss.backward() optimizer.step() train_epoch_loss += train_loss.item() train_epoch_acc += train_acc.item()
st30030
Hi guys, I have array of rgb images with shape (3000, 3, 96, 96 ) with shape of labels like (3000, 4). labels are hot vector. but I am getting error like “Expected input batch_size (150) to match target batch_size (50)” when it tries to calculate the loss. would you please tell me what should i change? network: class RNNModel(nn.Module): def __init__(self, input_dim, hidden_dim, layer_dim, output_dim): super(RNNModel, self).__init__() # Hidden dimensions self.hidden_dim = hidden_dim # Number of hidden layers self.layer_dim = layer_dim # Building your RNN # batch_first=True causes input/output tensors to be of shape # (batch_dim, seq_dim, input_dim) # batch_dim = number of samples per batch self.rnn = nn.RNN(input_dim, hidden_dim, layer_dim, batch_first=True, nonlinearity='relu') # Readout layer self.fc = nn.Linear(hidden_dim, output_dim) def forward(self, x): # Initialize hidden state with zeros # (layer_dim, batch_size, hidden_dim) h0 = torch.zeros(self.layer_dim, x.size(0), self.hidden_dim).requires_grad_() # We need to detach the hidden state to prevent exploding/vanishing gradients # This is part of truncated backpropagation through time (BPTT) out, hn = self.rnn(x, h0.detach()) out = self.fc(out[:, -1, :]) return out with parameters: input_dim = 96 hidden_dim = 100 layer_dim = 1 output_dim = 4 model = RNNModel(input_dim, hidden_dim, layer_dim, output_dim) criterion = nn.CrossEntropyLoss() learning_rate = 0.01 optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) print(len(list(model.parameters()))) print(list(model.parameters())[0].size()) # Input --> Hidden (A1) torch.Size([100, 96]) print(list(model.parameters())[2].size()) # Input --> Hidden BIAS (B1) torch.Size([100]) print(list(model.parameters())[1].size()) # Hidden --> Hidden (A3) torch.Size([100, 100]) print(list(model.parameters())[3].size()) # Hidden --> Hidden BIAS(B3) torch.Size([100]) print(list(model.parameters())[4].size()) # Hidden --> Output (A2) torch.Size([4, 100]) print(list(model.parameters())[5].size()) # Hidden -> Output BIAS (B2)torch.Size([4]) with train loop of: # Number of steps to unroll seq_dim = 96 num_epochs = 5 iter = 0 for epoch in range(num_epochs): for i, (images, labels) in enumerate(train_loader_fo): model.train() # Load images as tensors with gradient accumulation abilities images = images.float() images = images.view(-1, seq_dim, input_dim).requires_grad_() # Clear gradients w.r.t. parameters optimizer.zero_grad() # Forward pass to get output/logits # outputs.size() --> 100, 4 outputs = model(images) # Calculate Loss: softmax --> cross entropy loss loss = criterion(outputs, labels) # Getting gradients w.r.t. parameters loss.backward() # Updating parameters optimizer.step() iter += 1 if iter % 500 == 0: model.eval() # Calculate Accuracy correct = 0 total = 0 # Iterate through test dataset for images, labels in vali_loader_fo: # Load images to a Torch tensors with gradient accumulation abilities images = images.view(-1, seq_dim, input_dim) # Forward pass only to get logits/output outputs = model(images) # Get predictions from the maximum value _, predicted = torch.max(outputs.data, 1) # Total number of labels total += labels.size(0) # Total correct predictions correct += (predicted == labels).sum() accuracy = 100 * correct / total # Print Loss print('Iteration: {}. Loss: {}. Accuracy: {}'.format(iter, loss.item(), accuracy))
st30031
nn.CrossEntropyLoss won’t work with one-hot encoded targets and expects a LongTensor in the shape [batch_size] containing the class indices. However, since this is not the current error, could you please print the output and target shape before calculating the loss?
st30032
Hi, mi name is nicolas and i have a similar problem, in my case the rnn tensor is torch.Size([300, 7]) and labels torch.Size([100, 7])
st30033
Hi everyone! I have been trying to install Pytorch for over a week now, and I can not get it to work. After approximately 8 hours, the build always stops with: Making of project "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\caffe2\xla_tensor_test.vcxproj" is finished (Standardziele). Making of project "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\ALL_BUILD.vcxproj" is finished (Standardziele) -- ERROR. Making of project "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\install.vcxproj" is finished (Standardziele) -- ERROR. Error in build process. Then I get a bunch of similar warnings like: "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\install.vcxproj" (Standardziel) (1) -> "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\ALL_BUILD.vcxproj" (Standardziel) (3) -> "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\caffe2\proto\Caffe2_PROTO.vcxproj" (Standardziel) (4) -> "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\third_party\protobuf\cmake\protoc.vcxproj" (Standardziel) (5) -> "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\third_party\protobuf\cmake\libprotobuf.vcxproj" (Standardziel) (6) -> (ClCompile Ziel) -> cl : Command line warning D9025 : overriding “/W1” with “/w” [C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\third_party\protobuf\cmake\libprotobuf.vcxproj] And finally: "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\install.vcxproj" (Standardziel) (1) -> "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\ALL_BUILD.vcxproj" (Standardziel) (3) -> "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\caffe2\cuda_atomic_ops_test.vcxproj" (Standardziel) (132) -> (Link Ziel) -> cuda_atomic_ops_test_generated_cuda_atomic_ops_test.cu.obj : error LNK2019: unresolved external symbol ""float __cdecl pow(float,int)" (?pow@@YAMMH@Z)" in function ""void __cdecl test_atomic_mul<float>(void)" (? ?$test_atomic_mul@M@@YAXXZ)". [C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\caffe2\cuda_atomic_ops_test.vcxp roj] cuda_atomic_ops_test_generated_cuda_atomic_ops_test.cu.obj : error LNK2019: unresolved external symbol ""double __cdecl pow(double,int)" (?pow@@YANNH@Z)" in function ""void __cdecl test_atomic_mul<double>(void)" (??$test_atomic_mul@N@@YAXXZ)". [C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\caffe2\cuda_atomic_ops_test.v cxproj] C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\bin\Release\cuda_atomic_ops_test.exe : fatal error LNK1120: 2 unresolved externals [C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\caffe2\cuda_atomic_ops_test.vcxproj] 473 Warnings 3 Errors Passed Time 08:08:32.28 Traceback (most recent call last): File "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\setup.py", line 717, in <module> build_deps() File "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\setup.py", line 308, in build_deps build_caffe2(version=version, File "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\tools\build_pytorch_libs.py", line 62, in build_caffe2 cmake.build(my_env) File "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\tools\setup_helpers\cmake.py", line 345, in build self.run(build_args, my_env) File "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\tools\setup_helpers\cmake.py", line 141, in run check_call(command, cwd=self.build_dir, env=env) File "C:\Users\gooog\anaconda3\envs\torchbuild\lib\subprocess.py", line 373, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['cmake', '--build', '.', '--target', 'install', '--config', 'Release', '--', '/p:CL_MPCount=1']' returned non-zero exit status 1. I translated some german parts, so don’t be confused if something sounds off. I did not know, how (Standartziel) is called in english, but it basically means “default target”. I hope, everything else is understandable. Some general information on my setup: Windows 10 (64 bit) GPU: Nvidia GeForce 920M (Computing Capability = 3.5) Driver Version: 426.00 (latest) Visual Studio 2019 16.9.4 (Community) CUDA 10.1.243 CuDNN 8.0.5 This is how I install: cd C:\Users\gooog\Downloads mkdir Pytorch cd Pytorch conda create --name torchbuild y conda activate torchbuild conda install numpy ninja pyyaml mkl mkl-include setuptools cmake cffi typing_extensions future six requests dataclasses y conda install -c conda-forge libuv=1.39 y git clone --branch v1.7.0 https://github.com/pytorch/pytorch.git pytorch-1.7.0 cd pytorch-1.7.0 git clean -xdfcond python setup.py clean git submodule deinit -f --all git submodule sync --recursive git submodule update --init --recursive At this point, I manually change two things in the source code in order to fix some bugs I encountered earlier: Adding const to C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\aten\src\ATen\native\CompositeRandomAccessorCommon.h according to: Visual Studio Feedback Adding a few lines to C:\Users\gooog\Downloads\Pytorch \pytorch-1.7.0\cmake\public\cuda.cmake according to: [test] alternative fix for vc 16.8 with nvcc by peterjc123 · Pull Request #54391 · pytorch/pytorch · GitHub Then I continue installing: set TMP_DIR_WIN=C:\Users\gooog\Downloads C:/Users/gooog/Downloads/Use_mkl.bat C:/Users/gooog/Downloads/Use_sccache.bat set USE_NINJA=OFF set CMAKE_VERBOSE_MAKEFILE=1 set CMAKE_GENERATOR=Visual Studio 16 2019 set CMAKE_GENERATOR_TOOLSET_VERSION=14.28 set DISTUTILS_USE_SDK=1 set PATH=%TMP_DIR_WIN%\bin;%PATH% sccache --stop-server sccache --start-server sccache --zero-stats set CC=sccache-cl set CXX=sccache-cl "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" x64 -vcvars_ver=%CMAKE_GENERATOR_TOOLSET_VERSION% set CUDAHOSTCXX=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29910\bin\HostX64\x64\cl.exe set MAX_JOBS=1 python setup.py build --cmake python setup.py install Use_mkl.bat and Use_sccache.bat were copied from pytorch/.jenkins/pytorch/win-test-helpers/installation-helpers at master · pytorch/pytorch · GitHub Since the files were rather long, I uploaded: CMakeError.log: CMakeError.log - JustPaste.it 1 CMakeOutput.log: CMakeOutput.log - JustPaste.it 1 This is the first time I try to install something from source, so please excuse some (probably) strange steps, like manually changing the source files . I need pytorch for my thesis, so any help would be very very much appreciated. Also let me know, if you need anything else. Many thanks in advance!
st30034
Solved by peterjc123 in post #33 Sorry for the late reply. It’s an intermittent one. Just retry the build a few times.
st30035
Based on the provided log it seems the error is: `unresolved external symbol ""float __cdecl pow(float,int)"` which points towards this older issue 11, which should have been already solved in newer PyTorch versions. In case you need to use PyTorch 1.7.0 you could apply the proposed fixes mentioned in the issue or you could alternatively just update to the latest stable or nightly release.
st30036
Thanks for the reply! Since my GPU is only compatible with CUDA 10.1, I think I am restricted to Pytorch v1.7.0 according to this table: pytorch/CONTRIBUTING.md at master · pytorch/pytorch · GitHub I did not fully understand, how exactly CUDA and Pytorch versions depend on each other, so if you think that a newer version might also work, please let me know. Unfortunately, I was not able to find the older issue (were the square brackets supposed to be a link?). I found a bunch of other link errors, but none of them seemed to fit my problem. Could you maybe provide a link to the issue you meant?
st30037
PlsHelp: Since my GPU is only compatible with CUDA 10.1 I’m not sure why this would be the case. CUDA10.0 - CUDA11.3 all support GPUs with compute capability 3.5, so you could use all these CUDA toolkits. PlsHelp: I did not fully understand, how exactly CUDA and Pytorch versions depend on each other, so if you think that a newer version might also work, please let me know. Sorry for the wrong link, as apparently I didn’t post the right URL. Will edit the previous post and add the right link here 1 as well.
st30038
Thanks again for the help. ptrblck: I’m not sure why this would be the case. As far as I understood, CUDA v10.2 and higher require a graphics driver version >= 441.22, as mentioned in the second table here, but the newest version I could find for my GPU is 426 (nvidia offers 425.31 here, but somehow CUDA 10.1 included version 426.00). Once again, if this has to be seen as a recommendation more than a hard requirement, or if there is another way of getting newer driver versions, please let me know . ptrblck: right link here as well. I added a third manual fix according to this solution mentioned in your link and will now try again. Thanks again for your help, I will let you know if it worked.
st30039
I think the fix worked so far, as the build goes further than before. Unfortunately, I encountered another error for which I could not find a fix: Copying extension caffe2.python.caffe2_pybind11_state_gpu Copying caffe2.python.caffe2_pybind11_state_gpu from torch\Lib\site-packages\caffe2\python\caffe2_pybind11_state_gpu.cp39-win_amd64.pyd to C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\lib.win-amd64-3.9\caffe2\python\caffe2_pybind11_state_gpu.cp39-win_amd64.pyd copying torch\Lib\site-packages\caffe2\python\caffe2_pybind11_state_gpu.cp39-win_amd64.pyd -> C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\lib.win-amd64-3.9\caffe2\python building 'torch._C' extension creating build\temp.win-amd64-3.9 creating build\temp.win-amd64-3.9\Release creating build\temp.win-amd64-3.9\Release\torch creating build\temp.win-amd64-3.9\Release\torch\csrc C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29910\bin\HostX64\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\gooog\anaconda3\envs\torchbase\include -IC:\Users\gooog\anaconda3\envs\torchbase\include -IC:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29910\ATLMFC\include -IC:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29910\include -IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\ucrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\shared -IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\um -IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\winrt -IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\cppwinrt /Tctorch/csrc/stub.c /Fobuild\temp.win-amd64-3.9\Release\torch/csrc/stub.obj /MD /EHsc /DNOMINMAX /wd4267 /wd4251 /wd4522 /wd4522 /wd4838 /wd4305 /wd4244 /wd4190 /wd4101 /wd4996 /wd4275 stub.c C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29910\bin\HostX64\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\torch\lib /LIBPATH:C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v10.1/lib/x64 /LIBPATH:C:\Users\gooog\anaconda3\envs\torchbase\libs /LIBPATH:C:\Users\gooog\anaconda3\envs\torchbase\PCbuild\amd64 /LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29910\ATLMFC\lib\x64 /LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29910\lib\x64 /LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\ucrt\x64 /LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\um\x64 /LIBPATH:C:\Users\gooog\Downloads\mkl\lib torch_python.lib /EXPORT:PyInit__C build\temp.win-amd64-3.9\Release\torch/csrc/stub.obj /OUT:build\lib.win-amd64-3.9\torch\_C.cp39-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.9\Release\torch/csrc\_C.cp39-win_amd64.lib /NODEFAULTLIB:LIBCMT.LIB LINK : fatal error LNK1181: Input file ".obj" cannot be opened. error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.28.29910\\bin\\HostX64\\x64\\link.exe' failed with exit code 1181 I was not able to identify the relevant lines in the logs, so I send all 3: Console Log 1 CMakeOutput.log CMakeError.log I would be really thankful if you could help me again, since I do not know what to try anymore.
st30040
I’m unfortunately not deeply familiar with laptop GPUs, so don’t know much about the driver support. The current log error seems to be a bit vague in only mentioning that an “.obj” file cannot be opened. Note that the other two cmake files seem to be blocked.
st30041
Thank your for the ongoing support. I corrected the links and the CMake files should be available now. I think the (freely translated) relevant error message is: C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\CMakeFiles\CMakeTmp\src.cxx(1,10): fatal error C1083: cannot open file (Include): "glog/stl_logging.h": No such file or directory [C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\CMakeFiles\CMakeTmp\cmTC_e63a9.vcxproj] Which lead to this 1 issue. I checked my CMakeLists.txt, but all these changes were already included. Any idea, what might be the problem?
st30042
Could you disable the GLOG usage via USE_GLOG=0 in your env? Besides that it also seems that your current setup is missing pthread.h, mpi.h, cpuid.h, and execinfo.h. While these errors are raised as fatal error, I’m unsure if these would really break the build or skip the usage of some libs. Did you make sure to use the recommended Visual Studio version as described here 2?
st30043
Thank you for the suggestion! I reinstalled Visual Studio using this file (which installs BuildTools), and will set USE_GLOG=0, once it is done. While reinstalling CUDA, I now get the message that the installer can not find a supported version of Visual Studio, even though I located and added the following directories to my PATH: C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin\amd64 C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.28.29333\bin\Hostx64\x64 As far as I understood, CUDA wants a “real” Visual Studio version, e.g. Community, but the install instructions clearly suggest the BuildTools. Any idea on how to solve this? Do you think it might help to install the missing files you mentioned? Where are they normally delivered?
st30044
I’m unfortunately not familiar with the Windows setup and don’t know which Visual Studio version etc. is needed, so we would have to wait for a Windows expert such as @peterjc123.
st30045
Okay, nonetheless thank you very much for your help so far. Hopefully @peterjc123 can help me resolve the last issues .
st30046
No no no, don’t add those paths to PATH systemwide. Actually, there should be a shortcut called x64 Native Tools Command Prompt for VS 2019 if you use “Windows Search”. Opening that window, all the VS related environmental variables will be properly set. As far as I understood, CUDA wants a “real” Visual Studio version, e.g. Community, but the install instructions clearly suggest the BuildTools. Any idea on how to solve this? It doesn’t care if you have build tools or community. Nvcc would be happy if you have MSVC toolchain installed. As for your problem in building the library, it looks pretty similar to Cannot build PyTorch with Python 3.9 on Windows · Issue #47460 · pytorch/pytorch (github.com) 3 and is resolved by Fix python 3.9 builds on Windows by peterjc123 · Pull Request #47602 · pytorch/pytorch (github.com) 3.
st30047
Thanks for helping out. I deleted the two lines from my PATH, and will use the VS command prompt you suggested. Does that mean, I should remove the following commands from my installation routine? set CMAKE_GENERATOR=Visual Studio 16 2019 set CMAKE_GENERATOR_TOOLSET_VERSION=14.28 "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" x64 -vcvars_ver=%CMAKE_GENERATOR_TOOLSET_VERSION% set CUDAHOSTCXX=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29910\bin\HostX64\x64\cl.exe Another question: The issue that CUDA cannot find Visual Studio remains, even though I have MSVC v142 - VS 2019 C++-x64/x86-Buildtools (v14.28) installed (I installed Visual Studio and all components using this previously mentioned file) Should I just reinstall it using VS Community (which seemed to work), and install the newest MSVC and SDK? And if so, would you suggest VS Community 16.8.5 - matching the current Buildtools version - or the latest?
st30048
PlsHelp: I deleted the two lines from my PATH, and will use the VS command prompt you suggested. Does that mean, I should remove the following commands from my installation routine? If you want to build with the VS generator, then you should probably set CMAKE_GENERATOR, otherwise, the Ninja generator will be used and you don’t need to set any one of them. [quote=“PlsHelp, post:14, topic:121318”] The issue that CUDA cannot find Visual Studio remains, even though I have MSVC v142 - VS 2019 C+±x64/x86-Buildtools (v14.28) installed (I installed Visual Studio and all components using this previously mentioned file) Should I just reinstall it using VS Community (which seemed to work), and install the newest MSVC and SDK? If it could work, then maybe you could just reinstall that. Actually, I don’t know too much about your local environment. And if so, would you suggest VS Community 16.8.5 - matching the current Buildtools version - or the latest? I see that you are using my patch. So it won’t have any problem using the latest one.
st30049
peterjc123: If you want to build with the VS generator, then you should probably set CMAKE_GENERATOR, otherwise, the Ninja generator will be used and you don’t need to set any one of them. I do not remember exactly what happened, but I build with the VS generator, since Ninja had some issues for me. I reinstalled the latest Visual Studio Community and tried to build using the fix you provided in your first reply. However, after approximately 3 hours, the build errors out again. I think these are the relevant error messages in CMakeError.log: C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\CMakeFiles\CMakeTmp\src.c(6,13): error C2065: "asm": undeclared identifier [C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\CMakeFiles\CMakeTmp\cmTC_e23a0.vcxproj] C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\CMakeFiles\CMakeTmp\src.c(6,13): error C2143: Syntax error: Missing ";" infront of "volatile" [C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\CMakeFiles\CMakeTmp\cmTC_e23a0.vcxproj] Source file was: #include <stdint.h> static inline void cpuid(uint32_t *eax, uint32_t *ebx, uint32_t *ecx, uint32_t *edx) { uint32_t a = *eax, b, c = *ecx, d; asm volatile ( "cpuid" : "+a"(a), "=b"(b), "+c"(c), "=d"(d) ); *eax = a; *ebx = b; *ecx = c; *edx = d; } int main() { uint32_t a,b,c,d; cpuid(&a, &b, &c, &d); return 0; } Based on the command prompt output, the problem seems to be related to gloo: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160\Microsoft.CppCommon.targets( 241,5): error MSB8066: Der benutzerdefinierte Build für "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\third_party\ gloo\gloo\cuda.cu;C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\third_party\gloo\gloo\cuda_private.cu" wurde mit de m Code 1 beendet. [C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\third_party\gloo\gloo\gloo_cuda.vcxproj] ... "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\install.vcxproj" (Standardziel) (1) -> "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\ALL_BUILD.vcxproj" (Standardziel) (3) -> "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\caffe2\caffe2_pybind11_state.vcxproj" (Standardziel) (18) -> "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\caffe2\torch.vcxproj" (Standardziel) (26) -> "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\caffe2\torch_cuda.vcxproj" (Standardziel) (37) -> "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\third_party\gloo\gloo\gloo_cuda.vcxproj" (Standardziel) (39) - > (CustomBuild Ziel) -> C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160\Microsoft.CppCommon.target s(241,5): error MSB8066: Der benutzerdefinierte Build für "C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\third_part y\gloo\gloo\cuda.cu;C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\third_party\gloo\gloo\cuda_private.cu" wurde mit dem Code 1 beendet. [C:\Users\gooog\Downloads\Pytorch\pytorch-1.7.0\build\third_party\gloo\gloo\gloo_cuda.vcxproj] I do not understand what gloo does, but could it help to just set USE_GLOO=0, and would this in any way affect the build? On another note, I am still missing the following files (as ptrblck already pointed out): glog/stl_logging.h pthread.h mpi.h cpuid.h execinfo.h Would you confirm that this is not problematic for the build / later use?
st30050
Conserning the first issue, I tried to build again with USE_GLOO=0, but I am hitting the same error. Based on this somewhat smiliar issue, I think it should say __asm__ insted of asm in \build\CMakeFiles\CMakeTmp\src.c, but since this is a temporary file, that is generated only during the build, I do not know how to fix this. Any idea on what to do @peterjc123 ?
st30051
Could you please share me the full log? BTW, would you please share the log if you use the Ninja generator?
st30052
These are the logs of the last run (with USE_GLOO=0) CMakeError.log 1 CMakeOutput.log 1 I will now try to build with Ninja again and send you the logs once it is done. In order to do so, I just set USE_NINJA=ON and remove the following lines from my installation routine, right? set CMAKE_VERBOSE_MAKEFILE=1 set CMAKE_GENERATOR=Visual Studio 16 2019 set CMAKE_GENERATOR_TOOLSET_VERSION=14.29 set DISTUTILS_USE_SDK=1 "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" x64 -vcvars_ver=%CMAKE_GENERATOR_TOOLSET_VERSION% set CUDAHOSTCXX=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30037\bin\HostX64\x64\cl.exe So my new installation routine will be the following: set TMP_DIR_WIN=C:\Users\gooog\Downloads C:/Users/gooog/Downloads/Use_mkl.bat C:/Users/gooog/Downloads/Use_sccache.bat set USE_NINJA=ON set PATH=%TMP_DIR_WIN%\bin;%PATH% sccache --stop-server sccache --start-server sccache --zero-stats set CC=sccache-cl set CXX=sccache-cl set MAX_JOBS=1 set USE_GLOG=0 set USE_GLOO=0 python setup.py build --cmake python setup.py install Thanks a lot for your help!
st30053
PlsHelp: These are the logs of the last run (with USE_GLOO=0) CMakeError.log CMakeOutput.log The logs you provided are not informative. By “full log”, I mean you redirect stdout and stderr to a log file (by appending > build.log 2>&1 after every command or just write all the commands into a script and run that script with this pattern) and please upload that log file. I will now try to build with Ninja again and send you the logs once it is done. In order to do so, I just set USE_NINJA=ON and remove the following lines from my installation routine, right? You still need this if you use a regular CMD window instead of opening a x64 MSVC dev shell. "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" x64 -vcvars_ver=%CMAKE_GENERATOR_TOOLSET_VERSION% BTW, set DISTUTILS_USE_SDK=1 is still needed.
st30054
Hello everyone, I’m pretty new in Pytorch game, and need some help, hope you can help me ! Let me explain my problem. As a newbie, I’m training myself with the mnist DataSet to implement a DCGAN. Ok so I took very basic Network for my Generator and Discriminator (as you can see in my code below), and then I’m training my model. The problem is that I think the Loss Function of my Generator is fucked up : it’s value is either 100 or 0 at the first iteration and then I think that it breaks the whole network, here is what I get : iteration 0 / 329 – epoch 0 ---- Loss_D : 2.2673 Loss_G : 0.0 D(x) : 0.2363 D(G(z1)) : 0.35204 D(G(z2)) : 1.0 iteration 50 / 329 – epoch 0 ---- Loss_D : 100.0 Loss_G : 0.0 D(x) : 1.0 D(G(z1)) : 1.0 D(G(z2)) : 1.0 Can you help me on that and maybe explain me what’s wrong with my code ? I let you know just below the interesting section of my code (Generator, Discriminator and training loop). If you think you neew more to figure it out, let me know. Generator and Discriminator : class Generator(nn.Module): def __init__(self, ngpu): super(Generator, self).__init__() self.ngpu = ngpu self.main = nn.Sequential( # input is Z, going into a convolution nn.ConvTranspose2d( nz, ngf * 8, 4, 1, 0, bias=False), nn.BatchNorm2d(ngf * 8), nn.ReLU(True), # state size. (ngf*8) x 4 x 4 nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 4), nn.ReLU(True), # state size. (ngf*4) x 8 x 8 nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 2), nn.ReLU(True), # state size. (ngf*2) x 16 x 16 nn.ConvTranspose2d( ngf * 2, ngf, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf), nn.ReLU(True), # state size. (ngf) x 32 x 32 nn.ConvTranspose2d( ngf, nc, 4, 2, 1, bias=False), nn.Tanh() # state size. (nc) x 64 x 64 ) def forward(self, input): return self.main(input) class Discriminator(nn.Module): def __init__(self, ngpu): super(Discriminator, self).__init__() self.ngpu = ngpu self.main = nn.Sequential( # input is (nc) x 64 x 64 nn.Conv2d(nc, ndf, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf) x 32 x 32 nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 2), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf*2) x 16 x 16 nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 4), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf*4) x 8 x 8 nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 8), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf*8) x 4 x 4 nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False), nn.Sigmoid() ) def forward(self, input): return self.main(input) Weight init, Loss Function, Optimizer : def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm') != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0) G = Generator(1).to(device) D = Discriminator(1).to(device) G.apply(weights_init) D.apply(weights_init) BCE_loss = nn.BCELoss() G_optimizer = optim.Adam(G.parameters(), lr=learning_rate, betas=(beta1, 0.999)) D_optimizer = optim.Adam(D.parameters(), lr=learning_rate, betas=(beta1, 0.999)) real_label = 1 fake_label = 0 G_loss_l = [] D_loss_l = [] The Training Loop : print("Starting Training Loop...") for epoch in range(num_epoch) : for i, data in enumerate(dataloader, 0): #-------------------- Discriminator (maximize log(D(x)) + log(1 - D(G(z))))---------------------- #real datas D.zero_grad() real = data[0].to(device) #gpu b_size = real.size(0) label = torch.full((b_size,), real_label, dtype=torch.float, device=device) outputD_real = D(real).view(-1) loss_D_real = BCE_loss(outputD_real, label) loss_D_real.backward() #gradient #fake datas noise = torch.randn(b_size, nz, 1, 1, device=device) #noise tensor fake = G(noise) label.fill_(fake_label) outputD_fake = D(fake.detach()).view(-1) loss_D_fake = BCE_loss(outputD_fake, label) loss_D_fake.backward() D_G_z1 = outputD_fake.mean().item() loss_D = loss_D_real + loss_D_fake D_optimizer.step() #----------------- Generator (maximize log(D(G(z))))---------------------------- G.zero_grad() label.fill_(real_label) outputD2 = D(fake).view(-1) loss_G = BCE_loss(outputD2, label) loss_G.backward() D_G_z2 = outputD2.mean().item() G_optimizer.step() #on améliore G G_loss_l.append(loss_G.item()) D_loss_l.append(loss_D.item()) if i%50==0 : print("iteration ", i, "/", len(dataloader),"-- epoch", epoch, "---- Loss_D : ", loss_D.item(), " Loss_G : ", loss_G.item(), " D(x) : ", D_x, " D(G(z1)) : ", D_G_z1, " D(G(z2)) : ", D_G_z2)
st30055
How to get the follwing output? Inputs: bx1 = torch.tensor([[1,2],[3,4],[5,6],[7,8]]) tensor([[1, 2], [3, 4], [5, 6], [7, 8]]) bx2 = torch.tensor([[11,22],[33,44]]) tensor([[11, 22], [33, 44]]) OUtput: tensor([[[ 1, 2, 11, 22], [ 1, 2, 33, 44]], [[ 3, 4, 11, 22], [ 3, 4, 33, 44]], [[ 5, 6, 11, 22], [ 5, 6, 33, 44]], [[ 7, 8, 11, 22], [ 7, 8, 33, 44]]])
st30056
I think this can work: import torch bx1 = torch.tensor([[1,2],[3,4],[5,6],[7,8]]) bx2 = torch.tensor([[11,22],[33,44]]) temp = torch.repeat_interleave(bx1, 2, dim=0) temp = temp.reshape(4, 2, -1) output = torch.cat((temp, bx2.repeat(4, 1, 1)), dim=2) print(output) tensor([[[ 1, 2, 11, 22], [ 1, 2, 33, 44]], [[ 3, 4, 11, 22], [ 3, 4, 33, 44]], [[ 5, 6, 11, 22], [ 5, 6, 33, 44]], [[ 7, 8, 11, 22], [ 7, 8, 33, 44]]])
st30057
I need to use a rank-based correlation (Spearman’s Correlation) to compute my loss. Could anyone please help me with the implementation of Spearman’s Correlation between two vectors in Pytorch?
st30058
In case someone is trying to look for a solution: def cov(m): # m = m.type(torch.double) # uncomment this line if desired fact = 1.0 / (m.shape[-1] - 1) # 1 / N m -= torch.mean(m, dim=(1, 2), keepdim=True) mt = torch.transpose(m, 1, 2) # if complex: mt = m.t().conj() return fact * m.matmul(mt).squeeze() def compute_rank_correlation(x, y): x, y = rankmin(x), rankmin(y) return corrcoef(x, y) def corrcoef(x, y): batch_size = x.shape[0] x = torch.stack((x, y), 1) # calculate covariance matrix of rows c = cov(x) # normalize covariance matrix d = torch.diagonal(c, dim1=1, dim2=2) stddev = torch.pow(d, 0.5) stddev = stddev.repeat(1, 2).view(batch_size, 2, 2) c = c.div(stddev) c = c.div(torch.transpose(stddev, 1, 2)) return c[:, 1, 0] There is small difference between the above implementation and scipy’s spearmanr implementation: This operate on batches, that is, it expects input to be of dimension (N, x) where N is the batch size for both parameters x and y. scipy uses rank average while this uses rank min to compute the ranking before corrcoef. There is 10^-3 disagreement and although I suspect that this is the cause, this could possibly be. Please feel free to share your improvements on this as it could be useful for other people and me
st30059
Hi haltaha! haltaha: I need to use a rank-based correlation (Spearman’s Correlation) to compute my loss. Presumably you will use your “loss” to train your network with backpropagation by calling loss.backward(). Because the ranks of your data values are discrete integers, the Spearman’s-rank-correlation loss you propose calculating will not be (usefully) differentiable, so you will not be able to backpropagate nor train. x, y = rankmin(x), rankmin(y) You don’t show us the code for rankmin(), but presumably buried in there somewhere is a non-differentiable call that returns the indices for the sorted values of x (sometimes referred to as argsort()). Best. K. Frank
st30060
Hi Here is simplified version for computation of Spearman’s rank correlation coefficient. It’s non differentiable, but much faster than scipy.stats.spearmanr version. def _get_ranks(x: torch.Tensor) -> torch.Tensor: tmp = x.argsort() ranks = torch.zeros_like(tmp) ranks[tmp] = torch.arange(len(x)) return ranks def spearman_correlation(x: torch.Tensor, y: torch.Tensor): """Compute correlation between 2 1-D vectors Args: x: Shape (N, ) y: Shape (N, ) """ x_rank = _get_ranks(x) y_rank = _get_ranks(y) n = x.size(0) upper = 6 * torch.sum((x_rank - y_rank).pow(2)) down = n * (n ** 2 - 1.0) return 1.0 - (upper / down) Time comparison x = torch.rand(1000) y = torch.rand(1000) %timeit spearman_correlation(x, y) 206 µs ± 15.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %timeit spearmanr(x_n, y_n)[0] 592 µs ± 2.22 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
st30061
Hi, I found a differential version at post: Numerai Forum – 11 Mar 21 Differentiable Spearman in PyTorch (Optimize for CORR directly) 91 @mdo previously showed how to use a custom loss function which involved taking the gradient of the sharpe ratio of the Pearson correlations over different eras. Although Pearson and Spearman might return similar values, it could be rewarding to... Reading time: 4 mins 🕑 Likes: 36 ❤ Copying from above post: " A recent paper, Fast Differentiable Sorting and Ranking 13, introduced a novel method for differentiable sorting and ranking, with the added bonus of O(nlogn) complexity (I would encourage reading the paper to learn more). We can leverage their open sourced code google-research/fast-soft-sort 13 in order to implement a differentiable version of the Spearman"
st30062
Don’t know why this is happening, it used to work fine before. Screenshot (1)1103×633 51.2 KB Screenshot (3)713×407 16.5 KB Need help ASAP.
st30063
Could you please provide more details, such as source code and exactly what snippet is taking this memory?
st30064
Hi All, I am trying to use Pytorch for my application, which uses kokkos as well as pytorch. I am using cmake to build my application and I am hitting the following error cmake -Dref_data=14 -DKokkos_ROOT=/global/homes/n/namehta4/kokkos/install_cuda/lib64/cmake/Kokkos -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=/global/homes/n/namehta4/kokkos/install_cuda/bin/nvcc_wrapper ../ -- The C compiler identification is GNU 7.4.1 -- The CXX compiler identification is GNU 7.4.1 -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Check for working C compiler: /usr/bin/gcc - skipped -- Detecting C compile features -- Detecting C compile features - done -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Check for working CXX compiler: /global/homes/n/namehta4/kokkos/install_cuda/bin/nvcc_wrapper - skipped -- Detecting CXX compile features -- Detecting CXX compile features - done -- Enabled Kokkos devices: CUDA;SERIAL CMake Warning at /global/homes/n/namehta4/kokkos/install_cuda/lib64/cmake/Kokkos/KokkosConfigCommon.cmake:29 (MESSAGE): The installed Kokkos configuration does not support CXX extensions. Forcing -DCMAKE_CXX_EXTENSIONS=Off Call Stack (most recent call first): /global/homes/n/namehta4/kokkos/install_cuda/lib64/cmake/Kokkos/KokkosConfig.cmake:57 (INCLUDE) CMakeLists.txt:6 (find_package) -- Looking for pthread.h -- Looking for pthread.h - found -- Performing Test CMAKE_HAVE_LIBC_PTHREAD -- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Failed -- Looking for pthread_create in pthreads -- Looking for pthread_create in pthreads - not found -- Looking for pthread_create in pthread -- Looking for pthread_create in pthread - found -- Found Threads: TRUE -- Found CUDA: /usr/common/software/sles15_cgpu/cuda/11.0.3 (found version "11.0") -- Caffe2: CUDA detected: 11.0 -- Caffe2: CUDA nvcc is: /usr/common/software/sles15_cgpu/cuda/11.0.3/bin/nvcc -- Caffe2: CUDA toolkit directory: /usr/common/software/sles15_cgpu/cuda/11.0.3 -- Caffe2: Header version is: 11.0 -- Found CUDNN: /usr/common/software/sles15_cgpu/cudnn/8.0.5/cuda/11.0.3/lib64/libcudnn.so -- Found cuDNN: v? (include: /usr/common/software/sles15_cgpu/cudnn/8.0.5/cuda/11.0.3/include, library: /usr/common/software/sles15_cgpu/cudnn/8.0.5/cuda/11.0.3/lib64/libcudnn.so) CMake Error at /global/homes/n/namehta4/libtorch/share/cmake/Caffe2/public/cuda.cmake:170 (message): PyTorch requires cuDNN 7 and above. Call Stack (most recent call first): /global/homes/n/namehta4/libtorch/share/cmake/Caffe2/Caffe2Config.cmake:88 (include) /global/homes/n/namehta4/libtorch/share/cmake/Torch/TorchConfig.cmake:40 (find_package) CMakeLists.txt:7 (find_package) -- Configuring incomplete, errors occurred! I have the following modules listed Currently Loaded Modulefiles: 1) esslurm 2) cgpu/1.0 3) cmake/3.14.4 4) cuda/11.0.3 5) cudnn/8.0.5 6) pytorch/1.7.0-gpu Is there a mistake on my end, because I have cuda/11 as well as cudnn/8.0.5 loaded and it is being recognized by cmake but not by Caffe2? Thank you! Edit: This is my cmake 1 cmake_minimum_required (VERSION 3.12 FATAL_ERROR) 2 project(TestSNAP 3 LANGUAGES C CXX 4 ) 5 6 find_package(Kokkos REQUIRED) 7 find_package(Torch REQUIRED) 8 find_package(Python REQUIRED COMPONENTS Interpreter Development) 9 10 11 # don't allow in-source builds 12 if("${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_BINARY_DIR}") 13 message(STATUS "Warning! Building from the source directory is not allow") 14 message(STATUS "Remove 'CMakeCache.txt' and 'CMakeFiles' and build from a separate directory") 15 message(ERROR "In-source build") 16 endif() 17 18 SET(MyTarget test_snap) 19 20 message(STATUS "CMAKE_SOURCE_DIR = ${CMAKE_SOURCE_DIR}") 21 FILE(GLOB sources 22 ${CMAKE_SOURCE_DIR}/src/*.cpp 23 ${CMAKE_SOURCE_DIR}/src/*.h 24 ) 25 26 add_executable(${MyTarget} ${sources}) 27 28 target_compile_features(${MyTarget} PUBLIC cxx_std_17) 29 set_target_properties(${MyTarget} PROPERTIES 30 CXX_EXTENSIONS OFF 31 CXX_STANDARD_REQUIRED ON 32 ) 33 ADD_COMPILE_DEFINITIONS(REFDATA_TWOJ=${ref_data}) 34 35 target_include_directories(${MyTarget} PRIVATE -DCUSTOM_SYS_PATH="${TestSNAP_SOURCE_DIR}/include") 36 target_include_directories(${MyTarget} PRIVATE $<BUILD_INTERFACE:${TestSNAP_SOURCE_DIR}/include>) 37 target_include_directories(${MyTarget} SYSTEM PRIVATE ${PYTHON_INCLUDE_DIRS}) 38 target_link_libraries(${MyTarget} PRIVATE Kokkos::kokkos) 39 target_link_libraries(${MyTarget} PRIVATE "${TORCH_LIBRARIES}") 40 target_link_libraries(${MyTarget} PRIVATE Python::Python)
st30065
Which PyTorch branch are you using? Are you trying to build from the current master or an older version?
st30066
Hi Ptrblck, I am not sure. I am using the one on CORI system at NERSC. I can ask them and check but I do believe it must be the latest package. Thank you! Edit: It is stable pytorch v1.7.0 installed via conda
st30067
Based on the error and output it seems you are trying to build a library/package from source, so I don’t understand the “pytorch v1.7.0 installed via conda” statement. If you’ve installed the PyTorch binaries via conda, you wouldn’t have to rebuild anything.