id
stringlengths
3
8
text
stringlengths
1
115k
st99068
criterion = nn.CrossEntropyLoss() for i in range(10): _, output = torch.max(model(x_train_tensor[i]), 0) print(output, y_train_tensor[i]) print(criterion(output, y_train_tensor[i])) =================================== output is: tensor(0), tensor(0) error: RuntimeError: Dimension out of range (expected to be in range of [-1, 0], but got 1) how can i fix it?
st99069
jaeyung1001: print(criterion(output, y_train_tensor[i])) Maybe you misunderstood about nn.CrossEntropyLoss()? You need not take max and pass the index to the loss. nn.CrossEntropyLoss() expects a 2D array of logits where each row belongs to values predicted for a particular item.
st99070
if i need classify two classes[ex. true, false], which loss function should be used? can you suggest for me?
st99071
You can use either nn.BCELoss() or nn.CrossEntropyLoss(). For nn.BCELoss(), your network shall have one output node with Sigmoid output activation. For nn.CrossEntropyLoss(), your network shall have two output node without any activation.
st99072
if my DNN model’s last layer use Relu activation function, BCELoss function can not use?
st99073
I think, you should change the final node’s activation to Sigmoid if you are planning to use nn.BCELoss(). Because, 0 <= nn.ReLU(output) <= inf and BCELoss expects probability (0 to 1).
st99074
What is the meaning of padding size in Transposed Convolution? Strictly for Conv2dTranspose? Also, what if we had chance to pad 1’s instead of 0’s? Could this change the output of Conv2dTranspose? I cannot really understand the meaning of padding in the context of Transposed Convolution…
st99075
Hi, I am running the same training code with and without the line: model = nn.DataParallel(model, device_id=[0,1]) I am surprised that the training with multi-gpu get a much better result. I thought that was something random in training procedure. So I repeated several times the singe/multi-GPU training. The multi-gpu training always get a result 2% better than the single-gpu training. 2% is not a negligible difference in my task. I am using Resnet50 with my own data. I replaced the last fc layer. And dropout is used. So I want to know how to explain this? whether there are some operations working differently in multi-gpu mode? Thank you
st99076
the difference is the batch_size, when you uyse nn.DataParralle(), the batch size is multiple times as your single gpu’s one
st99077
I made a breakpoint at getitem inside Dataloader but got ValueError: I/O operation on closed file
st99078
Now, I have a model defined as follows: class TripletNet(nn.Module): def __init__(self, embedding_net): super(TripletNet, self).__init__() self.embedding_net = embedding_net def forward(self, x1, x2, x3): output1 = self.embedding_net(x1) output2 = self.embedding_net(x2) output3 = self.embedding_net(x3) return output1, output2, output3 def get_embedding(self, x): return self.embedding_net(x) model=TipleNet(embedding_net) model=torch.nn.DataParallel(model) now call the get_embedding function, model.get_embedding(x), an error occurs as follows: AttributeError: ‘DataParallel’ object has no attribute ‘get_embedding’ Now, I want to call the function get_embedding, what can I do?
st99079
module is a reference to the model that is packed inside nn.DataParallel. .modules() is a method inherited from nn.DataParallel's parent nn.Module. Refer this post for more info: Module.children() vs Module.modules() If you want to recursively iterate over modules, then you want to use .modules() For example, in the following network m = nn.Sequential(nn.Linear(2,2), nn.ReLU(), nn.Sequential(nn.Sigmoid(), nn.ReLU())) calling m.children() will return [Linear (2 -> 2), ReLU (), Sequential ( (0): Sigmoid () (1): ReLU () )] which means that it does not go inside the second Sequential, and thus does not print individually Sigmoid. On the other hand, m.modules() rec…
st99080
What would be faster? I thought I might be able to pair matrices and parallelise the computation with batched matrix multiplications, but it was slower: https://gist.github.com/gngdb/70fce4f27cdaeeb3f8f18cf9929e60d3 23
st99081
Hi gngdb, the recursive function you are using has an overhead for concatenation and slicing. Hence, for reducing smaller lists, the naive reduce may be faster. However, for list lengths of 128, I got the following result. functools: CPU: 2.2555802155067415 GPU: 3.1399718035379047 recursive: CPU: 10.128527292804142 GPU: 1.773943289081565 So your batching method scales better then the naive reduce.
st99082
Ah, that makes sense, thanks. Looking at this again today, there’s actually a massive mistake. The test to check that functools_reduce and recursive_reduce match was wrong, it was just testing to see that recursive_reduce and recursive_reduce were equal. Fixing that, I realised that the resulting matrix explodes, which makes the test a little difficult, so have to scale by sqrt of M to keep approximately unit variance.
st99083
Hi, Thanks for your contributions to this wonderful framework. I am working on a program with pytorch, and I come to this problem: I need my dataloader to return tensor in batch, and I need the batch is returned in order and without replacement. That is to say, I hope my dataloader can give me data batch with index 1, 2, 3, … 32 (suppose batch size is 32) for the first batch, and for the second batch it is expected to return 33, 34, 35, … 64, and so on. Until the last sample is returned, the epoch ends. How could I do this ?
st99084
Hi coincheung, what you have described is the default setting of the data loader. For help with Dataloaders, you can refer to this tutorial 464. Just set the shuffle argument to False for your use.
st99085
How do I train YoloV3 to indentify my own custom objects? All I can find is tutorials on how to train the COCO dataset with pretrained weights. I use this implementation of YoloV3: https://github.com/ayooshkathuria/pytorch-yolo-v3 406 This is an example of things i have to detect: Is there anywhere a topic on how to train completely new data? Can’t seem to find it anywhere. Thanks in advance
st99086
Check out @andy-yun’s repo 758. He added some training routines to the YOLO implementation.
st99087
Dear all, Recently I run a simple code for classification on MNIST dataset, I found some times I got 98% accuracy just after 1 epoch and some times just 50% after one epoch. The result changed every time and the difference were big. Then I tried to set random seed constant, and tried different value. I found the result in different random seed value changed much. For example, I used Adadelta as optimizer and ran 1 epoch, when I set random seed to 1, the accuracy was 98% and when I set random seed to 1000, the accuracy became 69%. Besides, when I use Adam as optimizer and run 1 epoch,the result are always bad( 60-70% accuracy, sometimes it can also reach 98% ) but use Adadelta the accuracy is usually good( 98% acuuracy). Optimizers are in default setting I can understand they will influence the result but I just feel this influence are so big. Can anyone tell me why it is? I would be really appreciated. Thanks!
st99088
Your model might be quite sensitive to the current initialization of your parameters. Are you using some the default init or did you initialize your parameters yourself? In an optimal setup, the training should reach comparable accuracies for different random seeds, although the training time might differ a bit. You should not “optimize” the seed in any way. It sounds like your model might be small and you reached 98% accuracy by chance in the first epoch.
st99089
I try to compile libtorch with PCL library. Both the libraries work fine when compiled dependently, but segmentation fault occurs when complie these libraries together. cmake file: cmake_minimum_required(VERSION 3.0 FATAL_ERROR) project(custom_ops) SET(CMAKE_BUILD_TYPE "Debug") list(APPEND CMAKE_PREFIX_PATH ${CMAKE_CURRENT_SOURCE_DIR}/libtorch) find_package(Torch REQUIRED) find_package(PCL 1.8 REQUIRED COMPONENTS common io visualization) include_directories( ${PCL_INCLUDE_DIRS} ) add_definitions(${PCL_DEFINITIONS}) add_executable(pytorch2pt src/main.cpp) target_link_libraries(pytorch2pt ${PCL_LIBRARIES} ${TORCH_LIBRARIES}) set_property(TARGET pytorch2pt PROPERTY CXX_STANDARD 11) main.cpp (I remove the code related to libtorch, but the seg fault still occur) // #include <torch/script.h> #include <iostream> #include <memory> #include <vector> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/visualization/cloud_viewer.h> int main() { std::string test_data = "./test.pcd"; # path to your pcd file pcl::PointCloud<pcl::PointXYZI>::Ptr in_cloud_ptr(new pcl::PointCloud<pcl::PointXYZI>); if (pcl::io::loadPCDFile<pcl::PointXYZI>(test_data.c_str(), *in_cloud_ptr) == -1) # segmetation fault here { PCL_ERROR ("Couldn't read pcd file \n"); return (-1); } } Besides, when I compile the project with “Release” mode, I get the information: CMakeFiles/pytorch2pt.dir/src/main.cpp.o: In function `main': main.cpp:(.text.startup+0x1da): undefined reference to `pcl::PCDReader::read(std::string const&, pcl::PCLPointCloud2&, Eigen::Matrix<float, 4, 1, 0, 4, 1>&, Eigen::Quaternion<float, 0>&, int&, int)' collect2: error: ld returned 1 exit status CMakeFiles/pytorch2pt.dir/build.make:345: recipe for target 'pytorch2pt' failed make[2]: *** [pytorch2pt] Error 1 CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/pytorch2pt.dir/all' failed make[1]: *** [CMakeFiles/pytorch2pt.dir/all] Error 2 Makefile:83: recipe for target 'all' failed make: *** [all] Error 2 The environment of my computer: OS: ubuntu 16.04 libtorch: nightly version with CPU only PCL: 1.7.2 (I have tried v1.8.1, but I got the same issue) Boost: 1.58.0 CUDA: 9.0 CUDNN: 7.1.3 Any idea about this issue?
st99090
Hi, I am unable to understand why LSTMs hidden parameters have the size of a minibatch as a dimension. Shouldn’t the model be independent of the size of minibatch which is an attribute of the training process. I am especially facing this issue while testing. The model expects me to still do the forward pass on a minibatch of certain size while I want to be able to make individual predictions.
st99091
Wondering if there are any easy pytorch functions to rebin a target 1-hot vector. E.g. Change the dimensionality from 1000->100
st99092
Could you explain your use case a bit? How would you rebin the one-hot vector? Just considering multiple entries in the original tensor as one bin in the new one? Another side question: what do you need the one-hot tensor for?
st99093
Thanks for helping, I’d be happy to. Targets tensor size: [10000 x 1000] So the shape of each is (1000,) as a 1-hot vector. I want to reduce the tensor to [10000 x 100] where the 1 is redistributed to the correct overlapping bin. As probably the real question, are there any loss functions that consider proximity of classes within the loss? So if the correct target class is N in range [0, C-1], it could consider a classification of N-1 or N+1 partially correct?
st99094
Well, you could use regression loss functions like nn.MSELoss, but they might perform poorly on a classification task. Another approach would be to soften your target and use soft labels in nn.CrossEntropyLoss. There are some shortcomings to this approach also, as explained here 8.
st99095
If I use different weights for the same network, the forward pass speeds are very different. One takes around 0.017s the other takes 0.6s I am unsure why this is happening. Both the weights file have the same size (101M). The first one is provided by author of a repository, while the other is just retrained. So I am guessing the pytorch version while saving the first model would have been different. So I am wondering if there is anything extra that needs to be done while using torch.save in pytorch 1.0
st99096
Solved by ptrblck in post #10 Sorry for the late reply. I’ve reproduced the timing issue, profiled your code using torch.utils.bottleneck, and it seems run with random weights just performs a lot more calls to layers/box_utils.py. It’s a guess as I’m not familiar with the code, but I think the random weights just might create a…
st99097
How do you time your code? Is it the CPU or GPU time? Are you using exactly the same code and just swap the weights? If so, could you provide these weights, so that we could try to replicate this issue?
st99098
I am sorry, I should have done that in the first place. This is the repository. https://github.com/amdegroot/ssd.pytorch.git 7. Here is another issue which has the same problem https://github.com/amdegroot/ssd.pytorch/issues/215 10 I have created a fork here to reproduce the bug: https://github.com/TheShadow29/ssd.pytorch 3. I simply downloaded VOC2007, and VOC2012, extracted them and then create a symlink to the VOCdevkit in the folder data/ after setting up VOC dataset. I think there is should be an easier approach, but that would require a bit more changes to the code so I have not done that. Then download pre-trained weight https://github.com/amdegroot/ssd.pytorch#download-a-pre-trained-network 4 from here and put it into the weights folder Then in eval2.py I just do a forward pass using pre-trained weights and without loading any weights. Here is my eval2.py code if __name__ == '__main__': # load net num_classes = len(labelmap) + 1 # +1 for background net = build_ssd('test', 300, num_classes) # initialize SSD net.cuda() net.eval() st_time = time.time() o = net(torch.rand(1, 3, 300, 300)) print(time.time() - st_time) if args.trained_model: print('Loading Existing Model', args.trained_model) net.load_state_dict(torch.load(args.trained_model)) net.cuda() net.eval() st_time = time.time() o = net(torch.rand(1, 3, 300, 300)) print(time.time() - st_time) Then I run python eval2.py --trained_model weights/ssd300_mAP_77.43_v2.pth And this is the output: Firs is the time for forward pass of the network without weights loaded, second is with weights loaded. Let me know if there is something missing in the setup.
st99099
Thanks for the information. Something seems to be strange in your current code. It seems you are pushing the model to the GPU, but are passing CPU tensors. Is it a typo in the posted code or am I missing something, e.g. a push to the device in the forward method? Also, if you are trying to time CUDA calls, note that they are asynchronous. That means you should call torch.cuda.synchronize() before starting and stopping the timer. Could you add these lines of code and time it again? I would just want to make sure it’s not a timing issue.
st99100
ptrblck: Is it a typo in the posted code or am I missing something, e.g. a push to the device in the forward method? Good point. Interestingly, after running the program, if I do a = torch.rand(1, 3, 300, 300) a.type() I get torch.cuda.FloatTensor(). Here is the relevant screenshot image.png698×240 19.3 KB Not sure, why this is happening. This is why it didn’t raise a bug even though it should have been a cpu tensor since it is residing in the gpu. ptrblck: That means you should call torch.cuda.synchronize() before starting and stopping the timer. Not sure if I am following you. Even if it was so, the same should happen for both of them. I have added torch.cuda.synchronize() before both start and end time. The results are still the same unfortunately. image.png705×85 9.12 KB I have pushed the changes to git repo as well. (https://github.com/TheShadow29/ssd.pytorch 4)
st99101
The default type is set at the beginning of the script 10, so that should be alright, It’s sometimes hard to tell which operations are still being executed in the background and might therefore influence the timing. Apparently, the synch calls do not change anything. Do you see the same speed difference on the CPU or just using the GPU?
st99102
There still seems to be a difference in speeds even on CPU image.png1512×103 11.3 KB But it is smaller than what it was previously
st99103
I also tried to do a full run of eval.py. The evaluation for the pretrained networks takes around 15 mins, while the other one takes more than 2 hours.
st99104
Sorry for the late reply. I’ve reproduced the timing issue, profiled your code using torch.utils.bottleneck, and it seems run with random weights just performs a lot more calls to layers/box_utils.py. It’s a guess as I’m not familiar with the code, but I think the random weights just might create a lot of more detection candidates which are evaluated one after the other. Could you confirm the assumption?
st99105
You are absolutely correct. I didn’t realize that nms was being called in the forward method itself. nms contains a while loop, which is causing the time difference. Thank you.
st99106
Hi folks, I am trying to build an ensemble with the following code: class PytorchMnistEnsModel(nn.Module): """ Basic MNIST model from github https://github.com/rickiepark/pytorch-examples/blob/master/mnist.ipynb """ def __init__(self, num_models=5): super(PytorchMnistEnsModel, self).__init__() # input is 28x28 # padding=2 for same padding self.conv1 = {} self.conv2 = {} self.fc1 = {} self.fc2 = {} self.num_models = num_models for i in range(self.num_models): self.conv1[i] = nn.Conv2d(1, 32, 5, padding=2) # feature map size is 14*14 by pooling # padding=2 for same padding self.conv2[i] = nn.Conv2d(32, 64, 5, padding=2) # feature map size is 7*7 by pooling self.fc1[i] = nn.Linear(64 * 7 * 7, 1024) self.fc2[i] = nn.Linear(1024, 10) def forward(self, x): preds_list = [] y = {} for i in range(self.num_models): y[i] = torch.tensor(x, requires_grad=True) y[i] = F.relu((self.conv1[i](y[i]))) y[i] = F.max_pool2d(y[i], 2) y[i] = F.relu(self.conv2[i](y[i])) y[i] = F.max_pool2d(y[i], 2) y[i] = y[i].view(-1, 64 * 7 * 7) # reshape Variable y[i] = F.relu(self.fc1[i](y[i])) y[i] = self.fc2[i](y[i]) preds_list.append(F.log_softmax(y[i], dim=-1)) preds_avg = torch.mean(torch.stack(preds_list), dim = 0) return preds_avg When I call model.parameters() on this, it returns an empty list. I am guessing it has something to do with my usage of dictionary for defining conv and fc layers. How do I go about fixing this? Thanks in advance!
st99107
Solved by madmax in post #4 Here is the modified code. Hopefully this helps someone in the future class PytorchMnistEnsModel(nn.Module): """ Basic MNIST model from github https://github.com/rickiepark/pytorch-examples/blob/master/mnist.ipynb """ def __init__(self, num_models=5): super(PytorchMnistEnsM…
st99108
You could either use nn.ModuleList or nn.Sequential to store the layers. Python lists and dicts aren’t the right ones for storing torch modules. The difference in usage between nn.ModuleList and python list I can’t figure out what the purpose of nn.ModuleList is because as far as I know, list can be used in most scenarios I come up with. For example, for the newtork structure below, def __init__(self): super(MyNN, self).__init__() fcs = [nn.Sequential( nn.Linear(fc_input_size, fc_hidden_size), nn.ReLU(), nn.Linear(fc_hidden_size,num_classes) ) for fc_hidden_size in fc_hidden_sizes] #self.network = nn.ModuleList(fcs) self.network = fcs I don’t see the difference between …
st99109
Here is the modified code. Hopefully this helps someone in the future class PytorchMnistEnsModel(nn.Module): """ Basic MNIST model from github https://github.com/rickiepark/pytorch-examples/blob/master/mnist.ipynb """ def __init__(self, num_models=5): super(PytorchMnistEnsModel, self).__init__() # input is 28x28 # padding=2 for same padding self.conv1 = nn.ModuleList() self.conv2 = nn.ModuleList() self.fc1 = nn.ModuleList() self.fc2 = nn.ModuleList() self.num_models = num_models for i in range(self.num_models): self.conv1.append(nn.Conv2d(1, 32, 5, padding=2)) # feature map size is 14*14 by pooling # padding=2 for same padding self.conv2.append(nn.Conv2d(32, 64, 5, padding=2)) # feature map size is 7*7 by pooling self.fc1.append(nn.Linear(64 * 7 * 7, 1024)) self.fc2.append(nn.Linear(1024, 10)) def forward(self, x): preds_list = [] y = {} for i in range(self.num_models): y[i] = torch.tensor(x, requires_grad=True) y[i] = F.relu((self.conv1[i](y[i]))) y[i] = F.max_pool2d(y[i], 2) y[i] = F.relu(self.conv2[i](y[i])) y[i] = F.max_pool2d(y[i], 2) y[i] = y[i].view(-1, 64 * 7 * 7) # reshape Variable y[i] = F.relu(self.fc1[i](y[i])) y[i] = self.fc2[i](y[i]) preds_list.append(F.log_softmax(y[i], dim=-1)) preds_avg = torch.mean(torch.stack(preds_list), dim = 0) return preds_avg
st99110
For an implementation of a graphical model I need to perform matmul along the axis 1 and 2 of a four-dimensional input tensor. The axis 0 and 3 should be broadcasted. The current implementation of torch matmul 16 performs the matrix multiplication across the final two axis and performs broadcasting across all of input[:-2]. Currently I solve this by first transposing the input and then performing matmul. input_row = input_col.transpose(1, 3) message = torch.matmul(self.gaussian, input_row) However, this is very slow. Profiling indicate that 67% of computational time of the entire model is a contiguous call inside matmul (see below). The only reason this contiguous call is necessary is the transpose right before the matmul, as input_col is contiguous. blocking.png673×745 41.2 KB Does anybody know how I can perform this operation without transposing input_col?
st99111
I’ve written a pytorch script, and looking to speed it up. I’ve tried the following: use a c4.4xlarge, in cpu mode, instead of Mac OS X, in cpu mode => result is twice as slow as on Mac use an aws g2, in cuda mode => twice as fast as Mac laptop. yay use an aws p2, in cuda mode => another 50% as fast as g2 Now at this point, I’m not sure which bits are slow If it was a c++ script, that didnt use cuda, I might use either statistical sampling: ie, start in debugger, stop it, and store the stacktrace. do this eg 5-10 times, and look at which bits/functions tend to me in man yof the stacktraces => this is the bottleneck if it was cltorch, or deepcl, well I pre-instrumented them with profilers in pytorch cuda, I suppose I should use an nviida profiler? Or … ? Its not clear to me which bits of the program are taking the time, could be cpu bits, so I’d prefer to start at a higher level than nvidia profiler probably. Thoughts on ideas / stadnard techinques, for profiling pytorch?
st99112
Edited, to remove the concrete script. Just to be clear, I’m not looking for ways to speed up the specific script, but for ways of profiling in pytorch generally.
st99113
I’ve just been using kernprof 1.5k, which led me to identifying several key bottlenecks and some other interesting things I may need to raise some issues for if I get a chance to track em down…
st99114
@ajbrock kernprof seems tentatively quite nice Off-topic for this thread, but just cos I find it interesting, I get radically different timings on cpu vs gpu, I mean, different things are slow. On cpu, it looks like my bottleneck is tanh, interestingly,whereas on gpu, it’s matrix multiplicaiton. Mac, CPU mode: 215 2585 40255 15.6 0.2 prev_dec_state = prev_dec_state.view(batch_size, hidden_size) 216 2585 182622 70.6 1.1 prev_dec_state_W = prev_dec_state @ self.W 217 2585 39752 15.4 0.2 enc_out_U = enc_out.view(seq_len * batch_size, hidden_size * 2) @ \ 218 2585 3005655 1162.7 17.8 self.U.transpose(0, 1) 219 2585 53347 20.6 0.3 enc_out_U = enc_out_U.view(seq_len, batch_size, hidden_size) 220 2585 2367 0.9 0.0 prev_dec_state_W_exp = prev_dec_state_W \ 221 2585 31246 12.1 0.2 .view(1, batch_size, hidden_size) \ 222 2585 68789 26.6 0.4 .expand(seq_len, batch_size, hidden_size) 223 2585 2063555 798.3 12.2 x = enc_out_U + prev_dec_state_W_exp 224 2585 10745470 4156.9 63.7 x = F.tanh(x) 225 2585 304178 117.7 1.8 x = x.view(seq_len * batch_size, hidden_size) @ self.v.view(-1, 1) 226 2585 40751 15.8 0.2 x = x.view(seq_len, batch_size) 227 2585 32390 12.5 0.2 x = x.transpose(0, 1) 228 2585 243247 94.1 1.4 x = F.softmax(x) tanh is slow on an aws p2, using cuda, and with some syncs thrown in, just to be sure (results are same without sync though, weirdly): 220 2541 48584 19.1 2.6 prev_dec_state = prev_dec_state.view(batch_size, hidden_size) 221 2541 211774 83.3 11.4 prev_dec_state_W = prev_dec_state @ self.W 222 2541 48346 19.0 2.6 enc_out_U = enc_out.view(seq_len * batch_size, hidden_size * 2) @ \ 223 2541 225530 88.8 12.1 self.U.transpose(0, 1) 224 2541 46828 18.4 2.5 enc_out_U = enc_out_U.view(seq_len, batch_size, hidden_size) 225 2541 2511 1.0 0.1 prev_dec_state_W_exp = prev_dec_state_W \ 226 2541 30299 11.9 1.6 .view(1, batch_size, hidden_size) \ 227 2541 92212 36.3 5.0 .expand(seq_len, batch_size, hidden_size) 228 2541 96198 37.9 5.2 x = enc_out_U + prev_dec_state_W_exp 229 2541 223889 88.1 12.0 cuda_sync() 230 2541 170755 67.2 9.2 x = F.tanh(x) 231 2541 62406 24.6 3.4 cuda_sync() 232 2541 281476 110.8 15.1 x = x.view(seq_len * batch_size, hidden_size) @ self.v.view(-1, 1) 233 2541 45434 17.9 2.4 cuda_sync() 234 2541 48591 19.1 2.6 x = x.view(seq_len, batch_size) 235 2541 29989 11.8 1.6 x = x.transpose(0, 1) 236 2541 194787 76.7 10.5 x = F.softmax(x) => matrix multiplication dominates in this case Hmmm, as I write, I’m wondering whether tanh is actually running multi-core, in the cpu version? Seems it might not be?
st99115
I raised an issue for it here: https://github.com/pytorch/pytorch/issues/2136 367
st99116
With lprun, how do you deal with the cuda synchronization problems? I was running it through my loop, but if I don’t use cuda.synchronize() in the loop, lprun says my cuda calls: x = x.cuda() are taking up nearly 50% of the time, whereas if I put a cuda.synchronize() at the top of each iteration of the training loop it says cuda.synchronize() takes up 50% of the time.
st99117
I have got some strange issues as shown below, I use Pytorch, the “.item()” costs too much time according to the results from kernprof which is not expected. image.png915×392 57.6 KB If I comment out the first row using .item() (“train_loss += loss.item()”) Then the most time-consuming part will be the next row using .item() as below, where .item() is only a transform from tensor to scalar, is it so time-consuming?
st99118
image.png905×391 55.7 KB This may be incurred by the synchronize problem, am I right?
st99119
I made the same conclusion. As .item() has to wait for all CUDA operations to be completed, it’s a synchronization point. The timing is therefore not right and reflects the waiting for other ops to finish.
st99120
A few weeks ago, when I started on a project with PyTorch, I wanted to be able to drop certain samples from my dataset as part of a Transform, but found no easy way to go about it. So I ended up creating nonechucks - a library for PyTorch that provides wrappers for datasets, samplers, and transforms to allow for dropping unwanted samples dynamically. Apart from allowing Transforms to act as Filters, it also allows you to iterate through a dataset containing samples that might be erroneous. Check it out at https://github.com/msamogh/nonechucks 22. If you have any feedback, please do let me know - either down below at the comments or at my email: [email protected]. I’d appreciate it very much. Thank you.
st99121
If you want to know the number of elements in an entire tensor, torch.Tensor.nelement() is convenient. Finding the number of elements of a slice is less elegant in Torch than it is in NumPy, where you can use numpy.prod and a slice of the shape. What’s the idiomatic way to do this in Torch? If the current idiom is to populate a tensor with a slice of the torch.Size, would be more natural for torch.Tensor.size() to return a tensor type? In [1]: import numpy as np; import torch In [2]: xnp = np.random.normal(size=(3, 4, 5, 6)) In [3]: np3dims = np.prod(xnp.shape[:3]) In [4]: xt = torch.randn((3, 4, 5, 6)) In [5]: torch.prod(xt.size()[:3]) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-a2fe80b56024> in <module>() ----> 1 torch.prod(xt.size()[:3]) TypeError: torch.prod received an invalid combination of arguments - got (torch.Size), but expected one of: * (torch.FloatTensor source) didn't match because some of the arguments have invalid types: (torch.Size) * (torch.FloatTensor source, int dim) * (torch.FloatTensor source, int dim, bool keepdim) In [6]: np.prod(xt.size()[:3]) Out[6]: 60
st99122
the least ugly i could come up with is: import operator reduce(operator.mul, list(x.size())[:3])
st99123
it is painful that size does not return the number of elements, while shape returns the shape, as in numpy
st99124
You can just use np.prod. it works with any thing that is “array-like”, including tuples, lists, and torch.Size. import numpy as np; import torch t = torch.zeros((3, 4)) print(np.prod(t.shape)) # prints "12"
st99125
I am trying to train a neural network for a very large input (5*100,000,000) and it requires much more memory than expected. Here is some minimal example: import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import time class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv1d(in_channels=5, out_channels=1, kernel_size=100000000, stride=10) def forward(self, x): x = self.conv1(x) x = torch.sigmoid(x) return x model = Net().cuda() optimizer = optim.Adam(model.parameters(), lr=0.001) criterion = torch.nn.BCELoss() data = torch.normal(torch.zeros(1,5,100000000),torch.ones(1,5,100000000)) data = data.cuda() label = torch.ones(1,1,1) label = label.cuda() for epoch in range(10): output = model(data) loss = criterion(output, label) optimizer.zero_grad() loss.backward() optimizer.step() print("Epoch :", epoch) The input is some random data, it uses approximately 2Gb, as expected (32 bit * 5 * 100,000,000= 1.86Gb).This variable has no gradient. The network consists of a single convolutional layer with one filter of the same size as an input, so it has 500M weights, that is another 2Gb. After the forward pass another 2Gb get used. After loss.backprop() 8Gb are used, after optimizer.step() 12 Gb are used, that is all the available memory. During the second epoch forward pass runs ok, but during backpropagation I get RuntimeError: CUDA error: out of memory. What exactly is saved in GPU memory during the epoch? Why the memory is not released after the optimization step is finished? How to reduce memory usage in this case?
st99126
I’m not very sure, but I think this maybe because pytorch uses dynamic memory management, something similar to the python automatic garbage collection, to manage and free up GPU memory. Since you have few tensors which occupy a huge chunk of memory, the automatic garbage collection doesn’t kick in. To make this work, you’ll need to manually delete the output and loss variable at the end of your epoch to free up your GPU memory.
st99127
That is a good idea. I tried to delete loss and output, but it had no effect. The thing is that I don’t know what uses all the memory so I don’t know what to delete. The issue is similar to this one How to free GPU memory? (and delete memory allocated variables) 16, but there is no solution there.
st99128
Hello guys, could any body have machine learning code in python for text recognization in the images, please share it
st99129
This ORC code 80 is a few months old, but you could probably use it as a starter and update it if necessary.
st99130
Hello Ptrblck, Thanks for the information, i could not able to find the pretrained weights , the file named train.pt not available, could you please update further on this if you have done this project. python train.pt --test-init True --test-epoch 10 --output-dir <path_to_folder_with_snapshots> Thanks, Suhas
st99131
Sorry, I’m not familiar with the repo, just found it as an OCR application. There is an open issue 8 asking also for pretrained weights, so it seems you would have to use your own or a public dataset.
st99132
Hello Ptrblck, Thanks for the information and much apprciation for your help. Regards, Suhas
st99133
It looks like calls to _th_get_device are some of the most expensive ops according to the Pytorch profiler. It’s called a couple thousand times and I don’t see anything that’d obviously do this. I thought checking the device type of a tensor was a culprit, but I’m not doing that anywhere. I only cast as a CudaTensor a few times, not thousands. Which methods call this op (_th_get_device)? UPDATE: It seems like slice might be checking the device since it needs to allocate a new tensor. Is that unavoidable? Here’s an idea of what is being shown by the profiler: https://gist.github.com/mrdrozdov/2fc8fbf0ed2a77ea2f568bcea441bb97 11 The ops slice, cat, and _th_get_device are the most costly.
st99134
I have a bunch of images but these image has invalid ones, I using PIL cleand but still load images have errors. UserWarning: Corrupt EXIF data. Expecting to read 4 bytes but only got 0 Anybody knows how to solve this things?
st99135
u can do it in ImageFolder, https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py 272, u can modify it to do your own task.
st99136
Thanks for your reply, BTW, I did a clean process and seems all images are clean. But, a question composed, I have a HUGE dataset which contains almost 28 GB images in 20 classes, these images are very big, not just MNIST or CIFAR10, I want do a classification on this dataset. But it seems pytorch dataloader will load all images at once, my program are still loading data, this is very unefficient. Did pytorch have anything like tensorflow records and implement a generator or something so that shouldn’t load all images at once?
st99137
Check out nonechucks 91 - a library I wrote for PyTorch that allows you to do exactly that (and more)! @jinfagang @SherlockLiao
st99138
Hi, I have a given cmap for labels in a dataset with 35 classes such as a 35x3 matrix, where each tuple is a value corresponding to the r,g,b value of pixel for some class. My final semantic segmentation output is of size <batch, 35, height, width> So doing the following I get the indexes of the pixels having the highest probability num_classes = 35 output = output_from_segmentation_model() _, pred = torch.max(output, dim=1) Hence pred is a tensor with the index values where pred.shape = [batch, height, width] and pred.min = 0, pred.max = 34 Now I want to cast this an 3 channel image : img = torch.zeroes(output.size[0], output.size[2], output.size[3]) such that for the respective value of pixel in pred the image has r,g,b frrom that class in cmap, where cmap is given as follows : cityscapes_map = np.array([[0. , 0. , 0. ], [0. , 0. , 0. ], [0. , 0. , 0. ], [0. , 0. , 0. ], [0.07843137, 0.07843137, 0.07843137], [0.43529412, 0.29019608, 0. ], [0.31764706, 0. , 0.31764706], [0.50196078, 0.25098039, 0.50196078], [0.95686275, 0.1372549 , 0.90980392], [0.98039216, 0.66666667, 0.62745098], [0.90196078, 0.58823529, 0.54901961], [0.2745098 , 0.2745098 , 0.2745098 ], [0.4 , 0.4 , 0.61176471], [0.74509804, 0.6 , 0.6 ], [0.70588235, 0.64705882, 0.70588235], [0.58823529, 0.39215686, 0.39215686], [0.58823529, 0.47058824, 0.35294118], [0.6 , 0.6 , 0.6 ], [0.6 , 0.6 , 0.6 ], [0.98039216, 0.66666667, 0.11764706], [0.8627451 , 0.8627451 , 0. ], [0.41960784, 0.55686275, 0.1372549 ], [0.59607843, 0.98431373, 0.59607843], [0.2745098 , 0.50980392, 0.70588235], [0.8627451 , 0.07843137, 0.23529412], [1. , 0. , 0. ], [0. , 0. , 0.55686275], [0. , 0. , 0.2745098 ], [0. , 0.23529412, 0.39215686], [0. , 0. , 0.35294118], [0. , 0. , 0.43137255], [0. , 0.31372549, 0.39215686], [0. , 0. , 0.90196078], [0.46666667, 0.04313725, 0.1254902 ], [0. , 0. , 0.55686275]]) something in pseudocode : img[…] = img[cmap[pred[x]]] Please advice on correct syntax…
st99139
Discussion continued here : How to visualize segmentation output - multiclass feature map to rgb image? 146
st99140
This time I got the following error message: … [ 89%] Built target caffe2_gpu [ 89%] Linking CXX executable …/bin/apply_test [ 89%] Linking CXX executable …/bin/undefined_tensor_test [ 89%] Linking CXX executable …/bin/stream_test [ 89%] Linking CXX executable …/bin/cuda_rng_test /root/install/pytorch/build/lib/libcaffe2_gpu.so: undefined reference to ncclGroupEnd' /root/install/pytorch/build/lib/libcaffe2_gpu.so: undefined reference toncclGroupStart’ collect2: error: ld returned 1 exit status caffe2/CMakeFiles/cuda_rng_test.dir/build.make:101: recipe for target ‘bin/cuda_rng_test’ failed make[2]: *** [bin/cuda_rng_test] Error 1 CMakeFiles/Makefile2:1391: recipe for target ‘caffe2/CMakeFiles/cuda_rng_test.dir/all’ failed make[1]: *** [caffe2/CMakeFiles/cuda_rng_test.dir/all] Error 2 make[1]: *** Waiting for unfinished jobs… /root/install/pytorch/build/lib/libcaffe2_gpu.so: undefined reference to ncclGroupEnd' /root/install/pytorch/build/lib/libcaffe2_gpu.so: undefined reference toncclGroupStart’ /root/install/pytorch/build/lib/libcaffe2_gpu.so: undefined reference to ncclGroupEnd' /root/install/pytorch/build/lib/libcaffe2_gpu.so: undefined reference toncclGroupStart’ collect2: error: ld returned 1 exit status caffe2/CMakeFiles/apply_test.dir/build.make:101: recipe for target ‘bin/apply_test’ failed make[2]: *** [bin/apply_test] Error 1 CMakeFiles/Makefile2:1431: recipe for target ‘caffe2/CMakeFiles/apply_test.dir/all’ failed make[1]: *** [caffe2/CMakeFiles/apply_test.dir/all] Error 2 collect2: error: ld returned 1 exit status caffe2/CMakeFiles/stream_test.dir/build.make:101: recipe for target ‘bin/stream_test’ failed make[2]: *** [bin/stream_test] Error 1 CMakeFiles/Makefile2:1351: recipe for target ‘caffe2/CMakeFiles/stream_test.dir/all’ failed make[1]: *** [caffe2/CMakeFiles/stream_test.dir/all] Error 2 /root/install/pytorch/build/lib/libcaffe2_gpu.so: undefined reference to ncclGroupEnd' /root/install/pytorch/build/lib/libcaffe2_gpu.so: undefined reference toncclGroupStart’ collect2: error: ld returned 1 exit status caffe2/CMakeFiles/undefined_tensor_test.dir/build.make:99: recipe for target ‘bin/undefined_tensor_test’ failed make[2]: *** [bin/undefined_tensor_test] Error 1 CMakeFiles/Makefile2:1471: recipe for target ‘caffe2/CMakeFiles/undefined_tensor_test.dir/all’ failed make[1]: *** [caffe2/CMakeFiles/undefined_tensor_test.dir/all] Error 2 Makefile:140: recipe for target ‘all’ failed make: *** [all] Error 2 Failed to run ‘bash …/tools/build_pytorch_libs.sh --use-cuda --use-nnpack nccl caffe2 libshm gloo THD c10d’ This is related to caffe2 and nccl. I searched Internet, and didn’t find a solution yet. My system is AMD x86_64 Ubuntu 18.04, with gcc 7.3.0, cuda 9.2, cudnn 7.2.1.
st99141
Solved by Chun_Li in post #2 Got it done. Seems updated cmake from version 3.11.0 to 3.12.0 resolved the problem (though I also updated some other software packages as well).
st99142
Got it done. Seems updated cmake from version 3.11.0 to 3.12.0 resolved the problem (though I also updated some other software packages as well).
st99143
pip install --upgrade cmake or apt upgrade cmake depends on cmake which was installed via pip or apt (on ubuntu).
st99144
I am running my model on the GPU. However data loading (loading only, not preprocessing) is happening on the CPU. I’m wrapping a dataset with the DataLoader class, specifying 4 workers. When I run ps aux | grep <username> I see my 5 processes: the parent that is running the script and the 4 workers doing the data loading. When I check the number of threads used by each process (ps -o nkwp <PID>), I see that each worker (child process) is using 2 threads (which makes sense as there are 2 threads per core). The parent process, on the other hand, is using 191 threads. My machine has 40 cores (should have 80 threads, I thought), so I don’t understand how the parent is using so many threads. I don’t understand what is commanding 191 threads in the parent. My model is running entirely on the GPU, and the data loading is done in separate processes. Why am I using so many CPU resources?
st99145
I was looking at code of Layer norm 2 and the tensors are implicitly being assigned float32 data type. Why has this been done?
st99146
Solved by albanD in post #2 Hi, All module’s parameters are created with the default tensor type torch.Tensor. If you want to change this, you can either change the default tensor type with torch.set_default_tensor_type() or by changing the type of the layer afterwards with your_layer.double() to convert to double or your_la…
st99147
Hi, All module’s parameters are created with the default tensor type torch.Tensor. If you want to change this, you can either change the default tensor type with torch.set_default_tensor_type() or by changing the type of the layer afterwards with your_layer.double() to convert to double or your_layer.to(new_type).
st99148
Hi All, I am trying to implement a LSTM time series model with Professor forcing loss.My input dimension is 4 and the same would be by output dimension.Has anyone implemented something similar to this.Any help would be much appreciated
st99149
It could be a useful feature to allow deletion of variable from the computational graph, when back-propagating before that point is no longer necessary to save space and allow for ‘persistent’ computational structures. Deletion means release memory held by earlier variables and set new leaf variables. A example use case could be running a RNN for infinite steps and but only need gradient for K steps back computed at every single step, and it feels like there should be a way to do this without the need of constructing a new graph every time when gradient is needed.
st99150
What’s the problem with constructing a new graph every time? That’s the whole framework philosophy, so that it’s not restricted to static graph. To cut the history you can repackage the Variable in a new one Variable(var.data) (this is acceptable, as long as you discard var immediately - we don’t support having many variables with the same data). Also, you can use .detach() to obtain a new Variable that doesn’t require the gradient.
st99151
Because it may avoid some redundant computations in some cases? Say if I want to compute gradient for every step of RNN while looking K steps back for the gradient, I may not want to construct a new graph from K steps back at every step because lots of the forward computations are already done before. Is this right?
st99152
Ok, so as far as I understand, you want to do k steps with your RNN, and then move that k-sized window one step forward, and compute backward for every move? So effectively (nearly) every path would get backproped through k times?
st99153
Yes. I guess there are other use cases where subpaths will be backproped through multiple times, and it will be great if we can keep the graph and don’t have to reconstruct the whole graph with every backward call. This deviates a little from my original question but if we allow the graph to persist and grow then it can come to a point that forgetting some history, possibly by allowing deleting variables and reassigning leaf variables, becomes necessary and thus the question I was asking.
st99154
No, we haven’t thought about this use case. Is it something you’re doing or just an example?
st99155
I don’t have a working model that works like this but I work with very long sequences that is not practical to backprop all the way through, and this is one way I would try. I do think such flexibility is going to be helpful for enabling new types of models and I hope you would agree. Thanks!
st99156
Has this been implemented? I have currently an implementation in which it would be great to backpropagate every output of an LSTM for K steps backwards instead of detaching the hidden state every K steps. I’m not sure of how would updates to the parameters look like, but it would be interesting to explore e.g. for the char-rnn.
st99157
Hi. I have the same need. I want to do truncated backpropagation through time, and want to stop the gradient propagation past the hidden state from T time-steps ago. My previous approach was just to buffer the last T inputs and do a full computation of the forward pass from t-T to t, but that involves a lot of repeated computation! I’m looking for a way that I can just take the hidden state variable from T steps ago, and tell torch “don’t backpropagate past this variable!”. Is there a workaround that allows this?
st99158
Hi. I have the same problem too, has it been implemented yet or has a workaround been found ? I think it would be very interesting to implement the feature (like a maximum graph depth or something like that). For now I’ll try to implement something to crop the graph, I’ll probably make a new conversation about this.
st99159
Check this solution: Implementing Truncated Backpropagation Through Time autograd Here is an implementation that will work for any k1 and k2 and will reduce memory usage as much as possible. If k2 is not huge and the one_step_module is relatively big, the slowdown of doing multiple backward should be negligible. The code is not super clean and has been tested only against current master branch (where Variable and Tensor are merged) so you might need slight modifications if you use 0.3. Hope this helps. class TBPTT(): def __init__(self, one_step_module, loss_module, k…
st99160
@garibarba Thanks for that, I still find it to be quite slow (my crude benchmark tells that it is about 2x slower than native .backward())
st99161
About torch.nn.functional.interpolate( input, size=None, scale_factor=None, mode='nearest', align_corners=None) Document says size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]) – output spatial size. But it looks not clear I tried to upsample this one torch.Size([1, 224, 224]) to (1, 341, 512) But followings didn’t work o_p_ref=F.interpolate(o_p_ref, size=(ori_img_s[0],ori_img_s[1])) o_p_ref=F.interpolate(o_p_ref, size=(1, ori_img_s[0],ori_img_s[1])) Only this ones with one integer work o_p_ref=F.interpolate(o_p_ref, size=(ori_img_s[0])) # torch.Size([1, 224, 341]) o_p_ref=F.interpolate(o_p_ref, size=(ori_img_s[1])) # torch.Size([1, 224, 512]) Looking for some advice.
st99162
It has been solved by adding dimension o_p_ref=o_p_ref.unsqueeze(dim=0) # print(o_p_ref.shape) # torch.Size([1, 1, 224, 224]) o_p_ref=F.interpolate(o_p_ref, size=(ori_img_s[0],ori_img_s[1])) # torch.Size([1, 1, 341, 512])
st99163
Hi :), I see some lstm model codes have init_hidden() in def forward() while some are in def __init__(). Where does this difference come from??
st99164
@arvindmohan I just find answer. Actually, my question was Should I initialize hidden state in every epoch? If I put init_hidden() method in forward() It will initialize hidden state in every epoch. What I found is, If I have independent sequence data like text, I have to initialize hidden state in every epoch. But If I have dependent sequence data like stock price or something. Hidden state should not be initialized because hidden state would be keep used in the data.
st99165
Imo this largely relies on what is in your training code and how you create batches. The hidden state of the LSTM encodes what the model has seen so far during training. So If you assume a certain window and an input to the LSTM would be a randomized batch of several unrelated windows you will need to re-initialize your hidden state each training batch. If your batch size = 1 and you train without randomization and no windows (not sure how), you still need to initialize the hidden state at each epoch otherwise the LSTM will think it’s a continuation of the previous epoch not a 2nd pass over the training data.
st99166
I get that this is a relatively new and fast moving project. But so many things just plain don’t work or have simple bugs everywhere in the tutorials. For instance, just running the following code: https://pytorch.org/tutorials/_downloads/cifar10_tutorial.py 3 will throw a runtime error, something to do with pickling. I’d love to fix the issue and open a PR but this one example isn’t even in the same repo as the other ones at https://github.com/spro/practical-pytorch 1 which the guy says is deprecated, but then people have to play more detective to find the “legit” ones by pytorch. Are we allowed to open PRs for the documentation on this site? Because ML + new framework + new language (for some) is tough enough without all the other roadblocks.
st99167
I need to implement custom loss function and I saw following tutorial. class LinearFunction(Function): @staticmethod def forward(ctx, input, weight, bias=None): ctx.save_for_backward(input, weight, bias) output = input.mm(weight.t()) if bias is not None: output += bias.unsqueeze(0).expand_as(output) return output @staticmethod def backward(ctx, grad_output): input, weight, bias = ctx.saved_tensors grad_input = grad_weight = grad_bias = None if ctx.needs_input_grad[0]: grad_input = grad_output.mm(weight) if ctx.needs_input_grad[1]: grad_weight = grad_output.t().mm(input) if bias is not None and ctx.needs_input_grad[2]: grad_bias = grad_output.sum(0).squeeze(0) return grad_input, grad_weight, grad_bias But I don’t know how to use above guide for my situation. I have ground truth data, but it’s not a label data. I perform math formulas with GT data through all image pixels and I obtain one float number. And I want to update weights in CNN as above float number loss value minimizes. How to implement forward() and backward() in this case?