id
stringlengths
3
8
text
stringlengths
1
115k
st104300
Hi, pytorch has done a great job for normal dense tensor, and I have used it for not only deep learning applications, but also some basic gpu boosted inference task, such as kmeans and tsne. However, currently the sparse tensor support is not so good. According to my observation, only matrix multiplication and element-wise math operation is supported, while other important functions such as slice and reduce sum is missing. This cause a lot trouble when we want to use pytorch’s sparse tensor to handle some inference jobs. Here I have a small project which present a sparseTensor wrapper for slice and reduce sum based on pytorch dense tensor, sparse tensor and some cupy kernels(only for inference, since no graph registration is handled) GitHub overshiki/sparseTensorUtils 10 sparseTensorUtils - sparse tensor utils based on pytorch tensor, provide a class:sparseTensor which support slice, reduce sum, element-wise math operation and so on If you guys have a plan to implement these features with c code, that would be excellent! since GPU memory is always a big problem when we want to handle some big data task. Would you like to do this soon? Or any long-term plans? Thanks a lot. Best
st104301
Yes, in the long term we’d like to support more operations on sparse. There is an issue open for slice but I’m sure about reduce sum and elementwise comparision: https://github.com/pytorch/pytorch/issues 44.
st104302
Hi everybody, I am currently trying to train a regressor that accepts 5 dimensional features an outputs a single value. The neural network architecture that I used accepts batch of input data and I use batchNorm in the first layer. But beacuse of the nature of batchNorm network generates normalized predictions. For evaluation stage ground truth values should be normalized in order to make a comparison. To do that I used a single batchNorm layer that only generates normalized values of batches with the same size that the network has been fed. My question is that; is this approach valid or not? Thanks. Can.
st104303
BatchNorm doesn’t necessarily generate normalized features, if affine=True. The additional weights and bias can scale and shift the input again, but that’s only a side note. During evaluation you should use the running statistics and not calculate the current batch statistics anymore. You can do this by setting your model to evaluation: model.eval(). The calculation therefore won’t depend on the batch size anymore.
st104304
Thanks for your reply, I have already used model.train() and model.eval() features of pyTorch. But still I get normalized outputs. But I think in order to evaluate the model in a valid manner I need same normalization scheme for the ground truth data for the regression problem.
st104305
Hello, I’m trying to work my way through Mixtures Density Network, and while I managed to figure it out for a single feature for the output, I’m stuck when it comes to several features. Among my problems, here’s the one concerning the Normal distribution class. Here’s an example: import torch from torch.distributions import Normal means = torch.zeros(1,2) stds = torch.ones(1,2) dist = Normal(means, stds) print('Sample is size {}'.format(dist.sample().shape)) print('Log prob of {} = {}'.format(torch.zeros(1,2), dist.log_prob(torch.zeros(1,2)))) Outputs: Sample is size torch.Size([1, 2]) Log prob of tensor([[ 0., 0.]]) = tensor([[-0.9189, -0.9189]]) Shouldn’t the log probability be of a single dimension ? Am I (certainly but what) doing something wrong ? Thanks a lot !
st104306
Never mind, I figured it out ! I think that Normal generates one normal distribution per feature. Hence, you have as many log_probs as you have distributions. However, in the case of multi-features, here’s what I propose: Either keep Normal, but sum log probs (or multiply probs) to get the probability you seek given multifeatures Use a Multivariate Normal, which avoids you to gather the probabilites yourself. If anyone has other insights, or if I’ve made a mistake, I’d be delighted to hear it ! Thanks !
st104307
I have converted a model from crnn in torch7 (https://github.com/bgshih/crnn 1), but the predictions are completely wrong. How can I debug it? I want to print the tensor value in each layer in torch7 and compare it with pytorch, but it seems that there is no print layer in torch7. Now I am trying to load the model in torch and remove some layers to get the output. Is there any better idea?
st104308
Did you make sure to set your model to evaluation with model.eval() before comparing its output to the torch7 model? I think in torch7 you can just print the output of each layer. Could you try to call this, if you used a Sequential model: net.modules[n].output
st104309
4D1E6621519DC40F0FD85FE766B719C6.jpg1308×504 93.2 KB I download pytorch from this link and get it installed in my server. It works fine in a test file. However, LD_LIBRARY_PATH contains no cudnn. I wondering pytorch installed in this way get no utilization of cudnn lib, leading to the slow training in DNNs. If I add to cudnn path to LD_LIBRARY_PATH, does pytorch automatically utilizes it ? Can I print the information of cudnn that pytorch is using? Thank you!
st104310
Solved by ptrblck in post #2 You can print the version with: print(torch.backends.cudnn.version()) The wheels come with some pre-built libraties (CUDA, cuDNN, etc.).
st104311
You can print the version with: print(torch.backends.cudnn.version()) The wheels come with some pre-built libraties (CUDA, cuDNN, etc.).
st104312
Hello , I can’t figure out this error , it seems to be linked to input dimension to my RNNclassifier. Thanks. class RNNClassifier(nn.Module): def __init__(self, input_size, hidden_size, output_size, n_layers=1): super(RNNClassifier, self).__init__() self.hidden_size = hidden_size self.n_layers = n_layers self.embedding = nn.Embedding(input_size, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size, n_layers) self.fc = nn.Linear(hidden_size, output_size) def forward(self, input): batch_size = input.size(0) print(" input", input.size()) embedded = self.embedding(input) print(" embedding", embedded.size()) hidden = self._init_hidden(batch_size) output, hidden = self.gru(embedded, hidden) print(" gru hidden output", hidden.size()) fc_output = self.fc(hidden) print(" fc output", fc_output.size()) return fc_output![Screenshot%20from%202018-06-21%2013-57-46|690x497](upload://kjt60ykx0SKELEjKJsFpS9151dd.png) def _init_hidden(self, batch_size): hidden = torch.zeros(self.n_layers, batch_size, self.hidden_size) return Variable(hidden) X_train, Y_train = Data('s2-gap-12dates.csv', train = True) X=X_train[0,:,:] X=torch.from_numpy(X) X=X.view(-1,12,20) inp = Variable(X) out = classifier(inp) Screenshot from 2018-06-21 13-57-46.png733×529 62.7 KB
st104313
Is there any experience for predict online with one image input and predict multiprocessing ?
st104314
In the Pytorch transfer learning tutorial 6, the following line of code appears: scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1) and during the model training: scheduler.step() I can’t find the documentation of lr_scheduler (only the method itself). Will someone please help me understand what exactly does these lines do and what (in general) does the lr_scheduler is inteneded to do? Thanks!
st104315
Solved by ptrblck in post #2 The learning rate scheduler adjusts the learning rates stored in the optimizer. In your example a step function is used to lower the learning rate after 7 steps with a multiplicative factor of gamma=0.1. Assuming that your initial learning rate is 1e-1: optimizer = optim.SGD(model.parameters(), l…
st104316
The learning rate scheduler adjusts the learning rates stored in the optimizer. In your example a step function is used to lower the learning rate after 7 steps with a multiplicative factor of gamma=0.1. Assuming that your initial learning rate is 1e-1: optimizer = optim.SGD(model.parameters(), lr=1e-1) Now after scheduler.step() is called 7 times, the learning rate will be lowered to lr = 1e-1 * gamma = 1e-2. This schedule looks like a step functions, thus the name. There are also other functions, like ExponentialLR or CosineAnnealingLR. You can find all schedulers here 61.
st104317
Hi, I am reading this 1 paper about pytorch . In section 3.1, they gave an example code: y = x.tanh() y.add_(3) y.backward() I could not understand the idea behind this code snippet. Does this snippet cause an error ? Or eventhough it does not cause an error, is it illegal to use such thing ? Thanks
st104318
The idea is that since add_ is an inplace operation, in this case, y will be modified inplace and so the gradient computation for the tanh operation won’t be able to be performed. This code snipped should cause an error during the backward pass. All these potential problems are tracked properly, so if no error is raised, the operation is valid and the result will be correct.
st104319
I am experimenting with the code that accompanied the paper “Regularizing and Optimizing LSTM Language Models” (Merity et al. 2018): https://github.com/salesforce/awd-lstm-lm/ 56. In it, they apply dropout on the embedding. I was wondering if it was possible to make the implementation a bit more conservative on memory (it creates an embedding-sized tensor in the process). I managed to do that, but when I put my implementation in place of theirs, I didn’t get the same numbers as them from the second iteration on. (A simplified version of) their implementation: def embedded_dropout(embed, words, dropout=0.1): mask = embed.weight.data.new_empty((embed.weight.size(0), 1)).bernoulli_(1 - dropout).expand_as(embed.weight) / (1 - dropout) masked_embed_weight = mask * embed.weight return torch.nn.functional.embedding(words, masked_embed_weight) Mine: def embedded_dropout(embed, words, dropout=0.1): emb = embed(words) mask = embed.weight.data.new_empty((embed.weight.size(0), 1)).bernoulli_(1 - dropout) / (1 - dropout) m = torch.gather(mask.expand(embed.weight.size(0), words.size(1)), 0, words) return (emb * m.unsqueeze(2).expand_as(emb)).squeeze() The outputs of the functions are identical. However, the gradients of embed (after going through a few LSTM layers + softmax) differ by 2.0763528e-19 after the first iteration, and then it gets progressively worse, to about 0.0037 after the 200th. My questions are: Am I using something that is not stable w.r.t. the gradient computation? Is it possible to come up with a solution that obtains the same gradients, but only requires a words-sized mask (as in my code) as opposed to an embedding-sized one (as in the original)?
st104320
That is a neat approach! A small difference (I seem to see ~1e-7 often when using float32) is expected when you compute the same thing in a different way (that is mathematically equivalent). Are you sure you have the exact same random for the dataloader and dropout? My guess would be that you have different embeddings by when you get significantly different results. Best regards Thomas
st104321
Yes, I wouldn’t have wondered if the two functions returned slightly different tensors. But they don’t – only their gradients differ. And you are right, the initial divergence is well in the ballpark of regular float errors. What bugs me is that behind the scenes, the two functions should be doing the same thing; all I am not doing is multiplying the unused vectors in the embedding – which shouldn’t receive gradients anyway. The random is definitely the same – the number of calls to the random number generator stays the same (embed.weight.size(0)). Even though I’ve changed quite a few things in the code aside from this function, but took extra care not to mess up the random sequence – I even deliberately left a (harmless) bug in the code so that I still get the same numbers. And you are definitely right, the embeddings diverge by the end, but it is not because the data fed to them is different (that is actually cached, so no randomness is involved there), but because of the cumulative effect of the difference in gradients. I am wondering if there is a way to see what (symbolic) operations this code translates to. A comparison there might reveal where the difference in gradients comes from.
st104322
There isn’t any symbolic code, the functions call various C++ functions for the embeddings, there is the CPU backward for dense matrices 4, next to it is a version for sparse matrices on CPU. The CUDA code is a bit more elaborate 4. I’m not sure the chances are good to find an obvious reason for the discrepancy - essentially the backward would seem to permute summing addition (for multiple occurrences of the same grad) with multiplying some parts with 0. Best regards Thomas
st104323
I see. I ran the code until convergence, and the final perplexity is almost the same as with the original function (as expected), so I don’t mind this all that much. It would have been nice to have the same numbers, though.
st104324
I had this error running my code from __future__ import print_function import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import Dataset, DataLoader from torch.autograd import Variable import numpy as np from Data import Data ''' STEP 1: LOADING DATASET ''' class train_dataset(Dataset): def __init__(self): features, labels = Data('s2-gap-12dates.csv', train=True) self.len = features.shape[0] self.features = torch.from_numpy(features) self.labels = torch.from_numpy(labels) def __getitem__(self, index): return self.features[index], self.labels[index] def __len__(self): return self.len class test_dataset(Dataset): def __init__(self): features, labels = Data('s2-gap-12dates.csv', train=False) self.len = features.shape[0] self.features = torch.from_numpy(features) self.labels = torch.from_numpy(labels) def __getitem__(self, index): return self.features[index], self.labels[index] def __len__(self): return self.len train_dataset = train_dataset() test_dataset = test_dataset() # Training settings batch_size = 100 n_iters = 3000 num_epochs = n_iters / (len(train_dataset) / batch_size) num_epochs = int(num_epochs) #------------------------------------------------------------------------------ ''' STEP 2: MAKING DATASET ITERABLE ''' train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False) ''' STEP 3: CREATE MODEL CLASS ''' 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, feature_dim) self.rnn = nn.RNN(input_dim, hidden_dim, layer_dim, batch_first=True, nonlinearity='tanh') # Readout layer self.fc = nn.Linear(hidden_dim, output_dim) def forward(self, x): # Initialize hidden state with zeros h0 = Variable(torch.zeros(self.layer_dim, x.size(0), self.hidden_dim)) # One time step out, hn = self.rnn(x, h0) out = self.fc(out[:, -1, :]) # out.size() --> 100, 10 return out ''' STEP 4: INSTANTIATE MODEL CLASS ''' input_dim = 20 hidden_dim = 100 layer_dim = 2 output_dim = 10 model = RNNModel(input_dim, hidden_dim, layer_dim, output_dim) ''' STEP 5: INSTANTIATE LOSS CLASS ''' criterion = nn.CrossEntropyLoss() ''' STEP 6: INSTANTIATE OPTIMIZER CLASS ''' learning_rate = 0.1 optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) ''' STEP 7: TRAIN THE MODEL ''' # Number of steps to unroll seq_dim = 12 iter = 0 for epoch in range(num_epochs): for i, (features, labels) in enumerate(train_loader): features = Variable(features.view(-1, seq_dim, input_dim)) labels = Variable(labels) # Clear gradients w.r.t. parameters optimizer.zero_grad() # Forward pass to get output/logits # outputs.size() --> 100, 10 outputs = model(features) # 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: # Calculate Accuracy correct = 0 total = 0 # Iterate through test dataset for features, labels in test_loader: features = Variable(features.view(-1, seq_dim, input_dim)) # Forward pass only to get logits/output outputs = model(features) # 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.data[0], accuracy)) Screenshot from 2018-06-20 14-58-13.png749×714 108 KB
st104325
You have probably cut the important part of your error message in your screenshot…
st104326
Screenshot from 2018-06-21 11-48-54.png733×626 86.6 KB the bottom of the screen-shot .
st104327
I want to stack list of something and convert it to gpu: torch.stack(fatoms, 0).to(device=device) As far as I know, tensor was created on cpu firstly and then would be transferred to specified device. How to put it on gpu straight?
st104328
Solved by ptrblck in post #4 If your fatoms list contains CPU tensors, then your example is the way to go. You could push the content onto the GPU before calling torch.stack, which is what my example shows.
st104329
If both tensors are already on the GPU, the result will also have the save device: a = torch.randn(10, device='cuda:0') b = torch.randn(10, device='cuda:0') c = torch.stack((a, b)) print(c.device) > device(type='cuda', index=0)
st104330
If your fatoms list contains CPU tensors, then your example is the way to go. You could push the content onto the GPU before calling torch.stack, which is what my example shows.
st104331
I just started learning PyTorch after using Keras exclusively for a couple of years. I really like how models in Keras are trained, and having nice qol features like model checking and early stopping. I was wondering if there’s a way to implement each of the following in PyTorch Reserving a portion of the training data as validation data so that the model predicts on the validation data at each epoch. Additionally, is there a way to randomize what data is put into the validation set Callbacks like early stopping, snapshot ensembling, and model checking Also in the tutorial on training a classifier (https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html 7) and several other PyTorch implementations of nn architectures, there typically isn’t an activation at the end (i.e. sigmoid/softmax). Why is this the case? Is the activation function not needed at the end?
st104332
Have a look at Ignite 21. They have some utilities and abstractions which you may find useful. You don’t need an activation function for certain loss functions. nn.CrossEntropyLoss for example expects logits, so that you shouldn’t have any activation at the end of your model. nn.NLLLoss on the other have expects log probabilities, so that you would have to add a nn.LogSoftmax as the last layer. Have a look at the loss functions in the docs 11 for more information. This is mostly done for numerical stability reasons. E.g. calling log on softmax separately might not be stable.
st104333
[root@localhost pytorch]# source activate py35 (py35) [root@localhost pytorch]# export CMAKE_PREFIX_PATH="/root/miniconda3/bin:/usr/lib64" (py35) [root@localhost pytorch]# python setup.py install … [100%] Generating lib/libnccl.so Compiling src/libwrap.cu > /opt/pytorch/third_party/build/nccl/obj/libwrap.o nvcc fatal : redefinition of keyword ‘code’ make[3]: *** [/opt/pytorch/third_party/build/nccl/obj/libwrap.o] 错误 1 make[2]: *** [lib/libnccl.so] 错误 2 make[1]: *** [CMakeFiles/nccl.dir/all] 错误 2 But for pytorch 20180617, it works fine
st104334
When I transfer my model to cuda:0: model = model.to(device=torch.device("cuda:0")) Everything is fine, but when I try to do the same for torch.device("cuda:1"), I got: RuntimeError: CUDA error (10): invalid device ordinal What I tried: os.environ[“CUDA_VISIBLE_DEVICES”] = “1” export CUDA_VISIBLE_DEVICES=1 and then python my_program.py CUDA_VISIBLE_DEVICES=1 python my_program.py However, I’d like to notice that print(torch.cuda.current_device()) give me 0 always. Also, I use conda env. Can conda be a reason of issue?
st104335
Solved by justusschock in post #2 If you set CUDA_VISIBLE_DEVICES = 1 your python script is only able to “see” this GPU and thus refers to it as “cuda:0” . If you start it on cuda:0 with CUDA_VISIBLE_DEVICES being set to 1 and afterwards use nvidia-smi you should see your model running on GPU1
st104336
If you set CUDA_VISIBLE_DEVICES = 1 your python script is only able to “see” this GPU and thus refers to it as “cuda:0” . If you start it on cuda:0 with CUDA_VISIBLE_DEVICES being set to 1 and afterwards use nvidia-smi you should see your model running on GPU1
st104337
I have trained a pytorch model and write one test py script to predict(input one image and load model and predict the result). I have 10 images, there are two ways: one thread just loop the 10 images order by order, the time of every test result is about 40ms multithread use python multithread, but the time of every test result is about 500ms, but the total execute time is similar with way one. It seems the multithread is not working. In the test script, the num_workers param of load testset method(torch.utils.data.DataLoader) is set to 0 is faster then 2 or 10.(it seems the bigger of num_workers ,the slower of the result) Could you help me how to improve the test performance? Many thanks, Alex
st104338
Can you try setting env var OMP_NUM_THREADS=1 before running your python script?
st104339
Hi guys, does PyTorch has the function that would return me the vectorized upper triangular matrix? For example, I have Tensors as [ [1, 2, 3], [4, 5, 6], [7, 8, 9]], and I want [1, 2, 3, 5, 6, 9]. I know numpy has triu_indices, which will return me the indices of upper triangular matrix, and use the index I can easily get the elements I want from numpy matrix. but it seems that I can’t do that in PyTorch. Thanks!
st104340
I don’t think that there’s a api for directly returning the vectorized upper triangular matrix, but you can still achieve that: >>> a = torch.arange(1, 10).view(3, 3) >>> a 1 2 3 4 5 6 7 8 9 [torch.FloatTensor of size 3x3] >>> triu_indices = a.triu().nonzero().transpose() >>> triu_indices 0 0 0 1 1 2 0 1 2 1 2 2 [torch.LongTensor of size 2x6] >>> vectorized_upper_triangular_matrix = a[triu_indices[0], triiu_indices[1]] >>> vectorized_upper_triangular_matrix 1 2 3 5 6 9 [torch.FloatTensor of size 6] Maybe there’s a better way that I’m not aware of.
st104341
Note that this only works when there are no zeros in the upper triangular part. It would be cool if we could get more support for this in core pytorch. Also important is the opposite – going from a vectorization to an upper/lower triangular matrix. I haven’t been able to find a clean way to do this yet.
st104342
Here’s another way that should work more generally: In [180]: x = torch.randn(3, 3) In [181]: x Out[181]: 1.6177 0.5082 1.3817 -0.5801 -0.4657 0.8086 -0.4783 -0.3208 1.4459 [torch.FloatTensor of size 3x3] In [182]: x[torch.triu(torch.ones(3, 3)) == 1] Out[182]: 1.6177 0.5082 1.3817 -0.4657 0.8086 1.4459 [torch.FloatTensor of size 6] And you can do the reverse similarly, In [183]: vec = x[torch.triu(torch.ones(3, 3)) == 1] In [184]: y = torch.zeros(3, 3) In [185]: y[torch.triu(torch.ones(3, 3)) == 1] = vec In [186]: y Out[186]: 1.6177 0.5082 1.3817 0.0000 -0.4657 0.8086 0.0000 0.0000 1.4459 [torch.FloatTensor of size 3x3]
st104343
Although this doesn’t seem to work on Variables: RuntimeError: can't assign Variable to a torch.FloatTensor using a mask (only torch.FloatTensor or float are supported)
st104344
You could do this with a mask def tril_mask(value): n = value.size(-1) coords = value.new(n) torch.arange(n, out=coords) return coords <= coords.view(n, 1) which is used as >>> value = torch.arange(9).view(3,3) >>> value[tril_mask(value)] 0 3 4 6 7 8 [torch.FloatTensor of size 6]
st104345
Trick is to use numpy itself in torch without hurting the backpropgration. For x as a 2D tensor this works for me: import numpy as np row_idx, col_idx = np.triu_indices(x.shape[1]) row_idx = torch.LongTensor(row_idx).cuda() col_idx = torch.LongTensor(col_idx).cuda() x = x[row_idx, col_idx] For 3D tensor (assuming first dimension is batch): row_idx, col_idx = np.triu_indices(x.shape[2]) row_idx = torch.LongTensor(row_idx).cuda() col_idx = torch.LongTensor(col_idx).cuda() x = x[:, row_idx, col_idx] Note that the whole process is still differentiable in pytorch.
st104346
Hello , I have the exact opposite issue ! I have a vector with n*(n-1)/2 elements . (the elements of an upper triangular matrix matrix without the main diagonal) I want to assign the vector into an upper triangular matrix (n by n) and still keep the whole process differentiable in pytorch. I have tried : mat[np.triu_indices(n, 1)] = vector 1 is the offset besause i dont use the main diagonal. and I get the RuntimeError: a leaf Variable that requires grad has been used in an in-place operation. Any suggestions without using in-place operations ?
st104347
No, but I have a suggestion without requiring grad on a leaf variable : n = 5 mat = torch.zeros(5, 5) vector = torch.randn(10, requires_grad=True) mat[numpy.triu_indices(n, 1)] = vector mat.sum().backward() vector.grad gives the expected vector of 10 ones. So mat doesn’t require_grad when it is instantiated, but only indirectly when you assign elements requiring grad to it. That works. Best regards Thomas
st104348
@tom I understood and reproduced your code snippet. I have an issue though in integrating it in a custom layer. My goal is to compute gradients for Q (3x3 matrix) ! My problem is that I cannot compute gradients (None is shown) I suspect there is something wrong with the computational graph or an inplace operation that I am missing. Here is a sample of my custom layer: (I tried to keep it clear and simple ) class AdaLayer(torch.nn.Module): def __init__(self, Li): super(AdaLayer, self).__init__() self.Q = nn.Parameter(torch.rand((3, 3), dtype=torch.float)) self.M = nn.Parameter(torch.mm(self.Q, self.Q.t()), requires_grad=True) #symmetric self.W = None self.mat = None self.linear1 = torch.nn.Linear(re_size*re_size*3, out_size) def forward(self, img_flat, uniq_dif): dim = img_flat.shape[0] self.M = nn.Parameter(torch.mm(self.Q, self.Q.t())) vector = Variable( torch.diag( torch.mm( torch.mm(uniq_dif, self.M) , uniq_dif.t())), requires_grad=True ) # as discussed self.mat = torch.zeros(dim, dim) self.mat[np.triu_indices(dim, 1)] = vector # auto-gradient reaches up to here ! self.W = nn.Parameter(torch.exp(-1*(torch.sqrt((self.mat + self.mat.t())))/2), requires_grad=True) y = (torch.mm(self.W, img_flat)).t().contiguous() print(y.shape) y = self.linear1(y.view(1,-1)) return y Output: ------------------Q 3x3 gradient---------------------- None ------------------M symmetric positive semidefinite gradient---------------------- None ------------------ mat gradient---------------------- None ------------------W gradient---------------------- tensor([[-1.7305e-05, -1.1781e-05, -1.3871e-05, …, -5.0380e-06, -1.9574e-05, -6.8704e-06], [ 1.3375e-06, 1.0680e-06, 1.2287e-06, …, 5.4148e-07, 1.3086e-06, 6.5805e-07], [-3.6731e-06, -2.9817e-06, -3.5238e-06, …, -1.0123e-06, -2.3968e-06, -1.4685e-06], …, etc… Any extra help would be greatly appreciated. ( I am new in pytorch ) Kind regards , black0017
st104349
One couldn’t reproduce this, as it won’t run (triple backticks “```” around the code comment would help the formatting, too). nn.Parameter breaks the computational graph and should only be used for model state, not for computed variables, so does Variable(...). It is almost certainly an error to instantiate new nn.Parameter that in forward. Best regards Thomas
st104350
I am looking into the adam optimizer code and I ran into the following code. if group['weight_decay'] != 0: grad = grad.add(group['weight_decay'], p.data) It is clear that weight_decay and p.data are muiltiplied and then added to the grad. However, checking the documentation, I cannot see the add method which does this.
st104351
It’s the second entry: https://pytorch.org/docs/stable/torch.html?highlight=add#torch.add 13 torch.add(input, value=1, other, out=None) But we should really make a note of it in the tensor.add docs.
st104352
Hello! I have just started to pytorch-ing. I saw that recently a new pytorch version (0.4) has been released. I wonder do the examples 1 or tutorials 1 in the official pytorch webpage is modified accordingly? For example, I heard that there is no more Variable type in pytorch but I still saw them in the examples I shared above. So, my question: Is it dangerous to use these examples if we are planning to use pytorch version 0.4? Thanks!
st104353
All of the examples and tutorials should be modified accordingly. Variable is deprecated, but you can still use it for backwards compatibility reasons. However, as you noted, it is better to not use Variables in your code: could you point me to where those are still being used in the examples/tutorials?
st104354
coyote: examples Sure, today I saw usage of variable only 1 on this example. I guess others have already been updated accordingly.
st104355
My bad. As you said, the variable I was talking about is part of TF code not pytorch. Then, I guess I should close this thread since I do not have any other example for now.
st104356
Hello, I have a fresh installation of cuda 8.0 and pytorch. I ran the following simple code: import torch a = torch.rand(4) a.cuda() When I try to use the GPU from pytorch I get the error: THCudaCheck FAIL file=/opt/conda/conda-bld/pytorch_1524577177097/work/aten/src/THC/THCTensorRandom.cu line=25 error=30 : unknown error Traceback (most recent call last): File “”, line 1, in RuntimeError: cuda runtime error (30) : unknown error at /opt/conda/conda-bld/pytorch_1524577177097/work/aten/src/THC/THCTensorRandom.cu:25 Upon installation I checked whether cuda installation is successful using deviceQuery test and I got a PASS. torch.cuda.is_available() returnsTrue. nvidia-smi returns: ±----------------------------------------------------------------------------+ | NVIDIA-SMI 390.48 Driver Version: 390.48 | |-------------------------------±---------------------±---------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 GeForce GTX TIT… Off | 00000000:03:00.0 On | N/A | | 22% 41C P8 16W / 250W | 423MiB / 12211MiB | 1% Default | ±------------------------------±---------------------±---------------------+ ±----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | 0 1458 G /usr/bin/X 120MiB | | 0 2974 G compiz 44MiB | | 0 3691 C python 242MiB | ±----------------------------------------------------------------------------+ nvcc -V returns nvcc: NVIDIA ® Cuda compiler driver Copyright © 2005-2016 NVIDIA Corporation Built on Tue_Jan_10_13:22:03_CST_2017 Cuda compilation tools, release 8.0, V8.0.61 Can someone point out what is potentially wrong with my system? I tried reinstalling both Cuda and pytorch multiple times and restarting. Thanks!
st104357
Hi! Have you solved the problem? I met the same mistake and failed to solve it after various attempts. Could you help? Thanks very much.
st104358
Hi, I am losing my mind a bit, I guess I missed something in the documentation somewhere but I cannot figure it out. I am taking the derivative of the sum of distances from one point (0,0) to 9 other points ( [-1,-1],[-1,0],…,[1,1] - AKA 3x3 grid positions). When I reshape one of the variables from (9x2) to (9x2) the derivative seems way off… If i leave it as is and do not reshape it from (9x2) to (9x2) then the derivate seems correct within float error. I’ve looked but I can’t figure out why. Can anyone help? or point me in the right direction? Thank you! from __future__ import print_function from torch.autograd import Variable import torch #make a grid t=torch.Tensor([-1,0,1]) a=t.reshape(1,3,1).expand(3,3,1) b=t.reshape(3,1,1).expand(3,3,1) grid=torch.cat((a,b),2) points=grid.reshape(-1,2) point=Variable(torch.Tensor([0,0]),requires_grad=True) #distances=torch.norm(points-point.expand(9,2).reshape(9,2),2,1) distances=torch.norm(points-point.expand(9,2),2,1) output=distances.sum() d_output_to_point = torch.autograd.grad(output,point,create_graph=True)[0] print(d_output_to_point) UPDATE: I cannot post because my account is on hold for some reason I found the answer, github.com/torch/cutorch Issue: reshape, view, resize differences 46 opened by szagoruyko on 2015-01-10 closed by szagoruyko on 2015-01-12 Could someone please clear the differences between THCudaTensor_resize(n)d and :view, :reshape? In which cases resize doesn't copy memory, and is there...
st104359
Ah! I’m a fool! github.com/torch/cutorch Issue: reshape, view, resize differences 40 opened by szagoruyko on 2015-01-10 closed by szagoruyko on 2015-01-12 Could someone please clear the differences between THCudaTensor_resize(n)d and :view, :reshape? In which cases resize doesn't copy memory, and is there... Makes sense
st104360
Hi! This is actually a bug. I’m tracking it at https://github.com/pytorch/pytorch/issues/8626 44 and working on it currently. Sorry about it!
st104361
Interesting I assumed that since a reshape copied over data it somehow lost the history in the process. With view it seems to be much more reasonable… at least in my case. Would this bug also affect contiguous and view calls after expand? or just reshape?
st104362
In this case view and reshape does the same thing. You can either replace reshape with contiguous() or clone() here as a workaround.
st104363
Awesome! Thanks for the quick reply Maybe this fix will make some of the existing code I have run a bit better , in the mean time will use workarounds! Thanks again!
st104364
What’s the main difference between legacy.nn and the new nn? Is legacy.nn slower or what problem does it have? Is there any documentation about why it became legacy? I like the legacy code because it’s easy to read while I can’t even find the implementation of updateGradInput and accGradParameters functions in the new nn package — where are they?
st104365
legacy.nn is there for backwards compatibility with lua torch. If you can find implementations for operations in python, then that means those ops are not being implemented in c++. In general our c++ implementations are faster than their python counterparts. It depends on what operation you’re looking for, but a number of those can be found here: https://github.com/pytorch/pytorch/tree/master/aten/src/TH/generic 16
st104366
>>> import torch >>> import numpy as np >>> torch.cat((np.ones((5,5)), np.zeros((5,5))),1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: expected Variable as element 0 in argument 0, but got tuple Well this error message didnt make sense to me, especially when Variables are deprecated in pytorch 0.4 I guess it could be improved…
st104367
Thank you for the report, I’ve filed an issue here: https://github.com/pytorch/pytorch/issues/8694 118
st104368
When I call: torch.nn.functional.grid_sample(array_5d, indices, mode='anything') mode can be anything. Why is that? Is there no mode to choose? I would like to choose mode=‘trilinear’, is that available? In the docs I can see there is mode=‘bilinear’ as default.
st104369
Only bilinear is supported: https://pytorch.org/docs/master/nn.html?highlight=grid_sample#torch.nn.functional.grid_sample 18 But the code should really throw an error if you try to pass anything other than bilinear. I’ve opened an issue here: https://github.com/pytorch/pytorch/issues/8693 22 for this.
st104370
Hi, I used to create leaf variable like: y = torch.autograd.Variable(torch.zeros([batch_size, c, h, w]), requires_grad=True) Then I want to assign value to indexed parts of y like below,(y_local is a Variable computed based on other variables and I want to assign the value of y_local to part of the y and ensure that the gradients from y can flow to the y_local.) y.data[:,:,local_x[i]:local_x[i+1],local_y[i]:local_y[i+1]] = y_local.data I am wondering such operation supports the normal gradient backward for the y_local varible?
st104371
Gradients won’t flow if you call .data and then index into it. They will flow, however, if you don’t use .data: y[:,:,local_x[i]:local_x[i+1],local_y[i]:local_y[i+1]] = y_local
st104372
Hi there friends! I’m building an RNN that uses nn.embedding() for its input and target. Unfortunately, I’m having trouble with the MSELoss, NLLLoss and other loss functions, which give me this error message when I try to run loss.backward: AssertionError: nn criterions don't compute the gradient w.r.t. targets - please mark these variables as volatile or not requiring gradients However, the nn.embeddings seems to require something similar to a gradient. What loss function can I use to go with the word embeddings I have chosen for target? Thanks in advance!
st104373
I don’t understand. Are you trying to learn the targets? Why do the targets come from an embedding? If you really want to back propagate to the targets you can just compute the MSE loss by: loss = ((input - target)**2).mean()
st104374
Hey! Thanks so much for your response. I super appreciate it. I’m not sure I explained my model well, so I apologize for any confusion. I’m building a word-level LSTM RNN for text generation (I’ve already built the char-level and am hoping to compare the convergence rate of the two). The corpus is so large, though, it’s computationally impossible to run the word-level on my GPU using one-hot vector encoding (the GPU crashes). I’d like to use nn.embedding() to create dense vectors with a fixed, reasonable dimension (I randomly picked 1x100), which makes it possible to run the model. I’m having problems when I get to back-prop, though. That’s where I’m getting stuck in my understanding of what’s going on. It’s my understanding if I’m feeding in a sequence of word-embedded vectors for each word, the loss function will compare the model’s output prediction with the word-embedded target, then I’ll call loss.backward for back-prop. Does that make it more clear why I’m using word-embedding for the target? Eventually, when sampling, I’ll convert the model’s word-embedding vector prediction to the word it represents. Please let me know if this clears anything up. Again, I’m super grateful for your help with this.
st104375
I think one normally passes the predicted embeddings through an nn.Linear(n_embed, n_vocab) (and then Softmax or LogSoftmax). That should give you relative “probabilities” of the next word.
st104376
Thanks for the response! So I already have the predicted embeddings, I need to back-propagate the results. But when I pass in the two embeddings (one being the predicted embeddings, the other being the target embedding) to the loss function, I get this: AssertionError: nn criterions don't compute the gradient w.r.t. targets - please mark these variables as volatile or not requiring gradients I’d just like to know the best way to compute loss then back-propagate AFTER receiving the predicted output, which is also an embedded vector. Is it clear what I’m asking? Thanks again for your help.
st104377
(Let me know if seeing any of my code would be helpful and what in particular I should share.)
st104378
If your targets are fixed (i.e. you are not optimizing the targets), do loss_fn(input, target.detach()). If you are also optimizing the targets, use the expression above.
st104379
Hi cooganb, when your model was done training, and you had it generate some text for you, what did you do when the predicted embedding wasn’t an actual word? It seems unreasonable to expect all 100 dimensions of the prediction to perfectly match a real word, so did you find the euclidean-closest embedding to the predicted one? Or maybe find the most cosine-similar embedding to the predicted one? Neither of those is getting good results for me, so I would really love to know how far you got with this.
st104380
As far as I understand, the usual thing to do is take a softmax with the inner products of embeddings with the output. This then puts you in the same place as you would be with a classification problem at the softmax layer. Best regards Thomas
st104381
I am curious about what loss function did you use in the end? Which gave the best performance? Also what optimizer worked the best?
st104382
Hello every body, Can you take 2min and run this program on your system and tell me the execution time please ? It’s just for me to be sure that my config system run correctly because on my system the program takes 6min against 1min30 on the web site normaly. You can download the script at the end of the page! code link : https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html#convnet-as-fixed-feature-extractor 1 Sorry I can’t copy the code here directly… Thanks
st104383
I have a 8-GPU server, however the performance of training using torchvision has no advantage over 4-GPU server. I checked the p2pbandwidth and topology of the gpus. I thought the bandwidth between first 4-gpus and second 4-gpus is quite low. Is it the problem? image.png1214×310 36 KB
st104384
I am browsing some code in the ATen lib and came across this 3: if (scale_grad_by_freq) { counts.reset(new int64_t[num_weights]); for (int i = 0; i < numel; i++) { counts[indices_data[i]] = 0; } for (int i = 0; i < numel; i++) { counts[indices_data[i]]++; } } Perhaps I’m missing something, but it looks strange to loop over the indices twice here.
st104385
The first zeros the counts, the second then counts. If you have the same index multiple times (which is the point of counting when you want to scale by frequency), you cannot combine the two. My guess for the first loop would be that it is cheaper to only initialize those indices that are actually used rather than all of them en bloc. Best regards Thomas
st104386
Hi, I’m trying to do an image classification task with my first neural network. I have minimal practical experience. I have about 650 8-bit gray value images of dimensions 21x21x21 that I want to put into two classes. Starting from one of the official tutorials here 2, after some fiddling I now have this code: import os from matplotlib import pyplot as plt import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torch.optim as optim import helpers batch_size = 4 rng = np.random.RandomState(128) #========================================================================= # Load data #========================================================================= # truth/target values path = "/NN_ROI_classification_data/" truth = pd.read_csv(os.path.join(path, 'assessments.csv')) # images temp = [] for img_name in truth.Number: image_path = os.path.join(path, 'images', str(img_name)) img = helpers.read_image_sequence(image_path) img = img.astype('float32') temp.append(img) imgs = np.stack(temp) imgs /= 255.0 truth = truth.Type.values # Split data into a training and a validation set training_no = 350 train_imgs, val_imgs = imgs[:training_no], imgs[training_no:] train_truth, val_truth = truth[:training_no], truth[training_no:] #========================================================================= # Define net #========================================================================= class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel, 6 output channels, 5x5 square convolution # kernel self.conv1 = nn.Conv2d(21, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) # an affine operation: y = Wx + b self.fc1 = nn.Linear(16 * 2 * 2, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 1) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 2 * 2) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x net = Net() criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) def batch_creator(batch_size): dataset_length = train_imgs.shape[0] batch_mask = rng.choice(dataset_length, batch_size) batch_imgs = train_imgs[batch_mask] batch_truth = train_truth[batch_mask] return batch_imgs, batch_truth #========================================================================= # Train net #========================================================================= total_batch = int(train_truth.shape[0] / batch_size) for epoch in range(2): # loop over the dataset multiple times running_loss = 0.0 for i in range(total_batch): # get the inputs img_batch, truth_batch = batch_creator(batch_size) imgs = Variable(torch.from_numpy(img_batch)) truth = Variable(torch.from_numpy(truth_batch), requires_grad=False) # @UndefinedVariable # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize outputs = net(imgs) loss = criterion(outputs, truth) loss.backward() optimizer.step() # print statistics running_loss += loss.item() if i % 2000 == 1999: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0 print('Finished Training') The line where the loss is computed generates this error: RuntimeError: Assertion `cur_target >= 0 && cur_target < n_classes' failed. at /pytorch/aten/src/THNN/generic/ClassNLLCriterion.c:97 At that point, this is what truth looks like: tensor([ 1, 1, 0, 1]) And this is outputs: tensor(1.00000e-02 * [[-2.2640], [-3.1873], [-2.1566], [-2.4766]])
st104387
Your last linear layer (fc3) should have 2 output units, since you are using CrossEntropyLoss. Just change it to self.fc3 = nn.Linear(84, 2) and run it again.
st104388
Thanks, that did it! Well, it runs, but it doesn’t work well: ... [2, 80] loss: 0.474 [2, 81] loss: 0.951 [2, 82] loss: 0.837 [2, 83] loss: 0.476 [2, 84] loss: 0.828 [2, 85] loss: 0.725 [2, 86] loss: 0.717 [2, 87] loss: 0.830 Finished Training My reasoning was, since I have two classes and truth values of 0 or 1 for each image, the net should have one output that is either closer to 0 or 1. Now that the net’s output is a vector with two entries, do the truth values also have to have two entries per image? I.e. (0,1) or (1,0)?
st104389
Since, you have only two classes, better to use binary cross entropy as the loss function and change your last layer to self.fc3 = nn.Linear(84, 1) as it was initially. BCE loss in pytorch -> torch.nn.BCELoss()
st104390
Thanks for the tip! BCELoss() awaits an input between 0 and 1, while my net outputs have entries like -5. Now my first thought was to normalize each output vector to [0,1] but on second thought, that’s a bad idea, right? Wouldn’t that change the overall loss values in a non linear way? If yes, what can I do instead?
st104391
Using BCELoss as @Jk749 suggested is another valid approach. Just use one output unit, add a sigmoid at your last layer, and try BCELoss. ... x = F.sigmoid(self.fc3(x)) return x
st104392
Ah, that was easy, thanks. It does little to improve the performance though: ... Truth: tensor([ 1., 0., 0., 0.]) Output: tensor([[ 0.5666], [ 0.5650], [ 0.5653], [ 0.5655]]) [2, 85] loss: 0.703 Truth: tensor([ 1., 0., 0., 1.]) Output: tensor([[ 0.5657], [ 0.5688], [ 0.5657], [ 0.5668]]) [2, 86] loss: 0.702 Truth: tensor([ 0., 1., 1., 0.]) Output: tensor([[ 0.5679], [ 0.5672], [ 0.5660], [ 0.5657]]) [2, 87] loss: 0.768 Truth: tensor([ 1., 0., 0., 0.]) Output: tensor([[ 0.5679], [ 0.5659], [ 0.5667], [ 0.5656]]) Finished Training Hmm. In the tutorial where I started from, 3-channel (RGB) images are categorized into ten classes. Now I have 21 channels and two classes. I guess the net architecture must be changed further…? I’ve trained an SVM with this same data and achieved about 95% accuracy.
st104393
Have you trained the SVM on the images directly? You could play around with the learning rate, optimizers etc. What kind of data do you have?
st104394
WIll do! Each image is a 21x21x21px 3D ROI of an 8 bit grey value phase microscopy image and the classifier should decide whether there’s a (one) cell present or not. I used the SVM from scikit learn and trained on the images directly, in the unraveled shape of 1x9261.
st104395
I’m running some pytorch code and it will randomly stop and output the text “Killed”. I don’t see that anywhere in my code so just wondering where it is coming from and what might be causing it? Edit: Never mind, looks like this is a python thing that the program took up too much resources somewhere.
st104396
I encountered the same issue. When you said it took up too much resources, are you referring to the GPU?
st104397
The Linux kernel has a mechanism to kill processes taking up all CPU ram. 363 “Killed” sounds like the typical output in that case, in sudo dmesg you’ll see log entries about “OOM”. Best regards Thomas
st104398
Hi, I’ve seen it’s possible to train with a hybrid system of gpu-cpu but in the end cpu do bottleneck I would like to know if it’s possible to use the standard RAM as additional memory which can be used by the GPU. Of course the main idea would be computing everything with the GPU.
st104399
If you are able to make your own autograd.Function, you can store things on CPU: class StorethingsOnCPU(torch.autograd.Function): @staticmethod def forward(ctx, inp): #...some calculation here... res = inp ctx.save_for_backward(inp.cpu()) ctx._device = inp.device return res @staticmethod def backward(ctx, grad_out): inp_cpu, = ctx.saved_tensors inp = inp_cpu.to(ctx._device) #...do the backward here... print (inp_cpu, inp) grad_in = grad_out return grad_in I don’t think there is a programmatic way to access the backwards of arbitrary built-in functions, though. At worst - and at the expense of a lot of time - you could re-do the forward on inp.detach().requires_grad_(), do a backward and return inp.grad. Best regards Thomas