instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
Pytorch get "RuntimeError: CUDA error: device-side assert triggered"
Snippet from my code : max = torch.tensor([3]) if USE_CUDA: max = max.cuda() max_embedding = self.max_embedding(max) # dim of max_embedding: 1*5 item_dict = {} for item in item_list: item = torch.tensor(item) if USE_CUDA: item = item.cuda() item_embedding = self.item_embedding(item) # dim of item_embedding: 1*20 embedded = torch.cat((max_embedding, item_embedding), 1) But I get error of "RuntimeError: CUDA error: device-side assert triggered". The output by adding CUDA_LAUNCH_BLOCKING=1: /pytorch/aten/src/THC/THCTensorIndex.cu:308: void indexSelectSmallIndex(TensorInfo<T, IndexType>, TensorInfo<long, IndexType>, int, int, IndexType, long) [with T = float, IndexType = unsigned int, DstDim =2, SrcDim = 2, IdxDim = -2: block: [0,0,0], thread: [0,0,0] Assertion `srcIndex < srcSelectDimSize` failed. /pytorch/aten/src/THC/THCTensorIndex.cu:308: void indexSelectSmallIndex(TensorInfo<T, IndexType>, TensorInfo<long, IndexType>, int, int, IndexType, long) [with T = float, IndexType = unsigned int, DstDim =2, SrcDim = 2, IdxDim = -2: block: [0,0,0], thread: [1,0,0] Assertion `srcIndex < srcSelectDimSize` failed. /pytorch/aten/src/THC/THCTensorIndex.cu:308: void indexSelectSmallIndex(TensorInfo<T, IndexType>, TensorInfo<long, IndexType>, int, int, IndexType, long) [with T = float, IndexType = unsigned int, DstDim =2, SrcDim = 2, IdxDim = -2: block: [0,0,0], thread: [2,0,0] Assertion `srcIndex < srcSelectDimSize` failed. /pytorch/aten/src/THC/THCTensorIndex.cu:308: void indexSelectSmallIndex(TensorInfo<T, IndexType>, TensorInfo<long, IndexType>, int, int, IndexType, long) [with T = float, IndexType = unsigned int, DstDim =2, SrcDim = 2, IdxDim = -2: block: [0,0,0], thread: [3,0,0] Assertion `srcIndex < srcSelectDimSize` failed. /pytorch/aten/src/THC/THCTensorIndex.cu:308: void indexSelectSmallIndex(TensorInfo<T, IndexType>, TensorInfo<long, IndexType>, int, int, IndexType, long) [with T = float, IndexType = unsigned int, DstDim =2, SrcDim = 2, IdxDim = -2: block: [0,0,0], thread: [4,0,0] Assertion `srcIndex < srcSelectDimSize` failed. Traceback (most recent call last): File "mytest.py", line 33, in <module> if USE_CUDA: item = item.cuda() RuntimeError: CUDA error: device-side assert triggered How to fix it?
This is a typical case of index-out-of-bounds error manifested itself in the context of embeddings. Check this link for solution to a similar problem.
https://stackoverflow.com/questions/58889968/
Saving Numpy Array as Lab Image via PIL
Hello everyone! I am writing a function which gets two Pytorch-Tensors as input and merges parts of both tensors to a new array which will be converted to a Lab-image afterwards. net_input is a tensor with 3 channels (L, a, b) and output is a tensor with 2 channels (a, b). Now, I want to take the L-channel from net_input and the a-channel and the b-channel from output. The first tensor, net_input, has values from -1 to 1. The second tensor, output, has values from 0 - 1. Thus, both of them must be mapped to values from -128 to 127. I do this, using interp1d Apparently the saved image has some unwanted patterns and is incorrect. original: . grayscale: from PIL import Image as pil import numpy as np from PIL import Image from scipy.interpolate import interp1d from datetime import datetime def output_to_image(net_input, output, index): # net_input.size() --> torch.Size([1, 3, 225, 225]) # l, a, b channel # output.size() --> torch.Size([1, 2, 225, 225]) # a, b channel # A - B - Channel map_a_b = interp1d([0.0, 1.0], [-128, 127]) # L-Channel map_l = interp1d([-1.0, 1.0], [-128, 127]) height = output.size()[2] width = output.size()[3] l = net_input.detach().numpy()[0][0] # l channel a = output.detach().numpy()[0][0] # a channel b = output.detach().numpy()[0][1] # b channel # pdb.set_trace() img_arr = np.empty([height, width, 3]) # lab img array l_arr = np.empty([height, width]) # grayscale img array for h in range(0, height-1): for w in range(0, width-1): img_arr[h][w] = [map_l(l[h][w]), map_a_b(a[h][w]), map_a_b(b[h][w])] l_arr[h][w] = map_l(l[h][w]) now = datetime.now() img = Image.fromarray(img_arr, "LAB") img.save(f"../images/output/{now.strftime('%d-%m-%Y %H:%M:%S')}-lab-img{index}.tiff") gray = Image.fromarray(l_arr, "L") gray.save(f"../images/output/{now.strftime('%d-%m-%Y %H:%M:%S')}-gray-img{index}.jpg") This is how L, a and b look like: (Pdb) >? print(l) [[-1. -1. -1. ... -1. -1. -1.] [-1. -1. -1. ... -1. -1. -1.] [-1. -1. -1. ... -1. -1. -1.] ... [-1. -1. -1. ... -1. -1. -1.] [-1. -1. -1. ... -1. -1. -1.] [-1. -1. -1. ... -1. -1. -1.]] (Pdb) >? print(a) [[0.51877767 0.5208904 0.5310791 ... 0.5340722 0.51334995 0.522657 ] [0.5142181 0.50250506 0.5197009 ... 0.51169556 0.5332947 0.5155644 ] [0.53288984 0.51795006 0.5224927 ... 0.51704454 0.53655064 0.50311136] ... [0.5270468 0.5071506 0.52318716 ... 0.5217321 0.53424454 0.5011423 ] [0.5216123 0.53247094 0.5254119 ... 0.53089285 0.5259453 0.532716 ] [0.53135234 0.5184961 0.51334924 ... 0.5131047 0.51930845 0.51474 ]] (Pdb) >? print(b) [[0.4812223 0.47910962 0.46892092 ... 0.46592775 0.48665005 0.47734302] [0.48578197 0.49749494 0.4802992 ... 0.4883045 0.46670532 0.48443565] [0.46711013 0.48204994 0.47750723 ... 0.4829555 0.46344927 0.4968886 ] ... [0.47295317 0.49284932 0.47681284 ... 0.47826794 0.46575552 0.49885774] [0.47838774 0.46752912 0.47458804 ... 0.46910718 0.47405463 0.46728405] [0.46864766 0.48150396 0.48665074 ... 0.48689532 0.48069155 0.48526 ]] (Pdb) Edit: After adjusting the interpolation range to 0..255, like Mark suggested, the output looks a little bit different: import numpy as np from PIL import Image from datetime import datetime def output_to_image(net_input, output, index): # net_input.size() --> torch.Size([1, 3, 225, 225]) # output.size() --> torch.Size([1, 3, 225, 225]) height = output.size()[2] width = output.size()[3] l = net_input.detach().numpy()[0][0] # l channel a = output.detach().numpy()[0][0] # a channel b = output.detach().numpy()[0][1] # b channel #pdb.set_trace() img_arr = np.empty([height, width, 3]) # lab img array l_arr = np.empty([height, width]) # grayscale img array for h in range(0, height-1): for w in range(0, width-1): img_arr[h][w] = [map_l(l[h][w]), map_a_b(a[h][w]), map_a_b(b[h][w])] l_arr[h][w] = map_l(l[h][w]) now = datetime.now() img = Image.fromarray(img_arr, "LAB") img.save(f"../images/output/{now.strftime('%d-%m-%Y %H:%M:%S')}-lab-img{index}.tiff") gray = Image.fromarray(l_arr, "L") gray.save(f"../images/output/{now.strftime('%d-%m-%Y %H:%M:%S')}-gray-img{index}.jpg") def map_l(x): return (x+1)*127 def map_a_b(x): return x*127
If you do this with PIL: im = Image.new('LAB',(80,80),color=(255,0,0)).save('a.tif') you'll get a cyan colour the same as if you use this colour converter and put in L/a/b = 100/-128/-128 If you do this: im = Image.new('LAB',(80,80),color=(255,255,0)).save('a.tif') you'll find that corresponds to L/a/b=100/128/-128 on the online converter. And if you do this: im = Image.new('LAB',(80,80),color=(255,255,255)).save('a.tif') you'll find that corresponds to L/a/b=100/128/128 on the online converter. So, I think you are targeting the wrong limits if using PIL. Your ranges for L, a and b should all be 0..255. As regards scaling, I wouldn't use interp1d() at all. If I need to scale the range -1..1 to the range 0..255, I would add 1 which brings me to the range 0..2 and then multiply by 255/2.
https://stackoverflow.com/questions/58892179/
Why does pre-trained ResNet18 have a higher validation accuracy than training?
For PyTorch's tutorial on performing transfer learning for computer vision (https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html), we can see that there is a higher validation accuracy than training accuracy. Applying the same steps to my own dataset, I see similar results. Why is this the case? Does it have something to do with ResNet 18's architecture?
Assuming there aren't bugs in your code and the train and validation data are in the same domain, then there are a couple reasons why this may occur. Training loss/acc is computed as the average across an entire training epoch. The network begins the epoch with one set of weights and ends the epoch with a different (hopefully better!) set of weights. During validation you're evaluating everything using only the most recent weights. This means that the comparison between validation and train accuracy is misleading since training accuracy/loss was computed with samples from potentially much worse states of your model. This is usually most noticeable at the start of training or right after the learning rate is adjusted since the network often starts the epoch in a much worse state than it ends. It's also often noticeable when the training data is relatively small (as is the case in your example). Another difference is the data augmentations used during training that aren't used during validation. During training you randomly crop and flip the training images. While these random augmentations are useful for increasing the ability of your network to generalize they aren't performed during validation because they would diminish performance. If you were really motivated and didn't mind spending the extra computational power you could get a more meaningful comparison by running the training data back through your network at the end of each epoch using the same data transforms used for validation.
https://stackoverflow.com/questions/58895804/
Using MIT Indoor scene database in CNN
I'm an engineering student and kind of a noob to programming. I'm taking an AI course, currently trying to do my final project. I have to create a CNN net, I have to use de MIT Indoor scene database (it can be found here: http://web.mit.edu/torralba/www/indoor.html). I don't have a problem doing the CNN since I've done a few before in the semester using CIFAR10, but I'm having trouble with this one since I don't know who to use this set of images. I think I need to create a dataset of my own, I've tried with PyTorch using https://pytorch.org/tutorials/beginner/data_loading_tutorial.html, but I get confused because I don't have a .csv with features, I have a lot of .xml files with several features for each picture. Also, I don't have a file just saying "bedroom, bar, etc" as I've seen in other tutorials. I would rather use PyTorch since I can use the "train_test_split" function, but if anyone could help me to understand how to make those 15620 my input to the net, I would really appreciate it.
you can generate your own csv files, although, you might not need it. There is a good tutorial on pytorch website https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html#load-data, which is very similar or easily applicable to your case. MIT Indoor dataset has the images one folder per class, and the txt files mentioned on the website are the train / test splits. So, if you create the following folder structure: train |- class 1 |- class 2 ... |- class n and the same for val / test, it should be straight-foward to use (adapt) the datasets.ImageFolder example for your case.
https://stackoverflow.com/questions/58903554/
How to compose several matrices into a big matrix diagonally in Pytorch
I have several matrices, let's say [M1,M2,M3,M4]. Each matrix has a different shape. How do I compose these matrices into one big matrix diagonally like: [[M1, 0, 0, 0] [0, M2, 0, 0] [0, 0, M2, 0] [0, 0, 0, M2]] Example: M1 = [[1,2],[2,1]] M2 = [[1,2]] M3 = [[3]] M4 = [[3,4,5],[4,5,6]] To compose this big matrix: [[1, 2, 0, 0, 0, 0, 0] [2, 1, 0, 0, 0, 0, 0] [0, 0, 1, 2, 0, 0, 0] [0, 0, 0, 0, 3, 4, 5] [0, 0, 0, 0, 4, 5, 6]]
Use PyTorch's torch.block_diag(): >>> torch.block_diag(M1,M2,M3,M4) tensor([[1, 2, 0, 0, 0, 0, 0, 0], [2, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 2, 0, 0, 0, 0], [0, 0, 0, 0, 3, 0, 0, 0], [0, 0, 0, 0, 0, 3, 4, 5], [0, 0, 0, 0, 0, 4, 5, 6]])
https://stackoverflow.com/questions/58905583/
How to free GPU memory for a specific tensor in PyTorch?
I’m currently running a deep learning program using PyTorch and wanted to free the GPU memory for a specific tensor. I’ve thought of methods like del and torch.cuda.empty_cache(), but del doesn’t seem to work properly (I’m not even sure if it frees memory at all) and torch.cuda.empty_cache() seems to free all unused memory, but I want to free memory for just a specific tensor. Is there any functionality in PyTorch that provides this? Thanks in advance.
del operator works but you won't see a decrease in the GPU memory used as the memory is not returned to the cuda device. It is an optimization technique and from the user's perspective, the memory has been "freed". That is, the memory is available for making new tensors now. Source: Pytorch forum
https://stackoverflow.com/questions/58925249/
how to batch dialog dataset in pytorch?
I want to do a task oriented dialog chatbot which is used to book restaurant.Because every dialog has different sequences(eg. some has 5 turns of dialogs which is 10 sentences while another may has 6 turns of dialogs which is 12 sentences totally),I don't know how to batch dataset. Could you give me some tutorial or github example?
There are some related questions to this on Stackoverflow. I liked the explanation/answer provided here. The tldr version is to use Packed Sequence. The answer I linked to provides the following example (copied from the link): a = [torch.tensor([1,2,3]), torch.tensor([3,4])] b = torch.nn.utils.rnn.pad_sequence(a, batch_first=True) >>>> tensor([[ 1, 2, 3], [ 3, 4, 0]]) torch.nn.utils.rnn.pack_padded_sequence(b, batch_first=True, lengths=[3,2]) >>>>PackedSequence(data=tensor([ 1, 3, 2, 4, 3]), batch_sizes=tensor([ 2, 2, 1]))
https://stackoverflow.com/questions/58929441/
How to set up loss function in PyTorch for Soft-Actor-Critic
I'm trying to implement a custom loss function for a soft Q-learning, actor-critic policy gradient algorithm in PyTorch. This comes from the following paper Learning from Imperfect Demonstrations. The structure of the algorithm is similar to deep q-learning, in that we are using a network to estimate Q-values, and we use a target network to stabilize results. Unlike DQN, however, we calculate V(s) from Q(s) by: This is simple enough to calculate with PyTorch. My main question has to do with how to set up the loss function. Part of the update equation is expressed as: Note that Q_hat comes from the target network. How can I go about putting something like this into a loss function? I can compute values for V and Q, but how can I handle the gradients in this case? If anyone can point me towards a similar example that would be much appreciated.
This turns out to be fairly simple assuming you can calculate V, Q, and Q^. After discussing this with some people offline I was able to get pytorch to calculate this loss by setting it up as: loss = (Q-V)*(Q-Q_hat).detach() optimizer.zero_grad() loss.backward() optimizer.step()
https://stackoverflow.com/questions/58943164/
Pytorch customize weight
I have a network class Net(nn.Module) and two different weights w0 and w1 (concatenate weights of all layers into a vector). Now I want to optimize the network on the line connecting w0 and w1, which means that the weight will have the form theta * w0 + (1-theta) * w1. So now the parameter I want to optimize is no longer the weight itself, but the theta. How can I implement this? In Pytorch, how can I define the parameter to be theta, and set the weight to be form I want. To be specific, if I create a new class NetOnLine(nn.Module) how should I write the forward(self, X) function?
You can define the parameter theta in your net as an nn.Parameter. You'd define the forward function the same way as normal - pass the data through the layers or operations you want and then return it. Here's a minimal example, where I train a "network" to learn to multiply a Tensor by 2: import numpy as np import torch class SampleNet(torch.nn.Module): def __init__(self): super(SampleNet, self).__init__() self.theta = torch.nn.Parameter(torch.rand(1)) def forward(self, x): x = x * self.theta.expand_as(x) # expand_as() to match sizes return x train_data = np.random.rand(1000, 10) train_data[:, 5:] = 2 * train_data[:, :5] train_data = torch.Tensor(train_data) sample_net = SampleNet() optimizer = torch.optim.Adam(params=sample_net.parameters()) mse_loss = torch.nn.MSELoss() for epoch in range(5): for data in train_data: x = data[:5] y = data[5:] optimizer.zero_grad() prediction = sample_net(x) loss = mse_loss(y, prediction) loss.backward() optimizer.step() print(f"Epoch {epoch}, Loss {loss.data.item()}") print(f"Learned theta: {sample_net.theta.data.item()}") which prints out Epoch 0, Loss 0.03369491919875145 Epoch 1, Loss 0.0018534092232584953 Epoch 2, Loss 1.2343853995844256e-05 Epoch 3, Loss 2.2044337466553543e-09 Epoch 4, Loss 4.0527581290916714e-12 Learned theta: 1.999994158744812
https://stackoverflow.com/questions/58946855/
Simple policy gradients (REINFORCE) overfits one action when playing Atari Breakout
Self-contained code: https://colab.research.google.com/drive/1HYEXMpicymPUySkhGOaCJdJ3pN4RzXYd The problem: I am trying to use a CNN to play Atari breakout from pixels (Breakout-V0 OpenAI gym). I am trying to use the simple policy gradients algorithm, implemented in PyTorch, to do this. There are four possible actions in this game [<NO-OP>, <FIRE> (play), <LEFT>, <RIGHT>]. Expected results: I would expect the policy to learn to play <NO-OP>, <LEFT>, <RIGHT> with about equal probability, and only play <FIRE> on the first frame of the game. Actual results: After ~4 weight updates, the network predicts ONE action with nearly 100% probability. This means the gradient vanishes and the policy never recovers. What I've tried: Only play random actions at the start of the game (take increasingly greedy actions that follow the policy). You can fiddle around with this in the notebook. I have rewarded only one action, just to prove to myself that it learns to only play that one action. It does, so I think I can rule out any PyTorch specific implementation errors. Introducing an entropy penalty to the loss to discourage high confidence in actions. My understanding is that this should not be necessary to explicitly introduce random actions because action = categorical.sample() does this. And if one action becomes dominant, but does not lead to reward, it should be subsequently discouraged. My thought was that my training batches were skewed so that taking the action <RIGHT> for example lead to more reward per episode than punishment, and hence it's likelihood kept increasing. I would have thought that taking totally random actions at the start of the game and only slowly beginning to listen to the policy would have fixed this, but in my experiments, it didn't. I'm really very confused as to why this doesn't work. BIG thanks to anyone who can help. I tried to debug this with a PhD in RL for 5 hours yesterday and made no progress. Extra Questions: Is it common to play e.g. 1000 rollouts, then sample a batch randomly from this rollout buffer to learn from? My understanding of policy gradients was that the policy is updated after every episode. Am I correct in thinking that in policy gradients, you only backprop through the neuron that you selected your action from, but the gradient gets distributed to ALL the network weights through the softmax?
We ran into a similar problem while training Breakout with VPG (Vanilla Policy Gradient). The solution was to enforce entropy loss over the following Entropy loss over the policy model output (Penalise selecting a specific action with high likelihood) Scaling the MSE between rewards to go and value function Not sure if you are aware of this but do use the Atari wrapper from Deepmind Q 1 : Is it common to play e.g. 1000 rollouts, then sample a batch randomly from this rollout buffer to learn from? My understanding of policy gradients was that the policy is updated after every episode. A 1 : In practice its better to batch multiple episodes in a single batch. Q 2 : Am I correct in thinking that in policy gradients, you only backprop through the neuron that you selected your action from, but the gradient gets distributed to ALL the network weights through the softmax? A 2 : Based on the expected rewards to go, likelihood of selection of specific action is suppressed or encouraged and the model backdrops this information
https://stackoverflow.com/questions/58956125/
Different filters for 2d convolution
I’m having an input of shape (B(atch), F(features), N(odes), T(timestamps)). Right now if I apply a 2d convolution with a kernel of shape (1,2) I will have a total of (F_out, F_in, 1,2) weights to learn which is alright. I want to extend this so that for each Node in the input I have it’s own filter with shape (1,2). Does any of you have any idea where should I start from? So far I looped through all N and apply the filter to its respective input. Unfortunately this approach is very slow.
You are looking for "grouped convolution". The doc for nn.Conv2d regarding the groups parameter: At groups=2, the operation becomes equivalent to having two conv layers side by side, each seeing half the input channels, and producing half the output channels, and both subsequently concatenated. In your case, you want groups= number of nodes. It's not that simple in your case, because you want to "merge" features and nodes, and to have only 1d grouped convolution over the "feature"+"node" dimension. Moreover, you need to permute between "node"s and "feature"s in order to group the features according to nodes. b = 10; inf = 8; outf = 13; n = 3; t = 50; x = torch.rand((b, inf, n, t)) # input tensor gconv = nn.Conv1d(inf, outf, kernel_size=(2), groups=n) #grouped conv x_ready = x.permute(0, 2, 1, 3).view(b, inf*n, t) y_grouped = gconv(x_ready) # "fix" y y = y_grouped.view(n, n, outf, t).permute(0, 2, 1, 3) # now y is b-outf-n-t
https://stackoverflow.com/questions/58956579/
Expected dimension sizes for pytorch models
I'm struggling with understanding what sort of dimensions my pytorch model needs as input. My model setup is: import torch from torch import nn, tensor class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(RNN, self).__init__() self.rnn_b = nn.RNN(input_size=input_size, hidden_size=hidden_size, num_layers=1, bias=False) self.hidden_size = hidden_size self.linearout = nn.Linear(hidden_size, output_size) def forward(self, input, hidden): out, hidden = self.rnn_b(input, hidden) output = self.linearout(out) return output, hidden def initHidden(self): return torch.zeros(1, self.hidden_size) model = RNN(1, 2, 1) If I call model(tensor(25.), tensor([[0., 0.]])) then I get the error: IndexError: dimension specified as 1 but tensor has no dimensions If I call model(tensor([25.]), tensor([[0., 0.]])) then I get the error IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1) Can someone please explain what's going on here? What is the correct way to format the data for the input to my model?
You need to encapsulate more. This is because pytorch automatically allows batches: model(tensor([[[25.]]]), tensor([[[0., 0.]]])) Output: (tensor([[[-0.7704]]], grad_fn=<AddBackward0>), tensor([[[1., 1.]]], grad_fn=<StackBackward>)) You can use multiple input, as a batch: model(tensor([[[25.]], [[25.]]]), tensor([[[0., 0.]]])) Output: (tensor([[[0.0341]], [[0.0341]]], grad_fn=<AddBackward0>), tensor([[[ 0.9999, -1.0000]]], grad_fn=<StackBackward>))
https://stackoverflow.com/questions/58959707/
How to create upper triangular matrix in Pytorch?
Simple question, but is there a native way to create an upper triangular matrix from an existing matrix in Pytorch? I was thinking of using a mask, but even that requires creating the upper triangular matrix.
import torch upper_tri = torch.ones(rol, col).triu() Eg: >> mat = torch.ones(3, 3).triu() >> print(mat) tensor([[1., 1., 1.], [0., 1., 1.], [0., 0., 1.]])
https://stackoverflow.com/questions/58965717/
How to adapt the gpu batch size during training?
I found surprising that I could not find any resources online on how to dynamically adapt the GPU batch size without halting training. The idea is the following: 1) Have a training script that is (almost) agnostic to the GPU in use. The batch size will dynamically adjust without interference of the user or need for tunning. 2) Still being able to specifying the desired training batch size, even if too big to fit in the biggest known GPU. For instance, let's say I want to train a model using a batch size of 4096 images, each image 1024x1024. Let's also say that I have access to a server with different NVidea GPUs, but I don't know which one will be assigned to me in advance. (Or that everybody wants to use the biggest GPU and that I am left waiting a long time before it is my term). I want my training script to find the max batch size (let's say it is 32 images per GPU batch), and only update the optimizer when all 4096 images have been processed (one training batch = 128 GPU batches).
There are different ways of solving this problem. But if specifying the GPU that can do the job, or using multiple GPUs are not an option, then it is handy to dynamically adapt the GPU batch size. I prepared this repo with an illustrative training example in pytorch (it should work similarly in TensorFlow) In the code below, the try/except is used to try different GPU batch sizes without halting training. When the batch becomes too large, it is downsized and the adaptation is turned off. Please check the repo for the implementation details and possible bug fixes. It is also implemented a technique called Batch Spoofing, which performs a number of forward passes before doing the backpropagation. In PyTorch it only requires replacing the optimizer.zero_grad(). import torch import torchvision import torch.optim as optim import torch.nn as nn # Example of how to use it with Pytorch if __name__ == "__main__": # ############################################################# # 1) Initialize the dataset, model, optimizer and loss as usual. # Initialize a fake dataset trainset = torchvision.datasets.FakeData(size=1_000_000, image_size=(3, 224, 224), num_classes=1000) # initialize the model, loss and SGD-based optimizer resnet = torchvision.models.resnet152(pretrained=True, progress=True) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(resnet.parameters(), lr=0.01) continue_training = True # criteria to stop the training # ############################################################# # 2) Set parameters for the adaptive batch size adapt = True # while this is true, the algorithm will perform batch adaptation gpu_batch_size = 2 # initial gpu batch_size, it can be super small train_batch_size = 2048 # the train batch size of desire # Modified training loop to allow for adaptive batch size while continue_training: # ############################################################# # 3) Initialize dataloader and batch spoofing parameter # Dataloader has to be reinicialized for each new batch size. trainloader = torch.utils.data.DataLoader(trainset, batch_size=int(gpu_batch_size), shuffle=True) # Number of repetitions for batch spoofing repeat = max(1, int(train_batch_size / gpu_batch_size)) try: # This will make sure that training is not halted when the batch size is too large # ############################################################# # 4) Epoch loop with batch spoofing optimizer.zero_grad() # done before training because of batch spoofing. for i, (x, y) in enumerate(trainloader): y_pred = resnet(x) loss = criterion(y_pred, y) loss.backward() # batch spoofing if not i % repeat: optimizer.step() optimizer.zero_grad() # ############################################################# # 5) Adapt batch size while no RuntimeError is rased. # Increase batch size and get out of the loop if adapt: gpu_batch_size *= 2 break # Stopping criteria for training if i > 100: continue_training = False # ############################################################# # 6) After the largest batch size is found, the training progresses with the fixed batch size. # CUDA out of memory is a RuntimeError, the moment we will get to it when our batch size is too large. except RuntimeError as run_error: gpu_batch_size /= 2 # resize the batch size for the biggest that works in memory adapt = False # turn off the batch adaptation # Number of repetitions for batch spoofing repeat = max(1, int(train_batch_size / gpu_batch_size)) # Manual check if the RuntimeError was caused by the CUDA or something else. print(f"---\nRuntimeError: \n{run_error}\n---\n Is it a cuda error?") If you have code that can do similarly in Tensorflow, Caffe or others, please share!
https://stackoverflow.com/questions/58971123/
Why the resnet110 I train on CIFAR10 dataset only get 77% test acc
I trained the Resnet110 on CIFAR10 dataset, and I got 100% acc on training, but only 77.85% on test dataset. What is the problem probally be? Otherwise, I use Pytorch framwork. Thank U very much! ------------------------------------------------------------------------ Train Epoch: 200 [0/50000 (0%)] Loss: 0.000811, Accuracy: 100.00 Train Epoch: 200 [12800/50000 (26%)] Loss: 0.000335, Accuracy: 100.00 Train Epoch: 200 [25600/50000 (51%)] Loss: 0.000757, Accuracy: 100.00 Train Epoch: 200 [38400/50000 (77%)] Loss: 0.000334, Accuracy: 100.00 Epoch time:45.98s Accuracy of plane : 81 % Accuracy of car : 88 % Accuracy of bird : 65 % Accuracy of cat : 60 % Accuracy of deer : 73 % Accuracy of dog : 69 % Accuracy of frog : 81 % Accuracy of horse : 82 % Accuracy of ship : 86 % Accuracy of truck : 86 % Test set: Average loss: 1.3605, Accuracy: 77.58%
ResNet-101 is definitely too big for CIFAR10, go with smaller versions, ResNet-18 from torchvision should be fine. Furthermore, you could train those really fast using super convergence (e.g. setting learning rate to 5 or 3), see this article or other related. You could do so in 18 epochs or so with torch.optim.AdamW I think. Furthermore, such high learning rate plays a regularizing role as it will only converge to really flat minima regions. In order to not overfit, use really powerful image augmentation, rotations, flipping, CutOut, maybe MixUp. You could find them inside albumentations third party library.
https://stackoverflow.com/questions/58986583/
Adapting Pytorch "NLP from Scratch" for bidirectional GRU
I have taken the code from the tutorial and attempted to modify it to include bi-directionality and any arbitrary numbers of layers for GRU. Link to the tutorial which uses uni-directional, single layer GRU: https://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html The model works fine, but when i use set bidirectional=True, i get the a dimension mismatch error (shown below). Any thoughts why this is? Encoder: import torch.nn.init as init class EncoderRNN(nn.Module): def __init__(self, input_size, hidden_size, n_layers=1, bidirectional=False): super(EncoderRNN, self).__init__() self.hidden_size = hidden_size self.hidden_var = hidden_size//2 if bidirectional else hidden_size self.n_layers = n_layers self.bidirectional = bidirectional self.n_directions = 2 if bidirectional else 1 self.embedding = nn.Embedding(input_size, hidden_size) self.gru = nn.GRU(hidden_size, self.hidden_var, num_layers=self.n_layers, bidirectional=self.bidirectional) def forward(self, input, hidden): embedded = self.embedding(input).view(1, 1, -1) output = embedded output, hidden = self.gru(output, hidden) #output = (output[:, :, :self.hidden_size] + # output[:, :, self.hidden_size:]) return output, hidden def initHidden(self): return torch.zeros(self.n_layers*self.n_directions, 1, self.hidden_var, device=device) AttnDecoder: class AttnDecoderRNN(nn.Module): def __init__(self, hidden_size, output_size, n_layers=1, dropout_p=0.1, max_length=MAX_LENGTH): super(AttnDecoderRNN, self).__init__() self.hidden_size = hidden_size self.output_size = output_size self.dropout_p = dropout_p self.max_length = max_length self.n_layers = n_layers self.embedding = nn.Embedding(self.output_size, self.hidden_size) self.attn = nn.Linear(self.hidden_size * 2, self.max_length) self.attn_combine = nn.Linear(self.hidden_size * 2, self.hidden_size) self.dropout = nn.Dropout(self.dropout_p) self.gru = nn.GRU(self.hidden_size, self.hidden_size, num_layers = self.n_layers) self.out = nn.Linear(self.hidden_size, self.output_size) def forward(self, input, hidden, encoder_outputs): embedded = self.embedding(input).view(1, 1, -1) embedded = self.dropout(embedded) attn_weights = F.softmax( self.attn(torch.cat((embedded[0], hidden[0]), 1)), dim=1) attn_applied = torch.bmm(attn_weights.unsqueeze(0), encoder_outputs.unsqueeze(0)) output = torch.cat((embedded[0], attn_applied[0]), 1) output = self.attn_combine(output).unsqueeze(0) output = F.relu(output) output, hidden = self.gru(output, hidden) output = F.log_softmax(self.out(output[0]), dim=1) return output, hidden, attn_weights def initHidden(self): return torch.zeros(1*self.n_layers, 1, self.hidden_size, device=device) Everything else from the tutorial is kept exactly the same apart from this code block ( to account for the new parameters): n_layers=1 bidirectional = True hidden_size = 256 encoder1 = EncoderRNN(input_lang.n_words, hidden_size, n_layers=n_layers, bidirectional=bidirectional).to(device) attn_decoder1 = AttnDecoderRNN(hidden_size, output_lang.n_words, dropout_p=0.1, n_layers=n_layers).to(device) trainIters(encoder1, attn_decoder1, 75000, print_every=5000) Error: --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-133-37084c93a197> in <module> 5 attn_decoder1 = AttnDecoderRNN(hidden_size, output_lang.n_words, dropout_p=0.1, n_layers=n_layers).to(device) 6 ----> 7 trainIters(encoder1, attn_decoder1, 75000, print_every=5000) <ipython-input-131-774ce8edefa6> in trainIters(encoder, decoder, n_iters, print_every, plot_every, learning_rate) 16 17 loss = train(input_tensor, target_tensor, encoder, ---> 18 decoder, encoder_optimizer, decoder_optimizer, criterion) 19 print_loss_total += loss 20 plot_loss_total += loss <ipython-input-130-67be7e8c2a58> in train(input_tensor, target_tensor, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, max_length) 39 for di in range(target_length): 40 decoder_output, decoder_hidden, decoder_attention = decoder( ---> 41 decoder_input, decoder_hidden, encoder_outputs) 42 topv, topi = decoder_output.topk(1) 43 decoder_input = topi.squeeze().detach() # detach from history as input ~/miniconda3/envs/pytorch/lib/python3.7/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 545 result = self._slow_forward(*input, **kwargs) 546 else: --> 547 result = self.forward(*input, **kwargs) 548 for hook in self._forward_hooks.values(): 549 hook_result = hook(self, input, result) <ipython-input-129-6dd1d30fe28f> in forward(self, input, hidden, encoder_outputs) 24 25 attn_weights = F.softmax( ---> 26 self.attn(torch.cat((embedded[0], hidden[0]), 1)), dim=1) 27 attn_applied = torch.bmm(attn_weights.unsqueeze(0), 28 encoder_outputs.unsqueeze(0)) ~/miniconda3/envs/pytorch/lib/python3.7/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 545 result = self._slow_forward(*input, **kwargs) 546 else: --> 547 result = self.forward(*input, **kwargs) 548 for hook in self._forward_hooks.values(): 549 hook_result = hook(self, input, result) ~/miniconda3/envs/pytorch/lib/python3.7/site-packages/torch/nn/modules/linear.py in forward(self, input) 85 86 def forward(self, input): ---> 87 return F.linear(input, self.weight, self.bias) 88 89 def extra_repr(self): ~/miniconda3/envs/pytorch/lib/python3.7/site-packages/torch/nn/functional.py in linear(input, weight, bias) 1367 if input.dim() == 2 and bias is not None: 1368 # fused op is marginally faster -> 1369 ret = torch.addmm(bias, input, weight.t()) 1370 else: 1371 output = input.matmul(weight.t()) RuntimeError: size mismatch, m1: [1 x 384], m2: [512 x 10] at /tmp/pip-req-build-58y_cjjl/aten/src/TH/generic/THTensorMath.cpp:752 Any help would be appreciated! Update based on user3923920 comment (encoder-decoder also includes LSTM option & now works with bidirectionality) New working and adapted Encoder class EncoderRNN(nn.Module): def __init__(self, input_size, hidden_size, n_layers=1, bidirectional=False, method='GRU'): super(EncoderRNN, self).__init__() self.hidden_size = hidden_size self.hidden_var = hidden_size // 2 if bidirectional else hidden_size self.n_layers = n_layers self.bidirectional = bidirectional self.n_directions = 2 if bidirectional else 1 self.method = method self.embedding = nn.Embedding(input_size, hidden_size) if self.method == 'GRU': self.net = nn.GRU(hidden_size, self.hidden_var, num_layers=self.n_layers, bidirectional=self.bidirectional) elif self.method == 'LSTM': self.net = nn.LSTM(hidden_size, self.hidden_var, num_layers=self.n_layers, bidirectional=self.bidirectional) def forward(self, input, hidden): embedded = self.embedding(input).view(1, 1, -1) output = embedded output, hidden = self.net(output, hidden) # output = (output[:, :, :self.hidden_size] + # output[:, :, self.hidden_size:]) return output, hidden, embedded def initHidden(self): if self.method == 'GRU': return torch.zeros(self.n_layers * self.n_directions, 1, self.hidden_var, device=device) elif self.method == 'LSTM': h_state = torch.zeros(self.n_layers * self.n_directions, 1, self.hidden_var) c_state = torch.zeros(self.n_layers * self.n_directions, 1, self.hidden_var) hidden = (h_state, c_state) return hidden New working and adapted Decoder class AttnDecoderRNN(nn.Module): def __init__(self, hidden_size, output_size, n_layers=1, dropout_p=0.1, max_length=MAX_LENGTH, method='GRU', bidirectional=False): super(AttnDecoderRNN, self).__init__() self.hidden_size = hidden_size self.output_size = output_size self.dropout_p = dropout_p self.max_length = max_length self.n_layers = n_layers self.method = method self.bidirectional = bidirectional self.embedding = nn.Embedding(self.output_size, self.hidden_size) self.attn = nn.Linear(self.hidden_size * 2, self.max_length) self.attn_combine = nn.Linear(self.hidden_size * 2, self.hidden_size) self.dropout = nn.Dropout(self.dropout_p) if self.method == 'GRU': self.net = nn.GRU(self.hidden_size, self.hidden_size, num_layers=self.n_layers) elif self.method == 'LSTM': self.net = nn.LSTM(self.hidden_size, self.hidden_size, num_layers=self.n_layers) self.out = nn.Linear(self.hidden_size, self.output_size) def forward(self, input, hidden, encoder_outputs): # Embed embedded = self.embedding(input).view(1, 1, -1) embedded = self.dropout(embedded) self.hidden = hidden # Concatenate all of the layers hidden_h_rows = () hidden_c_rows = () if self.method == 'LSTM': # hidden is a tuple of h_state and c_state decoder_h, decoder_c = hidden print(decoder_h.shape) hidden_shape = decoder_h.shape[0] # h_state for x in range(0, hidden_shape): hidden_h_rows += (decoder_h[x],) # c_state for x in range(0, hidden_shape): hidden_c_rows += (decoder_c[x],) elif self.method == "GRU": # hidden is not a tuple (GRU) decoder_h = hidden hidden_shape = decoder_h.shape[0] # h_state for x in range(0, hidden_shape): hidden_h_rows += (decoder_h[x],) if self.bidirectional: decoder_h_cat = torch.cat(hidden_h_rows, 1) # Make sure the h_dim size is compatible with num_layers with concatenation. decoder_h = decoder_h_cat.view((self.n_layers, 1, self.hidden_size)) # hidden_size=256 if self.method == "LSTM": decoder_c_cat = torch.cat(hidden_c_rows, 1) decoder_c = decoder_c_cat.view((self.n_layers, 1, self.hidden_size)) # hidden_size=256 hidden_lstm = (decoder_h, decoder_c) elif self.method == "GRU": hidden_gru = decoder_h # Attention Block attn_weights = F.softmax( self.attn(torch.cat((embedded[0], hidden_lstm[0][0] if self.method == "LSTM" else \ hidden_gru[0]), 1)), dim=1) attn_applied = torch.bmm(attn_weights.unsqueeze(0), encoder_outputs.unsqueeze(0)) output = torch.cat((embedded[0], attn_applied[0]), 1) output = self.attn_combine(output).unsqueeze(0) output = F.relu(output) output, hidden = self.net(output, hidden_lstm if self.method == "LSTM" else hidden_gru) # I am not sure about this! output = F.log_softmax(self.out(output[0]), dim=1) return output, hidden, attn_weights def initHidden(self): if self.method == 'GRU': return torch.zeros(self.n_layers * 1, 1, self.hidden_var, device=device) elif self.method == 'LSTM': h_state = torch.zeros(self.n_layers * 1, 1, self.hidden_var) c_state = torch.zeros(self.n_layers * 1, 1, self.hidden_var) hidden = (h_state, c_state) return hidden
So I'm not sure if this is 100% correct as I'm just learning how to program RNNs, but i changed my code in a couple of extra areas. For one you'll notice that the error says m1: [1x384] so the result of torch.cat((embedded[0], hidden[0]), 1)) when putting this through the attn weight layer is not a dimension ending with 512, the expected input size. This is because hidden is a tensor of shape [2, 1, 256] instead of some shape [1, 1, 512] or something. Since your dimensions don't exactly match mine I'm not exactly sure what is different, so in train(...) where it just sets decoder_hidden = encoder_hidden I do decoder_hidden = torch.cat((encoder_hidden[0], encoder_hidden[1]) , 1) decoder_hidden = decoder_hidden.view((1, 1, 512)) Hopefully that helps in some way
https://stackoverflow.com/questions/58996451/
How to extract images, labels from csv file and create a trainset using torch?
I downloaded a dataset for facial key point detection the image and the labels were in a CSV file I extracted it using pandas but I don't know how to convert it into a tensor and load it into a data loader for training. dataframe = pd.read_csv("training_facial_keypoints.csv") dataframe['Image'] = dataframe['Image'].apply(lambda i: np.fromstring(i, sep=' ')) dataframe= dataframe.dropna() images_array = np.vstack(dataframe['Image'].values)/255.0 images_array = images_array.astype(np.float32) images_array = images_array.reshape(-1, 96, 96, 1) print(images_array.shape) labels_array = dataframe[dataframe.columns[:-1]].values labels_array = (labels_array-48)/48 labels_array = labels_array.astype(np.float32) I have the images and labels in two arrays. How do I create a training set from this and use transforms. Then load it using a dataloader.
Create a subclass of torch.utils.data.Dataset, fill it with your data. You can pass desired torchvision.transforms to it and apply them to your data in __getitem__(self, index). Than you can pass it to torch.utils.data.DataLoader which allows multi-threaded loading of data. And PyTorch has an overwhelming documentation you should first refer to.
https://stackoverflow.com/questions/58997461/
error installing pytorch using pip on windows 10
I am trying to install pytorch with pip using pip install torch or pip3 install torch===1.3.1 torchvision===0.4.2 -f https://download.pytorch.org/whl/torch_stable.html with python 3.7.4 and with python 3.8 (latest stable release) both on 32 and 64 bit. and getting Collecting torch Using cached https://files.pythonhosted.org/packages/f8/02/880b468bd382dc79896eaecbeb8ce95e9c4b99a24902874a2cef0b562cea/torch-0.1.2.post2.tar.gz Collecting pyyaml (from torch) Downloading https://files.pythonhosted.org/packages/bc/3f/4f733cd0b1b675f34beb290d465a65e0f06b492c00b111d1b75125062de1/PyYAML-5.1.2-cp37-cp37m-win_amd64.whl (215kB) 100% |████████████████████████████████| 225kB 1.2MB/s Installing collected packages: pyyaml, torch Running setup.py install for torch ... error Complete output from command C:\Noam\Code\threadart\stav-rl\venv\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\noams\\AppData\\Local\\Temp\\pip-install-djc6s2t8\\torch\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read( ).replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\noams\AppData\Local\Temp\pip-record-zohv2zo7\install-record.txt --single-version-externally-managed --compile --install-headers C:\Noam\Code\threadart\stav-rl\venv\inclu de\site\python3.7\torch: running install running build_deps Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\noams\AppData\Local\Temp\pip-install-djc6s2t8\torch\setup.py", line 265, in <module> description="Tensors and Dynamic neural networks in Python with strong GPU acceleration", File "C:\Noam\Code\threadart\stav-rl\venv\lib\site-packages\setuptools-40.8.0-py3.7.egg\setuptools\__init__.py", line 145, in setup File "C:\Python37_x64\lib\distutils\core.py", line 148, in setup dist.run_commands() File "C:\Python37_x64\lib\distutils\dist.py", line 966, in run_commands self.run_command(cmd) File "C:\Python37_x64\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "C:\Users\noams\AppData\Local\Temp\pip-install-djc6s2t8\torch\setup.py", line 99, in run self.run_command('build_deps') File "C:\Python37_x64\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "C:\Python37_x64\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "C:\Users\noams\AppData\Local\Temp\pip-install-djc6s2t8\torch\setup.py", line 51, in run from tools.nnwrap import generate_wrappers as generate_nn_wrappers ModuleNotFoundError: No module named 'tools.nnwrap' ---------------------------------------- Command "C:\Noam\Code\threadart\stav-rl\venv\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\noams\\AppData\\Local\\Temp\\pip-install-djc6s2t8\\torch\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n'); f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\noams\AppData\Local\Temp\pip-record-zohv2zo7\install-record.txt --single-version-externally-managed --compile --install-headers C:\Noam\Code\threadart\stav-rl\venv\include\site\python3.7\torch" failed with error code 1 in C:\Users\noams\AppData\Local\Temp\pip-install-djc6s2t8\torch\ clearly, I am doing something wrong. Please help!
I had the same problem. Now the problem is fixed. (2020-05-31) Visited the site pytorch.org and find "QUICK START LOCALLY" on homepage of pytorch.org. ( it' can find by scroll down little ) Checking the environment form of your system (ex: Windows, pip, python, ,,) then, you can see the install command. "pip install torch===.... " Copy the install command and Execute the command at your system. Good Luck !!
https://stackoverflow.com/questions/59013496/
Turn CNN model into class
I am trying to build a CNN for multilabel classification in Pytorch (each image can have more than one label). So far I have built the model as follows: model.fc = nn.Sequential(nn.Linear(2048, 512), nn.ReLU(), nn.Dropout(0.2), nn.Linear(512, 10), nn.LogSigmoid()) # nn.LogSoftmax(dim=1)) criterion = nn.NLLLoss() # criterion = nn.BCELoss() optimizer = optim.Adam(model.fc.parameters(), lr=0.003) But I would like to build it using a class like the following example: class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 10, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(10, 20, 5) self.fc1 = nn.Linear(20 * 22 * 39, 100) self.fc2 = nn.Linear(100, 50) self.fc3 = nn.Linear(50, 10) self.fc4 = nn.Linear(10, 3) def forward(self, x): x = x.view(-1, 3, 100, 170) x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 20 * 22 * 39) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = F.relu(self.fc3(x)) return self.fc4(x) What would be the best way of accomplishing this given that I am dealing with a multilabel classification problem? Any insights I would appreciate it.
You should use torch.nn.BCEWithLogitsLoss for multilabel classification (and numerical stability), no LogSigmoid or NLLLoss as the output. You have to output N elements for each element in batch, where 1 on position N in vector would mean an existence of class N on image. Your network is fine, provided you only got 3 labels to predict (either 0 or 1). You may think about it's design or use something pretrained, other than that it should at least run.
https://stackoverflow.com/questions/59014699/
Can I specify kernel-weight specific learning rates in PyTorch?
I would like to set specific learning rates for each parameter on their lowest level. I.e. each value in a kernels weight and biases should have their own learning rate. I can specify filter-wise learning rates like that: optim = torch.optim.SGD([{'params': model.conv1.weight, 'lr': 0.1},], lr=0.01) But when I want to get a level lower, like that: optim = torch.optim.SGD([{'params': model.conv1.weight[0, 0, 0, 0], 'lr': 0.1},], lr=0.01) I receive an error: ValueError: can't optimize a non-leaf Tensor I also tried specifying a learning rate that has the same shape as the filter such as 'lr': torch.ones_like(model.conv1.weight), but that also didn't work out. Is there even a way to do this using torch.optim?
I might have found a solution. As one can only input the whole weights and biases of a Conv Layer, we need to insert a learning rate having the same shape as the weight/bias tensor. Here is an example using torch.optim.Adam: torch.optim.CustomAdam([{'params': param, 'lr': torch.ones_like(param, requires_grad=False) * lr} for name, param in model.named_parameters()]) Then we have to change a line in the optimizer itself. For that I created a custom optimizer: class CustomAdam(torch.optim.Adam): def step(self, closure=None): ... # change the last line: p.data.addcdiv_(-step_size, exp_avg, denom) to p.data.add_((-step_size * (exp_avg / denom)))
https://stackoverflow.com/questions/59018085/
I define a loss function but backward present error to me could someone tell me how to fix it
class loss(Function): @staticmethod def forward(ctx,x,INPUT): batch_size = x.shape[0] X = x.detach().numpy() input = INPUT.detach().numpy() Loss = 0 for i in range(batch_size): t_R_r = input[i,0:4] R_r = t_R_r[np.newaxis,:] t_R_i = input[i,4:8] R_i = t_R_i[np.newaxis,:] t_H_r = input[i,8:12] H_r = t_H_r[np.newaxis,:] t_H_i = input[i,12:16] H_i = t_H_i[np.newaxis,:] t_T_r = input[i, 16:32] T_r = t_T_r.reshape(4,4) t_T_i = input[i, 32:48] T_i = t_T_i.reshape(4,4) R = np.concatenate((R_r, R_i), axis=1) H = np.concatenate((H_r, H_i), axis=1) temp_t1 = np.concatenate((T_r,T_i),axis=1) temp_t2 = np.concatenate((-T_i,T_r),axis=1) T = np.concatenate((temp_t1,temp_t2),axis=0) phi_r = np.zeros((4,4)) row, col = np.diag_indices(4) phi_r[row,col] = X[i,0:4] phi_i = np.zeros((4, 4)) row, col = np.diag_indices(4) phi_i[row, col] = 1 - np.power(X[i, 0:4],2) temp_phi1 = np.concatenate((phi_r,phi_i),axis=1) temp_phi2 = np.concatenate((-phi_i, phi_r), axis=1) phi = np.concatenate((temp_phi1,temp_phi2),axis=0) temp1 = np.matmul(R,phi) temp2 = np.matmul(temp1,T) # error H_hat = H + temp2 t_Q_r = np.zeros((4,4)) t_Q_r[np.triu_indices(4,1)] = X[i,4:10] Q_r = t_Q_r + t_Q_r.T row,col = np.diag_indices(4) Q_r[row,col] = X[i,10:14] Q_i = np.zeros((4,4)) Q_i[np.triu_indices(4,1)] = X[i,14:20] Q_i = Q_i - Q_i.T temp_Q1 = np.concatenate((Q_r,Q_i),axis=1) temp_Q2 = np.concatenate((-Q_i,Q_r),axis=1) Q = np.concatenate((temp_Q1,temp_Q2),axis=0) t_H_hat_r = H_hat[0,0:4] H_hat_r = t_H_hat_r[np.newaxis,:] t_H_hat_i= H_hat[0,4:8] H_hat_i = t_H_hat_i[np.newaxis,:] temp_H1 = np.concatenate((-H_hat_i.T,H_hat_r.T),axis=0) H_hat_H = np.concatenate((H_hat.T,temp_H1),axis=1) temp_result1 = np.matmul(H_hat,Q) temp_result2 = np.matmul(temp_result1,H_hat_H) Loss += np.log10(1+temp_result2[0][0]) Loss = t.from_numpy(np.array(Loss / batch_size)) return Loss @staticmethod def backward(ctx,grad_output): print('gradient') return grad_output def criterion(output,input): return loss.apply(output,input) This is my loss function. But it present the error: Traceback (most recent call last): File "/Users/mrfang/channel_capacity/training.py", line 24, in loss.backward() File "/Users/mrfang/anaconda3/lib/python3.6/site-packages/torch/tensor.py", line 150, in backward torch.autograd.backward(self, gradient, retain_graph, create_graph) File "/Users/mrfang/anaconda3/lib/python3.6/site-packages/torch/autograd/init.py", line 99, in backward allow_unreachable=True) # allow_unreachable flag RuntimeError: function lossBackward returned an incorrect number of gradients (expected 2, got 1) How could I fix it. Thanks very much
Your forward(ctx,x,INPUT) takes two inputs, x and INPUT, thus backward should output two gradients as well, grad_x and grad_INPUT. In addition, in your snippet, you're not really computing a custom gradient, so you could compute that with Pytorch's autograd, without having to define a special Function. If this is working code and you're going to define the custom loss, here's a quick boilerplate of what backward should comprise: @staticmethod def forward(ctx, x, INPUT): # this is required so they're available during the backwards call ctx.save_for_backward(x, INPUT) # custom forward @staticmethod def backward(ctx, grad_output): x, INPUT = ctx.saved_tensors grad_x = grad_INPUT = None # compute grad here return grad_x, grad_INPUT You don't need to return gradients for inputs that don't require it, thus you can return None for them. More info here and here.
https://stackoverflow.com/questions/59019399/
pytorch debugging timeout with PyCharm
I have a frustrating problem, where I cannot debug my pytorch code while in Pycharm. While trying to inspect (breakpoint, then print e.g.) the code below, I receive a "Loading time out" import torch tensors = [] num_tensors = 16 shape = (1, 3, 512, 512) for i in range(num_tensors): tensors.append(torch.zeros(shape)) I saw this[1,2] posts, set variable loading policy to syncronyous, disabled Qt debugger options, and all the options specified, But I believe there is something basic I'm missing. pycharm 2019.2.5, happens both in python2 and python3.
Are you using DataLoader? If yes, you can try reducing the num_workers to 0.
https://stackoverflow.com/questions/59030675/
.grad() returns None in pytorch
I am trying to write a simple script for parameter estimation (where parameters are weights here). I am facing problem when .grad() returns None. I have gone through this and this link also and understood the concept both theoretically and practically. For me following script should work but unfortunately, it is not working. My 1st attempt: Following script is my first attempt alpha_xy = torch.tensor(3.7, device=device, dtype=torch.float, requires_grad=True) beta_y = torch.tensor(1.5, device=device, dtype=torch.float, requires_grad=True) alpha0 = torch.tensor(1.1, device=device, dtype=torch.float, requires_grad=True) alpha_y = torch.tensor(0.9, device=device, dtype=torch.float, requires_grad=True) alpha1 = torch.tensor(0.1, device=device, dtype=torch.float, requires_grad=True) alpha2 = torch.tensor(0.9, device=device, dtype=torch.float, requires_grad=True) alpha3 = torch.tensor(0.001, device=device, dtype=torch.float, requires_grad=True) learning_rate = 1e-4 total_loss = [] for epoch in tqdm(range(500)): loss_1 = 0 for j in range(x_train.size(0)): input = x_train[j:j+1] target = y_train[j:j+1] input = input.to(device,non_blocking=True) target = target.to(device,non_blocking=True) x_dt = gamma*input[0][0] + \ alpha_xy*input[0][0]*input[0][2] + \ alpha1*input[0][0] y0_dt = beta_y*input[0][0] + \ alpha2*input[0][1] y_dt = alpha0*input[0][1] + \ alpha_y*input[0][2] + \ alpha3*input[0][0]*input[0][2] pred = torch.tensor([[x_dt], [y0_dt], [y_dt]],device=device ) loss = (pred - target).pow(2).sum() loss_1 += loss loss.backward() print(pred.grad, x_dt.grad, gamma.grad) Above code throws an error message element 0 of tensors does not require grad and does not have a grad_fn at line loss.backward() My Attempt 2: Improvement in 1st attempt is as follows: gamma = torch.tensor(2.0, device=device, dtype=torch.float, requires_grad=True) alpha_xy = torch.tensor(3.7, device=device, dtype=torch.float, requires_grad=True) beta_y = torch.tensor(1.5, device=device, dtype=torch.float, requires_grad=True) alpha0 = torch.tensor(1.1, device=device, dtype=torch.float, requires_grad=True) alpha_y = torch.tensor(0.9, device=device, dtype=torch.float, requires_grad=True) alpha1 = torch.tensor(0.1, device=device, dtype=torch.float, requires_grad=True) alpha2 = torch.tensor(0.9, device=device, dtype=torch.float, requires_grad=True) alpha3 = torch.tensor(0.001, device=device, dtype=torch.float, requires_grad=True) learning_rate = 1e-4 total_loss = [] for epoch in tqdm(range(500)): loss_1 = 0 for j in range(x_train.size(0)): input = x_train[j:j+1] target = y_train[j:j+1] input = input.to(device,non_blocking=True) target = target.to(device,non_blocking=True) x_dt = gamma*input[0][0] + \ alpha_xy*input[0][0]*input[0][2] + \ alpha1*input[0][0] y0_dt = beta_y*input[0][0] + \ alpha2*input[0][1] y_dt = alpha0*input[0][1] + \ alpha_y*input[0][2] + \ alpha3*input[0][0]*input[0][2] pred = torch.tensor([[x_dt], [y0_dt], [y_dt]],device=device, dtype=torch.float, requires_grad=True) loss = (pred - target).pow(2).sum() loss_1 += loss loss.backward() print(pred.grad, x_dt.grad, gamma.grad) # with torch.no_grad(): # gamma -= leraning_rate * gamma.grad Now the script is working but except pred.gred other two return None. I want to update all the parameters after computing loss.backward() and update them but it is not happening due to None. Can anyone suggest me how to improve this script? Thanks.
You're breaking the computation graph by declaring a new tensor for pred. Instead you can use torch.stack. Also, x_dt and pred are non-leaf tensors so the gradients aren't retained by default. You can override this behavior by using .retain_grad(). gamma = torch.tensor(2.0, device=device, dtype=torch.float, requires_grad=True) alpha_xy = torch.tensor(3.7, device=device, dtype=torch.float, requires_grad=True) beta_y = torch.tensor(1.5, device=device, dtype=torch.float, requires_grad=True) alpha0 = torch.tensor(1.1, device=device, dtype=torch.float, requires_grad=True) alpha_y = torch.tensor(0.9, device=device, dtype=torch.float, requires_grad=True) alpha1 = torch.tensor(0.1, device=device, dtype=torch.float, requires_grad=True) alpha2 = torch.tensor(0.9, device=device, dtype=torch.float, requires_grad=True) alpha3 = torch.tensor(0.001, device=device, dtype=torch.float, requires_grad=True) learning_rate = 1e-4 total_loss = [] for epoch in tqdm(range(500)): loss_1 = 0 for j in range(x_train.size(0)): input = x_train[j:j+1] target = y_train[j:j+1] input = input.to(device,non_blocking=True) target = target.to(device,non_blocking=True) x_dt = gamma*input[0][0] + \ alpha_xy*input[0][0]*input[0][2] + \ alpha1*input[0][0] # retain the gradient for non-leaf tensors x_dt.retain_grad() y0_dt = beta_y*input[0][0] + \ alpha2*input[0][1] y_dt = alpha0*input[0][1] + \ alpha_y*input[0][2] + \ alpha3*input[0][0]*input[0][2] # use stack instead of declaring a new tensor pred = torch.stack([x_dt, y0_dt, y_dt], dim=0).unsqueeze(1) # pred is also a non-leaf tensor so we need to tell pytorch to retain its grad pred.retain_grad() loss = (pred - target).pow(2).sum() loss_1 += loss loss.backward() print(pred.grad, x_dt.grad, gamma.grad) with torch.no_grad(): gamma -= learning_rate * gamma.grad Closed form solution Assuming you want to optimize for the parameters defined at the top of the function gamma, alpha_xy, beta_y, etc... Then what you have here is an example of ordinary least squares. See least squares for a slightly friendlier introduction to the topic. Take a look at the components of pred and you'll notice that x_dt, y0_dt, and y_dt are actually independent of each other with respect to the parameters (in this case it's obvious because they each use totally different parameters). This makes the problem much easier because it means we can actually optimize the terms (x_dt - target[0])**2, (y0_dt - target[1])**2 and (y_dt - target[2])**2 separately! Without getting into the details the solution (without back-propagation or gradient descent) ends up being # supposing x_train is [N,3] and y_train is [N,3] x1 = torch.stack((x_train[:, 0], x_train[:, 0] * x_train[:, 2]), dim=0) y1 = y_train[:, 0].unsqueeze(1) # avoid inverses using solve to get p1 = inv(x1 . x1^T) . x1 . y1 p1, _ = torch.solve(x1 @ y1, x1 @ x1.transpose(1, 0)) # gamma and alpha1 are redundant. As long as gamma + alpha1 = p1[0] we get the same optimal value for loss gamma = p1[0] / 2 alpha_xy = p1[1] alpha1 = p1[0] / 2 x2 = torch.stack((x_train[:, 0], x_train[:, 1]), dim=0) y2 = y_train[:, 1].unsqueeze(1) p2, _ = torch.solve(x2 @ y2, x2 @ x2.transpose(1, 0)) beta_y = p2[0] alpha2 = p2[1] x3 = torch.stack((x_train[:, 1], x_train[:, 2], x_train[:, 0] * x_train[:, 2]), dim=0) y3 = y_train[:, 2].unsqueeze(1) p3, _ = torch.solve(x3 @ y3, x3 @ x3.transpose(1, 0)) alpha0 = p3[0] alpha_y = p3[1] alpha3 = p3[2] loss_1 = torch.sum((x1.transpose(1, 0) @ p1 - y1)**2 + (x2.transpose(1, 0) @ p2 - y2)**2 + (x3.transpose(1, 0) @ p3 - y3)**2) mse = loss_1 / x_train.size(0) To test this code is working I generated some fake data which I knew the underlying model coefficients (there's some noise added so the final result won't exactly match the expected). def gen_fake_data(samples=50000): x_train = torch.randn(samples, 3) # define fake data with known minimal solutions x1 = torch.stack((x_train[:, 0], x_train[:, 0] * x_train[:, 2]), dim=0) x2 = torch.stack((x_train[:, 0], x_train[:, 1]), dim=0) x3 = torch.stack((x_train[:, 1], x_train[:, 2], x_train[:, 0] * x_train[:, 2]), dim=0) y1 = x1.transpose(1, 0) @ torch.tensor([[1.0], [2.0]]) # gamma + alpha1 = 1.0 y2 = x2.transpose(1, 0) @ torch.tensor([[3.0], [4.0]]) y3 = x3.transpose(1, 0) @ torch.tensor([[5.0], [6.0], [7.0]]) y_train = torch.cat((y1, y2, y3), dim=1) + 0.1 * torch.randn(samples, 3) return x_train, y_train x_train, y_train = gen_fake_data() # optimization code from above ... print('loss_1:', loss_1.item()) print('MSE:', mse.item()) print('Expected 0.5, 2.0, 0.5, 3.0, 4.0, 5.0, 6.0, 7.0') print('Actual', gamma.item(), alpha_xy.item(), alpha1.item(), beta_y.item(), alpha2.item(), alpha0.item(), alpha_y.item(), alpha3.item()) which results in loss_1: 1491.731201171875 MSE: 0.029834624379873276 Expected 0.5, 2.0, 0.5, 3.0, 4.0, 5.0, 6.0, 7.0 Actual 0.50002 2.0011 0.50002 3.0009 3.9997 5.0000 6.0002 6.9994
https://stackoverflow.com/questions/59031703/
any similar function like df.mask for tensor in pytorch?
I want to replace all 0s in a 2-D tensor with -5. With dataframe, i can easily do this: df = df.mask(df=0, -5) but this does not work for tensors. I have tried: y = torch.where(y = 0, -5, y)
There are two general ways. One, given above by prhmma is to use in-place mutation like y[y == 0] = -5. It is nice and efficient, but will break autograd operation. So if you want gradient to flow through y, you should not do that. The other is to use torch.where, as you have attempted. The proper incantation is y = torch.where(y == 0, torch.tensor(-5), y) or, if you want to be device- and dtype-agnostic five = torch.tensor(-5, dtype=y.dtype, device=y.device) y = torch.where(y == 0, five, y) the fact that where does not accept scalars is an annoying papercut, but that's how it is ATM. Note that while the choice itself is discrete and obviously not differentiable, this operation will let gradients flow through both operands.
https://stackoverflow.com/questions/59037704/
Pytorch equivalent of Google Seedbank
Does Pytorch have an equivalent of Google Seedbank ? Everything in Seedbank is (unsurprisingly) Tensorflow based, and I want to learn Pytorch.
You can check out Pytorch Hub. Compared to Seedback, it has more emphasis on re-useable models (and less on tutorials), although many entries do have Colab notebooks for reference.
https://stackoverflow.com/questions/59042241/
Conda package install [Errno 13] Permission denied while installing conda-forge::protobuf-3.8.0
I have a conda environment with Python 3.6 and something went wrong with my Pytorch installation so I tried to install it again. Towards the end of the installation I get this error: ERROR conda.core.link:_execute(700): An error occurred while installing package 'conda-forge::protobuf-3.8.0-py36h6de7cb9_1'. Rolling back transaction: done [Errno 13] Permission denied: '/Users/myusername/anaconda3/envs/torch/lib/python3.6/site-packages/google/protobuf/__init__.py' () Also, it says "The environment is inconsistent" which is probably a clue something was already wrong. Full details: $ conda install pytorch torchvision -c pytorch Collecting package metadata (current_repodata.json): done Solving environment: - The environment is inconsistent, please check the package plan carefully The following packages are causing the inconsistency: - conda-forge/osx-64::tensorboard==1.14.0=py36_0 - conda-forge/noarch::tensorboardx==1.9=py_0 done ## Package Plan ## environment location: /Users/myusername/anaconda3/envs/torch added / updated specs: - pytorch - torchvision The following packages will be downloaded: package | build ---------------------------|----------------- intel-openmp-2019.4 | 233 887 KB mkl-2019.4 | 233 101.9 MB pytorch-1.3.1 | py3.6_0 32.7 MB pytorch torchvision-0.4.2 | py36_cpu 5.9 MB pytorch ------------------------------------------------------------ Total: 141.4 MB The following NEW packages will be INSTALLED: intel-openmp pkgs/main/osx-64::intel-openmp-2019.4-233 libprotobuf conda-forge/osx-64::libprotobuf-3.8.0-hfbae3c0_0 mkl pkgs/main/osx-64::mkl-2019.4-233 protobuf conda-forge/osx-64::protobuf-3.8.0-py36h6de7cb9_1 pytorch pytorch/osx-64::pytorch-1.3.1-py3.6_0 torchvision pytorch/osx-64::torchvision-0.4.2-py36_cpu The following packages will be UPDATED: openssl 1.1.1c-h01d97ff_0 --> 1.1.1d-h0b31af3_0 Proceed ([y]/n)? y Downloading and Extracting Packages pytorch-1.3.1 | 32.7 MB | ##################################### | 100% torchvision-0.4.2 | 5.9 MB | ##################################### | 100% mkl-2019.4 | 101.9 MB | ##################################### | 100% intel-openmp-2019.4 | 887 KB | ##################################### | 100% Preparing transaction: done Verifying transaction: done Executing transaction: done ERROR conda.core.link:_execute(700): An error occurred while installing package 'conda-forge::protobuf-3.8.0-py36h6de7cb9_1'. Rolling back transaction: done [Errno 13] Permission denied: '/Users/myusername/anaconda3/envs/torch/lib/python3.6/site-packages/google/protobuf/__init__.py' () UPDATE: I tried uninstalling tensorboard and tensorboardx but the same error occurs preventing the uninstall. ALSO: Tried pip uninstall protobuf but that caused a similar error: Uninstalling protobuf-3.10.0: Would remove: ... ERROR: Exception: Traceback (most recent call last): File "/Users/myusername/anaconda3/envs/torch/lib/python3.6/shutil.py", line 544, in move os.rename(src, real_dst) PermissionError: [Errno 13] Permission denied: '/Users/myusername/anaconda3/envs/torch/lib/python3.6/site-packages/google/protobuf/' -> '/Users/myusername/anaconda3/envs/torch/lib/python3.6/site-packages/google/~-otobuf' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/myusername/anaconda3/envs/torch/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 153, in _main status = self.run(options, args) File "/Users/myusername/anaconda3/envs/torch/lib/python3.6/site-packages/pip/_internal/commands/uninstall.py", line 79, in run auto_confirm=options.yes, verbose=self.verbosity > 0, File "/Users/myusername/anaconda3/envs/torch/lib/python3.6/site-packages/pip/_internal/req/req_install.py", line 755, in uninstall uninstalled_pathset.remove(auto_confirm, verbose) File "/Users/myusername/anaconda3/envs/torch/lib/python3.6/site-packages/pip/_internal/req/req_uninstall.py", line 394, in remove moved.stash(path) File "/Users/myusername/anaconda3/envs/torch/lib/python3.6/site-packages/pip/_internal/req/req_uninstall.py", line 283, in stash renames(path, new_path) File "/Users/myusername/anaconda3/envs/torch/lib/python3.6/site-packages/pip/_internal/utils/misc.py", line 338, in renames shutil.move(old, new) File "/Users/myusername/anaconda3/envs/torch/lib/python3.6/shutil.py", line 556, in move rmtree(src) File "/Users/myusername/anaconda3/envs/torch/lib/python3.6/shutil.py", line 494, in rmtree return _rmtree_unsafe(path, onerror) File "/Users/myusername/anaconda3/envs/torch/lib/python3.6/shutil.py", line 389, in _rmtree_unsafe onerror(os.unlink, fullname, sys.exc_info()) File "/Users/myusername/anaconda3/envs/torch/lib/python3.6/shutil.py", line 387, in _rmtree_unsafe os.unlink(fullname) PermissionError: [Errno 13] Permission denied: '/Users/myusername/anaconda3/envs/torch/lib/python3.6/site-packages/google/protobuf/descriptor.py' I have no idea how to fix this other than deleting the whole environment and start again.
I faced a similar error like this when I was trying to update/uninstall a python package(matplotlib) from my environment. The reason turned out to be that I had another python application which was running and had a matplotlib plot window open, so therefore since a process was accessing the package, it couldn't be deleted. When i closed all the python programs, I was able to upgrade the package without the permission error. So moral of the story, if you trying to update/uninstall a package, make sure all your python scripts are not running.
https://stackoverflow.com/questions/59063954/
somehow my accuracy is very low on cifar10?
with torch.no_grad(): for data in test_loader: images,labels = data images, labels = images.to(device), labels.to(device) outputs, features = net(images) _ , predicted = torch.max(outputs,1) total += labels.size(0) correct += (predicted==labels).sum().item() print('Accuracy of the network on the 10000 test images: %d %%' % ( 100 * (correct / total))) How do I obtain GPU results with a label? I got almost 10% accuracy but my original training is accuracy is 70%.
The trick training that exact dataset (cifar10) and getting better accuracy is to use data augmentation. Originally cifar10 has 50.000 images for training and 10.000 for validation. If you don't augment images while training you will overfit. Training accuracy will be much bigger than validation accuracy. So your goal is to reduce overfitting. Best Way to Reduce overfitting is to train on more data (augment your data). Here is one repo that may help you dealing with augmentation in PyTorch. And in PyTorch check these to augment your data such as RandomRotation, Resize, RandomVerticalFlip, RandomSizedCrop, ... One example of a native PyTorch transform may look like: t = transforms.Compose([transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.RandomErasing(), transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))] ) dl_train = DataLoader( torchvision.datasets.CIFAR10('/data/cifar10', download=True, train=True, transform=t), batch_size=bs, shuffle=True) dl_valid = DataLoader( torchvision.datasets.CIFAR10('/data/cifar10', download=True, train=False, transform=t), batch_size=bs, shuffle=True)
https://stackoverflow.com/questions/59067277/
Why multiprocessing suddenly stops after a certain number of tasks?
I'm trying to write some code to parallelize a bunch of tasks. Basically, the script is organized as the following. import multiprocessing as mp def obj_train(x): return x.train() class ServerModel(nn.Module): self.S = nn.Parameter(torch.rand(x, y), requires_grad=True) class ClientModel(nn.Module): self.S = nn.Parameter(torch.rand(x, y), requires_grad=True) self.U = nn.Parameter(torch.rand(x, y), requires_grad=True) class Server: def __init__(self, model): self.model = model ... def train(clients): for i, c in enumerate(clients): sd = c.model.state_dict() sd['S'] = self.model.S c.model.load_state_dict(sd) self.c_list = random.sample(clients, 200) pool = mp.Pool(mp.cpu_count()-1) results = pool.map(obj_train, self.c_list) pool.close() pool.join() print("Training complete") class Client: def __init__(self, client_id, model, train_set): self.id = client_id self.model = model self.train_set = train_set def train(self): self.optimizer = optim.SGD([self.model.S, self.model.U]) for i in self.train_set: loss = self.model(i) loss.backward() self.optimizer.step() print("Trained client %d", self.id) return self.model.S if __name__ == '__main__': ... server = Server(server_model) clients = [Client(u, ClientModel(), train_set[u]) for u in range(n_clients)] server.train(clients) Ok, the problem is in multiprocessing. I tried with a lot of approaches but all of them gives me the same problem. Server should manage the training of 200 clients, but after a certain number of trainings (it depends on the approach, but approx 50-100), the script completely stucks and cores of the CPU stop working. Have you any ideas? Other approaches I tried are for example mp.Pool and with ProcessPoolExecutor. Thank you for your help.
Could it be that you hit the maximum number of processes/threads your machine is able to handle? It is common, for example, when moving a web crawler from development to production that the machine does not allow more processes. I would give a look at the file /etc/sysctl.d and in case increase the number of possible processes for the machine to handle. Another reason might be that you capped RAM limit or something similar, try to give another quick look at the command htop followed by free -m and see what they tell you. It might be a hardware problem. While from a software it might be that the library you are using https://docs.python.org/2/library/multiprocessing.html has a hard-coded limit. Also here you can easily set it higher within the library parameters. Last but not least, try to find the problem incrementally. I would test it with with 2 processes and increment slowly to see when the application starts having issues. And at that point it would probably be even clearer what the issue was. Good luck!
https://stackoverflow.com/questions/59068181/
ModuleNotFoundError: No module named 'torch'
I try to use pytorch module by conda but I get an error Traceback (most recent call last): File "train.py", line 8, in <module> import torch ModuleNotFoundError: No module named 'torch' when I write conda list | findstr torch I see that torch is installed: What is the problem? I tried: conda update conda -n root conda install mkl=2018 but get: Collecting package metadata (current_repodata.json): done Solving environment: done # All requested packages already installed. Could Not Find C:\WINDOWS\TEMP\conda-23721-26470.tmp Could Not Find C:\WINDOWS\TEMP\tmpry_dlvar.bat and the same error occurrence
Try the below mentioned one, surely it will work. conda install -c pytorch pytorch
https://stackoverflow.com/questions/59070936/
Use numpy in script class (torch.jit.script)
I was wondering if I can use numpy APIs in a function which is going to be scripted by torch.jit.script. I have this simple function which does not work: import torch import torch.nn as nn class MyModule(nn.Module): def __init__(self): super(MyModule, self).__init__() @torch.jit.ignore def call_np(): return torch.jit.export(np.random.choice(2, p=[.95,.05])) def forward(self): pass @torch.jit.export def func(self): done = self.call_np() print (done) scripted_module = torch.jit.script(MyModule()) scripted_module.func() which results in: --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-133-ab1ce37d6edc> in <module>() 18 print (done) 19 ---> 20 scripted_module = torch.jit.script(MyModule()) 21 scripted_module.func() C:\ProgramData\Anaconda3\lib\site-packages\torch\jit\__init__.py in script(obj, optimize, _frames_up, _rcb) 1201 1202 if isinstance(obj, torch.nn.Module): -> 1203 return torch.jit.torch.jit._recursive.recursive_script(obj) 1204 1205 qualified_name = _qualified_name(obj) C:\ProgramData\Anaconda3\lib\site-packages\torch\jit\_recursive.py in recursive_script(mod, exclude_methods) 171 filtered_methods = filter(ignore_overloaded, methods) 172 stubs = list(map(make_stub, filtered_methods)) --> 173 return copy_to_script_module(mod, overload_stubs + stubs) 174 175 C:\ProgramData\Anaconda3\lib\site-packages\torch\jit\_recursive.py in copy_to_script_module(original, stubs) 93 setattr(script_module, name, item) 94 ---> 95 torch.jit._create_methods_from_stubs(script_module, stubs) 96 97 # Now that methods have been compiled, take methods that have been compiled C:\ProgramData\Anaconda3\lib\site-packages\torch\jit\__init__.py in _create_methods_from_stubs(self, stubs) 1421 rcbs = [m.resolution_callback for m in stubs] 1422 defaults = [get_default_args(m.original_method) for m in stubs] -> 1423 self._c._create_methods(self, defs, rcbs, defaults) 1424 1425 # For each user-defined class that subclasses ScriptModule this meta-class, RuntimeError: Unable to cast Python instance of type <class 'int'> to C++ type 'unsigned __int64' I appreciate any help or comment.
I got an answered at the pytorch forum: https://discuss.pytorch.org/t/use-numpy-in-script-class-torch-jit-script/62351
https://stackoverflow.com/questions/59079411/
Forward Propagate RNN using Pytorch
I am trying to create an RNN forward pass method that can take a variable input, hidden, and output size and create the rnn cells needed. To me, it seems like I am passing the correct variables to self.rnn_cell -- the input values of x and the previous hidden layer. However, the error I receive is included below. I have also tried using x[i] and x[:,i,i] (as suggested by my professor) to no avail. I am confused and just looking for guidance as to whether or not I am doing the right thing here. My prof suggested that since I keep receiving errors, I should restart the kernel in jupyter notebook and rerun code. I have, and I receive the same errors... Please let me know if you need additional context. class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(RNN, self).__init__() self.hidden_size = hidden_size self.rnn_cell = nn.RNNCell(input_size, hidden_size) self.fc = nn.Linear(hidden_size, output_size) self.softmax = nn.LogSoftmax(dim=1) def forward(self, x): """ x: size [seq_length, 1, input_size] """ h = torch.zeros(x.size(1), self.hidden_size) for i in range(x.size(0)): ### START YOUR CODE ### h = self.rnn_cell(x[:,:,i], h) ### END YOUR CODE ### ### START YOUR CODE ### # Hint: first call fc, then call softmax out = self.softmax(self.fc(self.hidden_size, h.size(0))) ### END YOUR CODE ### return out IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
I am not an expert at RNNs but giving it a try. class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(RNN, self).__init__() self.hidden_size = hidden_size self.rnn_cell = nn.RNN(input_size, hidden_size) self.fc = nn.Linear(hidden_size, output_size) def forward(self, x): """ x: size [seq_length, 1, input_size] """ h = torch.zeros(num_layers(hidden), x.size(0), self.hidden_size) ### START YOUR CODE ### out,hidden = self.rnn_cell(x, h) ### END YOUR CODE ### ### START YOUR CODE ### # Hint: first call fc, then call softmax out = out.contiguous().view(-1, self.hidden_dim) #You need to reshape the output to fit the FC layer out = self.fc(out) return F.softmax(out) ### END YOUR CODE ### return out Please try running this and let me know in case of errors or any doubts. (Cannot ask you details as I can't comment rn.) If you got any idea from my answer, do support.
https://stackoverflow.com/questions/59080681/
NOT using multiprocessing but get CUDA error on google colab while using PyTorch DataLoader
I've cloned my GitHub repo into google colab and trying to load data using PyTorch's DataLoader. global gpu, device if torch.cuda.is_available(): gpu = True device = 'cuda:0' torch.set_default_tensor_type('torch.cuda.FloatTensor') print("Using GPU") else: gpu = False device = 'cpu' print("Using CPU") data_transforms = transforms.Compose([ #transforms.Resize(224), transforms.ToTensor(), transforms.Normalize([0.3112, 0.2636, 0.2047], [0.2419, 0.1972, 0.1554]) ]) train_path = '/content/convLSTM/code/data/train/' val_path = '/content/convLSTM/code/data/val/' test_path = '/content/convLSTM/code/data/test/' train_data = datasets.ImageFolder(root=train_path, transform=data_transforms) val_data = datasets.ImageFolder(root=val_path, transform=data_transforms) test_data = datasets.ImageFolder(root=test_path, transform=data_transforms) train_loader = torch.utils.data.DataLoader( train_data, batch_size=18, num_workers=4, shuffle=False, pin_memory=True ) val_loader = torch.utils.data.DataLoader( val_data, batch_size=18, shuffle=False, num_workers=4, pin_memory=True ) test_loader = torch.utils.data.DataLoader( test_data, batch_size=18, shuffle=False, num_workers=4, pin_memory=True ) for batch_idx, (data, target) in enumerate(train_loader): print(batch_idx) if batch_idx==3: break I'm getting the following error when I run the last for loop: RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method I tried num_workers = 1 instead of 4 but the error persists. I'm not using any multiprocessing. I also tried without setting torch.set_default_tensor_type('torch.cuda.FloatTensor') but the error persists. Python : 3.6.8 | PyTorch : 1.3.1 What seems to be the problem?
Not sure if you fixed it already but just in case someone else reads this, using n number of works activates pytorch multi processing. To disable it you need to have the default number of workers which is 0, not 1. Try setting num_workers to 0 or using the Torch Multiprocessing submodule.
https://stackoverflow.com/questions/59081290/
Running in Google Colab
Good evening. I want to run my python program on Google collab, but in what place I should download files and when open in python file? How do I open this file?
You can always upload files to Google colab and you can create a directory as well. You can create a directory named data And then upload the files which you want to be placed in the directory as shown below. * Remember the data uploaded or created during runtime will not be saved * Alternatively, you can save the files to your google drive and mount the drive -> Google Colab: how to read data from my google drive? to save your runtime files and folder directly to the drive.
https://stackoverflow.com/questions/59093925/
Flatten Tensor in Pytorch Convolutional Neural Network (size mismatch error)
I made a reproducible example with random pixels. I'm trying to flatten the tensors for the dense layers after the convolutional layers. The problem is at the intersection of the convolutional layers and the dense layers. I don't know how to put the right number of neurons. tl;dr I'm looking for the manual equivalent of keras.layers.Flatten() since it doesn't exist in pytorch. import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader x = np.random.rand(1_00, 3, 100, 100) y = np.random.randint(0, 2, 1_00) if torch.cuda.is_available(): x = torch.from_numpy(x.astype('float32')).cuda() y = torch.from_numpy(y.astype('float32')).cuda() class ConvNet(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 32, 3) self.conv2 = nn.Conv2d(32, 64, 3) self.conv3 = nn.Conv2d(64, 128, 3) self.fc1 = nn.Linear(128, 1024) # 128 is wrong here self.fc2 = nn.Linear(1024, 1) def forward(self, x): x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2)) x = F.max_pool2d(F.relu(self.conv3(x)), (2, 2)) x = x.view(x.size(0), -1) x = F.relu(self.fc1(x)) x = torch.sigmoid(self.fc2(x)) return x net = ConvNet() net.cuda() optimizer = optim.Adam(net.parameters(), lr=0.03) loss_function = nn.BCELoss() class Train: def __init__(self): self.len = x.shape[0] self.x_train = x self.y_train = y def __getitem__(self, index): return x[index], y[index].unsqueeze(0) def __len__(self): return self.len train = Train() train_loader = DataLoader(dataset=train, batch_size=64, shuffle=True) epochs = 1 train_losses = list() for e in range(epochs): running_loss = 0 for images, labels in train_loader: optimizer.zero_grad() log_ps = net(images) loss = loss_function(log_ps, labels) loss.backward() optimizer.step() running_loss += loss.item() print('It\'s working.')
Here's a function I made to automatically fit the right number of neurons while flattening a convolutional tensor: def flatten(w, k=3, s=1, p=0, m=True): """ Returns the right size of the flattened tensor after convolutional transformation :param w: width of image :param k: kernel size :param s: stride :param p: padding :param m: max pooling (bool) :return: proper shape and params: use x * x * previous_out_channels Example: r = flatten(*flatten(*flatten(w=100, k=3, s=1, p=0, m=True)))[0] self.fc1 = nn.Linear(r*r*128, 1024) """ return int((np.floor((w - k + 2 * p) / s) + 1) / 2 if m else 1), k, s, p, m In your case: def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 32, 3) self.conv2 = nn.Conv2d(32, 64, 3) self.conv3 = nn.Conv2d(64, 128, 3) r = flatten(*flatten(*flatten(w=100, k=3, s=1, p=0, m=True)))[0] self.fc1 = nn.Linear(r*r*128, 1024) self.fc2 = nn.Linear(1024, 1) def forward(self, x): ...
https://stackoverflow.com/questions/59108988/
How can I do to evaluate mean and std for a dataset?
I am using pytorch and the dataset fashion MNIST but I do not know how can I do to evaluate the mean and the std for this dataset. Here is my code : import torch from torchvision import datasets, transforms import torch.nn.functional as F transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((mean), (std))]) batch_size = 32 train_loader = torch.utils.data.DataLoader(datasets.MNIST( '../data', train=True, download=True, transform=transform) , batch_size=batch_size, shuffle=True) Could you help me please ? Thank you very much !
Use this to calculate mean and std- loader = data.DataLoader(dataset, batch_size=10, num_workers=0, shuffle=False) mean = 0. std = 0. for images, _ in loader: batch_samples = images.size(0) # batch size (the last batch can have smaller size!) images = images.view(batch_samples, images.size(1), -1) mean += images.mean(2).sum(0) std += images.std(2).sum(0) mean /= len(loader.dataset) std /= len(loader.dataset)
https://stackoverflow.com/questions/59116831/
How to use gensim with pytorch to create an intent classifier (With LSTM NN)?
The problem to solve: Given a sentence, return the intent behind it (Think chatbot) Reduced example dataset (Intent on the left of dict): data_raw = {"mk_reservation" : ["i want to make a reservation", "book a table for me"], "show_menu" : ["what's the daily menu", "do you serve pizza"], "payment_method" : ["how can i pay", "can i use cash"], "schedule_info" : ["when do you open", "at what time do you close"]} I have stripped down the sentences with spaCy, and tokenized each word by using the word2vec algorithm provided by the gensim library. This is what resulted from the use of word2vec model GoogleNews-vectors-negative300.bin: [[[ 5.99331968e-02 6.50703311e-02 5.03010787e-02 ... -8.00536275e-02 1.94782894e-02 -1.83010306e-02] [-2.14406010e-02 -1.00447744e-01 6.13847338e-02 ... -6.72588721e-02 3.03986594e-02 -4.14126664e-02] [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 ... 0.00000000e+00 0.00000000e+00 0.00000000e+00] ... [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 ... 0.00000000e+00 0.00000000e+00 0.00000000e+00] [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 ... 0.00000000e+00 0.00000000e+00 0.00000000e+00] [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 ... 0.00000000e+00 0.00000000e+00 0.00000000e+00]] [[ 4.48647663e-02 -1.03907576e-02 -1.78682189e-02 ... 3.84555124e-02 -2.29179319e-02 -2.05144612e-03] [-5.39291985e-02 -9.88398306e-03 4.39085700e-02 ... -3.55276838e-02 -3.66208404e-02 -4.57760505e-03] [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 ... 0.00000000e+00 0.00000000e+00 0.00000000e+00] ... [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 ... 0.00000000e+00 0.00000000e+00 0.00000000e+00] [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 ... 0.00000000e+00 0.00000000e+00 0.00000000e+00] [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 ... 0.00000000e+00 0.00000000e+00 0.00000000e+00]]] This is a List of sentences, and each sentence is a list of words ([sentences[sentence[word]]]) Each sentence (list) must be of size 10 words (I am padding the remaining with zeroes) Each word (list) has 300 elements (word2vec dimensions) By following some tutorials i transformed this to a TensorDataset. At this moment, i am very confused on how to use the word2vec and probably i have just been wasting time, as of now i believe the embeddings layer from an LSTM configuration should be composed by importing the word2vec model weights using: import gensim model = gensim.models.KeyedVectors.load_word2vec_format('path/to/file') weights = torch.FloatTensor(model.vectors) word_embeddings = nn.Embedding.from_pretrained(weights) This is not enough as pytorch is saying it does not accept embeddings where indices are not INT type . EDIT: I found out that importing the weight matrix from gensim word2vec is not straightforward, one has to import the word_index table as well. As soon as i fix this issue i'll post it here.
You don't need neither a neural network nor word embeddings. Use parsed trees with NLTK, where intents are Verbs V acting on entities (N) in a given utterance: To classify a sentence, then you can use a Neural Net. I personally like BERT in fast.ai. Once again, you won't need embeddings to run the classification, and you can do it in multilanguage: Fast.ai_BERT_ULMFit Also, you can use Named Entity Recognition if you are working on a chatbot, to guide conversations.
https://stackoverflow.com/questions/59120553/
Heroku: slug size too large after installing Pytorch
I've been getting the slug size too large warning (Compiled slug size: 789.8M is too large (max is 500M)) from Heroku and I can't figure out why, as my model size (cnn.pth below) is fairly small and my file directory is only 1.1mb in total: screenshot of directory. It seems like the size increase is caused by running pipenv install torch, as the slug size was 89.1mb before installing torch and 798.8mb after. My Pipfile currently has these packages installed: [packages] flask = "*" flask-sqlalchemy = "*" psycopg2 = "*" psycopg2-binary = "*" requests = "*" numpy = "*" gunicorn = "*" pillow = "*" torch = "*" Is there any workaround for this? Edit: I'm running Mac OSX 10.10.5, using Flask and pipenv.
The pytorch package that you're installing comes with both cpu and gpu support, thus has a large size. It seems you're using the free version of heroku, and only require the cpu support. The solution is to install the pytorch package for cpu only i.e. In requirements.txt, write the wheel file path corresponding to the version of pytorch (cpu) that you're interested in. You can find the list of wheel files, which can be installed with pip. For example, for PyTorch 1.3.1, torchvision 0.4.2, Python 3.7, Linux, you can write the following for pytorch and torchvision respectively: https://download.pytorch.org/whl/cpu/torch-1.3.1%2Bcpu-cp37-cp37m-linux_x86_64.whl https://download.pytorch.org/whl/cpu/torchvision-0.4.2%2Bcpu-cp37-cp37m-linux_x86_64.whl The above will download torch-1.3.1+cpu-cp37-cp37m-linux_x86_64.whl (107MB) torchvision-0.4.2+cpu-cp37-cp37m-linux_x86_64.whl (13MB) respectively.
https://stackoverflow.com/questions/59122308/
How is spectral norm of a parameter calculated?
when I do, import torch, torch.nn as nn x = nn.Linear(3, 3) y = torch.nn.utils.spectral_norm(x) then it gives four different weight matrices, y.weight_u tensor([ 0.6534, -0.1644, 0.7390]) y.weight_orig Parameter containing: tensor([[ 0.2538, 0.3196, 0.3380], [ 0.4946, 0.0519, 0.1022], [-0.5549, -0.0401, 0.1654]], requires_grad=True) y.weight_v tensor([-0.3650, 0.2870, 0.8857]) y.weight tensor([[ 0.5556, 0.6997, 0.7399], [ 1.0827, 0.1137, 0.2237], [-1.2149, -0.0878, 0.3622]], grad_fn=<DivBackward0>) how are these four matrices calculated?
I just finished reading the paper for this method which can be found on arxiv. If you have the appropriate mathematical background I would recommend reading it. See appendix A for the power algorithm which describes what u and v are. That said I'll try to summarize here. First, you should know that the spectral norm of a matrix is the maximum singular value. The authors propose finding the spectral norm of weight matrix W, then dividing W by its spectral norm to make it close to 1 (justification for this decision is in the paper). While we could just use torch.svd to find a precise estimate of the singular values, they instead use a fast (but imprecise) method called "power iteration". Long story short, the weight_u and weight_v are rough approximations of the left and right singular vectors corresponding to the largest singular value of W. They are useful because the associated singular value, i.e. the spectral norm, of W is equal to u.transpose(1,0) @ W @ v if u and v are the actual left/right singular vectors of W. y.weight_orig contains the original values in the layer. y.weight_u is the approximation of the first left singular vector of y.weight_orig. y.weight_v is the approximation of the first right singular vector of y.weight_orig. y.weight is the updated weight matrix which is y.weight_orig divided by its approximate spectral norm. We can verify these claims by showing that the actual left and right singular vectors are nearly parallel to y.weight_u and y.weight_v import torch import torch.nn as nn # pytorch default is 1 n_power_iterations = 1 y = nn.Linear(3,3) y = nn.utils.spectral_norm(y, n_power_iterations=n_power_iterations) # spectral normalization is performed during forward pre hook for technical reasons, we # need to send something through the layer to ensure normalization is applied # NOTE: After this is performed, x.weight is changed in place! _ = y(torch.randn(1,3)) # test svd vs. spectral_norm u/v estimates u,s,v = torch.svd(y.weight_orig) cos_err_u = 1.0 - torch.abs(torch.dot(y.weight_u, u[:, 0])).item() cos_err_v = 1.0 - torch.abs(torch.dot(y.weight_v, v[:, 0])).item() print('u-estimate cosine error:', cos_err_u) print('v-estimate cosine error:', cos_err_v) # singular values actual_orig_sn = s[0].item() approx_orig_sn = (y.weight_u @ y.weight_orig @ y.weight_v).item() print('Actual original spectral norm:', actual_orig_sn) print('Approximate original spectral norm:', approx_orig_sn) # updated weights singular values u,s_new,v = torch.svd(y.weight.data, compute_uv=False) actual_sn = s_new[0].item() print('Actual updated spectral norm:', actual_sn) print('Desired updated spectral norm: 1.0') which results in u-estimate cosine error: 0.00764310359954834 v-estimate cosine error: 0.034041762351989746 Actual original spectral norm: 0.8086231350898743 Approximate original spectral norm: 0.7871124148368835 Actual updated spectral norm: 1.0273288488388062 Desired updated spectral norm: 1.0 Increasing the n_power_iterations parameter will increase the accuracy of the estimate at the cost of computation time.
https://stackoverflow.com/questions/59123577/
installing py-torch in anaconda , got error
C:\WINDOWS\system32>python -m pip install torch Collecting torch Using cached https://files.pythonhosted.org/packages/f8/02/880b468bd382dc79896eaecbeb8ce95e9c4b99a24902874a2cef0b562cea/torch-0.1.2.post2.tar.gz Requirement already satisfied: pyyaml in c:\programdata\anaconda3\lib\site-packages (from torch) (5.1) Building wheels for collected packages: torch Building wheel for torch (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'C:\ProgramData\Anaconda3\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\vinayak\\AppData\\Local\\Temp\\pip-install-67llvrv3\\torch\\setup.py'"'"'; __file__='"'"'C:\\Users\\vinayak\\AppData\\Local\\Temp\\pip-install-67llvrv3\\torch\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\vinayak\AppData\Local\Temp\pip-wheel-_w68wcvp' --python-tag cp37 cwd: C:\Users\vinayak\AppData\Local\Temp\pip-install-67llvrv3\torch\ Complete output (30 lines): running bdist_wheel running build running build_deps Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\vinayak\AppData\Local\Temp\pip-install-67llvrv3\torch\setup.py", line 265, in <module> description="Tensors and Dynamic neural networks in Python with strong GPU acceleration", File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools\__init__.py", line 145, in setup return distutils.core.setup(**attrs) File "C:\ProgramData\Anaconda3\lib\distutils\core.py", line 148, in setup dist.run_commands() File "C:\ProgramData\Anaconda3\lib\distutils\dist.py", line 966, in run_commands self.run_command(cmd) File "C:\ProgramData\Anaconda3\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "C:\ProgramData\Anaconda3\lib\site-packages\wheel\bdist_wheel.py", line 192, in run self.run_command('build') File "C:\ProgramData\Anaconda3\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "C:\ProgramData\Anaconda3\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "C:\ProgramData\Anaconda3\lib\distutils\command\build.py", line 135, in run self.run_command(cmd_name) File "C:\ProgramData\Anaconda3\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "C:\ProgramData\Anaconda3\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "C:\Users\vinayak\AppData\Local\Temp\pip-install-67llvrv3\torch\setup.py", line 51, in run from tools.nnwrap import generate_wrappers as generate_nn_wrappers ModuleNotFoundError: No module named 'tools.nnwrap' ---------------------------------------- ERROR: Failed building wheel for torch Running setup.py clean for torch ERROR: Command errored out with exit status 1: command: 'C:\ProgramData\Anaconda3\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\vinayak\\AppData\\Local\\Temp\\pip-install-67llvrv3\\torch\\setup.py'"'"'; __file__='"'"'C:\\Users\\vinayak\\AppData\\Local\\Temp\\pip-install-67llvrv3\\torch\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' clean --all cwd: C:\Users\vinayak\AppData\Local\Temp\pip-install-67llvrv3\torch Complete output (2 lines): running clean error: [Errno 2] No such file or directory: '.gitignore' ---------------------------------------- ERROR: Failed cleaning build dir for torch Failed to build torch Installing collected packages: torch Running setup.py install for torch ... error ERROR: Command errored out with exit status 1: command: 'C:\ProgramData\Anaconda3\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\vinayak\\AppData\\Local\\Temp\\pip-install-67llvrv3\\torch\\setup.py'"'"'; __file__='"'"'C:\\Users\\vinayak\\AppData\\Local\\Temp\\pip-install-67llvrv3\\torch\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\vinayak\AppData\Local\Temp\pip-record-x966ekmg\install-record.txt' --single-version-externally-managed --compile cwd: C:\Users\vinayak\AppData\Local\Temp\pip-install-67llvrv3\torch\ Complete output (23 lines): running install running build_deps Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\vinayak\AppData\Local\Temp\pip-install-67llvrv3\torch\setup.py", line 265, in <module> description="Tensors and Dynamic neural networks in Python with strong GPU acceleration", File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools\__init__.py", line 145, in setup return distutils.core.setup(**attrs) File "C:\ProgramData\Anaconda3\lib\distutils\core.py", line 148, in setup dist.run_commands() File "C:\ProgramData\Anaconda3\lib\distutils\dist.py", line 966, in run_commands self.run_command(cmd) File "C:\ProgramData\Anaconda3\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "C:\Users\vinayak\AppData\Local\Temp\pip-install-67llvrv3\torch\setup.py", line 99, in run self.run_command('build_deps') File "C:\ProgramData\Anaconda3\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "C:\ProgramData\Anaconda3\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "C:\Users\vinayak\AppData\Local\Temp\pip-install-67llvrv3\torch\setup.py", line 51, in run from tools.nnwrap import generate_wrappers as generate_nn_wrappers ModuleNotFoundError: No module named 'tools.nnwrap' ---------------------------------------- ERROR: Command errored out with exit status 1: 'C:\ProgramData\Anaconda3\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\vinayak\\AppData\\Local\\Temp\\pip-install-67llvrv3\\torch\\setup.py'"'"'; __file__='"'"'C:\\Users\\vinayak\\AppData\\Local\\Temp\\pip-install-67llvrv3\\torch\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\vinayak\AppData\Local\Temp\pip-record-x966ekmg\install-record.txt' --single-version-externally-managed --compile Check the logs for full command output.
Select the right options based on hardware configuration and install it from https://pytorch.org/get-started/locally/ Should work without any problems.
https://stackoverflow.com/questions/59129241/
Conv2d and the value of padding
I would like to ask about the value of padding we set in the Conv2d function. I know what zero-padding is. However, what does it mean that the padding is 0 for instance, or 1,2, or 3. What do these values mean? Do they represent the number of columns and rows that will be filled with zeros? Thanks a lot.
As the documentation states: padding controls the amount of implicit zero-paddings on both sides for padding number of points for each dimension. Therefore, padding=1 means you pad your input with 1 column and row from each size. If you want more control over the amount of padding and its value you can either use a Padding layer, or the pad functional.
https://stackoverflow.com/questions/59131945/
How can we calculate receptive field of a network includes transposed convolutional layer?
A network I designed includes transposed convolutional layer. (ConvTranspose2d in pytorch) I want to get receptive field size of my network. Does the concept of receptive field also hold on with transposed convolutional layer? If yes, then how can I get it?
You can use the library pytorch-receptive-field to automatically compute all layers' receptive fields.
https://stackoverflow.com/questions/59132357/
Train a single pytorch model on multiple GPUs with some layers fixed?
I met some problems when using pytorch DistributedDataParallel. The situation is: My model is A, and it has been trained on a single GPU as usual. Suppose that there are three layers in A: class A(nn.module): def __init__(self): super(A,self).__init__() self.layer0 = layer0 self.layer1 = layer1 self.layer2 = layer2 def forward(self,x): x=self.layer0(x) x=self.layer1(x) x=self.layer2(x) return x Now I have some new data. I want to fine-tune A with it on multiple GPUs. I need to wrap A as a multi-GPU model B. But there are two training stages. In the 1st stage, I want to fix layer0 and layer1 of B. In the 2nd stage, only to fix layer0. Then requires_grad of parameters in layer1 should be changed during training. However, DistributedDataParallel doc says: You should never try to change your model’s parameters after wrapping up your model with DistributedDataParallel. In fact, I tried to use B.module to refer A wrapped in B. But the test results were abnormal compared to the single-GPU model. Maybe this way is disallowed. What should I do? Is there any proper way to wrap my model? And what should be take care for when saving and loading the model? Just run it on a single machine with multiple GPUs so you can ignore the distributed situation using multiple machines. Many thanks. Update 2019.12.03 As suggested by @jodag, I tried DataParallel, but it didn't work. This time I didn't change anything in B (except training it) after wrapping it. For simplification, My code is like this (and I refered this): class B(nn.DataParallel): def __getattr__(self, name): try: return super().__getattr__(name) except AttributeError: return getattr(self.module, name) a = A() b = B(a,device_ids=[0,1]) b = b.cuda() trained_param = b.layer2.parameters() # trained_param = [{'params':b.layer2.parameters()},{'params':b.layer1.parameters()}] optimizer = optim.Adam(trained_param) b.train() ... for x, label in data_loader: optimizer.zero_grad() x = x.to(0) # This line can be commented. y = b(x) l = loss(y, label) l.backword() optimizer.step()
If you only try to optimize part of the parameters, why not try controlling this via the optimizer, rather than the model? You can leave your model as-is (wrapped in a DistributedDataParallel) and pass only part of its parameters to the relevant optimizer.
https://stackoverflow.com/questions/59134785/
Receptive fields for feed forward network
I am pretty new to artificial intelligence and neural networks. I have implemented a feed-forward neural network in PyTorch for classification on the MNIST data set. Now I want to visualize the receptive fields of (a subset of) hidden neurons. But I am having some problems with understanding the concept of receptive fields and when I google it all results are about CNNs. So can anyone help me with how I could do this in PyTorch and how to interpret the results?
I have previously described the concept of a receptive field for CNNs in this answer, just to give you some context that might be useful in my actual answer. It seems that you are also struggling with the idea of receptive fields. Generally, you can best understand it by asking the question "which part of the (previous) layer representation is affecting my current input?" In Convolutional layers, the formula to compute the current layer only takes part of the image as an input (or at least only changes the outcome based on a this subregion). This is precisely what the receptive field is. Now, a fully connected layer, as the name implies, has a connection from every previous hidden state to every new hidden state, see the image below: In that case, the receptive field is simply "every previous state" (e.g., in the image, a cell in the first turquoise layer is affected by all yellow cells), which is not very helpful. The whole idea would be to have a smaller subset instead of all available states. Therefore, I think your question regarding implementations in PyTorch do not really make much sense, unfortunately, but I hope that the answer still provided some clarity on the topic. As a follow-up, I also encourage you to think about the implications of this "connectedness", especially when it comes to the number of tunable parameters.
https://stackoverflow.com/questions/59140195/
Running PyTorch multiprocessing in a Docker container with Gunicorn worker manager
I am trying to deploy a service on GCP. It's a Docker container that uses Gunicorn for worker management. The code runs a torch.multiprocessing.process to run a POST response as a background process. This works if I run the script using a python3 command. But hangs when using Gunicorn. My understanding is that CUDA needs threadsafe multiprocessing and that is why torch has its own implementation. When we set up Gunicorn to manage workers, this may be causing some conflict or thread safety issues. Has anyone come across this before. Would there be a different worker manager that I could be using? In Dockerfile: CMD gunicorn -w 1 -t 6000 -b 0.0.0.0:8080 --timeout 6000 --preload app_script:app - this is how i am running the app in docker. So yes I am using preload. And the issue happens even if I run the docker container locally so its not just a gcp situation p=torch.multiprocessing.Process(target=my_function args=(args, )) . p.start() - this is how a post call is getting handled.
I spent a lot of time investigating a similar issue. Pytorch calls were stuck when running on a docker container with gunicorn. The solution that worked for me was removing the --preload flag from the Docker gunicorn command.
https://stackoverflow.com/questions/59144482/
Stacking tensors in a list of tuples of tensors
I have a list of tuples of PyTorch tensors. It looks like this: [ (tensor([1, 2, 3]), tensor([4, 5, 6, 7]), tensor([8])), (tensor([9, 10,11]), tensor([11,12,13,14]), tensor([15])), (tensor([16,17,18]), tensor([19,20,21,22]), tensor([23])), ... ] Tensors in each column (that is, tensors that position k of their respective tuple) share the same shape. I want to stack the tensors in each column so that I end up with a single tuple, each value being the tensors concatenated along the dimension of the column. In this case, the output tuple would have three values, and look like this: ( tensor([[1,2,3], [9,10,11], [16,17,18]]), tensor([[4,5,6,7], [11,12,13,14], [19,20,21,22]], tensor([[8],[15],[23]) ) This is a made-up example. I want to do this for tuples of any length, and tensors of arbitrary size. What is the best way to do this type of concatenation quickly using PyTorch?
If anyone gets themselves into the same convoluted scenario, I was able to solve it with a lovely one-liner: tuple(map(torch.stack, zip(*x))) In this case, x is the original list I mentioned above. This line of code transforms x into the exact desired format.
https://stackoverflow.com/questions/59149275/
How can I save model weights to mlflow tracking sever using pytorch-lightning?
I would like to save model weights to mlflow tracking using pytorch-lightning. pytorch-lightning supports logging. However, it seems that saving model weights as a artifact on mlflow is not supported. At first, I planed to override ModelCheckpoint class to do it, but I found it is difficult for me because of complex Mixin operations. Anybody knows simple way to accomplish it?
As @xela said, you can use the experiment object of the mlflow logger to log artifacts. In case you want to frequently log model weights during training, you could extend ModelCheckpoint: class MLFlowModelCheckpoint(ModelCheckpoint): def __init__(self, mlflow_logger, *args, **kwargs): super().__init__(*args, **kwargs) self.mlflow_logger = mlflow_logger @rank_zero_only def on_validation_end(self, trainer, pl_module): super().on_validation_end(trainer, pl_module) run_id = self.mlflow_logger.run_id self.mlflow_logger.experiment.log_artifact(run_id, self.best_model_path) And then use in your training code mlflow_logger = MLFlowLogger() checkpoint_callback = MLFlowModelCheckpoint(mlflow_logger) trainer = pl.Trainer(checkpoint_callback=checkpoint_callback, logger=mlflow_logger)
https://stackoverflow.com/questions/59149725/
Cannot install pytorch in a virtualenv on windows
I know there are a few topics about that on this website but still, I can't find the solution. So here is what I did : I created a projecton Visual Studio 19 for python. I added an virtual environment with Python 3.7 using the file requirements.txt It contains mypy==0.750 pylint==2.4.4 pytest==5.3.1 matplotlib==3.1.1 torch==1.3.1 tensorflow==2.1.0rc0 This requirement file works perfectly well on linux. But on vs19 I get the following : ERROR: Could not find a version that satisfies the requirement torch==1.3.1 (from -r E:\Documents\Blub\Granolar\requirements.txt (line 5)) (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2)` Since I don't want to downgrade to 0.1.2 (obviously) how can I fix it?
I went to the PyTorch documentation on how to "Start Locally" and selected what seems to be your environment: PyTorch Build: Stable (1.3) Your OS: Windows Package: Pip Language: Python 3.7 CUDA: None The resulting instruction I got back as a result is: pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html So most likely you could modify your requirements.txt like this: mypy==0.750 pylint==2.4.4 pytest==5.3.1 matplotlib==3.1.1 torch==1.3.1+cpu --find-links https://download.pytorch.org/whl/torch_stable.html tensorflow==2.1.0rc0
https://stackoverflow.com/questions/59152261/
why is my Neural Network stuck at high loss value after the first epochs
I'm doing regression using Neural Networks. It should be a simple task for NN to do, I have 10 features and 1 output that I want to predict.I’m using pytorch for my project but my Model is not learning well. the loss start with a very high value (40000), then after the first 5-10 epochs the loss decrease rapidly to 6000-7000 and then it stuck there, no matter what I make. I tried even to change to skorch instead of pytorch so that I can use cross validation functionality but that also didn’t help. I tried different optimizers and added layers and neurons to the network but that didn’t help, it stuck at 6000 which is a very high loss value. I’m doing regression here, I have 10 features and I’m trying to predict one continuous value. that should be easy to do that’s why it is confusing me more. here is my network: I tried here all the possibilities from making more complex architectures like adding layers and units to batch normalization, changing activations etc.. nothing have worked class BearingNetwork(nn.Module): def __init__(self, n_features=X.shape[1], n_out=1): super().__init__() self.model = nn.Sequential( nn.Linear(n_features, 512), nn.BatchNorm1d(512), nn.LeakyReLU(), nn.Linear(512, 64), nn.BatchNorm1d(64), nn.LeakyReLU(), nn.Linear(64, n_out), # nn.LeakyReLU(), # nn.Linear(256, 128), # nn.LeakyReLU(), # nn.Linear(128, 64), # nn.LeakyReLU(), # nn.Linear(64, n_out) ) def forward(self, x): out = self.model(x) return out and here are my settings: using skorch is easier than pytorch. here I'm monitoring also the R2 metric and I made RMSE as a custom metric to also monitor the performance of my model. I also tried the amsgrad for Adam but that didn't help. R2 = EpochScoring(r2_score, lower_is_better=False, name='R2') explained_var_score = EpochScoring(EVS, lower_is_better=False, name='EVS Metric') custom_score = make_scorer(RMSE) rmse = EpochScoring(custom_score, lower_is_better=True, name='rmse') bearing_nn = NeuralNetRegressor( BearingNetwork, criterion=nn.MSELoss, optimizer=optim.Adam, optimizer__amsgrad=True, max_epochs=5000, batch_size=128, lr=0.001, train_split=skorch.dataset.CVSplit(10), callbacks=[R2, explained_var_score, rmse, Checkpoint(), EarlyStopping(patience=100)], device=device ) I also standardize the Input values. my Input have the shape: torch.Size([39006, 10]) and shape of output is: torch.Size([39006, 1]) I’m using 128 as my Batch_size but I also tried other values like 32, 64, 512 and even 1024. Although normalizing output is not necessary but I also tried that and It didn’t work when I predict values, the loss is high. Please someone help me on this, I would appreciate every helpful advice. I ll also add a screenshot of my training and val losses and metrics over epochs to visualize how the loss is decreasing in the first 5 epochs and then it stays like forever at the value 6000 which is a very high value for a loss.
considering that your training and dev loss are decreasing over time, it seems like your model is training correctly. With respect to your worry regarding your training and dev loss values, this is entirely dependent on the scale of your target values (how big are your target values?) and the metric used to compute the training and dev losses. If your target values are big and you want smaller train and dev loss values, you can normalise the target values. From what I gather with respect to your experiments as well as your R2 scores, it seems that you are looking for a solution in the wrong area. To me, it seems like your features aren't strong enough considering that your R2 scores are low, which could mean that you have a data quality issue. This would also explain why your architecture tuning has not improved your model's performance as it is not your model that is the issue. So if I were you, I would think about what new useful features I could add and see if that helps. In machine learning, the general rule is that models are only as good as the data that they are trained on. I hope this helps!
https://stackoverflow.com/questions/59153248/
How to install PyTorch on Python 3.7 / Windows 10 with pip
I am trying to install PyTorch 1.3 using pip : pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html I got the command line from this page : https://pytorch.org/get-started/locally/#start-locally It fails, with the following error message : ERROR: Could not find a version that satisfies the requirement torch==1.3.1+cpu (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2) ERROR: No matching distribution found for torch==1.3.1+cpu Using verbose mode (-v) give a little more info : Skipping link: unsupported archive format: .html: https://download.pytorch.org/whl/torch_stable.html (from -f) Analyzing links from page https://pypi.org/simple/torch/ It seems pip cannot use the url I provide and will get packages from another URL. That one support at best Python 3.6. Since I have installed 3.7.5 (which is support by URL initially provided) none of the packages match and it fails. I could downgrade to 3.6 but since 3.7 is officially supported I would like to try to fix that issue first. EDIT : pip is up to date. I got exact same error on both Windows 10 and 7 64 bit machines. Also: the PyTorch page says : Please ensure that you have met the prerequisites below (e.g., numpy) But AFAIK does not list any library in that section. During my tests, numpy was installed and up to date. As requested, here is the full output of pip : https://pastebin.com/8Wpqp6du
You error is being triggered because the version 1.3.1+cpu doesn't exist. If you go to pytorch.org you will be able to select a version of pytorch and your OS, where it will give you a command to install pyTorch correctly, for Python 3.7 and PIP use the following: pip3 install --find-links https://download.pytorch.org/whl/torch_stable.html torch==1.3.1 torchvision==0.4.2 Remember to check that the pip3 binary you are using is the one installed over Python 3.7. Also, mind that the documentation you are pointing at is for MacOS.
https://stackoverflow.com/questions/59161453/
How I make pytorch read the numpy format?
I'm trying to create a code with PyTorch and Keras that uses the BERT algorithm to detect fake news, but I got an error tells me: can't convert np.ndarray of type numpy.bool_. The only supported types are: double, float, float16, int64, int32, and uint8. Please access the code on my Google Codelab. The error can be seen in the last cell. The only requirement for running it is downloading a CSV file for the training process.
I can't confirm but I believe your problem will be solved by changing: train_y = np.array(train_labels) == 'fake' test_y = np.array(test_labels) == 'fake' to: train_y = (np.array(train_labels) == 'fake').astype(int) test_y = (np.array(test_labels) == 'fake').astype(int) The train_y data is currently an array of type Bool (True or False) and the tensor needs and int (0 or 1).
https://stackoverflow.com/questions/59167119/
How to make a PyTorch Distribution on GPU
Is it possible to make the PyTorch distributions create their samples directly on GPU. If I do from torch.distributions import Uniform, Normal normal = Normal(3, 1) sample = normal.sample() Then sample will be on CPU. Of course it is possible to do sample = sample.to(torch.device("cuda")) to make it on GPU. But is there a way to have the sample go directly to GPU without first creating it on CPU? PyTorch distributions inherit from Object, not nn.Module so it does not have a to method the put the distribution instance on GPU. Any ideas?
Distributions use the reparametrization trick. Thus giving size 0 tensors which are on GPU to the distribution constructor works. As follows: normal = Normal(torch.tensor(0).to(device=torch.device("cuda")), torch.tensor(1).to(device=torch.device("cuda")))
https://stackoverflow.com/questions/59179609/
pytorch net creation does not generate weights if done in a list
I'm creating a net in pytorch by writing a class called MyNet with init() and forward() method. If I create a layer in init() like: self.fc = nn.Linear(5, 10) everything works fine and net = MyNet() paramL = list(net.parameters()) gives me a list with some weights inside. However, if I create layers in the following way self.layerL = [nn.Linear(5,10)] something seems to go wrong, since list(net.parameters()) now gives an empty list :-( Any idea what I'm doing wrong ?? Many thanks
In simple terms, this is because it is not a torch.nn object. For this use torch.nn.Sequential. For example, self.Layer = torch.nn.Sequential(nn.Linear(5,10), nn.Linear(10,10), ...)
https://stackoverflow.com/questions/59180955/
Wrong value of standard deviation
Hello I am trying to evaluate the standard deviation and the mean of the dataset MNIST and I get a wrong value for the standard deviation. Here is my code : import torch from torchvision import datasets, transforms import torch.nn.functional as F loader = torch.utils.data.DataLoader(datasets.MNIST( '../data', train=True, download=True, transform=transform1), batch_size=32, num_workers=0, shuffle=False) mean = 0. std = 0. for images, _ in loader: batch_samples = images.size(0) images = images.view(batch_samples, images.size(1), -1) mean += images.mean(2).sum(0) std += images.std(2).sum(0) mean /= len(loader.dataset) std /= len(loader.dataset) print("The mean is ", mean) print("The standard deviation is ", std) My problem is the following, I get as mean the value 0.1307 and for the standard deviation the value 0.3015 instead of 0.3081. I suppose I have an error in my code but I don't see where. Could you help me please ? Thank you very much !
torch.std uses the batches mean as part of the computation so it's not the same as using torch.std on the entire dataset since that would use a different mean. We can use the following well known expression for variance to get the desired result Var(X) = E[X**2] - E[X]**2 mean = 0. mean_square = 0. samples = 0 for images, _ in loader: batch_samples = images.size(0) images = images.view(batch_samples, images.size(1), -1) mean += images.mean(2).sum(0) mean_square += (images**2).mean(2).sum(0) samples += images.size(2) * images.size(0) mean /= len(loader.dataset) mean_square /= len(loader.dataset) # extra scale factor for unbias std estimate (it's effectively 1.0) scale = samples / (samples - 1) std = torch.sqrt((mean_square - mean**2) * scale) print("The mean is ", mean) print("The standard deviation is ", std) Of course in the special case of the torchvision MNIST dataset you could just directly compute mean and standard deviation... mean = torch.mean(loader.dataset.data.float() / 255.0) std = torch.std(loader.dataset.data.float() / 255.0)
https://stackoverflow.com/questions/59182363/
windows spyder invalid syntax error while running py file
I am trying to run the last example from the page. I have cloned the repository in the directory C:/Users/nn/Desktop/BERT/transformers-master. I am on windows machine and using spyder IDE. Why i do get below error and how could i resolve it? How do i input the initial part of the poem? import os os.chdir('C:/Users/nn/Desktop/BERT/transformers-master/examples') os.listdir()# It shows run_generation.py file python run_generation.py \ --model_type=gpt2 \ --length=100 \ --model_name_or_path=gpt2 \ python run_generation.py \ --model_type=gpt2 \ --length=100 \ --model_name_or_path=gpt2 \ File "<ipython-input-10-501d266b0e64>", line 1 python run_generation.py \ ^ SyntaxError: invalid syntax I went to command prompt and tried below cd C:/Users/nn/Desktop/BERT/transformers-master/examples python3 run_generation.py \--model_type=gpt2 \--length=100 \--model_name_or_path=gpt2 \--promt="Hello world" nothing happens :( when i try the same with python command i get an error as below :( python run_generation.py \--model_type=gpt2 \--length=100 \--model_name_or_path=gpt2 \--promt="Hello world" 2019-12-04 11:23:36.345648: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_100.dll'; dlerror: cudart64_100.dll not found 2019-12-04 11:23:36.352875: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. usage: run_generation.py [-h] --model_type MODEL_TYPE --model_name_or_path MODEL_NAME_OR_PATH [--prompt PROMPT] [--padding_text PADDING_TEXT] [--xlm_lang XLM_LANG] [--length LENGTH] [--num_samples NUM_SAMPLES] [--temperature TEMPERATURE] [--repetition_penalty REPETITION_PENALTY] [--top_k TOP_K] [--top_p TOP_P] [--no_cuda] [--seed SEED] [--stop_token STOP_TOKEN] run_generation.py: error: the following arguments are required: --model_type, --model_name_or_path ####update 2 ------------------ I followed suggestions in the comments and it worked. It seems that the code downloads 3 files. Can i copy those files manually so that I dont have to rely on downloading them every time in a temp folder? Where should i store those files? which folder location? would it be C:\Users\nnn\Desktop\BERT\transformers-master\examples - same as run_generation.py file? abc C:\Users\nnn\Desktop\BERT\transformers-master\examples>python run_generation.py --model_type=gpt2 --length=100 --model_name_or_path=gpt2 --prompt="My job is" 2019-12-12 11:11:57.740810: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_100.dll'; dlerror: cudart64_100.dll not found 2019-12-12 11:11:57.748330: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. 12/12/2019 11:12:01 - INFO - transformers.file_utils - https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-vocab.json not found in cache or force_download set to True, downloading to C:\Users\nnn\AppData\Local\Temp\tmpt_29gyqi 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1042301/1042301 [00:00<00:00, 2275416.04B/s] 12/12/2019 11:12:02 - INFO - transformers.file_utils - copying C:\Users\nnn\AppData\Local\Temp\tmpt_29gyqi to cache at C:\Users\nnn\.cache\torch\transformers\f2808208f9bec2320371a9f5f891c184ae0b674ef866b79c58177067d15732dd.1512018be4ba4e8726e41b9145129dc30651ea4fec86aa61f4b9f40bf94eac71 12/12/2019 11:12:02 - INFO - transformers.file_utils - creating metadata file for C:\Users\nnn\.cache\torch\transformers\f2808208f9bec2320371a9f5f891c184ae0b674ef866b79c58177067d15732dd.1512018be4ba4e8726e41b9145129dc30651ea4fec86aa61f4b9f40bf94eac71 12/12/2019 11:12:02 - INFO - transformers.file_utils - removing temp file C:\Users\nnn\AppData\Local\Temp\tmpt_29gyqi 12/12/2019 11:12:03 - INFO - transformers.file_utils - https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-merges.txt not found in cache or force_download set to True, downloading to C:\Users\nnn\AppData\Local\Temp\tmpj1_y4sn8 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 456318/456318 [00:00<00:00, 1456594.78B/s] 12/12/2019 11:12:03 - INFO - transformers.file_utils - copying C:\Users\nnn\AppData\Local\Temp\tmpj1_y4sn8 to cache at C:\Users\nnn\.cache\torch\transformers\d629f792e430b3c76a1291bb2766b0a047e36fae0588f9dbc1ae51decdff691b.70bec105b4158ed9a1747fea67a43f5dee97855c64d62b6ec3742f4cfdb5feda 12/12/2019 11:12:03 - INFO - transformers.file_utils - creating metadata file for C:\Users\nnn\.cache\torch\transformers\d629f792e430b3c76a1291bb2766b0a047e36fae0588f9dbc1ae51decdff691b.70bec105b4158ed9a1747fea67a43f5dee97855c64d62b6ec3742f4cfdb5feda 12/12/2019 11:12:03 - INFO - transformers.file_utils - removing temp file C:\Users\nnn\AppData\Local\Temp\tmpj1_y4sn8 12/12/2019 11:12:03 - INFO - transformers.tokenization_utils - loading file https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-vocab.json from cache at C:\Users\nnn\.cache\torch\transformers\f2808208f9bec2320371a9f5f891c184ae0b674ef866b79c58177067d15732dd.1512018be4ba4e8726e41b9145129dc30651ea4fec86aa61f4b9f40bf94eac71 12/12/2019 11:12:03 - INFO - transformers.tokenization_utils - loading file https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-merges.txt from cache at C:\Users\nnn\.cache\torch\transformers\d629f792e430b3c76a1291bb2766b0a047e36fae0588f9dbc1ae51decdff691b.70bec105b4158ed9a1747fea67a43f5dee97855c64d62b6ec3742f4cfdb5feda 12/12/2019 11:12:04 - INFO - transformers.file_utils - https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-config.json not found in cache or force_download set to True, downloading to C:\Users\nnn\AppData\Local\Temp\tmpyxywrts1 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 176/176 [00:00<00:00, 17738.31B/s] 12/12/2019 11:12:04 - INFO - transformers.file_utils - copying C:\Users\nnn\AppData\Local\Temp\tmpyxywrts1 to cache at C:\Users\nnn\.cache\torch\transformers\4be02c5697d91738003fb1685c9872f284166aa32e061576bbe6aaeb95649fcf.085d5f6a8e7812ea05ff0e6ed0645ab2e75d80387ad55c1ad9806ee70d272f80 12/12/2019 11:12:04 - INFO - transformers.file_utils - creating metadata file for C:\Users\nnn\.cache\torch\transformers\4be02c5697d91738003fb1685c9872f284166aa32e061576bbe6aaeb95649fcf.085d5f6a8e7812ea05ff0e6ed0645ab2e75d80387ad55c1ad9806ee70d272f80 12/12/2019 11:12:04 - INFO - transformers.file_utils - removing temp file C:\Users\nnn\AppData\Local\Temp\tmpyxywrts1 12/12/2019 11:12:04 - INFO - transformers.configuration_utils - loading configuration file https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-config.json from cache at C:\Users\nnn\.cache\torch\transformers\4be02c5697d91738003fb1685c9872f284166aa32e061576bbe6aaeb95649fcf.085d5f6a8e7812ea05ff0e6ed0645ab2e75d80387ad55c1ad9806ee70d272f80 12/12/2019 11:12:04 - INFO - transformers.configuration_utils - Model config { "attn_pdrop": 0.1, "embd_pdrop": 0.1, "finetuning_task": null, "initializer_range": 0.02, "layer_norm_epsilon": 1e-05, "n_ctx": 1024, "n_embd": 768, "n_head": 12, "n_layer": 12, "n_positions": 1024, "num_labels": 1, "output_attentions": false, "output_hidden_states": false, "output_past": true, "pruned_heads": {}, "resid_pdrop": 0.1, "summary_activation": null, "summary_first_dropout": 0.1, "summary_proj_to_labels": true, "summary_type": "cls_index", "summary_use_proj": true, "torchscript": false, "use_bfloat16": false, "vocab_size": 50257 } 12/12/2019 11:12:04 - INFO - transformers.file_utils - https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-pytorch_model.bin not found in cache or force_download set to True, downloading to C:\Users\nnn\AppData\Local\Temp\tmpn8i9o_tm 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 548118077/548118077 [01:12<00:00, 7544610.26B/s] 12/12/2019 11:13:18 - INFO - transformers.file_utils - copying C:\Users\nnn\AppData\Local\Temp\tmpn8i9o_tm to cache at C:\Users\nnn\.cache\torch\transformers\4295d67f022061768f4adc386234dbdb781c814c39662dd1662221c309962c55.778cf36f5c4e5d94c8cd9cefcf2a580c8643570eb327f0d4a1f007fab2acbdf1 12/12/2019 11:13:24 - INFO - transformers.file_utils - creating metadata file for C:\Users\nnn\.cache\torch\transformers\4295d67f022061768f4adc386234dbdb781c814c39662dd1662221c309962c55.778cf36f5c4e5d94c8cd9cefcf2a580c8643570eb327f0d4a1f007fab2acbdf1 12/12/2019 11:13:24 - INFO - transformers.file_utils - removing temp file C:\Users\nnn\AppData\Local\Temp\tmpn8i9o_tm 12/12/2019 11:13:24 - INFO - transformers.modeling_utils - loading weights file https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-pytorch_model.bin from cache at C:\Users\nnn\.cache\torch\transformers\4295d67f022061768f4adc386234dbdb781c814c39662dd1662221c309962c55.778cf36f5c4e5d94c8cd9cefcf2a580c8643570eb327f0d4a1f007fab2acbdf1 12/12/2019 11:13:32 - INFO - __main__ - Namespace(device=device(type='cpu'), length=100, model_name_or_path='gpt2', model_type='gpt2', n_gpu=0, no_cuda=False, num_samples=1, padding_text='', prompt='My job is', repetition_penalty=1.0, seed=42, stop_token=None, temperature=1.0, top_k=0, top_p=0.9, xlm_lang='') 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 100/100 [00:23<00:00, 2.49it/s] to know when it will change, it's up to you." National Communications Director Alex Brynner said the Trump administration needs to help then-Secretary of State Rex Tillerson learn from him. "The Cabinet, like any other government job, has to be attentive to the needs of an individual that might challenge his or her position," Brynner said. "This is especially true in times of renewed volatility." Brynner said Tillerson has not "failed at vetting
Did you read the pre-requisites of the task: Installing PyTorch-Transformers on your Machine Installing Pytorch-Transformers is pretty straightforward in Python. You can simply use pip install: pip install pytorch-transformers or if you are working on Colab: !pip install pytorch-transformers Since most of these models are GPU-heavy, I would suggest working with Google Colab for this part of the article. Link to Colab: https://colab.research.google.com/notebooks/welcome.ipynb#recent=true The command syntax used in colab is little bit different, as you can observe from pip command above. The example command most probably runs better with removal of \ characters (when on cmd) and having all command arguments on same line separated by space char only. Command may require heavy calculation, so colab with syntax from example directly works in there. Edit: Now, looking back your code, there is an important typo: use prompt with another p, not promt. Then you'd most probably be able to input the seed for the algorithm. I am testing this on my own computer and will soon comment if I find another issue. Edit2: My test took some time, now I am ready. I had to follow 3 Readme.md files to get the tutorial to work: one from the root folder, one below tranformers and lastly, the one from samples. Then running this command I got my first results: python pytorch-transformers/examples/run_generation.py --model_type=gpt2 --length=2 --model_name_or_path=gpt2 --prompt="My job is" ..and the computer thought a time and said quite well: "to know".
https://stackoverflow.com/questions/59182421/
How to apply bounds on a variable when performing optimisation in Pytorch?
I am trying to use Pytorch for non-convex optimisation, trying to maximise my objective (so minimise in SGD). I would like to bound my dependent variable x > 0, and also have the sum of my x values be less than 1000. I think I have the penalty implemented correctly in the form of a ramp penalty, but am struggling with the bounding of the x variable. In Pytorch you can set the bounds using clamp but it doesn't seem appropriate in this case. I think this is because optim needs the gradients free under the hood. Full working example: import torch from torch.autograd import Variable import numpy as np def objective(x, a, b, c): # Want to maximise this quantity (so minimise in SGD) d = 1 / (1 + torch.exp(-a * (x))) # Checking constraint exceeded_limit = constraint(x).item() #print(exceeded_limit) obj = torch.sum(d * (b * c - x)) # If overlimit add ramp penalty if exceeded_limit < 0: obj = obj - (exceeded_limit * 10) print("Exceeded limit") return - obj def constraint(x, limit = 1000): # Must be > 0 return limit - x.sum() N = 1000 # x is variable to optimise for x = Variable(torch.Tensor([1 for ii in range(N)]), requires_grad=True) a = Variable(torch.Tensor(np.random.uniform(0,100,N)), requires_grad=True) b = Variable(torch.Tensor(np.random.rand(N)), requires_grad=True) c = Variable(torch.Tensor(np.random.rand(N)), requires_grad=True) # Would like to include the clamp # x = torch.clamp(x, min=0) # Non-convex methodf opt = torch.optim.SGD([x], lr=.01) for i in range(10000): # Zeroing gradients opt.zero_grad() # Evaluating the objective obj = objective(x, a, b, c) # Calculate gradients obj.backward() opt.step() if i%1000==0: print("Objective: %.1f" % -obj.item()) print("\nObjective: {}".format(-obj)) print("Limit: {}".format(constraint(x).item())) if torch.sum(x<0) > 0: print("Bounds not met") if constraint(x).item() < 0: print("Constraint not met") Any suggestions as to how to impose the bounds would be appreciated, either using clamp or otherwise. Or generally advice on non-convex optimisation using Pytorch. This is a much simpler and scaled down version of the problem I'm working so am trying to find a lightweight solution if possible. I am considering using a workaround such as transforming the x variable using an exponential function but then you'd have to scale the function to avoid the positive values becoming infinite, and I want some flexibility with being able to set the constraint.
I meet the same problem with you. I want to apply bounds on a variable in PyTorch, too. And I solved this problem by the below Way3. Your example is a little compliex but I am still learning English. So I give a simpler example below. For example, there is a trainable variable v, its bounds is (-1, 1) v = torch.tensor((0.5, ), require_grad=True) v_loss = xxxx optimizer.zero_grad() v_loss.backward() optimizer.step() Way1. RuntimeError: a leaf Variable that requires grad has been used in an in-place operation. v.clamp_(-1, 1) Way2. RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. v = torch.clamp(v, -1, +1) # equal to v = v.clamp(-1, +1) Way3. NotError. I solved this problem in Way3. with torch.no_grad(): v[:] = v.clamp(-1, +1) # You must use v[:]=xxx instead of v=xxx
https://stackoverflow.com/questions/59192705/
Weight Initialization from pretrained BERT error in pytorch
I am trying to train the model using pretrained model(BERT) using pytorch. The pretrained model weights still arent accepted. I see this error: Weights of BertForMultiLable not initialized from pretrained model: ['classifier.weight', 'classifier.bias'] Weights from pretrained model not used in BertForMultiLable: ['cls.predictions.bias', 'cls.predictions.transform.dense.weight', 'cls.predictions.transform.dense.bias', 'cls.predictions.transform.LayerNorm.weight', 'cls.predictions.transform.LayerNorm.bias', 'cls.predictions.decoder.weight', 'cls.seq_relationship.weight', 'cls.seq_relationship.bias'] Here is the complete traceback: Training/evaluation parameters Namespace(adam_epsilon=1e-08, arch='bert', data_name='ICD9', do_data=False, do_lower_case=True, do_test=False, do_train=True, epochs=6, eval_batch_size=8, eval_max_seq_len=256, fp16=False, fp16_opt_level='O1', grad_clip=1.0, gradient_accumulation_steps=1, learning_rate=2e-05, local_rank=-1, loss_scale=0, mode='min', monitor='valid_loss', n_gpu='0', resume_path='', save_best=True, seed=42, sorted=1, train_batch_size=8, train_max_seq_len=256, valid_size=0.2, warmup_proportion=0.1, weight_decay=0.01) Loading examples from cached file pybert/dataset/cached_train_examples_bert Loading features from cached file pybert/dataset/cached_train_features_256_bert sorted data by th length of input Loading examples from cached file pybert/dataset/cached_valid_examples_bert Loading features from cached file pybert/dataset/cached_valid_features_256_bert initializing model loading configuration file pybert/pretrain/bert/base-uncased/config.json Model config { "attention_probs_dropout_prob": 0.1, "finetuning_task": null, "hidden_act": "gelu", "hidden_dropout_prob": 0.1, "hidden_size": 768, "initializer_range": 0.02, "intermediate_size": 3072, "is_decoder": false, "layer_norm_eps": 1e-12, "max_position_embeddings": 512, "num_attention_heads": 12, "num_hidden_layers": 12, "num_labels": 19, "output_attentions": false, "output_hidden_states": false, "output_past": true, "pruned_heads": {}, "torchscript": false, "type_vocab_size": 2, "use_bfloat16": false, "vocab_size": 28996 } loading weights file pybert/pretrain/bert/base-uncased/pytorch_model.bin Weights of BertForMultiLable not initialized from pretrained model: ['classifier.weight', 'classifier.bias'] Weights from pretrained model not used in BertForMultiLable: ['cls.predictions.bias', 'cls.predictions.transform.dense.weight', 'cls.predictions.transform.dense.bias', 'cls.predictions.transform.LayerNorm.weight', 'cls.predictions.transform.LayerNorm.bias', 'cls.predictions.decoder.weight', 'cls.seq_relationship.weight', 'cls.seq_relationship.bias'] initializing callbacks ***** Running training ***** Num examples = 21479 Num Epochs = 6 Total train batch size (w. parallel, distributed & accumulation) = 8 Gradient Accumulation steps = 1 Total optimization steps = 16110 Warning: There's no GPU available on this machine, training will be performed on CPU. Warning: The number of GPU's configured to use is 0, but only 0 are available on this machine. Traceback (most recent call last): File "run_bert.py", line 227, in <module> main() File "run_bert.py", line 220, in main run_train(args) File "run_bert.py", line 125, in run_train trainer.train(train_data=train_dataloader, valid_data=valid_dataloader, seed=args.seed) File "/home/aditya_vartak/bert_pytorch/pybert/train/trainer.py", line 168, in train summary(self.model,*(input_ids, segment_ids,input_mask),show_input=True) File "/home/aditya_vartak/bert_pytorch/pybert/common/tools.py", line 307, in summary model(*inputs) File "/home/aditya_vartak/virtualenvs/anaconda3/envs/pytorch/lib/python3.7/site-packages/torch/nn/modules/module.py", line 541, in __call__ result = self.forward(*input, **kwargs) File "/home/aditya_vartak/bert_pytorch/pybert/model/nn/bert_for_multi_label.py", line 14, in forward outputs = self.bert(input_ids, token_type_ids=token_type_ids,attention_mask=attention_mask, head_mask=head_mask) File "/home/aditya_vartak/virtualenvs/anaconda3/envs/pytorch/lib/python3.7/site-packages/torch/nn/modules/module.py", line 541, in __call__ result = self.forward(*input, **kwargs) File "/home/aditya_vartak/virtualenvs/anaconda3/envs/pytorch/lib/python3.7/site-packages/transformers/modeling_bert.py", line 722, in forward embedding_output = self.embeddings(input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds) File "/home/aditya_vartak/virtualenvs/anaconda3/envs/pytorch/lib/python3.7/site-packages/torch/nn/modules/module.py", line 533, in __call__ result = hook(self, input) File "/home/aditya_vartak/bert_pytorch/pybert/common/tools.py", line 269, in hook summary[m_key]["input_shape"] = list(input[0].size()) IndexError: tuple index out of range Any help would be great. Thanks in advance
for the Error you cited, actually I think that is only a Warning that states you you are loading on your architecture BertForMultiLable the Weights from pretrained model that was not trained for that specific tasks. Similar warning discussion here The real error here it's another: IndexError: tuple index out of range. but for that you should attach some code and more information about what you are doing .
https://stackoverflow.com/questions/59195071/
Text classification with torchnlp
i'm trying to build a neural network using pytorch-nlp (https://pytorchnlp.readthedocs.io/en/latest/). My intent is to build a network like this: Embedding layer (uses pytorch standard layer and from_pretrained method) Encoder with LSTM (also uses standard nn.LSTM) Attention mechanism (uses torchnlp.nn.Attention) Decoder siwth LSTM (as encoder) Linear layer standard I'm encountering a major problem with the dimensions of the input sentences (each word is a vector) but most importantly with the attention layer : I don't know how to declare it because i need the exact dimensions of the output from the encoder, but the sequences have varying dimensions (corresponding to the fact that sentences have different number of words). I've tried to look at torch.nn.utils.rnn.pad_packed_sequence and torch.nn.utils.rnn.pack_padded_sequence since they're supported by LSTM, but i cannot find the solution. Can anyone help me? EDIT I thought about padding all sequences to a specific dimension, but I don't want to truncate longer sequences because I want to keep all the information.
You are on the right track with padding all sequences to a specific dimension. You will have to pick a dimension that is larger than "most" of your sentences but you will need to cutoff some sentences. This blog article should help.
https://stackoverflow.com/questions/59215618/
PyTorch - to NumPy yields unsized object?
Converting a PyTorch tensor to NumPy I get print(nn_result.shape) # (2433, 2) np_result = torch.argmax(nn_result).numpy() type(np_result) # <type 'numpy.ndarray'> print(len(np_result)) TypeError: len() of unsized object Why? I thought per documentation the numpy() function would return a proper ndarray, yet it seems to be incomplete somehow?
Perhaps you'd want to use torch.argmax(nn_result, dim=1) ? Since dim defaults to 0, it returns just a single number constructed as a tensor. Let me illustrate with the below example: >>> x = np.array(1) >>> x.shape () >>> len(x) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: len() of unsized object >>> x = np.array([1]) >>> x.shape (1,) >>> len(x) 1 Essentially np.array will take up any object type that you construct with. In the first case, object is not an array because of which you do not see a valid shape. Since it is not an array calling len throws an error. torch.argmax with dim=0 returns a tensor as seen in the first case of the above example and hence the error.
https://stackoverflow.com/questions/59217874/
PyTorch vectorise sum lookup quantity into buckets
Using PyTorch, I have figured out the following code for calculating totals of an item's property by some "bucket index": DATASET_SIZE = 10 NUM_BUCKETS = 4 bucket_assignment = torch.tensor([0,1,2,3,0,1,2,3,0,1], dtype = torch.long) values_to_add = torch.tensor([1,2,3,4,5,6,7,8,9,10], dtype = torch.float) buckets = torch.zeros(NUM_BUCKETS, dtype = torch.float) buckets.index_add_(0, bucket_assignment, values_to_add) # Buckets is now tensor([15., 18., 10., 12.]) In my case this is specifically to check allocation bounds on a problem, and later code checks that no bucket is under- or over- allocated. I would like to check multiple different possible assignments at once (and later pick a best option, code not shown). I thought I could do this by adding another dimension to bucket_assignment plus to buckets and have each row be a different set of assignments. However, this does not work as intended, because the second argument of index_add_ must be a simple vector, I cannot pass in any higher rank tensor. E.g. BATCH_SIZE = 2 DATASET_SIZE = 5 NUM_BUCKETS = 3 bucket_assignment = torch.tensor([[0,1,2,0,1], [1,1,1,2,1]], dtype = torch.long) values_to_add = torch.tensor([1,2,3,4,5], dtype = torch.float) buckets = torch.zeros(BATCH_SIZE, NUM_BUCKETS, dtype = torch.float) buckets.index_add_(0, bucket_assignment, values_to_add) I would like to get this result: tensor([[5., 7., 3.], [ 0., 11., 4.]]) Instead, I get an error: RuntimeError: invalid argument 3: Index is supposed to be a vector at ../aten/src/TH/generic/THTensorEvenMoreMath.cpp:733 That's not unexpected due to the limitations of .index_add, but I don't know how to progress. I am not sure what other approach would allow me to solve this problem in PyTorch - is there some other torch method I could use that would allow me to achieve the same thing. The main goal here is vectorisation and avoiding loops in Python, as in reality the batch sizes are large and I will be taking advantage of GPU acceleration.
If the batch size is the problem you could use torch.masked_select to get the values to add up for each bucket torch.masked_select(values_to_add, bucket_assignment == bucket_num), where PyTorch will broadcast the values_to_add and then only iterate over the buckets in plain python like so: def bucket_sizes(bucket_num): mask = bucket_assignment == bucket_num buckets = torch.masked_select(values_to_add, mask) buckets = torch.split(buckets, list(mask.sum(dim=1))) return [bucket.sum() for bucket in buckets] torch.tensor([bucket_sizes(i) for i in range(NUM_BUCKETS)]).T
https://stackoverflow.com/questions/59219635/
how to convert mnist images to variables images and labels
I have a code as below: dataset = MNIST(path=data_path, download=True, shuffle=True) if train: images, labels = dataset.get_train() else: images, labels = dataset.get_test() images, labels = images[:n_examples], labels[:n_examples] images, labels = iter(images.view(-1, 784) / 255), iter(labels) but when i run it, it gives me this error: Traceback (most recent call last): File "C:\Users\Ati\Downloads\Compressed\bindsnet_experiments- master\experiments\mnist\two_layer_backprop.py", line 135, in <module> images, labels = dataset.get_train() AttributeError: 'TorchvisionDatasetWrapper' object has no attribute 'get_train' I think because get_train() is out of date , it doesn’t support by torchvision But i tested different ways for converting mnist data to images and labels variables Who know how could i change it when get_train() doesn’t work I will appreciate your help if someone helps me on this
Yes, it looks like class does not exist in the package anymore. I was able to find the source code for the package you are looking for: import os import functools import operator import gzip import struct import array import tempfile try: from urllib.request import urlretrieve except ImportError: from urllib import urlretrieve # py2 try: from urllib.parse import urljoin except ImportError: from urlparse import urljoin import numpy __version__ = '0.2.2' # `datasets_url` and `temporary_dir` can be set by the user using: # >>> mnist.datasets_url = 'http://my.mnist.url' # >>> mnist.temporary_dir = lambda: '/tmp/mnist' datasets_url = 'http://yann.lecun.com/exdb/mnist/' temporary_dir = tempfile.gettempdir class IdxDecodeError(ValueError): """Raised when an invalid idx file is parsed.""" pass def download_file(fname, target_dir=None, force=False): """Download fname from the datasets_url, and save it to target_dir, unless the file already exists, and force is False. Parameters ---------- fname : str Name of the file to download target_dir : str Directory where to store the file force : bool Force downloading the file, if it already exists Returns ------- fname : str Full path of the downloaded file """ target_dir = target_dir or temporary_dir() target_fname = os.path.join(target_dir, fname) if force or not os.path.isfile(target_fname): url = urljoin(datasets_url, fname) urlretrieve(url, target_fname) return target_fname def parse_idx(fd): """Parse an IDX file, and return it as a numpy array. Parameters ---------- fd : file File descriptor of the IDX file to parse endian : str Byte order of the IDX file. See [1] for available options Returns ------- data : numpy.ndarray Numpy array with the dimensions and the data in the IDX file 1. https://docs.python.org/3/library/struct.html #byte-order-size-and-alignment """ DATA_TYPES = {0x08: 'B', # unsigned byte 0x09: 'b', # signed byte 0x0b: 'h', # short (2 bytes) 0x0c: 'i', # int (4 bytes) 0x0d: 'f', # float (4 bytes) 0x0e: 'd'} # double (8 bytes) header = fd.read(4) if len(header) != 4: raise IdxDecodeError('Invalid IDX file, ' 'file empty or does not contain a full header.') zeros, data_type, num_dimensions = struct.unpack('>HBB', header) if zeros != 0: raise IdxDecodeError('Invalid IDX file, ' 'file must start with two zero bytes. ' 'Found 0x%02x' % zeros) try: data_type = DATA_TYPES[data_type] except KeyError: raise IdxDecodeError('Unknown data type ' '0x%02x in IDX file' % data_type) dimension_sizes = struct.unpack('>' + 'I' * num_dimensions, fd.read(4 * num_dimensions)) data = array.array(data_type, fd.read()) data.byteswap() # looks like array.array reads data as little endian expected_items = functools.reduce(operator.mul, dimension_sizes) if len(data) != expected_items: raise IdxDecodeError('IDX file has wrong number of items. ' 'Expected: %d. Found: %d' % (expected_items, len(data))) return numpy.array(data).reshape(dimension_sizes) def download_and_parse_mnist_file(fname, target_dir=None, force=False): """Download the IDX file named fname from the URL specified in dataset_url and return it as a numpy array. Parameters ---------- fname : str File name to download and parse target_dir : str Directory where to store the file force : bool Force downloading the file, if it already exists Returns ------- data : numpy.ndarray Numpy array with the dimensions and the data in the IDX file """ fname = download_file(fname, target_dir=target_dir, force=force) fopen = gzip.open if os.path.splitext(fname)[1] == '.gz' else open with fopen(fname, 'rb') as fd: return parse_idx(fd) def train_images(): """Return train images from Yann LeCun MNIST database as a numpy array. Download the file, if not already found in the temporary directory of the system. Returns ------- train_images : numpy.ndarray Numpy array with the images in the train MNIST database. The first dimension indexes each sample, while the other two index rows and columns of the image """ return download_and_parse_mnist_file('train-images-idx3-ubyte.gz') def test_images(): """Return test images from Yann LeCun MNIST database as a numpy array. Download the file, if not already found in the temporary directory of the system. Returns ------- test_images : numpy.ndarray Numpy array with the images in the train MNIST database. The first dimension indexes each sample, while the other two index rows and columns of the image """ return download_and_parse_mnist_file('t10k-images-idx3-ubyte.gz') def train_labels(): """Return train labels from Yann LeCun MNIST database as a numpy array. Download the file, if not already found in the temporary directory of the system. Returns ------- train_labels : numpy.ndarray Numpy array with the labels 0 to 9 in the train MNIST database. """ return download_and_parse_mnist_file('train-labels-idx1-ubyte.gz') def test_labels(): """Return test labels from Yann LeCun MNIST database as a numpy array. Download the file, if not already found in the temporary directory of the system. Returns ------- test_labels : numpy.ndarray Numpy array with the labels 0 to 9 in the train MNIST database. """ return download_and_parse_mnist_file('t10k-labels-idx1-ubyte.gz') You can store this in any file, import that file and use the functions as you need (without creating the MNIST object). Hope this helps. Good luck.
https://stackoverflow.com/questions/59223995/
Text generation using huggingface's distilbert models
I've been struggling with huggingface's DistilBERT model for some time now, since the documentation seems very unclear and their examples (e.g. https://github.com/huggingface/transformers/blob/master/notebooks/Comparing-TF-and-PT-models-MLM-NSP.ipynb and https://github.com/huggingface/transformers/tree/master/examples/distillation) are extremely thick and the thing they are showcasing doesn't seem well documented. I'm wondering if anyone here has any experience and knows of some good code example for basic in-python usage of their models. Namely: How to properly decode the output of the model into actual text (no matter how I change its shape the tokenizer seems willing to decode it and always yields some sequence of [UNK] tokens) How to actually use their schedulers+optimizers to train a model for a simple text to text task.
To decode the output, you can do prediction_as_text = tokenizer.decode(output_ids, skip_special_tokens=True) output_ids contains the generated token ids. It can also be a batch (output ids at every row), then the prediction_as_text will also be a 2D array containing text at every row. skip_special_tokens=True filters out the special tokens used in the training such as (end of sentence), (start of sentence), etc. These special tokens vary from model to model of course but almost every model has such special tokens used during training and inference. There is not an easy way to get rid of unknown tokens[UNK]. The models have limited vocabulary. If a model encounters a subword that is not in its in vocabulary, it is replaced by a special unknown token and the model is trained with these tokens. So, it also learn to generate [UNK]. There are various way to deal with it such as replacing it with the second-highest probable token, or using beam search and taking the most probable sentence that do not contain any unknown tokens. However, if you really want to get rid of these, you should rather use a model that uses Byte Pair Encoding. It solves the problem of unknown words completely. As you can read in this link, Bert and DistilBert uses subwork tokenization and have such a limitation. https://huggingface.co/transformers/tokenizer_summary.html To use the schedulers and optimizers, you should use the class Trainer and TrainingArguments. Below I posted an example from one of my own projects. output_dir=model_directory, num_train_epochs=args.epochs, per_device_train_batch_size=args.batch_size, per_device_eval_batch_size=args.batch_size, warmup_steps=500, weight_decay=args.weight_decay, logging_dir=model_directory, logging_steps=100, do_eval=True, evaluation_strategy='epoch', learning_rate=args.learning_rate, load_best_model_at_end=True, # the last checkpoint is the best model wrt metric_for_best_model metric_for_best_model='eval_loss', lr_scheduler_type = 'linear' greater_is_better=False, save_total_limit=args.epochs if args.save_total_limit == -1 else args.save_total_limit, ) trainer = Seq2SeqTrainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=val_dataset, optimizers=[torch.optim.Adam(params=model.parameters(), lr=args.learning_rate), None], // optimizers tokenizer=tokenizer, ) For other scheduler types, see this link: https://huggingface.co/transformers/main_classes/optimizer_schedules.html
https://stackoverflow.com/questions/59240668/
CTC: blank must be in label range
summary I'm adding alphabets to captcha recognition, but pytorch's CTC seems to not working properly when alphabets are added. What I've tried At first, I modified BLANK_LABEL to 62 since there are 62 labels(0-9, a-z, A-Z), but it gives me runtime error blank must be in label range. I also tried BLANK_LABEL=0 and then assigning 1~63 as nonblank labels but it outputs NaN as loss. The code This is the colab link for the current version of my code: here below are just core parts of the code. Constants: DATASET_PATH = "/home/ik1ne/Downloads/numbers" MODEL_PATH = "/home/ik1ne/Downloads" BATCH_SIZE = 50 TRAIN_BATCHES = 180 TEST_BATCHES = 20 TOTAL_BATCHES = TRAIN_BATCHES+TEST_BATCHES TOTAL_DATASET = BATCH_SIZE*TOTAL_BATCHES BLANK_LABEL = 63 dataset generation: !pip install captcha from captcha.image import ImageCaptcha import itertools import os import random import string if not os.path.exists(DATASET_PATH): os.makedirs(DATASET_PATH) characters = "0123456789"+string.ascii_lowercase + string.ascii_uppercase while(len(list(Path(DATASET_PATH).glob('*'))) < TOTAL_BATCHES): captcha_str = "".join(random.choice(characters) for x in range(6)) if captcha_str in list(Path(DATASET_PATH).glob('*')): continue ImageCaptcha().write(captcha_str, f"{DATASET_PATH}/{captcha_str}.png") dataset: def convert_strseq_to_numseq(s): for c in s: if c >= '0' and c <= '9': return int(c) elif c>='a' and c <='z': return ord(c)-ord('a')+10 else: return ord(c)-ord('A')+36 class CaptchaDataset(Dataset): """CAPTCHA dataset.""" def __init__(self, root_dir, transform=None): self.root_dir = root_dir self.image_paths = list(Path(root_dir).glob('*')) self.transform = transform def __getitem__(self, index): image = Image.open(self.image_paths[index]) if self.transform: image = self.transform(image) label_sequence = [convert_strseq_to_numseq(c) for c in self.image_paths[index].stem] return (image, torch.tensor(label_sequence)) def __len__(self): return len(self.image_paths) model: class StackedLSTM(nn.Module): def __init__(self, input_size=60, output_size=11, hidden_size=512, num_layers=2): super(StackedLSTM, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.dropout = nn.Dropout() self.fc = nn.Linear(hidden_size, output_size) self.lstm = nn.LSTM(input_size, hidden_size, num_layers) def forward(self, inputs, hidden): batch_size, seq_len, input_size = inputs.shape outputs, hidden = self.lstm(inputs, hidden) outputs = self.dropout(outputs) outputs = torch.stack([self.fc(outputs[i]) for i in range(width)]) outputs = F.log_softmax(outputs, dim=2) return outputs, hidden def init_hidden(self, batch_size): weight = next(self.parameters()).data return (weight.new(self.num_layers, batch_size, self.hidden_size).zero_(), weight.new(self.num_layers, batch_size, self.hidden_size).zero_()) net = StackedLSTM().to(device) training: net.train() # set network to training phase epochs = 30 # for each pass of the training dataset for epoch in range(epochs): train_loss, train_correct, train_total = 0, 0, 0 h = net.init_hidden(BATCH_SIZE) # for each batch of training examples for batch_index, (inputs, targets) in enumerate(train_dataloader): inputs, targets = inputs.to(device), targets.to(device) h = tuple([each.data for each in h]) BATCH_SIZE, channels, height, width = inputs.shape # reshape inputs: NxCxHxW -> WxNx(HxC) inputs = (inputs .permute(3, 0, 2, 1) .contiguous() .view((width, BATCH_SIZE, -1))) optimizer.zero_grad() # zero the parameter gradients outputs, h = net(inputs, h) # forward pass # compare output with ground truth input_lengths = torch.IntTensor(BATCH_SIZE).fill_(width) target_lengths = torch.IntTensor([len(t) for t in targets]) loss = criterion(outputs, targets, input_lengths, target_lengths) loss.backward() # backpropagation nn.utils.clip_grad_norm_(net.parameters(), 10) # clip gradients optimizer.step() # update network weights # record statistics prob, max_index = torch.max(outputs, dim=2) train_loss += loss.item() train_total += len(targets) for i in range(BATCH_SIZE): raw_pred = list(max_index[:, i].cpu().numpy()) pred = [c for c, _ in groupby(raw_pred) if c != BLANK_LABEL] target = list(targets[i].cpu().numpy()) if pred == target: train_correct += 1 # print statistics every 10 batches if (batch_index + 1) % 10 == 0: print(f'Epoch {epoch + 1}/{epochs}, ' + f'Batch {batch_index + 1}/{len(train_dataloader)}, ' + f'Train Loss: {(train_loss/1):.5f}, ' + f'Train Accuracy: {(train_correct/train_total):.5f}') train_loss, train_correct, train_total = 0, 0, 0
This error will occur when the index of blank is larger than the total number of classes, which equals number of chars + blank. What's more, the index starts from 0, instead of 1, so if you have 62 characters in total, their index should be 0-61 and the index of blank should be 62 instead of 63. (Or you can set blank as 0, other characters from 1-62) You should also check the shape of the output tensor, it should has shape [T, B, C], where T is the time step length, B is the batch size, C is the class num, remember to add blank in to the class num or you will meet the problem
https://stackoverflow.com/questions/59242835/
Why does torch.from_numpy require a different byte ordering while matplotlib doesn't?
Here is a piece of code (running on Linux CentOS 7.7.1908, x86_64) import torch #v1.3.0 import numpy as np #v1.14.3 import matplotlib.pyplot as plt from astropy.io.fits import getdata #v3.0.2 data, hdr = getdata("afile.fits", 0, header=True) #gives dtype=float32 2d array plt.imshow(data) plt.show() This gives a nice 512x512 image Now, I would like to convert "data" into a PyTorch tensor: a = torch.from_numpy(data) Although, PyTorch raises: ValueError: given numpy array has byte order different from the native byte order. Conversion between byte orders is currently not supported. Well, I have tried different manipulations with no success: ie. byteswap(), copy() An idea? PS: the same error occurs when I transfer my data to Mac OSX (Mojave) while still matplotlib is ok.
FITS stores data in big-endian byte ordering (at the time FITS was developed this was a more common machine architecture; sadly the standard has never been updated to allow flexibility on this, although it could easily be done with a single header keyword to indicate endianness of the data...) According to the Numpy docs Numpy arrays report the endianness of the underlying data as part of its dtype (e.g. a dtype of '>i' means big-endian ints, and 'and change the array's dtype to reflect the new byte order. Your solution of calling .astype(np.float32) should work, but that's because the np.float32 dtype is explicitly little-endian, so .astype(...) copies an existing array and converts the data in that array, if necessary, to match that dtype. I just wanted to explain exactly why that works, since it might be otherwise unclear why you're doing that. As for matplotlib it doesn't really have much to do with your question. Numpy arrays can transparently perform operations on data that does not match the endianness of your machine architecture, by automatically performing byte swaps as necessary. Matplotlib and many other scientific Python libraries work directly with Numpy arrays and thus automatically benefit from its transparent handling of endianness. It just happens that PyTorch (in part because of its very high performance and GPU-centric data handling model) requires you to hand it data that's already in little-endian order, perhaps just to avoid ambiguity. But that's particular to PyTorch and is not specifically a contrast with matplotlib.
https://stackoverflow.com/questions/59247385/
Using Pytorch's dataloaders & transforms with sklearn
I have been using pytorch a lot and got used to their dataloaders and transforms, in particular when it comes to data augmentation, as they're very user-friendly and easy to understand. However, I need to run some ML models from sklearn. Is there a way to use pytorch's dataloaders for sklearn ?
Yes, you can. You can do this with sklearn's partial_fit method. Read HERE. 6.1.3. Incremental learning Finally, for 3. we have a number of options inside scikit-learn. Although all algorithms cannot learn incrementally (i.e. without seeing all the instances at once), all estimators implementing the partial_fit API are candidates. Actually, the ability to learn incrementally from a mini-batch of instances (sometimes called “online learning”) is key to out-of-core learning as it guarantees that at any given time there will be only a small amount of instances in the main memory. Choosing a good size for the mini-batch that balances relevancy and memory footprint could involve some tuning [1]. Not all algorithms can do this, however. Then, you can use pytorch's dataloader to preprocess the data and feed it in batches to partial_fit.
https://stackoverflow.com/questions/59253507/
State persistence in shared LSTM layers in Keras
I am trying to use a shared LSTM layer with state in a Keras model, but it seems that the internal state is modified by each parallel use. This raises two questions: When training a model with a shared LSTM layer and using stateful=True, are the parallel uses updating the same state also during training? If my observation is valid, is there a way to use weight-sharing LSTMs such that the state is stored independently for each of the parallel uses? The code below exemplifies the problem with three sequences sharing the LSTM. The prediction of a full input is compared with the result from splitting the prediction input into two halves and feeding them into the network consecutively. What can be observed, is that the a1 is the same as the first half of aFull, meaning that the the uses of the LSTM really are in parallel with independent states during the first prediction. I.e., z1 is not affected by the parallel call creating z2 and z3. But a2 is different from the second half of aFull, so there is some interaction between the states of the parallel uses. What I was hoping is that the concatenation of the two pieces a1 and a2 would be the same as the result from calling the prediction with a longer input sequence, but this doesn't seem to be the case. A further concern is that when this kind of interaction takes place in the prediction, is it also happening during the training. import keras import keras.backend as K import numpy as np nOut = 3 xShape = (3, 50, 4) inShape = (xShape[0], None, xShape[2]) batchInShape = (1, ) + inShape x = np.random.randn(*xShape) # construct network xIn = keras.layers.Input(shape=inShape, batch_shape=batchInShape) # shared LSTM layer sharedLSTM = keras.layers.LSTM(units=nOut, stateful=True, return_sequences=True, return_state=False) # split the input on the first axis x1 = keras.layers.Lambda(lambda x: x[:,0,:,:])(xIn) x2 = keras.layers.Lambda(lambda x: x[:,1,:,:])(xIn) x3 = keras.layers.Lambda(lambda x: x[:,2,:,:])(xIn) # pass each input through the LSTM z1 = sharedLSTM(x1) z2 = sharedLSTM(x2) z3 = sharedLSTM(x3) # add a singleton dimension y1 = keras.layers.Lambda(lambda x: K.expand_dims(x, axis=1))(z1) y2 = keras.layers.Lambda(lambda x: K.expand_dims(x, axis=1))(z2) y3 = keras.layers.Lambda(lambda x: K.expand_dims(x, axis=1))(z3) # combine the outputs y = keras.layers.Concatenate(axis=1)([y1, y2, y3]) model = keras.models.Model(inputs=xIn, outputs=y) model.compile(loss='mse', optimizer='adam') model.summary() # no need to train, since we're interested only what is happening mechanically # reset to a known state and predict for full input model.reset_states() aFull = model.predict(x[np.newaxis,:,:,:]) # reset to a known state and predict for the same input, but in two pieces model.reset_states() a1 = model.predict(x[np.newaxis,:,:xShape[1]//2,:]) a2 = model.predict(x[np.newaxis,:,xShape[1]//2:,:]) # combine the pieces aSplit = np.concatenate((a1, a2), axis=2) print('full diff: {}, first half diff: {}, second half diff: {}'.format(str(np.sum(np.abs(aFull - aSplit))), str(np.sum(np.abs(aFull[:,:,:xShape[1]//2,:] - aSplit[:,:,:xShape[1]//2,:]))), str(np.sum(np.abs(aFull[:,:,xShape[1]//2:,:] - aSplit[:,:,xShape[1]//2:,:]))))) Update: The behaviour described above was observed with Keras using Tensorflow 1.14 and 1.15 as the backend. Running the same code with tf2.0 (with the adjusted imports) changes the result so that a1 is no longer the same as the first half of aFull. This can be still accomplished by setting stateful=False in the layer instantiation. This would suggest to me that the way I'm trying to use the recursive layer with shared parameters, but own states for parallel uses, is not really possible like this. Update 2: It seems that the same functionality has been missed by also other earlier: closed, unanswered question at Keras' github. For a comparison, here is a scribbling in pytorch (the first time I've tried to use it) implementing a simple network with N parallel LSTMs sharing the weights, but having independent states. In this case the states are stored explicitly in a list and provided to the LSTM cell manually. import torch import numpy as np class sharedLSTM(torch.nn.Module): def __init__(self, batchSz, nBands, nDims, outDim): super(sharedLSTM, self).__init__() self.internalLSTM = torch.nn.LSTM(input_size=nDims, hidden_size=outDim, num_layers=1, bias=True, batch_first=True) allStates = list() for bandIdx in range(nBands): h_0 = torch.zeros(1, batchSz, outDim) c_0 = torch.zeros(1, batchSz, outDim) allStates.append((h_0, c_0)) self.allStates = allStates self.nBands = nBands def forward(self, x): allOut = list() for dimIdx in range(self.nBands): thisSlice = x[:,dimIdx,:,:] # (batchSz, nSteps, nFeats) thisState = self.allStates[dimIdx] thisY, thisState = self.internalLSTM(thisSlice, thisState) self.allStates[dimIdx] = thisState allOut.append(thisY[:,None,:,:]) # => (batchSz, 1, nSteps, nFeats) y = torch.cat(allOut, dim=1) # => (batchSz, nDims, nSteps, nFeats) return y def resetStates(self): for bandIdx in range(nBands): self.allStates[bandIdx][0][:] = 0.0 self.allStates[bandIdx][1][:] = 0.0 batchSz = 5 nBands = 3 nFeats = 4 nOutDims = 2 net = sharedLSTM(batchSz, nBands, nFeats, nOutDims) net = net.float() print(net) N = 20 x = torch.from_numpy(np.random.rand(batchSz, nBands, N, nFeats)).float() x1 = x[:, :, :N//2, :] x2 = x[:, :, N//2:, :] aa = net.forward(x) net.resetStates() a1 = net.forward(x1) a2 = net.forward(x2) print('(with reset) first half abs diff: {}'.format(str(torch.sum(torch.abs(a1 - aa[:,:,:N//2,:])).detach().numpy()))) print('(with reset) second half abs diff: {}'.format(str(torch.sum(torch.abs(a2 - aa[:,:,N//2:,:])).detach().numpy()))) Result: the output is the same regardless if we do the prediction in one go or in pieces. I've tried to replicate this in Keras using sub-classing, but without success: import keras import numpy as np class sharedLSTM(keras.Model): def __init__(self, batchSz, nBands, nDims, outDim): super(sharedLSTM, self).__init__() self.internalLSTM = keras.layers.LSTM(units=outDim, stateful=True, return_sequences=True, return_state=True) self.internalLSTM.build((batchSz, None, nDims)) self.internalLSTM.reset_states() allStates = list() allSlicers = list() for bandIdx in range(nBands): allStates.append(None) allSlicers.append(keras.layers.Lambda(lambda x, b: x[:, :, b, :], arguments = {'b' : bandIdx})) self.allStates = allStates self.allSlicers = allSlicers self.Concat = keras.layers.Lambda(lambda x: keras.backend.concatenate(x, axis=2)) self.nBands = nBands def call(self, x): allOut = list() for bandIdx in range(self.nBands): thisSlice = self.allSlicers[bandIdx]( x ) thisState = self.allStates[bandIdx] thisY, *thisState = self.internalLSTM(thisSlice, initial_state=thisState) self.allStates[bandIdx] = thisState.copy() allOut.append(thisY[:,:,None,:]) y = self.Concat( allOut ) return y batchSz = 1 nBands = 3 nFeats = 4 nOutDims = 2 N = 20 model = sharedLSTM(batchSz, nBands, nFeats, nOutDims) model.compile(optimizer='SGD', loss='mae') x = np.random.rand(batchSz, N, nBands, nFeats) x1 = x[:, :N//2, :, :] x2 = x[:, N//2:, :, :] aa = model.predict(x) model.reset_states() a1 = model.predict(x1) a2 = model.predict(x2) print('(with reset) first half abs diff: {}'.format(str(np.sum(np.abs(a1 - aa[:,:N//2,:,:]))))) print('(with reset) second half abs diff: {}'.format(str(np.sum(np.abs(a2 - aa[:,N//2:,:,:]))))) If you now ask "why don't you then use torch and shut up?", the answer is that the surrounding experimental framework has been built assuming Keras and changing it would be a non-negligible amount of work.
Based on my current understanding of the behaviour of LSTMs (and other RNNs) in Keras is that using a shared LSTM layer in a stateful=True mode does not work as one would expect and there is only one state variable that gets updated through all the parallel uses. So the answers to the questions appear to be: Yes, they are. The processing runs over one of the many parallel sequences, stores the state at the end, and uses this as the initial state for the second parallel sequence, and so forth. Yes, but it requires some work. See below for the details. I've managed to accomplish handling the states in two ways. First is deriving sub-classes from Keras' LSTM and LSTMCell, and overloading LSTMCell.call() to handle the parallel data streams by splitting the input, and storing and recovering the state of each parallel stream. A drawback here is that the input shape to an RNN is fixed to be 3D, which means that the parallel inputs need to be reshaped into the feature dimension along with the real features. The second approach is to create a wrapper Layer not completely dissimilar to the sharedLSTM-Model in the question, containing slicing of the input to parallel streams, calling the internal LSTM with the correct state for each stream, and storing the returned states. The state storage update in the list works through add_update() call inserted into the end of call(). This add_update() does not (seem to) work with Model, hence Layer. However, when run with Keras <2.3, the weights of the nested layers are not tracked or updated, so Keras 2.3+ or TF2 is needed.
https://stackoverflow.com/questions/59281849/
PyTorch: initializing weight with numpy array + create a constant tensor
I have the following code : self.wi = nn.Embedding(num_embeddings, embedding_dim) self.wj = nn.Embedding(num_embeddings1, embedding_dim) self.bi = nn.Embedding(num_embeddings, 1) self.bj = nn.Embedding(num_embeddings1, 1) self.wi.weight.data.uniform_(-1, 1) self.wj.weight.data.uniform_(-1, 1) self.bi.weight.data.zero_() self.bj.weight.data.zero_() I want to initialize the weights with numpy array, and I want to create a constant tensor, which is also a numpy array. I am new to PyTorch, and I appreciate any help.
You can initialize embedding layers with the function nn.Embedding.from_pretrained(). In your specific case, you would still have to firstly convert the numpy.array to a torch.Tensor, but otherwise it is very straightforward: import torch as t import torch.nn as nn import numpy as np # This can be whatever initialization you want to have init_array = np.zeros([num_embeddings, embedding_dims]) # As @Daniel Marchand mentioned in his answer, # you do have to cast it explicitly as a tensor, otherwise it won't work. wi = nn.Embedding.from_pretrained(t.tensor(init_array), freeze=False) The parameter freeze=False is important if you still want to train your network afterwards, as otherwise you would keep the embeddings at the same constant values. Generally, .from_pretrained is used to "transfer" learned embeddings, but it does work for your case, too.
https://stackoverflow.com/questions/59294274/
Using tensorboard in pytorch, but get blank page?
I am using tensorboard in pytorch 1.3.1, and I did exactly the same in the pytorch docs for tensorboard. After running tensorboard --logdir=runs, I got this enter image description here. $ tensorboard --logdir=runs TensorFlow installation not found - running with reduced feature set. Serving TensorBoard on localhost; to expose to the network, use a proxy or pass --bind_all TensorBoard 2.1.0 at http://localhost:6006/ (Press CTRL+C to quit) And after opening http://localhost:6006/, I got blank page like this I also tried tensorboardX, and got the same result. Could you please tell how to solve the problem? thx.
I am using Torch 1.4.0 on Windows and I had the same issue. Turns out I had installed the 2.x version of Tensorboard. I reverted back to 1.15.0 and it solved the issue.
https://stackoverflow.com/questions/59308202/
How to convert Conv1d into Conv2d? [PyTorch]
Is it possible with PyTorch to use Conv2d to perform a Conv1d? The question may seem weird, but I need to use a tool that is not compatible with conv1d, but it works with conv2d. What if I have Conv1d(in,out, kernel_size=3, stride=stride, padding=1, bias=False)? May unsqueeze help me? I have the same problem with AvgPool1d (-> AvgPool2d) and MaxPool1d (-> MaxPool2d).
A Conv2D is mostly a generalized version of Conv1D. You can of course use a degenerate version of Conv2D to reproduce a 1D convolution - You'll need to add in another dimension to the data: data_pnt = data_pnt [..., numpy.newaxis] You'll also need to specify the kernel size - You'll be choosing a 1D kernel - for example: Conv2d(in,out, kernel_size=(3,1), <Other Parameters>)
https://stackoverflow.com/questions/59308390/
Is Pytorch DataLoader Iteration order stable?
Is the iteration order for a Pytorch Dataloader guaranteed to be the same (under mild conditions)? For instance: dataloader = DataLoader(my_dataset, batch_size=4, shuffle=True, num_workers=4) print("run 1") for batch in dataloader: print(batch["index"]) print("run 2") for batch in dataloader: print(batch["index"]) So far, I've tried testing it and it appears to not be fixed, same order for both runs. Is there a way to make the order the same? Thanks edit: i have also tried doing unlabeled_sampler = data.sampler.SubsetRandomSampler(unlabeled_indices) unlabeled_dataloader = data.DataLoader(train_dataset, sampler=unlabeled_sampler, batch_size=args.batch_size, drop_last=False) and then iterating through the dataloader twice, but the same non-determinism results.
The short answer is no, when shuffle=True the iteration order of a DataLoader isn't stable between iterations. Each time you iterate on your loader the internal RandomSampler creates a new random order. One way to get a stable shuffled DataLoader is to create a Subset dataset using a shuffled set of indices. shuffled_dataset = torch.utils.data.Subset(my_dataset, torch.randperm(len(my_dataset)).tolist()) dataloader = DataLoader(shuffled_dataset, batch_size=4, num_workers=4, shuffled=False)
https://stackoverflow.com/questions/59314174/
install conda on windows with conda or pip
I am trying to install pytorch on my window. First, I get command conda install pytorch torchvision cpuonly -c pytorchfrom here (PyTorch Build:Stable(1.3);Your OS:Windows;Package:Conda;Language:Python3.6;CUDA:None), there are some problems described as followings: **(python36) C:\Users\li_dan0109>conda install pytorch torchvision cpuonly -c pytorch Collecting package metadata (current_repodata.json): done Solving environment: failed with initial frozen solve. Retrying with flexible solve. Collecting package metadata (repodata.json): done Solving environment: failed with initial frozen solve. Retrying with flexible solve. PackagesNotFoundError: The following packages are not available from current channels: - pytorch Current channels: - https://conda.anaconda.org/pytorch/win-32 - https://conda.anaconda.org/pytorch/noarch - https://repo.anaconda.com/pkgs/main/win-32 - https://repo.anaconda.com/pkgs/main/noarch - https://repo.anaconda.com/pkgs/r/win-32 - https://repo.anaconda.com/pkgs/r/noarch - https://repo.anaconda.com/pkgs/msys2/win-32 - https://repo.anaconda.com/pkgs/msys2/noarch To search for alternate channels that may provide the conda package you're looking for, navigate to https://anaconda.org and use the search bar at the top of the page.** Then I also switch pip install by the command pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html Then I met this error: **(python36) C:\Users\li_dan0109>pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html Looking in links: https://download.pytorch.org/whl/torch_stable.html ERROR: Could not find a version that satisfies the requirement torch==1.3.1+cpu (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2) ERROR: No matching distribution found for torch==1.3.1+cpu** I really don't know how to fix it, please help me and thank you very much!
It looks as though you may have the 32-bit installation of Python, in which case you're issue is this: #16633. Just be aware, that pyTorch doesn't work on 32-bit systems. Please use Windows and Python 64-bit version.
https://stackoverflow.com/questions/59315344/
Pytorch Deep Learning - Class Model() and training function
I am new to Pytorch and I am going through this tutorial to figure out how to do deep learning with this library. I have problem figuring out part of the code. There is a class called Net and an object called model instantiated from it. Then there is the training function called train(epoch). In the next line in the train function body I see this: model.train() which I can't make any sense of. Would you please help me in understanding this part of the code? how we are calling a method of a class when this method has not been defined inside the class? and how come the method has the exact same name as function it has been called inside? This is the class definition: class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=3) self.conv2 = nn.Conv2d(32, 64, kernel_size=3) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(2304, 256) self.fc2 = nn.Linear(256, 17) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(x.size(0), -1) # Flatten layer x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) return F.sigmoid(x) model = Net() # On CPU # model = Net().cuda() # On GPU And this is the function defined after this class: def train(epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader): # data, target = data.cuda(async=True), target.cuda(async=True) # On GPU data, target = Variable(data), Variable(target) optimizer.zero_grad() output = model(data) loss = F.binary_cross_entropy(output, target) loss.backward() optimizer.step() if batch_idx % 10 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.data[0]))
train vs model.train The def train(epochs): ... is the method to train the model and is not an attribute of Net class. model is an object of Net class, that inherits from nn.Module. In PyTorch, all layers inherit from nn.Module and that gives them a lot of common functionality like model.children() or layer.children(), model.apply(), etc. The model.train() is similarly implemented in nn.Module. It doesn't actually train the model or any layer that inherits from nn.Module but sets it in train mode, so say it's equivalent to doing model.set_train(). There is an equivalent method model.eval() you would call in to set the evaluation mode before testing the model. Why do you even need it? There can be some parameters in a layer/model that are suppose to act differently while training and evaluation modes. The obvious example are BatchNorm's γ and β
https://stackoverflow.com/questions/59320800/
Using pretrained models in Pytorch for Semantic Segmentation, then training only the fully connected layers with our own dataset
I am learning Pytorch and trying to understand how the library works for semantic segmentation. What I've understood so far is that we can use a pre-trained model in pytorch. I've found an article which was using this model in the .eval() mode but I have not been able to find any tutorial on using such a model for training on our own dataset. I have a very small dataset and I need transfer learning to get results. My goal is to only train the FC layers with my own data. How is that achievable in Pytorch without complicating the code with OOP or so many .py files. I have been having a hard time figuring out such repos in github as I am not the most proficient person when it comes to OOP. I have been using Keras for Deep Learning until recently and there everything is easy and straightforward. Do I have the same options in Pycharm? I appreciate any guidance on this. I need to run a piece of code that does the semantic segmentation and I am really confused about many of the steps I need to take.
Assume you start with a pretrained model called model. All of this occurs before you pass the model any data. You want to find the layers you want to train by looking at all of them and then indexing them using model.children(). Running this command will show you all of the blocks and layers. list(model.children()) Suppose you have now found the layers that you want to finetune (your FC layers as you describe). If the layers you want to train are the last 5 you can grab all of the layers except for the last 5 in order to set their requires_grad params to False so they don't train when you run the training algorithm. list(model.children())[-5:] Remove those layers: layer_list = list(model.children())[-5:] Rebuild model using sequential: model_small = nn.Sequential(*list(model.children())[:-5]) Set requires_grad params to False: for param in model_small.parameters(): param.requires_grad = False Now you have a model called model_small that has all of the layers except the layers you want to train. Now you can reattach the layers that your removed and they will intrinsically have the requires_grad param set to True. Now when you train the model it will only update the weights on those layers. model_small.avgpool_1 = nn.AdaptiveAvgPool2d() model_small.lin1 = nn.Linear() model_small.logits = nn.Linear() model_small.softmax = nn.Softmax() model = model_small.to(device)
https://stackoverflow.com/questions/59321942/
Custom backward/optimization steps in pytorch-lightning
I would like to implement the training loop below in pytorch-lightning (to be read as pseudo-code). The peculiarity is that the backward and optimization steps are not performed for every batch. (Background: I am trying to implement a few-shots learning algorithm; although I need to make predictions at every step -- forward method -- I need to perform the gradient updates at random -- if- block. for batch in batches: x, y = batch loss = forward(x,y) optimizer.zero_grad() if np.random.rand() > 0.5: loss.backward() optimizer.step() My proposed solution entails implementing the backward and the optimizer_step methods as follows: def backward(self, use_amp, loss, optimizer): self.compute_grads = False if np.random.rand() > 0.5: loss.backward() nn.utils.clip_grad_value_(self.enc.parameters(), 1) nn.utils.clip_grad_value_(self.dec.parameters(), 1) self.compute_grads = True return def optimizer_step(self, current_epoch, batch_nb, optimizer, optimizer_i, second_order_closure=None): if self.compute_grads: optimizer.step() optimizer.zero_grad() return Note: In this way I need to store a compute_grads attribute at the class level. What is the "best-practice" way to implement it in pytorch-lightning? Is there a better way to use the hooks?
This is a good way to do it! that's what the hooks are for. There is a new Callbacks module that might also be helpful: https://pytorch-lightning.readthedocs.io/en/0.7.1/callbacks.html
https://stackoverflow.com/questions/59327048/
RuntimeError: cuda runtime error (710) : device-side assert triggered at
Traning the image classification with pytorch got following error messageK RuntimeError Traceback (most recent call last) in 29 print(len(train_loader.dataset),len(valid_loader.dataset)) 30 #break ---> 31 train_loss, train_acc ,model= train(model, device, train_loader, optimizer, criterion) 32 valid_loss, valid_acc,model = evaluate(model, device, valid_loader, criterion) 33 in train(model, device, iterator, optimizer, criterion) 21 acc = calculate_accuracy(fx, y) 22 #print("5.") ---> 23 loss.backward() 24 25 optimizer.step() ~/venv/lib/python3.7/site-packages/torch/tensor.py in backward(self, gradient, retain_graph, create_graph) 164 products. Defaults to False. 165 """ --> 166 torch.autograd.backward(self, gradient, retain_graph, create_graph) 167 168 def register_hook(self, hook): ~/venv/lib/python3.7/site-packages/torch/autograd/init.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables) 97 Variable._execution_engine.run_backward( 98 tensors, grad_tensors, retain_graph, create_graph, ---> 99 allow_unreachable=True) # allow_unreachable flag 100 101 RuntimeError: cuda runtime error (710) : device-side assert triggered at /pytorch/aten/src/THC/generic/THCTensorMath.cu:26 Related code block is here def train(model, device, iterator, optimizer, criterion): print('train') epoch_loss = 0 epoch_acc = 0 model.train() for (x, y) in iterator: #print(x,y) x,y = x.cuda(), y.cuda() #x = x.to(device) #y = y.to(device) #print('1') optimizer.zero_grad() #print('2') fx = model(x) #print('3') loss = criterion(fx, y) #print("4.loss->",loss) acc = calculate_accuracy(fx, y) #print("5.") loss.backward() optimizer.step() epoch_loss += loss.item() epoch_acc += acc.item() return epoch_loss / len(iterator), epoch_acc / len(iterator),model EPOCHS = 5 SAVE_DIR = 'models' MODEL_SAVE_PATH = os.path.join(SAVE_DIR, 'please.pt') from torch.utils.data import DataLoader best_valid_loss = float('inf') if not os.path.isdir(f'{SAVE_DIR}'): os.makedirs(f'{SAVE_DIR}') print("start") for epoch in range(EPOCHS): print('================================',epoch ,'================================') for i , (train_idx, valid_idx) in enumerate(zip(train_indexes, valid_indexes)): print(i,train_idx,valid_idx,len(train_idx),len(valid_idx)) traindf = df_train.iloc[train_index, :].reset_index() validdf = df_train.iloc[valid_index, :].reset_index() #traindf = df_train #validdf = df_train train_dataset = TrainDataset(traindf, mode='train', transforms=data_transforms) valid_dataset = TrainDataset(validdf, mode='valid', transforms=data_transforms) train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) valid_loader = DataLoader(valid_dataset, batch_size=batch_size, shuffle=False) print(len(train_loader.dataset),len(valid_loader.dataset)) #break train_loss, train_acc ,model= train(model, device, train_loader, optimizer, criterion) valid_loss, valid_acc,model = evaluate(model, device, valid_loader, criterion) if valid_loss < best_valid_loss: best_valid_loss = valid_loss torch.save(model,MODEL_SAVE_PATH) print(f'| Epoch: {epoch+1:02} | Train Loss: {train_loss:.3f} | Train Acc: {train_acc*100:05.2f}% | Val. Loss: {valid_loss:.3f} | Val. Acc: {valid_acc*100:05.2f}% |') splits = zip(train_indexes, valid_indexes) [ 3692 3696 3703 ... 30733 30734 30735] [ 0 1 2 ... 4028 4041 4046] [ 0 1 2 ... 30733 30734 30735] [3692 3696 3703 ... 7986 7991 8005] [ 0 1 2 ... 30733 30734 30735] [ 7499 7500 7502 ... 11856 11858 11860] [ 0 1 2 ... 30733 30734 30735] [11239 11274 11280 ... 15711 15716 15720] [ 0 1 2 ... 30733 30734 30735] [15045 15051 15053 ... 19448 19460 19474] [ 0 1 2 ... 30733 30734 30735] [18919 18920 18926 ... 23392 23400 23402] [ 0 1 2 ... 30733 30734 30735] [22831 22835 22846 ... 27118 27120 27124] [ 0 1 2 ... 27118 27120 27124] [26718 26721 26728 ... 30733 30734 30735]
What was your loss function? I got this error too. My problem was a multi-class classification and I was using a crossEntropy loss. As it say in the documentations, labels should be in the range [0, C-1] where C is number of classes. But my labels were not in the range and when I used proper values for labels, Everything was ok.
https://stackoverflow.com/questions/59331326/
Why Keras behave better than Pytorch under the same network configuration?
Recently, I have compared unet++ implementation of Keras version and Pytorch version on the same dataset. However, with Keras the loss decrease continuously and the accuracy is higher after 10 epochs, while with Pytorch the loss decrease unevenly and the accuracy is lower after 10 epochs. Anyone has met such problems and has any answers? the final pytorch training process is like: 2019-12-15 18:14:20 Epoch:9 Iter: 1214/1219 loss:0.464673 acc:0.581713 2019-12-15 18:14:21 Epoch:9 Iter: 1215/1219 loss:0.450462 acc:0.584101 2019-12-15 18:14:21 Epoch:9 Iter: 1216/1219 loss:0.744811 acc:0.293406 2019-12-15 18:14:22 Epoch:9 Iter: 1217/1219 loss:0.387612 acc:0.735630 2019-12-15 18:14:23 Epoch:9 Iter: 1218/1219 loss:0.767146 acc:0.364759 the final keras training process is like: 685/690 [============================>.] - ETA: 2s - loss: 0.4940 - acc: 0.7309 686/690 [============================>.] - ETA: 1s - loss: 0.4941 - acc: 0.7306 687/690 [============================>.] - ETA: 1s - loss: 0.4939 - acc: 0.7308 688/690 [============================>.] - ETA: 0s - loss: 0.4942 - acc: 0.7303 689/690 [============================>.] - ETA: 0s - loss: 0.4943 - acc: 0.7302
Well, it's pretty hard to say without any code snippets. that being said, in general, initialization is way more important than you might think. I'm sure that the default initialization of pytorch is different from keras and I had similar issues in the past. Another thing to check is the optimizer parameters, make sure that not only you are using the same optimizer(sgd, adam, ...) but also with the same parameters(lr, beta, momentum, ...)
https://stackoverflow.com/questions/59344571/
Is there any diffrence between index_select and tensor[sequence] in PyTorch?
everyone. I'm new to PyTorch. Now I'm learning the indexing of a tensor. I notice that we can indexing a tensor by tensor.index_select() and tensor[sequence]. In [1]: x = torch.randn(3, 4) In [2]: indices = torch.tensor([0, 2]) In [3]: x.index_select(0, indices) Out[3]: tensor([[ 0.2760, -0.9543, -1.0499, 0.7828], [ 1.3514, -1.1289, 0.5052, -0.0547]]) In [4]: x[[0,2]] Out[4]: tensor([[ 0.2760, -0.9543, -1.0499, 0.7828], [ 1.3514, -1.1289, 0.5052, -0.0547]]) I am puzzled about these two methods and look for some doc. But I failed. Can anyone can tell me are there some differences between them and what are these difference?
This looks like a remnant of old (slower) indexing. See this pull request. I also think you used to not be able to do binary logical indexing on tensors. a = torch.randn((1,3,4,4)) dim = 2 indices = [0,1] %timeit a.index_select(dim, torch.tensor(indices)) 12.7 µs ± 1.28 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each) %timeit a[:,:,indices,:] 16.7 µs ± 640 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
https://stackoverflow.com/questions/59344751/
Pytorch RuntimeError: Expected object of device type cuda but got device type cpu for argument #1 'self' in call to _th_index_select
I am training a model that takes tokenized strings which are then passed through an embedding layer and an LSTM thereafter. However, there seems to be an error in the input, as it does not pass through the embedding layer. class DrugModel(nn.Module): def __init__(self, input_dim, output_dim, hidden_dim, drug_embed_dim, lstm_layer, lstm_dropout, bi_lstm, linear_dropout, char_vocab_size, char_embed_dim, char_dropout, dist_fn, learning_rate, binary, is_mlp, weight_decay, is_graph, g_layer, g_hidden_dim, g_out_dim, g_dropout): super(DrugModel, self).__init__() # Save model configs self.drug_embed_dim = drug_embed_dim self.lstm_layer = lstm_layer self.char_dropout = char_dropout self.dist_fn = dist_fn self.binary = binary self.is_mlp = is_mlp self.is_graph = is_graph self.g_layer = g_layer self.g_dropout = g_dropout self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # For one-hot encoded SMILES if not is_mlp: self.char_embed = nn.Embedding(char_vocab_size, char_embed_dim, padding_idx=0) self.lstm = nn.LSTM(char_embed_dim, drug_embed_dim, lstm_layer, bidirectional=False, batch_first=True, dropout=lstm_dropout) # Distance function self.dist_fc = nn.Linear(drug_embed_dim, 1) if binary: # Binary Cross Entropy self.criterion = lambda x, y: y*torch.log(x) + (1-y)*torch.log(1-x) def init_lstm_h(self, batch_size): return (Variable(torch.zeros( self.lstm_layer*1, batch_size, self.drug_embed_dim)).cuda(), Variable(torch.zeros( self.lstm_layer*1, batch_size, self.drug_embed_dim)).cuda()) # Set Siamese network as basic LSTM def siamese_sequence(self, inputs, length): # Character embedding inputs = inputs.long() inputs = inputs.cuda() self.char_embed = self.char_embed(inputs.to(self.device)) c_embed = self.char_embed(inputs) # c_embed = F.dropout(c_embed, self.char_dropout) maxlen = inputs.size(1) if not self.training: # Sort c_embed _, sort_idx = torch.sort(length, dim=0, descending=True) _, unsort_idx = torch.sort(sort_idx, dim=0) maxlen = torch.max(length) # Pack padded sequence c_embed = c_embed.index_select(0, Variable(sort_idx).cuda()) sorted_len = length.index_select(0, sort_idx).tolist() c_packed = pack_padded_sequence(c_embed, sorted_len, batch_first=True) else: c_packed = c_embed # Run LSTM init_lstm_h = self.init_lstm_h(inputs.size(0)) lstm_out, states = self.lstm(c_packed, init_lstm_h) hidden = torch.transpose(states[0], 0, 1).contiguous().view( -1, 1 * self.drug_embed_dim) if not self.training: # Unsort hidden states outputs = hidden.index_select(0, Variable(unsort_idx).cuda()) else: outputs = hidden return outputs def forward(self, key1, key2, targets, key1_len, key2_len, status, predict = False): if not self.is_mlp: output1 = self.siamese_sequence(key1, key1_len) output2 = self.siamese_sequence(key2, key2_len) After instantiating the class I get the following error when passing the input through the embedding layer: <ipython-input-128-432fcc7a1e39> in forward(self, key1, key2, targets, key1_len, key2_len, status, predict) 129 def forward(self, key1, key2, targets, key1_len, key2_len, status, predict = False): 130 if not self.is_mlp: --> 131 output1 = self.siamese_sequence(key1, key1_len) 132 output2 = self.siamese_sequence(key2, key2_len) 133 set_trace() <ipython-input-128-432fcc7a1e39> in siamese_sequence(self, inputs, length) 74 inputs = inputs.cuda() 75 ---> 76 self.char_embed = self.char_embed(inputs.to(self.device)) 77 set_trace() 78 c_embed = self.char_embed(inputs) ~/miniconda3/lib/python3.7/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 539 result = self._slow_forward(*input, **kwargs) 540 else: --> 541 result = self.forward(*input, **kwargs) 542 for hook in self._forward_hooks.values(): 543 hook_result = hook(self, input, result) ~/miniconda3/lib/python3.7/site-packages/torch/nn/modules/sparse.py in forward(self, input) 112 return F.embedding( 113 input, self.weight, self.padding_idx, self.max_norm, --> 114 self.norm_type, self.scale_grad_by_freq, self.sparse) 115 116 def extra_repr(self): ~/miniconda3/lib/python3.7/site-packages/torch/nn/functional.py in embedding(input, weight, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse) 1482 # remove once script supports set_grad_enabled 1483 _no_grad_embedding_renorm_(weight, input, max_norm, norm_type) -> 1484 return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse) 1485 1486 RuntimeError: Expected object of device type cuda but got device type cpu for argument #1 'self' in call to _th_index_select despite the fact that the input (e.g. key1) has already been passed to cuda and has been transformed into long format: tensor([[25, 33, 30, ..., 0, 0, 0], [25, 7, 7, ..., 0, 0, 0], [25, 7, 30, ..., 0, 0, 0], ..., [25, 7, 33, ..., 0, 0, 0], [25, 33, 41, ..., 0, 0, 0], [25, 33, 41, ..., 0, 0, 0]], device='cuda:0')
setting model.device to cuda does not change your inner module devices, so self.lstm, self.char_embed, and self.dist_fc are all still on cpu. correct way of doing it is by using DrugModel().to(device) in general, it's better not to feed a device to your model and write it in a device-agnostic way. to make your init_lstm_h function device-agnostic you can use something like this
https://stackoverflow.com/questions/59347111/
Cannot convert Pandas Dataframe columns to float
I am using Pandas to read a CSV file containing several columns that must be converted to floats: df = pd.read_csv(r'dataset.csv', low_memory=False, sep = ',') df.head(2) Coal Flow 01 Air Flow 01 Outlet Temp 01 Inlet Temp 01 Bowl DP 01 Current 01 Vibration 01 0 51.454407 101.432340 64.917089 234.2488932 2.470623 96.727352 1.874374 1 51.625368 100.953089 64.726890 233.2340394 2.495698 96.309512 1.996391 Next I specify the columns that need to be converted to floats in a variable called features: features = ['Coal Flow 01', 'Air Flow 01', 'Outlet Temp 01', 'Inlet Temp 01', 'Bowl DP 01', 'Current 01', 'Vibration 01'] Then I needed to convert the the value of the columns to float, but I got an error. features = np.stack([df[col].values for col in features], 1) features = torch.tensor(features, dtype=torch.float) features[:5] and the error that Pandas is showing me is: KeyError: "None of [Index([ 51.45440668, 101.4323397, 64.91708906, '234.2488932',\n 2.470623484, 96.72735193, 1.87437372],\n dtype='object')] are in the [columns]"
Why not just use astype: df = pd.read_csv(r'dataset.csv', low_memory=False, sep = ',') df[features] = df[features].apply(lambda x: x.apply(lambda x: x[0]).astype(float))
https://stackoverflow.com/questions/59350190/
Pytorch is installed but is not working on ubuntu 18.04
I am trying to install Pytorch via pip on ubuntu 18.04.I have python 3.6 and my laptop is HP-Pavilion notebook 15 The installation seems to be right because i get the message: Installing collected packages: torch, torchvision Successfully installed torch-1.3.1+cpu torchvision-0.4.2+cpu i run the verification code and it is ok from __future__ import print_function import torch x = torch.rand(5, 3) print(x) However, when i close the terminal or reboot and try to run he same code i get the error: Traceback (most recent call last): File "torch.py", line 2, in import torch AttributeError: module 'torch' has no attribute 'rand'
How are you executing the python script? Which python are you using? Maybe you installed the package in a different python version? Try to set alias to the python you want to use: alias python=/usr/local/bin/python3.6 Then pip install the package with that python alias you will always be using. python pip install <package name> Python now will install the package in the python files with the alias python - heading to files: /usr/local/bin/python3.6 Let me know if the error still occurs!
https://stackoverflow.com/questions/59358141/
Is there a way to write a custom BCE loss in pytorch?
I am writing a custom BCE in pytorch but in some cases it returns -inf and nan most cases. Which is due to the log function. bce_loss=y_true*torch.log2(y_pred) +(one_torch-y_true)*torch.log2(one_torch-y_pred) Is there a way to rewrite this? Note y_pred is a sigmoid output which is between 0 and 1.
You can clamp the preds to stop from log error. y_pred = torch.clamp(y_pred, 1e-7, 1 - 1e-7)
https://stackoverflow.com/questions/59366048/
Use skimage feature extractors in PyTorch Transforms
I want to apply skimage’s Local Binary Pattern feature extraction on my data, and was wondering if there was any possibility of doing this inside my torch’s Transforms, which right now is the following: data_transforms = { 'train': transforms.Compose([ transforms.CenterCrop(178), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]) ]), 'val': transforms.Compose([ transforms.CenterCrop(178), transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]) ]), } If not, how would I implement it? Would I have to do it when importing the data?
You can implement the Transform using the lamdba funtion. As @dhananjay correctly pointed out. Building on that comment, the implementation would be as follows: def lbp(x): radius = 2 n_points = 8 * radius METHOD = 'uniform' lbp = local_binary_pattern(x, n_points, radius, METHOD) return lbp data_transforms = { 'train': transforms.Compose([ transforms.CenterCrop(178), transforms.RandomHorizontalFlip(), transforms.Lambda(lbp), transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]) ]), 'val': transforms.Compose([ transforms.CenterCrop(178), transforms.Lambda(lbp), transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]) ]), } BUT. This is a bad idea because it defeats the very purpose of the pytorch tranform. A transform is ideal for an operation that either 1. Can be computed trivially (at low compute cost) from the original data. Hence there is no advantage to applying it on your data and storing a copy. Normalize is one such transform. 2. Introduces an element of stochasticity or randomn perturbation in the original data. E.g RandomHorizontalFlip etc. The key thing to remember is that your transform will be applied at every batch to the dataset while learning. Considering the above, you absolutely do not want to implement your lbp as a transform. It is better to compute it offline and store it. Else you will be significantly slowing down your batch loading.
https://stackoverflow.com/questions/59376332/
pytorch: RuntimeError: bool value of Tensor with more than one value is ambiguous
it works with x[x >= 0.2] = 1 x[x < 0.2] = 0 x is a tensor here. but when i am trying to use x[x > 0 and x < 1] = 1 it reports: RuntimeError: bool value of Tensor with more than one value is ambiguous ? dose anyone know why?
Just a syntax thing. x = torch.randn((1,3,20,20)) x[(x > 0) & (x < 1)] = 1
https://stackoverflow.com/questions/59381021/
Construct a rotation matrix in Pytorch
I want to construct a rotation matrix, which have unknown Eular angles. I want to build some regression solution to find the value of Eular angles. My code is here. roll = yaw = pitch = torch.randn(1,requires_grad=True) RX = torch.tensor([ [1, 0, 0], [0, cos(roll), -sin(roll)], [0, sin(roll), cos(roll)] ],requires_grad=True) RY = torch.tensor([ [cos(pitch), 0, sin(pitch)], [0, 1, 0], [-sin(pitch), 0, cos(pitch)] ],requires_grad=True) RZ = torch.tensor([ [cos(yaw), -sin(yaw), 0], [sin(yaw), cos(yaw), 0], [0, 0, 1] ],requires_grad=True) R = torch.mm(RZ, RY).requires_grad_() R = torch.mm(R, RX).requires_grad_() R = R.mean().requires_grad_() R.backward() Matrix cannot differentiate the Euler angles. There isn't any gradient value of matrix. Can anyone fix my problems? Thanks! debug result
torch.tensor is viewed as an operation and that is not able to do backpropgation. A dirty way to fix your code: roll = torch.randn(1,requires_grad=True) yaw = torch.randn(1,requires_grad=True) pitch = torch.randn(1,requires_grad=True) tensor_0 = torch.zeros(1) tensor_1 = torch.ones(1) RX = torch.stack([ torch.stack([tensor_1, tensor_0, tensor_0]), torch.stack([tensor_0, cos(roll), -sin(roll)]), torch.stack([tensor_0, sin(roll), cos(roll)])]).reshape(3,3) RY = torch.stack([ torch.stack([cos(pitch), tensor_0, sin(pitch)]), torch.stack([tensor_0, tensor_1, tensor_0]), torch.stack([-sin(pitch), tensor_0, cos(pitch)])]).reshape(3,3) RZ = torch.stack([ torch.stack([cos(yaw), -sin(yaw), tensor_0]), torch.stack([sin(yaw), cos(yaw), tensor_0]), torch.stack([tensor_0, tensor_0, tensor_1])]).reshape(3,3) R = torch.mm(RZ, RY) R = torch.mm(R, RX) R_mean = R.mean() R_mean.backward()
https://stackoverflow.com/questions/59387182/
RuntimeError: Error(s) in loading state_dict for Generator: size mismatch for weights and biases using Pytorch
I'm training a 3D-GAN to generate MRI volumes. I defined my model as follows: ###### Definition of the generator ###### class Generator(nn.Module): def __init__(self, ngpu): #super() makes Generator a subclass of nn.Module, so that it inherites all the methods of nn.Module super(Generator, self).__init__() self.ngpu = ngpu #we can use Sequential() since the output of one layer is the input of the next one self.main = nn.Sequential( # input is latent vector z, going into a convolution nn.ConvTranspose3d(nz, ngf * 8, 4, stride=2, padding=0, bias=True), # try to put kernel = (batch_size,4,4,4,512) nn.BatchNorm3d(ngf * 8), nn.ReLU(True), #True means that it does the operation inplace, default is False nn.ConvTranspose3d(ngf * 8, ngf * 4, 4, stride=2, padding=1, bias=True), # try to put kernel = (batch_size,8,8,8,256) nn.BatchNorm3d(ngf * 4), nn.ReLU(True), nn.ConvTranspose3d(ngf * 4, ngf * 2, 4, stride=2, padding=1, bias=True), # try to put kernel = (batch_size,16,16,16,128) nn.BatchNorm3d(ngf * 2), nn.ReLU(True), nn.ConvTranspose3d( ngf * 2, ngf, 4, stride=2, padding=1, bias=True), # try to put kernel = (batch_size,32,32,32,64) nn.BatchNorm3d(ngf), nn.ReLU(True), nn.ConvTranspose3d(ngf, nc, 4, stride=2, padding=1, bias=True), # try to put kernel = (batch_size,64,64,64,1) nn.Sigmoid() ) def forward(self, x): return self.main(x) ###### Definition of the Discriminator ###### class Discriminator(nn.Module): def __init__(self, ngpu): super(Discriminator, self).__init__() self.ngpu = ngpu self.main = nn.Sequential( nn.Conv3d(nc, ndf, 4, stride=2, padding=1, bias=True), nn.BatchNorm3d(ndf), nn.LeakyReLU(leak_value, inplace=True), nn.Conv3d(ndf, ndf * 2, 4, stride=2, padding=1, bias=True), nn.BatchNorm3d(ndf * 2), nn.LeakyReLU(leak_value, inplace=True), nn.Conv3d(ndf * 2, ndf * 4, 4, stride=2, padding=1, bias=True), nn.BatchNorm3d(ndf * 4), nn.LeakyReLU(leak_value, inplace=True), nn.Conv3d(ndf * 4, ndf * 8, 4, stride=2, padding=1, bias=True), nn.BatchNorm3d(ndf * 8), nn.LeakyReLU(leak_value, inplace=True), nn.Conv3d(ndf * 8, nc, 4, stride=1, padding=0, bias=True), nn.Sigmoid() ) def forward(self, x): return self.main(x) I then train the model and save it. When loading the model for evaluation and testing I get the following error: RuntimeError: Error(s) in loading state_dict for Generator: size mismatch for main.0.weight: copying a param with shape torch.Size([64, 1, 4, 4, 4]) from checkpoint, the shape in current model is torch.Size([200, 512, 4, 4, 4]). size mismatch for main.0.bias: copying a param with shape torch.Size([64]) from checkpoint, the shape in current model is torch.Size([512]). size mismatch for main.1.weight: copying a param with shape torch.Size([64]) from checkpoint, the shape in current model is torch.Size([512]). size mismatch for main.1.running_mean: copying a param with shape torch.Size([64]) from checkpoint, the shape in current model is torch.Size([512]). size mismatch for main.1.bias: copying a param with shape torch.Size([64]) from checkpoint, the shape in current model is torch.Size([512]). size mismatch for main.1.running_var: copying a param with shape torch.Size([64]) from checkpoint, the shape in current model is torch.Size([512]). size mismatch for main.3.weight: copying a param with shape torch.Size([128, 64, 4, 4, 4]) from checkpoint, the shape in current model is torch.Size([512, 256, 4, 4, 4]). size mismatch for main.3.bias: copying a param with shape torch.Size([128]) from checkpoint, the shape in current model is torch.Size([256]). size mismatch for main.4.weight: copying a param with shape torch.Size([128]) from checkpoint, the shape in current model is torch.Size([256]). size mismatch for main.4.running_mean: copying a param with shape torch.Size([128]) from checkpoint, the shape in current model is torch.Size([256]). size mismatch for main.4.bias: copying a param with shape torch.Size([128]) from checkpoint, the shape in current model is torch.Size([256]). size mismatch for main.4.running_var: copying a param with shape torch.Size([128]) from checkpoint, the shape in current model is torch.Size([256]). size mismatch for main.6.bias: copying a param with shape torch.Size([256]) from checkpoint, the shape in current model is torch.Size([128]). size mismatch for main.7.weight: copying a param with shape torch.Size([256]) from checkpoint, the shape in current model is torch.Size([128]). size mismatch for main.7.running_mean: copying a param with shape torch.Size([256]) from checkpoint, the shape in current model is torch.Size([128]). size mismatch for main.7.bias: copying a param with shape torch.Size([256]) from checkpoint, the shape in current model is torch.Size([128]). size mismatch for main.7.running_var: copying a param with shape torch.Size([256]) from checkpoint, the shape in current model is torch.Size([128]). size mismatch for main.9.weight: copying a param with shape torch.Size([512, 256, 4, 4, 4]) from checkpoint, the shape in current model is torch.Size([128, 64, 4, 4, 4]). size mismatch for main.9.bias: copying a param with shape torch.Size([512]) from checkpoint, the shape in current model is torch.Size([64]). size mismatch for main.10.weight: copying a param with shape torch.Size([512]) from checkpoint, the shape in current model is torch.Size([64]). size mismatch for main.10.running_mean: copying a param with shape torch.Size([512]) from checkpoint, the shape in current model is torch.Size([64]). size mismatch for main.10.bias: copying a param with shape torch.Size([512]) from checkpoint, the shape in current model is torch.Size([64]). size mismatch for main.10.running_var: copying a param with shape torch.Size([512]) from checkpoint, the shape in current model is torch.Size([64]). size mismatch for main.12.weight: copying a param with shape torch.Size([1, 512, 4, 4, 4]) from checkpoint, the shape in current model is torch.Size([64, 1, 4, 4, 4]). What I'm I doing wrong? Thanks in advance!
The model you loaded and the target model is not identical, so the error raise to inform about mismatches of size, layers, check again your code, or your saved model may not be saved properly
https://stackoverflow.com/questions/59390160/
What is the fastest Mask R-CNN implementation available
I'm running a Mask R-CNN model on an edge device (with an NVIDIA GTX 1080). I am currently using the Detectron2 Mask R-CNN implementation and I archieve an inference speed of around 5 FPS. To speed this up I looked at other inference engines and model implementations. For example ONNX, but I'm not able to gain a faster inference speed. TensorRT looks very promising to me but I did not found a ready "out-of-the-box" implementation for it. Are there any other mature and fast inference engines or other techniques to speed up the inference?
It's almost impossible to get higher inference speed for Mask R-CNN on GTX 1080. You may check detectron2 by Facebook AI Research. Otherwise, I'd suggest to use YOLACT - (You Only Look At CoefficienTs), it can achieve real-time instance segmentation. On the other hand, if you don't need instance segmentation, you can use YOLO, SSD, etc for object detection.
https://stackoverflow.com/questions/59394530/
RuntimeError: Given input size: (10x7x7). Calculated output size: (10x0x0). Output size is too small
Trying to train the mnist 28x28x1 images my model is def __init__(self): super(CNN_mnist, self).__init__() self.conv = nn.Sequential( # 3 x 128 x 128 nn.Conv2d(1, 32, 3, 1, 1), nn.BatchNorm2d(32), nn.LeakyReLU(0.2), # 32 x 128 x 128 nn.Conv2d(32, 64, 3, 1, 1), nn.BatchNorm2d(64), nn.LeakyReLU(0.2), # 64 x 128 x 128 nn.MaxPool2d(2, 2), # 64 x 64 x 64 nn.Conv2d(64, 128, 3, 1, 1), nn.BatchNorm2d(128), nn.LeakyReLU(0.2), # 128 x 64 x 64 nn.Conv2d(128, 256, 3, 1, 1), nn.BatchNorm2d(256), nn.LeakyReLU(0.2), # 256 x 64 x 64 nn.MaxPool2d(2, 2), # 256 x 32 x 32 nn.Conv2d(256, 10, 3, 1, 1), nn.BatchNorm2d(10), nn.LeakyReLU(0.2) ) # 256 x 32 x 32 self.avg_pool = nn.AvgPool2d(32) # 256 x 1 x 1 self.classifier = nn.Linear(10, 10) def forward(self, x): features = self.conv(x) flatten = self.avg_pool(features).view(features.size(0), -1) output = self.classifier(flatten) return output, features and I got following error RuntimeError: Given input size: (10x7x7). Calculated output size: (10x0x0). Output size is too small not sure what this error mean and where should I fix it?
Your [avg_pool] layer expects its input size to be (at least) 32x32, as the kernel size defined for this layer is 32. However, given the size of the input, the feature map this pooling layer gets is only 7x7 in size. This is too small for kernel size of 32. You should either increase the input size, or define a smaller (e.g., 7) kernel size for the avg_pooling layer.
https://stackoverflow.com/questions/59405042/
how to adjust dataloader and make a new dataloader?
let say I have a data loader of cifar10 if I want to remove some value from the dataloader and make a new dataloader how should I do it? def load_data_cifar10(batch_size=128,test=False): if not test: train_dset = torchvision.datasets.CIFAR10(root='/mnt/3CE35B99003D727B/input/pytorch/data', train=True, download=True, transform=transform) else: train_dset = torchvision.datasets.CIFAR10(root='/mnt/3CE35B99003D727B/input/pytorch/data', train=False, download=True, transform=transform) train_loader = torch.utils.data.DataLoader(train_dset, batch_size=batch_size, shuffle=True) print("LOAD DATA, %d" % (len(train_loader))) return train_loader
You can use the Subset dataset. This takes another dataset as input as well as a list of indices to construct a new dataset. Say you want the first 1000 entries, then you could do subset_train_dset = torch.utils.data.Subset(train_dset, range(1000)) You can also construct datasets composed of multiple datasets using ConcatDataset dataset, or combinations of ConcatDataset and Subset to build whatever you like frankenstein_dset = torch.utils.data.ConcatDataset(( torch.utils.data.Subset(dset1, range(1000)), torch.utils.data.Subset(dset2, range(100))) In your case you would need to either look into the implementation details to determine which indices to keep, or you could write some code to iterate through the original dataset first and save all the indicies you want to keep, then define a Subset with the appropriate indices.
https://stackoverflow.com/questions/59412287/
loop through the batch image loader pytorch
Let say I have batch with imgs = torch.Size([128, 1, 28, 28]) if I want to loop through the each image for img in imgs: print(img.shpae) -> torch.Size([1, 28, 28]) if I want to get a torch.Size([1,1, 28, 28]) for each image what should I do?
unsqueeze Just pass dim, In which position you want to add one extra singleton dimension. imgs = torch.zeros([128, 1, 28, 28]) # dim (int) – the index at which to insert the singleton dimension imgs.unsqueeze_(dim = 1) imgs.shape >>> torch.Size([128, 1, 1, 28, 28])
https://stackoverflow.com/questions/59419648/
how to import coco_utils and coco_eval?
To get a PyTorch script to work, I need to be able to do: import coco_utils import coco_eval I'm using Ubuntu 18.04 with Python 3. Based on this post: How to install COCO PythonAPI in python3 I've done the following so far: cd ~ git clone https://github.com/cocodataset/cocoapi.git cd cocoapi/PythonAPI # open Makefile in gedit, change the two instances of "python" to "python3" python3 setup.py build_ext --inplace sudo python3 setup.py install now this works: import pycocotools but these still don't: import coco_utils import coco_eval How can I import coco_utils and coco_eval ??
coco_utils.py and coco_eval.py must be the name of the files that should be in the repository you're trying to use. Possibly you're looking for the object detection reference training scripts provided in the detection (vision/references/detection/) module of torchvision.
https://stackoverflow.com/questions/59433282/
RuntimeError: Only Tensors of floating point dtype can require gradients
RuntimeError: Only Tensors of floating point dtype can require gradients got following error from input = Variable(preprocessed_img, requires_grad = True) img=train_loader.dataset.data[0] print(type(img)) img_tensor = torch.tensor(img) preprocess_image(img) > def preprocess_image(img): means=[0.485, 0.456, 0.406] stds=[0.229, > 0.224, 0.225] > > preprocessed_img = img.copy()[: , :, ::-1] for i in range(3): > preprocessed_img[:, :, i] = preprocessed_img[:, :, i] - means[i] > preprocessed_img[:, :, i] = preprocessed_img[:, :, i] / stds[i] > preprocessed_img = \ > np.ascontiguousarray(np.transpose(preprocessed_img, (2, 0, 1))) > preprocessed_img = torch.from_numpy(preprocessed_img) > preprocessed_img.unsqueeze_(0) input = Variable(preprocessed_img, > requires_grad = True) return input
Use torch.Tensor(img) instead of torch.tensor(img). This should probably solve your issue.
https://stackoverflow.com/questions/59433832/
How do I make a minimal and reproducible example for neural networks?
I would like to know how to make a minimal and reproducible deep learning example for Stack Overflow. I want to make sure that people have enough information to pinpoint the exact problem with my code. Is it enough to just provide the traceback? c:\users\samuel\appdata\local\programs\python\python35\lib\site-packages\keras\engine\training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix) 135 ': expected ' + names[i] + ' to have shape ' + 136 str(shape) + ' but got array with shape ' + --> 137 str(data_shape)) 138 return data 139 Or should I simply post the error message? Value Error: Error when checking input: expected dense_1_input to have shape (4,) but got array with shape (1,)
Here are a few tips to make a reproducible, minimal deep learning Example. It's good advice whether it be for Keras, Pytorch, or Tensorflow. We can't use your data, but in most cases, it doesn't matter. All we need is the right shape. Use randomly generated numbers of the right shape. E.g., np.random.randint(0, 256, (100, 30, 30, 3) for 100 colored pictures of size 30x30 E.g., np.random.choice(np.arange(10), 100) for 100 samples of 10 categories We don't need to see your entire pipeline. Only provide the bare minimum to run your code. Make the most out of Keras and its debugging abilities. Include the traceback. It will most likely point out the exact problem. Neural networks are all about fitting the right shapes. At a minimum, always provide the input shapes. Make it easy to test and reproduce. Post your entire neural network architecture. Include your library imports. Define all variables. Here is an example of a perfect minimal and reproducible example: "I have an error. When I run this code, it gives me this error:" ValueError: Error when checking target: expected dense_2 to have shape (10,) but got array with shape "Here is my architecture, with generated data:" import numpy as np import keras from keras.models import Sequential from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D xtrain, xtest = np.random.rand(2, 1000, 30, 30, 3) ytrain, ytest = np.random.choice(np.arange(10), 2000).reshape(2, 1000) model = Sequential([ Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=xtrain.shape[1:]), Conv2D(64, (3, 3), activation='relu'), MaxPooling2D(pool_size=(2, 2)), Flatten(), Dense(128, activation='relu'), Dense(10, activation='softmax')]) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adam(), metrics=['accuracy']) model.fit(xtrain, ytrain, batch_size=16, epochs=10, validation_data=(xtest, ytest))
https://stackoverflow.com/questions/59437658/
How to use trained deep learning model to predict in excel?
After we trained my neural network and saved my model with tensorflow, we can load the model and predict result like following: from keras.models import load_model model = load_model('my_model.h5') result = model.predict(test_input) Is there any way we can use the trained model in excel to do the similar job? I assume we can build a excel user defined function to take n parameter and give a number. Can we do in VBA? How to load the model file and run the predict?
My solution is to use xlwings (https://www.xlwings.org/) to call python code.
https://stackoverflow.com/questions/59449308/
How can we convert a .pth model into .pb file?
I have already got the complete model by using pytorch, however I wanna convert the .pth file into .pb, which could be used in Tensorflow. Does anyone have some ideas?
You can use ONNX: Open Neural Network Exchange Format To convert .pth file to .pb First, you need to export a model defined in PyTorch to ONNX and then import the ONNX model into Tensorflow (PyTorch => ONNX => Tensorflow) This is an example of MNISTModel to Convert a PyTorch model to Tensorflow using ONNX from onnx/tutorials Save the trained model to a file torch.save(model.state_dict(), 'output/mnist.pth') Load the trained model from file trained_model = Net() trained_model.load_state_dict(torch.load('output/mnist.pth')) # Export the trained model to ONNX dummy_input = Variable(torch.randn(1, 1, 28, 28)) # one black and white 28 x 28 picture will be the input to the model torch.onnx.export(trained_model, dummy_input, "output/mnist.onnx") Load the ONNX file model = onnx.load('output/mnist.onnx') # Import the ONNX model to Tensorflow tf_rep = prepare(model) Save the Tensorflow model into a file tf_rep.export_graph('output/mnist.pb') AS noted by @tsveti_iko in the comment NOTE: The prepare() is build-in in the onnx-tf, so you first need to install it through the console like this pip install onnx-tf, then import it in the code like this: import onnx from onnx_tf.backend import prepare and after that you can finally use it as described in the answer.
https://stackoverflow.com/questions/59450262/
Local fully connected layer - Pytorch
Assume we have a feature representation with kN neurons before the classification layer. Now, the classification layer produces an output layer of size N with only local connections. That is, the kth neuron at the output is computed using input neurons at locations from kN to kN+N. Hence, every N locations in the input layer (with stride N) give single neuron value at the output. This is done using conv1dlocal in Keras, however, the PyTorch does not seem to have this. Weight matrix in standard linear layer: kNxN = kN^2 variables Weight matrix with local linear layer: (kx1)@N times = NK variables
This is currently triaged on the PyTorch issue tracker, in the mean time you can get a similar behavious using fold and unfold. See this answer: https://github.com/pytorch/pytorch/issues/499#issuecomment-503962218 class LocalLinear(nn.Module): def __init__(self,in_features,local_features,kernel_size,padding=0,stride=1,bias=True): super(LocalLinear, self).__init__() self.kernel_size = kernel_size self.stride = stride self.padding = padding fold_num = (in_features+2*padding-self.kernel_size)//self.stride+1 self.weight = nn.Parameter(torch.randn(fold_num,kernel_size,local_features)) self.bias = nn.Parameter(torch.randn(fold_num,local_features)) if bias else None def forward(self, x:torch.Tensor): x = F.pad(x,[self.padding]*2,value=0) x = x.unfold(-1,size=self.kernel_size,step=self.stride) x = torch.matmul(x.unsqueeze(2),self.weight).squeeze(2)+self.bias return x
https://stackoverflow.com/questions/59455386/
How to get top k accuracy in semantic segmentation using PyTorch?
How do you compute the top k accuracy in semantic segmentation? In classification, we might compute the topk accuracy as: correct = output.eq(gt.view(1, -1).expand_as(output))
You are looking for torch.topk function that computes the top k values along a dimension. The second output of torch.topk is the "arg top k": the k indices of the top values. Here's how this can be used in the context of semantic segmentation: Suppose you have the ground truth prediction tensor y of shape b-h-w (dtype=torch.int64). Your model predicts per-pixel class logits of shape b-c-h-w, with c is the number of classes (including "background"). These logits are the "raw" predictions before softmax function transforms them into class probabilities. Since we are only looking at the top k, it does not matter if the predictions are "raw" or "probabilities". # compute the top k predicted classes, per pixel: _, tk = torch.topk(logits, k, dim=1) # you now have k predictions per pixel, and you want that one of them will match the true labels y: correct_pixels = torch.eq(y[:, None, ...], tk).any(dim=1) # take the mean of correct_pixels to get the overall average top-k accuracy: top_k_acc = correct_pixels.mean() Note that this method does not take into account "ignore" pixels. This can be done with a slight modification to the above code: valid = y != ignore_index top_k_acc = correct_pixels[valid].mean()
https://stackoverflow.com/questions/59474987/
How to run lua ML model from Google Colab
I am trying to run this neural style transfer model from Github but on Google Colab because my computer doesn't have enough memory/CPU/anything. I have mounted my google drive to my notebook, cloned the repo onto my drive by following this tutorial downloaded the models to my drive folder, and just to test that it works, I'm using the most basic example of running the Brad Pitt example in the readme using: th neural_style.lua -style_image examples/inputs/picasso_selfport1907.jpg -content_image examples/inputs/brad_pitt.jpg But for some reason it won't work. Using subprocess.run() just returned No such file or directory Using !th neural_style.lua... returns th: command not found I've tried like four other things and they all give me a variant of the above two error messages. Any thoughts? Here is the full notebook code to reproduce my setup on Colab from start to end/error: # Mount the drive from google.colab import drive drive.mount('/content/drive') # Clone the repo onto the drive !git clone https://github.com/jcjohnson/neural-style # Install Pytorch !pip3 install http://download.pytorch.org/whl/cu80/torch-0.3.0.post4-cp36-cp36m-linux_x86_64.whl !pip3 install torchvision # Download the models per the github repo instructions !bash models/download_models.sh !th neural_style.lua -style_image examples/inputs/picasso_selfport1907.jpg -content_image examples/inputs/brad_pitt.jpg
First: %cd /content/ !git clone https://github.com/nagadomi/distro.git torch --recursive import os os.chdir('./torch/') !bash install-deps !./install.sh !. ./install/bin/torch-activate Now it should work using absolute path to th: !/content/torch/install/bin/th neural_style.lua -style_image examples/inputs/picasso_selfport1907.jpg -content_image examples/inputs/brad_pitt.jpg
https://stackoverflow.com/questions/59478109/
PureFrameworkTensorFoundError, Runtime error -FedeartedLearning
I am trying a Linear Regression algorithm with Federated learning using Pytorch and I face the following error. I am implementing it on Colab. According to me this error might be due to some code line in the train() function. Kindly help is you have worked with Pysyft and have faced such error before. RuntimeError: invalid argument 8: lda should be at least max(1, 0), but have 0 at /pytorch/aten/src/TH/generic/THBlas.cpp:363 And the following is the code: #import the necessasry packages import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import syft as sy #create target and data variables as tensors x_data=Variable(torch.Tensor([[1.0],[0.0],[1.0],[0.0]])) y_data=Variable(torch.Tensor([[0.0],[0.0],[1.0],[1.0]])) #Create virtual Workers hook = sy.TorchHook(torch) bob = sy.VirtualWorker(hook, id="bob") alice = sy.VirtualWorker(hook, id="alice") data_bob = x_data[0:2] target_bob = y_data[0:2] data_alice = x_data[2:0] target_alice = y_data[2:0] #creating a class that does Linear Regression class LinearRegression (nn.Module): def __init__(self): super(LinearRegression,self). __init__ () self.linear = torch.nn.Linear(1,1) def forward(self, x): y_pred = self.linear(x) return y_pred #assign the function to the variable name 'Model' model=LinearRegression() #send the data to the virtual worker pointers data_bob = data_bob.send(bob) data_alice = data_alice.send(alice) target_bob = target_bob.send(bob) target_alice = target_alice.send(alice) # organize pointers into a list datasets = [(data_bob,target_bob),(data_alice,target_alice)] #create optimizer and calculate the loss opt = torch.optim.SGD(params=model.parameters(),lr=0.1) criterion = torch.nn.MSELoss(size_average=False) def train(): opt = torch.optim.SGD(params=model.parameters(),lr=0.1) for epoch in range (20): model.train() print("Training started..") for x_data,y_data in datasets: model.send(x_data.location) opt.zero_grad() #forwardpass #the model here is the linear regression model y_pred = model(x_data) #ComputeLoss loss=criterion(y_pred,y_data) #BackwardPass loss.backward() opt.step() model.get() print(loss.get()) train()
you have a typo here: data_alice = x_data[2:0] target_alice = y_data[2:0] Should be [2:] Because data_alice is failing, you had this error.
https://stackoverflow.com/questions/59484278/
azure ml & Pytorch: sample conda-dependencies.yml and docker?
Could you please point me to the documentation sample showcasing how to put together pytorch dependencies for training on AzureML? Few related questions to the scenario of running pytorch training workloads on AzureML: How can I set cuda version to 10.1? Could you please point to sample demonstrating how to use “official” pytorch docker https://hub.docker.com/r/pytorch/pytorch (which should have all cuda stuff https://github.com/pytorch/pytorch/blob/master/docker/pytorch/Dockerfile)?. I’ve found distributed-pytorch-with-horovod.yml in the docs but it does not mention any pytorch dependencies -- am I looking in the right place?
Install Pytorch with CUDA Version 10.1 with the following command on windows pip3 install torch===1.3.1 torchvision===0.4.2 -f https://download.pytorch.org/whl/torch_stable.htm. From .yml file: https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/ml-frameworks/pytorch/deployment/train-hyperparameter-tune-deploy-with-pytorch/train-hyperparameter-tune-deploy-with-pytorch.yml Please follow the below documents for pytorch on Azure. https://notebooks.azure.com/pytorch https://azure.microsoft.com/en-us/blog/pytorch-on-azure-full-support-for-pytorch-1-2/
https://stackoverflow.com/questions/59492635/
PyTorch regression is producing the same numbers as prediction
I have applied a simple NN for regression to the traditional boston housing price dataset. The problem I’m getting is, when I make predictions using the trained model it always predicts the same numbers. Here is my code: import numpy as np import pandas as pd from sklearn import datasets data = datasets.load_boston() X = pd.DataFrame(data.data, columns=data.feature_names) Y = pd.DataFrame(data.target, columns=["MEDV"]) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.20, random_state=1234) import torch x_train = torch.tensor(X_train.values, dtype=torch.float) y_train = torch.tensor(y_train.values, dtype=torch.float) x_test = torch.tensor(X_test.values, dtype=torch.float) y_test = torch.tensor(y_test.values, dtype=torch.float) import torch.nn.functional as F class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.predict = torch.nn.Linear(n_hidden, n_output) def forward(self, x): x = F.relu(self.hidden(x)) x = self.predict(x) return x net = Net(n_feature=13, n_hidden=50, n_output=1) optimizer = torch.optim.SGD(net.parameters(), lr=0.2) loss_func = torch.nn.MSELoss() for t in range(200): prediction = net(x_train) loss = loss_func(prediction, y_train) print(t, loss.item()) optimizer.zero_grad() loss.backward() optimizer.step() Here is the loss per epoch log: 0 6414.029296875 1 3.883837028532696e+19 2 5.963952279684907e+18 3 2.1470207536047063e+18 4 7.729279495852524e+17 5 2.7825424945486234e+17 6 1.001715136546734e+17 7 3.606170935335322e+16 8 1.2982211888283648e+16 9 4673591211720704.0 10 1682493577101312.0 11 605696890503168.0 12 218050926215168.0 13 78498328739840.0 14 28259370663936.0 15 10173364043776.0 16 3662410940416.0 17 1318467796992.0 18 474648543232.0 19 170873470976.0 20 61514457088.0 21 22145208320.0 22 7972275200.0 23 2870019072.0 24 1033206912.0 25 371954528.0 26 133903616.0 27 48205360.0 28 17353982.0 29 6247483.5 30 2249145.25 31 809743.25 32 291558.65625 33 105012.1171875 34 37855.3984375 35 13678.982421875 36 4975.46826171875 37 1842.20361328125 38 714.2283325195312 39 308.15716552734375 40 161.97158813476562 41 109.34477233886719 42 90.39911651611328 43 83.57867431640625 44 81.12332153320312 45 80.23938751220703 46 79.92117309570312 47 79.8066177368164 48 79.76537322998047 49 79.75053405761719 50 79.74518585205078 51 79.7432632446289 52 79.74256896972656 53 79.74231719970703 54 79.74223327636719 55 79.74219512939453 56 79.7421875 57 79.74217987060547 58 79.74217987060547 59 79.74217987060547 60 79.74217987060547 61 79.74217987060547 62 79.74217987060547 63 79.74217987060547 64 79.74217987060547 65 79.74217987060547 66 79.74217987060547 67 79.74217987060547 68 79.74217987060547 69 79.74217987060547 70 79.74217987060547 71 79.74217987060547 72 79.74217987060547 73 79.74217987060547 74 79.74217987060547 75 79.74217987060547 76 79.74217987060547 77 79.74217987060547 78 79.74217987060547 79 79.74217987060547 80 79.74217987060547 81 79.74217987060547 82 79.74217987060547 83 79.74217987060547 84 79.74217987060547 85 79.74217987060547 86 79.74217987060547 87 79.74217987060547 88 79.74217987060547 89 79.74217987060547 90 79.74217987060547 91 79.74217987060547 92 79.74217987060547 93 79.74217987060547 94 79.74217987060547 95 79.74217987060547 96 79.74217987060547 97 79.74217987060547 98 79.74217987060547 99 79.74217987060547 100 79.74217987060547 101 79.74217987060547 102 79.74217987060547 103 79.74217987060547 104 79.74217987060547 105 79.74217987060547 106 79.74217987060547 107 79.74217987060547 108 79.74217987060547 109 79.74217987060547 110 79.74217987060547 111 79.74217987060547 112 79.74217987060547 113 79.74217987060547 114 79.74217987060547 115 79.74217987060547 116 79.74217987060547 117 79.74217987060547 118 79.74217987060547 119 79.74217987060547 120 79.74217987060547 121 79.74217987060547 122 79.74217987060547 123 79.74217987060547 124 79.74217987060547 125 79.74217987060547 126 79.74217987060547 127 79.74217987060547 128 79.74217987060547 129 79.74217987060547 130 79.74217987060547 131 79.74217987060547 132 79.74217987060547 133 79.74217987060547 134 79.74217987060547 135 79.74217987060547 136 79.74217987060547 137 79.74217987060547 138 79.74217987060547 139 79.74217987060547 140 79.74217987060547 141 79.74217987060547 142 79.74217987060547 143 79.74217987060547 144 79.74217987060547 145 79.74217987060547 146 79.74217987060547 147 79.74217987060547 148 79.74217987060547 149 79.74217987060547 150 79.74217987060547 151 79.74217987060547 152 79.74217987060547 153 79.74217987060547 154 79.74217987060547 155 79.74217987060547 156 79.74217987060547 157 79.74217987060547 158 79.74217987060547 159 79.74217987060547 160 79.74217987060547 161 79.74217987060547 162 79.74217987060547 163 79.74217987060547 164 79.74217987060547 165 79.74217987060547 166 79.74217987060547 167 79.74217987060547 168 79.74217987060547 169 79.74217987060547 170 79.74217987060547 171 79.74217987060547 172 79.74217987060547 173 79.74217987060547 174 79.74217987060547 175 79.74217987060547 176 79.74217987060547 177 79.74217987060547 178 79.74217987060547 179 79.74217987060547 180 79.74217987060547 181 79.74217987060547 182 79.74217987060547 183 79.74217987060547 184 79.74217987060547 185 79.74217987060547 186 79.74217987060547 187 79.74217987060547 188 79.74217987060547 189 79.74217987060547 190 79.74217987060547 191 79.74217987060547 192 79.74217987060547 193 79.74217987060547 194 79.74217987060547 195 79.74217987060547 196 79.74217987060547 197 79.74217987060547 198 79.74217987060547 199 79.74217987060547 After training the model, I’ve used the following code to make predictions: with torch.no_grad(): y_val = net(x_test) When I print the predictions I get the following results: tensor([[22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099], [22.4099]])
It seems to me that the model does not fit to your dataset well. After inspecting your code, I think I could guess where went wrong. The way you perform gradient descent is somehow incorrect to me. Bear in mind that we are optimizing on a non-convex function. So pack the whole train dataset in a batch would not work, and your model will be stuck in a local-minium, which always not good enough. This could turn into a more complicated discussion with quite a lengthy explanation. I found a good reference for you to understand why we cannot do that on a non-convex function from Here. My suggestion is to try to sample your training data into small batch-size and run forward-backward update with small batches with a loop inside your epoch loop. for instance, from 8 to 96, and see how that works. In your toy example, you could shuffle your training data each epoch and select your mini-batch one by one. If you wanted to go fancier(or, more standard for performing deep learning in Pytorch), you could write a PyTorch dataset to handle data loading and batching. The loss of your training data should be very small if you are doing this correctly. Edit: You might also want to gradually decrease your learning rate, say, 10 times after every 60 epochs to get a better-optimized loss function.
https://stackoverflow.com/questions/59506405/
Can't use GPU with Pytorch
I keep getting this error when trying to use Pytorch. RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU. I installed Pytorch using conda install pytorch torchvision cudatoolkit=10.1 -c pytorch. With tensorflow my GPU runs just fine.
You can fix this error by installing CUDA 10.2 (The Latest Version) and, additionally re-install Pytorch with this command: conda install pytorch torchvision cudatoolkit=10.2 -c pytorch
https://stackoverflow.com/questions/59506935/