id
stringlengths
3
8
text
stringlengths
1
115k
st100700
In more detail: As Simon says, einsum collapses the dimensions of the factors internally to reduce to bmm. If that cannot be done with a view, it will do a reshape and thus have a copy of the factor. Best regards Thomas
st100701
My code halted with following error. File “train.py”, line 466, in main loss.backward() File “/opt/conda/lib/python3.6/site-packages/torch/tensor.py”, line 93, in backward torch.autograd.backward(self, gradient, retain_graph, create_graph) File “/opt/conda/lib/python3.6/site-packages/torch/autograd/init.py”, line 90, in backward allow_unreachable=True) # allow_unreachable flag RuntimeError: invalid argument 3: divide by zero at /opt/conda/conda-bld/pytorch_1532579805626/work/aten/src/THC/generic/THCTensorMathPairwise.cu:88 Backward through a mean where the input of the mean is an size-0 tensor.
st100702
In particular, Is it that each GPU separately computes its own parameters for batch norm over minibatch allocated to it? or do they communicate with each other for computing those parameters? If GPUs are independently computing these parameters, then how do GPUs combine these parameters, say, during inference or evaluation mode, and when do they do it?
st100703
Solved by ngimel in post #3 Yes, each GPU separately computes its own parameters They don’t, in inference the parameters that the master gpu accumulated are used This implementation of synchronized batch norm may be of interest if you indeed want the gpus to accumulate parameters between their respective mini-batches http://…
st100704
Yes, each GPU separately computes its own parameters They don’t, in inference the parameters that the master gpu accumulated are used This implementation of synchronized batch norm may be of interest if you indeed want the gpus to accumulate parameters between their respective mini-batches http://hangzh.com/PyTorch-Encoding/syncbn.html 273
st100705
PyTorch compatible Synchronized Cross-GPU encoding.nn.BatchNorm2d 325 and the example 251.
st100706
@zhanghang1989, would you be able to update links to the synchronized batch norm implementation as they don’t work anymore? Thanks!
st100707
I am trying to save the bicubic and HR_np images. I can plot it right but I am having a hard time in saving it. Below is my code. I tried using torchvision.utils.save_image(imgs[‘bicubic_np’], ‘ccc.png’.format(), nrow=8, padding=2, normalize=False, range=None, scale_each=False, pad_value=0) but it did not work. Tell me where I am going wrong. from future import print_function import matplotlib.pyplot as plt %matplotlib inline import argparse import os os.environ[‘CUDA_VISIBLE_DEVICES’] = ‘0’ import numpy as np from models import * import torch import torch.optim from skimage.measure import compare_psnr from models.downsampler import Downsampler from utils.sr_utils import * torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark =True dtype = torch.cuda.FloatTensor imsize = -1 factor = 4 # 8 enforse_div32 = ‘CROP’ # we usually need the dimensions to be divisible by a power of two (32 in this case) PLOT = True To produce images from the paper we took *_GT.png images from LapSRN viewer for corresponding factor, e.g. x4/zebra_GT.png for factor=4, and x8/zebra_GT.png for factor=8 path_to_image = ‘/home/smitha/Documents/Falcon.png’ imgs = load_LR_HR_imgs_sr(path_to_image , imsize, factor, enforse_div32) imgs[‘bicubic_np’], imgs[‘sharp_np’], imgs[‘nearest_np’] = get_baselines(imgs[‘LR_pil’], imgs[‘HR_pil’]) if PLOT: plot_image_grid([imgs[‘HR_np’], imgs[‘bicubic_np’], imgs[‘sharp_np’], imgs[‘nearest_np’]], 4,12); print (‘PSNR bicubic: %.4f PSNR nearest: %.4f’ % ( compare_psnr(imgs[‘HR_np’], imgs[‘bicubic_np’]), compare_psnr(imgs[‘HR_np’], imgs[‘nearest_np’]))) input_depth = 32 INPUT = ‘noise’ pad = ‘reflection’ OPT_OVER = ‘net’ KERNEL_TYPE=‘lanczos2’ LR = 0.01 tv_weight = 0.0 OPTIMIZER = ‘adam’ if factor == 4: num_iter = 2000 reg_noise_std = 0.03 elif factor == 8: num_iter = 4000 reg_noise_std = 0.05 else: assert False, ‘We did not experiment with other factors’ net_input = get_noise(input_depth, INPUT, (imgs[‘HR_pil’].size[1], imgs[‘HR_pil’].size[0])).type(dtype).detach() NET_TYPE = ‘skip’ # UNet, ResNet net = get_net(input_depth, ‘skip’, pad, skip_n33d=128, skip_n33u=128, skip_n11=4, num_scales=5, upsample_mode=‘bilinear’).type(dtype) Losses mse = torch.nn.MSELoss().type(dtype) img_LR_var = np_to_torch(imgs[‘LR_np’]).type(dtype) downsampler = Downsampler(n_planes=3, factor=factor, kernel_type=KERNEL_TYPE, phase=0.5, preserve_size=True).type(dtype) def closure(): global i, net_input if reg_noise_std > 0: net_input = net_input_saved + (noise.normal_() * reg_noise_std) out_HR = net(net_input) out_LR = downsampler(out_HR) total_loss = mse(out_LR, img_LR_var) if tv_weight > 0: total_loss += tv_weight * tv_loss(out_HR) total_loss.backward() # Log psnr_LR = compare_psnr(imgs['LR_np'], torch_to_np(out_LR)) psnr_HR = compare_psnr(imgs['HR_np'], torch_to_np(out_HR)) print ('Iteration %05d PSNR_LR %.3f PSNR_HR %.3f' % (i, psnr_LR, psnr_HR), '\r', end='') # History psnr_history.append([psnr_LR, psnr_HR]) if PLOT and i % 100 == 0: out_HR_np = torch_to_np(out_HR) plot_image_grid([imgs['HR_np'], imgs['bicubic_np'], np.clip(out_HR_np, 0, 1)], factor=13, nrow=3) i += 1 return total_loss psnr_history = [] net_input_saved = net_input.detach().clone() noise = net_input.detach().clone() i = 0 p = get_params(OPT_OVER, net, net_input) optimize(OPTIMIZER, p, closure, LR, num_iter) out_HR_np = np.clip(torch_to_np(net(net_input)), 0, 1) result_deep_prior = put_in_center(out_HR_np, imgs[‘orig_np’].shape[1:]) For the paper we acually took _bicubic.png files from LapSRN viewer and used result_deep_prior as our result plot_image_grid([imgs[‘HR_np’], imgs[‘bicubic_np’], out_HR_np], factor=4, nrow=1);
st100708
Solved by ptrblck in post #7 Sure, no worries. Here is a small example using random values for your imgs: imgs = {} imgs['bicubic_np'] = np.random.randn(1, 576, 576) tensors_to_plot = torch.from_numpy(imgs['bicubic_np']) torchvision.utils.save_image(tensors_to_plot, 'test.png') You have just to use the last two lines of code…
st100709
What shape and type does imgs['bicubic_np'] have? This code works fine: images1 = [torch.randn(3, 96, 96) for _ in range(16)] images2 = torch.randn(16, 3, 96, 96) save_image(images1, 'test1.png', nrow=4) save_image(images2, 'test2.png', nrow=4)
st100710
This is the type and shape <class ‘numpy.ndarray’> (1, 576, 576) I used this code. print(type(imgs[‘bicubic_np’]),imgs[‘bicubic_np’].shape)
st100711
I’ve imported save_image from torchvision.utils. You could also write torchvision.utils.save_image instead. Cast the numpy array to a tensor using torch.from_numpy() and try it again.
st100712
I am new to this. I have never used torch.from_numpy(). Can you tell me how to do this?
st100713
Sure, no worries. Here is a small example using random values for your imgs: imgs = {} imgs['bicubic_np'] = np.random.randn(1, 576, 576) tensors_to_plot = torch.from_numpy(imgs['bicubic_np']) torchvision.utils.save_image(tensors_to_plot, 'test.png') You have just to use the last two lines of code as your array is already filled.
st100714
Have somebody know how to train a model with sparse matrices? That is to say, the W is a sparse matrix.
st100715
With one GPU and a batch size of 14 an epoch on my data set takes about 24 minutes. With 2 GPUs and a batch size of 28 it’s still taking 24 minutes per epoch. Any suggestions on what might be going wrong? Does the batch normalization layer try to normalize across both GPUs and thus add large amounts of extra memory traffic? Please say it doesn’t. Thanks. Top shows 2 CPUs saturated: Tasks: 255 total, 1 running, 254 sleeping, 0 stopped, 0 zombie %Cpu(s): 16.3 us, 2.5 sy, 0.1 ni, 81.1 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st KiB Mem : 65885928 total, 40001592 free, 11878640 used, 14005696 buff/cache KiB Swap: 67017724 total, 67017724 free, 0 used. 52840116 avail Mem PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 4622 mmacy 20 0 49.225g 5.809g 977604 S 200.0 9.2 111:32.30 work/vnet.base. The memory allocation on the two GPUs is also uneven. If they’re both doing the same operations with the same batch size, why is GPU1 using 1/3rd more memory than GPU0? +-----------------------------------------------------------------------------+ | NVIDIA-SMI 367.57 Driver Version: 367.57 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 TITAN X (Pascal) Off | 0000:01:00.0 On | N/A | | 51% 82C P2 74W / 250W | 7906MiB / 12186MiB | 99% Default | +-------------------------------+----------------------+----------------------+ | 1 TITAN X (Pascal) Off | 0000:02:00.0 Off | N/A | | 47% 78C P2 107W / 250W | 10326MiB / 12189MiB | 95% Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | 0 1086 G /usr/lib/xorg/Xorg 105MiB | | 0 8469 C work/vnet.base.20170316_0434 7797MiB | | 1 8469 C work/vnet.base.20170316_0434 10323MiB | +-----------------------------------------------------------------------------+ I also see that parallel_apply in data_parallel relies on python threading, which isn’t very worthwhile given how much of the code has to run under the GIL. The only way to get any sort of reasonable parallelism while using regular python GIL protected code is to run separate python processes. Are other people actually seeing a speedup from DataParallel? I think I’m probably only seeing one thread make progress at a time.
st100716
No, it doesn’t. I can’t understand what’s the problem. Are you expecting a larger speedup? You’ve doubled the amount of computing power along with the input size, so the time staying constant is a great result. Maybe you have some conditional branching in your model? our multi-GPU code is nearly as fast as it can be. You still need the GIL to execute most of the autograd operations so it doesn’t matter if we don’t use Python threads. In our CNN benchmarks we have perf very similar to that of Caffe2, and faster than Lua Torch, which has very good multi-GPU implementation.
st100717
Usually “data parallel” means data operations run in parallel, but here data parallel only means that the forward passes, the fast part, have any parallel component. That’s just not very useful - as larger batches can reduce the convergence rate. So I’m using twice the power, generating twice the heat and am getting no real benefit. The use of python makes parallelism unduly hard but one could run the autograd pass in separate processes just like hogwild, but without sharing the model weights by having each process broadcast the updates from the cost function’s backward pass. Each process would average in the updates from other GPUs.
st100718
Yes, and the operations run in parallel indeed. Both in forward and in backward. I’m not sure how is that not useful and what’s the problem. Data parallelism is a well known term used to describe weak scaling of these models, and this is exactly what happens in here. It’s very useful, because in some cases you need batch sizes so large, that they don’t fit on a single GPU. The behaviour is exactly what’s wanted in a lot of situations. It doesn’t make it hard, I really don’t understand what’s bothering you. You can do hogwild training, even on GPUs if you wan. No one is stopping you. We even have a hogwild example in the examples repo.
st100719
as adam pointed out, DataParallel is very very well defined in Deep Learning. We split the mini-batches over multiple GPUs, and accumulate the gradients at the end from all the GPUs before doing the optimization step. Getting a linear speedup when doubling the batch size is the best case scenario, and you are hitting that. If there was a confusion in terminology, i hope it’s clarified now.
st100720
I don’t think @mattmacy is getting linear speed-up, as his epoch time does not change, not time-per-minibatch. It’s more like no speed-up at all (same time per epoch indicates twice-as-big time for twice-as-big minibatch). There are many scenarios where speed-up from data parallel would not be that great - e.g. OpenNMT example hardly benefits from data parallel.
st100721
@ngimel batch-size 14 : 1 GPU: 24 mins batch-size 28: 2 GPU: 24 mins in terms of weak-scaling, this seems appropriate right? We cannot expect any better speedup than this theorerically.
st100722
You expect your epoch to become twice as fast with two GPUs. Time per minibatch should stay constant with perfect weak scaling, but you should have two times less minibatches per epoch (if dataset consists of 140 samples, it is 10 minibatches with minibatch size of 14, and 5 minibatches with minibatch size of 28).
st100723
oh, my bad. I got confused a whole lot because all my life I am used to seeing mini-batch times. Sorry for the misunderstanding @mattmacy , I apologize. But as @ngimel and @apaszke pointed out, there are many scenarios in which DataParallel is not great, especially if you have too little compute or if you have too many parameters in your model.
st100724
@ngimel thank you! Yes when I go from 340 mini batches to 170 minibatches I expect the wall clock time to drop from 22 minutes to 11 minutes. Instead I’m seeing no change. @smth I think I’m missing something, DataParallel only splits up the forward pass, I would think that in order to see a proper speed up during training I’d need to encapsulate the whole train loop so that all weights from the loss backward pass were averaged and then propagated. This snippet is the logic I’m referring to: http://docs.chainer.org/en/latest/tutorial/gpu.html#data-parallel-computation-on-multiple-gpus-without-trainer 36 Is there some equivalent to their ParallelUpdater that I’m overlooking? Otherwise, I have 61989982 parameters in my model. I guess that’s too many parameters? Why would DataParallel be rate limited by that? And is it possible I’m doing something wrong such that I’m ending up with more parameters than I mean to have? It’s just 5 level encoder-decoder FCN with 1-3 convolutions at each level and a skip connection from the output of the encoder levels to the level with same resolution and number of channels in the decoder stage. See the diagram from the paper https://github.com/mattmacy/vnet.pytorch/blob/master/images/diagram.png 16 if my description doesn’t make sense. Thank you for your time.
st100725
DataParallel also distributes backward pass, it is hidden in autograd. DataParallel has to broadcast and reduce all the parameters, so parallelization efficiency decreases when you computation time is small and you have a lot of parameters.
st100726
in the backward pass of DataParallel, we reduce the weights from GPU2 onto GPU1. Our DataParallel algorithm is roughly like this: in forward: scatter mini-batch to GPU1, GPU2 replicate model on GPU2 (it is already on GPU1) model_gpu1(input_gpu1), model_gpu2(input_gpu2) (this step is parallel_apply) gather output mini-batch from GPU1, GPU2 onto GPU1 in backward: scatter grad_output and input parallel_apply model’s backward pass reduce GPU2 replica’s gradients onto GPU1 model Now there is only a single model again with accumulated gradients from GPU1 and GPU2 gather the grad_input Hence, unlike in Chainer, you do not actually have to have a separate trainer that is aware of DataParallel. Hope this makes it clear. wrt why your model is slower via DataParallel, you have 61 million parameters. So, I presume you have some Linear layers at the end (i.e. fully connected layers). Put them outside the purview of DataParallel to avoid having to distribute / reduce those parameter weights and gradients. Here is an example of doing that: https://github.com/pytorch/examples/blob/master/imagenet/main.py#L68 https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py When training AlexNet or VGG, we only put model.features in DataParallel, and not the whole model itself, because AlexNet and VGG have large Linear layers at the end of the network. Maybe your situation is similar?
st100727
Is it necessary to replicate all of the gradients? Couldn’t you just replicate the output of the backward pass of just the loss function and then average the results? There are no fully connected layers. I guess 3d convolutions with >= 128 channels have an exorbitant number of parameters. I may have made an error in going up to 512 when I only meant to go up to 256, so at least you’ve prompted me to take a closer look at the model. Thanks again. This is the result of printing the number of parameters for each of the basic elements Conv3d: 2016 BatchNorm3d: 32 Conv3d: 4128 BatchNorm3d: 64 Conv3d: 128032 BatchNorm3d: 64 Conv3d: 16448 BatchNorm3d: 128 Conv3d: 512064 BatchNorm3d: 128 Conv3d: 512064 BatchNorm3d: 128 Conv3d: 65664 BatchNorm3d: 256 Conv3d: 2048128 BatchNorm3d: 256 Conv3d: 2048128 BatchNorm3d: 256 Conv3d: 2048128 BatchNorm3d: 256 Conv3d: 262400 BatchNorm3d: 512 Conv3d: 8192256 BatchNorm3d: 512 Conv3d: 8192256 BatchNorm3d: 512 Conv3d: 8192256 BatchNorm3d: 512 ConvTranspose3d: 262272 BatchNorm3d: 256 Conv3d: 8192256 BatchNorm3d: 512 Conv3d: 8192256 BatchNorm3d: 512 Conv3d: 8192256 BatchNorm3d: 512 ConvTranspose3d: 131136 BatchNorm3d: 128 Conv3d: 2048128 BatchNorm3d: 256 Conv3d: 2048128 BatchNorm3d: 256 ConvTranspose3d: 32800 BatchNorm3d: 64 Conv3d: 512064 BatchNorm3d: 128 ConvTranspose3d: 8208 BatchNorm3d: 32 Conv3d: 128032 BatchNorm3d: 64 Conv3d: 8002 BatchNorm3d: 4 Conv3d: 6
st100728
@smth Revisiting it, the channel split numbers are in fact correct. I tried replacing each of the 5x5x5 filters with 2 3x3x3 filters - which reduced the parameters to 27 million, but it actually increased the memory consumption on the GPU and provided no speed up. So I guess I’ll just have to stick with using the additional GPU for hyperparameter search. Thanks.
st100729
@smth I tried removing some of the largest convolutional layers - with no ill effect - and now DataParallel epochs are taking 15 minutes. Thanks for the explanations!
st100730
smth: in forward: scatter mini-batch to GPU1, GPU2 replicate model on GPU2 (it is already on GPU1) model_gpu1(input_gpu1), model_gpu2(input_gpu2) (this step is parallel_apply) gather output mini-batch from GPU1, GPU2 onto GPU1 in backward:- scatter grad_output and input- parallel_apply model’s backward pass- reduce GPU2 replica’s gradients onto GPU1 model- ## Now there is only a single model again with accumulated gradients from GPU1 and GPU2- gather the grad_input Soumith and Adam, I am having a great time exploring PyTorch! Thanks for the awesome library. I am trying to saturate a 64-core/256-thread CPU in addition to the GPUs. Any pointers on how I can extend Data_parallel.py to create 3 scatters on GPU0, GPU1, and CPU(0-255)? With Keras I modified this script to saturate the CPU: github.com kuza55/keras-extras/blob/master/utils/multi_gpu.py 14 from keras.layers import merge from keras.layers.core import Lambda from keras.models import Model import tensorflow as tf def make_parallel(model, gpu_count): def get_slice(data, idx, parts): shape = tf.shape(data) size = tf.concat([ shape[:1] // parts, shape[1:] ],axis=0) stride = tf.concat([ shape[:1] // parts, shape[1:]*0 ],axis=0) start = stride * idx return tf.slice(data, start, size) outputs_all = [] for i in range(len(model.outputs)): outputs_all.append([]) #Place a copy of the model on each GPU, each getting a slice of the batch for i in range(gpu_count): This file has been truncated. show original
st100731
@FuriouslyCurious So you want to run the model in parallel on two GPUs and all cores? We don’t have any utility for that, and I don’t think it’s even worth it The code will be more complex and you’ll probably see hardly any speedup.
st100732
Due to the statements in his thread, is there no speedup expected for classic DNNs @apaszke ? I currently run speaker recognition DNN’s with pytorch and increasing the number of GPUs (e.g. 2) used, while at the same time increasing the batchsize ( 256 -> 512 ), does not affect the training time at all. Single GPU training on Switchboard takes me ~300 minutes for a full epoch with a single GPU, as well as with 2 GPUs and doubling the batchsize. The model is a 6 Layer 2048 node DNN. The 2 GPUs are utilized, e.g., are not idle at all. So for DNN’s there is no speedup expected, if the model parameters are large?
st100733
ngimel: There are many scenarios where speed-up from data parallel would not be that great - e.g. OpenNMT example hardly benefits from data parallel. @ngimel @smth I’m running into a situation where using DataParallel ends up training slower than without it and on one gpu (while keeping everything else constant). If I try to increase the batch size, I run out of memory. I’m running an encoder - decoder (with attention) model with 3 million parameters. When running on one gpu, I’m able to run a batch size of 2048 sequences which takes up about 6000mb out of the 6078mb. Whereas on two gpus (using DataParallel on all layers in the encoder and decoder), running the same batch size takes up 6070mb on GPU 1 and only 1022mb on GPU 2. +-----------------------------------------------------------------------------+ | NVIDIA-SMI 375.66 Driver Version: 375.66 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 GeForce GTX 980 Ti Off | 0000:06:00.0 Off | N/A | | 0% 51C P2 167W / 300W | 6070MiB / 6078MiB | 73% Default | +-------------------------------+----------------------+----------------------+ | 1 GeForce GTX 980 Ti Off | 0000:07:00.0 On | N/A | | 0% 45C P2 93W / 300W | 1021MiB / 6075MiB | 35% Default | +-------------------------------+----------------------+----------------------+ I have tried putting the linear layers outside of DataParallel to no avail - machine ran out of memory. I understand that the computations on GPU 1 require more memory than those on GPU 2, but I was expecting more memory to be used on GPU 2. Am I at the maximum capacity / performance? Is there anything I can do with this seq-to-seq model to train more batches at a time or shorten training time.
st100734
I have attached the screenshots of my code and the error. Can anyone tell me where I am going wrong? Screenshot-2018-8-30 super-resolution.png2144×1014 140 KB Screenshot-2018-8-30 super-resolution(1).png2144×1014 285 KB Screenshot-2018-8-30 super-resolution(2).png2144×1014 124 KB Screenshot-2018-8-30 super-resolution(3).png2144×1014 147 KB Screenshot-2018-8-30 super-resolution(4).png2144×1014 170 KB Screenshot-2018-8-30 super-resolution(5).png2144×1014 146 KB
st100735
Solved by ptrblck in post #4 You haven’t posted the code of your model, but I assume the last layer is a convolution with out_channels=3. You can add code using three backticks `. It’ll make debugging easier and the search of this forum can find your code, if someone else has this problem. Are you dealing with gray-scale imag…
st100736
The nn.MSELoss requires the input and target to have the same shape. In your case the input has 3 channels, while the target only one. Are you dealing with a segmentation use case and would like to classify each pixel?
st100737
Well I am trying to run the Deep Image Prior’s Super-Resolution code. I am new to this. How can I make the input as 3 channels or otherwise?
st100738
You haven’t posted the code of your model, but I assume the last layer is a convolution with out_channels=3. You can add code using three backticks `. It’ll make debugging easier and the search of this forum can find your code, if someone else has this problem. Are you dealing with gray-scale images in general or did you convert the target to a single channel image? If your targets are gray-scale, you could just use out_channels=1 in your last conv layer.
st100739
Well, the images are from the Cryo Electron Microscopy datasets. It was working fine then I resized it. Now I am getting this error. (Still it works fine with the original image. But the resized one it doesnt. ) This is where I got the code. (https://github.com/DmitryUlyanov/deep-image-prior/ 3)
st100740
Could you post your Dataset and the image processing code so that we could have a look?
st100741
The dataset is in .tif format. I cannot post it here (as it takes only .png, .jpeg format) Here’s the code. I havent changed anything from the Deep Image Prior. It’s the same. Code: from future import print_function import matplotlib.pyplot as plt %matplotlib inline import argparse import os os.environ[‘CUDA_VISIBLE_DEVICES’] = ‘1’ import numpy as np from models import * import torch import torch.optim from skimage.measure import compare_psnr from models.downsampler import Downsampler from utils.sr_utils import * torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark =True dtype = torch.cuda.FloatTensor imsize = -1 factor = 4 # 8 enforse_div32 = ‘CROP’ # we usually need the dimensions to be divisible by a power of two (32 in this case) PLOT = True path_to_image = ‘data/sr/zebra_GT.png’ Load image and baselines imgs = load_LR_HR_imgs_sr(path_to_image , imsize, factor, enforse_div32) imgs[‘bicubic_np’], imgs[‘sharp_np’], imgs[‘nearest_np’] = get_baselines(imgs[‘LR_pil’], imgs[‘HR_pil’]) if PLOT: plot_image_grid([imgs[‘HR_np’], imgs[‘bicubic_np’], imgs[‘sharp_np’], imgs[‘nearest_np’]], 4,12); print (‘PSNR bicubic: %.4f PSNR nearest: %.4f’ % ( compare_psnr(imgs[‘HR_np’], imgs[‘bicubic_np’]), compare_psnr(imgs[‘HR_np’], imgs[‘nearest_np’]))) input_depth = 32 INPUT = ‘noise’ pad = ‘reflection’ OPT_OVER = ‘net’ KERNEL_TYPE=‘lanczos2’ LR = 0.01 tv_weight = 0.0 OPTIMIZER = ‘adam’ if factor == 4: num_iter = 2000 reg_noise_std = 0.03 elif factor == 8: num_iter = 4000 reg_noise_std = 0.05 else: assert False, ‘We did not experiment with other factors’ net_input = get_noise(input_depth, INPUT, (imgs[‘HR_pil’].size[1], imgs[‘HR_pil’].size[0])).type(dtype).detach() NET_TYPE = ‘skip’ # UNet, ResNet net = get_net(input_depth, ‘skip’, pad, skip_n33d=128, skip_n33u=128, skip_n11=4, num_scales=5, upsample_mode=‘bilinear’).type(dtype) mse = torch.nn.MSELoss().type(dtype) img_LR_var = np_to_torch(imgs[‘LR_np’]).type(dtype) downsampler = Downsampler(n_planes=3, factor=factor, kernel_type=KERNEL_TYPE, phase=0.5, preserve_size=True).type(dtype) def closure(): global i, net_input if reg_noise_std > 0: net_input = net_input_saved + (noise.normal_() * reg_noise_std) out_HR = net(net_input) out_LR = downsampler(out_HR) total_loss = mse(out_LR, img_LR_var) if tv_weight > 0: total_loss += tv_weight * tv_loss(out_HR) total_loss.backward() psnr_LR = compare_psnr(imgs['LR_np'], torch_to_np(out_LR)) psnr_HR = compare_psnr(imgs['HR_np'], torch_to_np(out_HR)) print ('Iteration %05d PSNR_LR %.3f PSNR_HR %.3f' % (i, psnr_LR, psnr_HR), '\r', end='') psnr_history.append([psnr_LR, psnr_HR]) if PLOT and i % 100 == 0: out_HR_np = torch_to_np(out_HR) plot_image_grid([imgs['HR_np'], imgs['bicubic_np'], np.clip(out_HR_np, 0, 1)], factor=13, nrow=3) i += 1 return total_loss psnr_history = [] net_input_saved = net_input.detach().clone() noise = net_input.detach().clone() i = 0 p = get_params(OPT_OVER, net, net_input) optimize(OPTIMIZER, p, closure, LR, num_iter) out_HR_np = np.clip(torch_to_np(net(net_input)), 0, 1) result_deep_prior = put_in_center(out_HR_np, imgs[‘orig_np’].shape[1:]) plot_image_grid([imgs[‘HR_np’], imgs[‘bicubic_np’], out_HR_np], factor=4, nrow=1);
st100742
Could you check the shape of your loaded iamges: imgs = load_LR_HR_imgs_sr(path_to_image , imsize, factor, enforse_div32) imgs[‘bicubic_np’], imgs[‘sharp_np’], imgs[‘nearest_np’] = get_baselines(imgs[‘LR_pil’], imgs[‘HR_pil’]) Also, which part have you added to the working code to resize the images?
st100743
I have attached the screenshot of the code for resizing and it’s output. Screenshot-2018-9-3 Untitled2.png1920×907 44.9 KB Also, I have not added it in the code. I saved the resized image and using it here. (Super-Resolution)
st100744
The code looks good. Could you print the shapes of the loaded images (imgs['bicubic_np'], imgs['sharp_np'] and imgs['nearest_np'])? It seems some or all of your images are single channel images, which yields the error message.
st100745
I have attached the image of it. It is about 65536. Screenshot-2018-9-4 super-resolution(2).png1920×907 209 KB
st100746
When I run the flowing code, import torch import torch.nn.functional as F from torchvision.transforms import transforms tmp = np.array(Image.open(source_image_path).convert('RGB')) a = torch.FloatTensor(tmp) print(a.dtype) input_data = a.reshape([1, 3, 256, 256]) b = torch.tensor(pixel_flow, requires_grad=True) grid = b.reshape([1, 256, 256, 2]) c = F.grid_sample(input_data, grid) I meet this error: TypeError: FloatSpatialGridSamplerBilinear_updateOutput received an invalid combination of arguments - got (int, Tensor, Tensor, Tensor, int), but expected (int state, torch.FloatTensor input, torch.FloatTensor grid, torch.FloatTensor output, int padding_mode) So what is the difference between Tensor and FloatTensor?
st100747
I know where is wrong, when I modified a and b like this a = torch.tensor(tmp, requires_grad=False, dtype=torch.float64) b = torch.tensor(pixel_flow, requires_grad=False, dtype=torch.float64) it works!
st100748
As a small side note even though it’s working now: If you are dealing with numpy arrays, I would recommend using torch.from_numpy().
st100749
Thank you very much, and I still find that, when I use torch.from_numpy(), I can set the tensor’s grad by setting tensor.requires_grad_(). It is really amazing, thank you very much!
st100750
I tries to build pytorch wheel for personal usage. as basically my macs have the similar environment, and I can’t build wheel for each mac. this is what I’m doing now: using pytorch github, download source code $ cd pytorch $ python setup.py bdist_wheel find in dist/, I have torch-0.5.0a0+c8b246a-cp36-cp36m-linux_x86_64.whl. could you confirm it’s the wheel, which could be used for another envrionment? I’m not sure if caffe2 has already been packaged together with pytorch? could you confirm?
st100751
or for caffe2, do I need to build via $ FULL_CAFFE2=1 python setup_caffe2.py bdist_wheel
st100752
Quick question. Do you know how to transfer a cuda.tensor to numpy.ndarray, say the out put from a CNN, then do implementation on the numpy.ndarray, then put it back to tensor, in order to let it in the session, and use autograde?
st100753
Short answer: No. When you convert the tensor to numpy array, you are essentially moving out of pytorch ecosystem and autograd will not have trace of operations on numpy array. Try to make use of torch APIs to perform the operation or write your own pytorch extension to calculate gradients.
st100754
Hi, Arul. Is it possible that I use something like tensor.clone().cpu().numpy() and torch.from_numpy? I’m trying to let the tensor and the numpy to share the same memory, so if I change the numpy, the tensor is also changed. It’s just my idea, I don’t know whether it is possible. Many Thanks Jiaming
st100755
As I said in previous post, autograd doesn’t work with numpy. If it is possible, try to compose your operation using pure torch APIs.
st100756
Hi, I have a problem with loading a saved model with torch.load. When debugging, it showed that it has problems here: (in /py3env/lib/python3.5/site-packages/torch/nn/modules/module.py, lines 666-671) I am using the BiDAF model from ([https://github.com/galsang/BiDAF-pytorch 1]): for key, input_param in state_dict.items(): if key.startswith(prefix): input_name = key[len(prefix):] input_name = input_name.split('.', 1)[0] # get the name of param/buffer/child if input_name not in self._modules and input_name not in local_state: unexpected_keys.append(key) ... Last good iteration: key[len(prefix):] = ‘word_emb.weight’ --> input_name = word_emb Bad iteration: key[len(prefix):] = u’highway_linear0.0.linear.weight’ --> input_name = u’highway_linear0 and the next checking is bad: u’highway_linear0 not in self._modules returns True (I checked, “highway_linear0’” not in self._modules returns False) The output of the program is: … File “/home/py3env/lib/python3.5/site-packages/torch/nn/modules/module.py”, line 669, in _load_from_state_dict input_name = input_name.split(’.’, 1)[0] # get the name of param/buffer/child File “/home/py3env/lib/python3.5/site-packages/ww/wrappers/strings.py”, line 359, in split chunks = multisplit(self, *separators, **kwargs) # type: Iterable[str] File “/home/py3env/lib/python3.5/site-packages/ww/tools/strings.py”, line 152, in multisplit “”".format(sep, i, type(sep))) TypeError: ‘1’, the separator at index ‘1’, is of type ‘<class ‘int’>’. multisplit() only accepts unicode strings. So I guess the u’…’ convention caused the problem. I’m using Python 3.5.2, PyTorch 0.4.1 Could you help me to solve this problem? Thank you very much in advance.
st100757
Hi I’m very new to using PyTorch and am still wrapping my head around it all, but I was wondering given the dynamic nature of pytorch how it might be possible to add new neurons (with different parameters than the other nodes potentially) to the hidden layer partway through training. Or if I train first, add new neurons, train again, this detail is not so important… Is it as simple as modifying the tensors containing the weights? Or would it be best to allocate the layer with all potential nodes, with some being ‘silenced’, and make them available through training?
st100758
Solved by smth in post #2 you can keep your “neurons” in a ParameterList, and keep adding new Variable or nn.Parameter of neurons to that list, whether that be each individual neurons (not super efficient), or say a block of 4096 neurons whenever you want a new set. You can also take the “some are silenced” approach, and th…
st100759
you can keep your “neurons” in a ParameterList, and keep adding new Variable or nn.Parameter of neurons to that list, whether that be each individual neurons (not super efficient), or say a block of 4096 neurons whenever you want a new set. You can also take the “some are silenced” approach, and that’s not a bad idea either.
st100760
A bit of code showing how this should be done would be extremely helpful. I’m trying to add neurons to my initial layer and update the model as new data comes in. Is it possible to initialize the model from a ParameterList which will then update with the new layer dimensions as you append new neurons?
st100761
This is a simple working example of how I’ve been doing it, not exactly as smth described, but it works for me . In your case, you would only have one weight matrix to update (since it’s the input layer). In short: initialize the new weights for the units I’m adding concatenate to a copy of the current weight matrices adjust the sizes of the model parameters such that they match the size of the new matrices in Step 2. set the weight values to the values in Step 2. class Model(nn.Module): def __init__(self, layer_size, hidden, input_size, output_size): super(Model, self).__init__() self.input_size = input_size self.output_size = output_size self.layer_size = layer_size self.relu = nn.ReLU() # initialize weights self.fcs = nn.ModuleList([nn.Linear(self.input_size, self.layer_size)]) self.fcs.append(nn.Linear(self.layer_size, self.output_size)) def forward(self, x): # Your typical forward pass goes here def add_units(self, n_new): # take a copy of the current weights stored in self.fcs current = [ix.weight.data for ix in self.fcs] # make the new weights in and out of hidden layer you are adding neurons to hl_input = torch.zeros([n_new, current[0].shape[1]]) nn.init.xavier_uniform_(hl_input, gain=nn.init.calculate_gain('relu')) hl_output = torch.zeros([current[1].shape[0], n_new]) nn.init.xavier_uniform_(hl_input, gain=nn.init.calculate_gain('relu')) # concatenate the old weights with the new weights new_wi = torch.cat([current[0], hl_input], dim=0) new_wo = torch.cat([current[1], hl_output], dim=1) # reset weight and grad variables to new size self.fcs[0] = nn.Linear(current[0].shape[1], self.layer_size) self.fcs[1] = nn.Linear(self.layer_size, current[1].shape[0]) # set the weight data to new values self.fcs[0].weight.data = torch.tensor(new_wi, requires_grad=True, device=self.device) self.fcs[1].weight.data = torch.tensor(new_wo, requires_grad=True, device=self.device)
st100762
import torch a = torch.Tensor([1, 3]) b = torch.Tensor([1, 4]) torch.sum(a == b) * 1.0 / 3 # ==> 0
st100763
Solved by SimonW in post #3 for now, you should be able to do torch.sum(a == b).float()
st100764
We’re working on making binary op semantics match Python / numpy semantics. This will be in a future release, thank you for pointing it out, @fangyh
st100765
I am trying to make my custom collate file for the data.DataLoader, I have some difficulty in terms of understanding it. what format should the inputs of collate have? meaning if my collate is like: def detection_collate(batch): """Custom collate fn for dealing with batches of images that have a different number of associated object annotations (bounding boxes). Arguments: batch: (tuple) A tuple of tensor images and lists of annotations and their ids Return: A tuple containing: 1) (tensor) batch of images stacked on their 0 dim 2) (list of tensors) annotations for a given image are stacked on 0 dim 3) (list of str) id of images """ targets = [] imgs = [] ids = [] for sample in batch: imgs.append(sample[0]) targets.append(torch.FloatTensor(sample[1])) ids.append(sample[2]) return torch.stack(imgs, 0), targets, ids is there anything wrong with this collate? Honestly i feel something might be wrong but im not sure, i remember from somewhere that i should not send str to collate? Any feedback from pytorch expert would be so helpful Thanks
st100766
Suppose, I have a tensor of N*K, where N represents the number of a batch. import torch a = torch.Tensor(1000, 1) dist = torch.Tensor(1000, 100) points = torch.arange(100) # for each a[i], I need to calculate the `distance loss` with each point. for i in range(a.size(0)): for j in range(points.size(0)): dist[i][j] = 1/(0.1*torch.pow((a[i] - points[j]), 2) + 1e-8) However, it is too slow using for-loop. Does anyone have better solutions?
st100767
Solved by Naruto-Sasuke in post #2 import torch a = torch.randn(1000, 1) a_clone = a.clone() a = a.expand(1000, 100) dist = torch.zeros(1000, 100) p = torch.arange(100) #p = torch.arange(100).view(100, 1) p_clone = p.clone() p = p.expand(1000, 100) #p = p.expand(100, 1000).permute(1, 0) loss = 1./(0.1*torch.pow((a-p), 2)+ 1e-5) f…
st100768
import torch a = torch.randn(1000, 1) a_clone = a.clone() a = a.expand(1000, 100) dist = torch.zeros(1000, 100) p = torch.arange(100) #p = torch.arange(100).view(100, 1) p_clone = p.clone() p = p.expand(1000, 100) #p = p.expand(100, 1000).permute(1, 0) loss = 1./(0.1*torch.pow((a-p), 2)+ 1e-5) for i in range(a_clone.size(0)): for j in range(p_clone.size(0)): tmp = 1/(0.1*torch.pow((a_clone[i] - p_clone[j]), 2) + 1e-5) dist[i, j] = tmp[0] print dist.mean() print loss.size() print loss.mean()
st100769
I’m running into trouble when training my model on GPU. The model is rather complicated (varying input batch sizes among others) so it is almost impossible to guarantee that there will never be any errors. At the moment I catch errors both inside my model and during the training loop, which according to this thread that should be safe: https://discuss.pytorch.org/t/is-it-safe-to-recover-from-cuda-oom/12754 14 However, as the most recent comment in that thread noted, the memory is not fully freed after an error. What seems to happen is that when the error some tensors are stored somewhere in a place where I can’t access them (nor clear them with backward() ). The result is a gradual increase in memory usage that can not be cleared at all. This is not just reserved memory, the model will eventually crash with cuda out of memory errors. Moving the model to cpu, then calling torch.cuda.empty_cache() and then moving it back to gpu does not touch this extra memory consumption. Furthermore, if I delete my model and all references to it, the python garbage collector is still able to find references to tensors stored on gpu even though none should exist. Attempting to delete those tensors after they are found by the gc does not work either. Any help would be much appreciated! torch version: 0.4.1 cuda version: 9.0.176 I was working on a reproducible example but have not been able to create a simple version yet.
st100770
Solved by albanD in post #2 Does this depends on the method that created the OOM error? Also could it be that when the python error is raised, it gets a ref to every local objects where the error occurred. I am not sure how these objects behave but they might be holding onto some tensors.
st100771
Does this depends on the method that created the OOM error? Also could it be that when the python error is raised, it gets a ref to every local objects where the error occurred. I am not sure how these objects behave but they might be holding onto some tensors.
st100772
It was indeed due to the python error. I seemed to have incorrectly printed the error messages, so it kept track of those tensors. Thanks for the help!
st100773
Can I backpropagate through forward hooks? For example: import torch import torch.nn as nn class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.net = nn.Sequential( nn.Conv2d(3,32, 3), # layer0 nn.ReLU(True), nn.Conv2d(32,64, 3), # layer1 nn.ReLU(True), nn.Conv2d(64,64, 3), # layer2 nn.ReLU(True), nn.Conv2d(64,1, 1)) # layer3 self.other_net = nn.Conv2d(64,1,1) # Forward hooks to store the outputs self.layer_outputs = {} self.net[1].register_forward_hook( save_outputs(self.layer_outputs, 'layer1')) def forward(self, x): pred = self.net(x) other_pred = self.other_net(self.layer_outputs['layer1']) return pred, other_pred def save_outputs(output_dict, name): '''Closure to save the outputs in a forward hook''' def hook(self, input, out): output_dict[name] = out return hook crit =nn.MSELoss() model = Net() x = torch.rand(1,3,4,4) pred, other_pred = model(x) loss = crit(pred, torch.ones(1,1,4,4)) + crit(other_pred, torch.ones(1,1,4,4)) loss.backward() Of course, the gradient from pred, which is predicted from a full pass through the network, contributes to the update. However, does the gradient from other_pred contribute as well? Does a forward hook preserve the gradients so that layer1 is updated by both the loss from pred and other_pred?
st100774
The gradients will propagate regardless where you put the calculation (well, except with torch.no_grad(): blocks an so). Personally, I would just spell out the forward instead of using hooks. It’s more readable and probably less code overall, too. def forward(self, x): y = x for y in range(2): y = self.net[i](y) other_pred = self.other_net(y) for y in range(2, len(self.net)): y = self.net[i](y) return y, other_pred or so. Or you could just split the net into a lower and upper sequential part and call those instead of the for loops: def forward(self, x): y = self.net_lower(x) other_pred = self.other_net(y) pred = self.net_upper(y) return pred, other_pred Best regards Thomas
st100775
Code here: https://github.com/spencerkraisler/Dog_Breed_Identification 14 At first the images were normalized to be filled with floats between 0 and 1, however the images were near black. And the problem was still the same: weights approached 0 as the network was trained. I then took out the normalization (so the image tensors are filled with integers between 0 and 255) yet the problem still persisted. ​ The images don’t seem to be distorted when I use the showTorchImage() method.
st100776
Do you need to use nn.MSELoss for your classification task? If not, could you switch to nn.CrossEntropyLoss and remove the one-hot-encoding as the CrossEntropyLoss needs a target storing class indices.
st100777
import torch def main(): data=torch.rand(1, 2, 2, 3) print("input", data) print(data.size()) model=torch.nn.Upsample((4, 6), mode='bilinear', align_corners=True) pre=model(data) print("output", pre) print(pre.size()) print("Transform the model to proto") torch.onnx.export(model, data, "model.proto", verbose=True) main() when I run the code upside, I got the problem as follow: TypeError: upsample_bilinear2d() got an unexpected keyword argument 'align_corners' (occurred when translating upsample_bilinear2d) It seems that the function has already updated, the old transform function can not support the new function. How can I solve this, Thanks.
st100778
you have to update pytorch and onnx to lastest version. I sloved it right now! but it only support ‘align_corners=False’
st100779
Thanks lizhengwei1922, I think I have already updated the software to the lastest version with Python 0.4.0 and onnx 1.3.0. But the problem still remains.
st100780
I encounter the following problem: RuntimeError: Error(s) in loading state_dict for SphereFace: While copying the parameter named "fc2.weight", whose dimensions in the model are torch.Size([81391, 512]) and whose dimensions in the checkpoint are torch.Size([81931, 512]). The error is not telling me what’s wrong. Is this a bug? The very weird thing is that if I train with a smaller model with class size 10572 instead of 81931, the same code works (loading trained model). But when it is the larger model with class size 81931, it complains. How can the model being bigger cause an error? The following is how I save the model: save_checkpoint({ 'epoch': epoch, 'arch': args.arch, 'model_config': {'num_classes': model.num_classes, 'use_prelu': model.use_prelu, 'use_se': model.use_se, 'weight_scale': model.weight_scale, 'feature_scale': model.feature_scale}, 'state_dict': model.state_dict(), 'optimizer' : optimizer.state_dict(), 'loss': best_loss, 'prec1': top1.avg, 'prec5': top5.avg }, is_best, savedir) def save_checkpoint(state, is_best, savedir): if not os.path.exists(savedir): os.makedirs(savedir) checkpoint_savepath = os.path.join(savedir, 'checkpoint.pth.tar') torch.save(state, checkpoint_savepath) if is_best: best_savename = '_'.join([state['arch'], 'epoch' + str(state['epoch'])]) + '.pth.tar' best_savepath = os.path.join(savedir, best_savename) shutil.copyfile(checkpoint_savepath, best_savepath)
st100781
I think you might have a small type, as you model’s fc2.weight shape is [81391, 512], while in the checkpoint it’s [81931, 512]. Note the reversed 39-93.
st100782
It looks like uninitialized memory. If you need certain values, I would stick to torch.randn or any other method which initialized the data.
st100783
I am trying to reproduce Noise2Noise paper in PyTorch. The input and target of the model is the same image with different Gaussian noise added to it. Here is the dataset and model’s code. I have GCP instance with Ubuntu 16.0.4, 20GB RAM, 1 tesla k80 GPU and I am getting memory error after 2 iteration even when using 64x64 size images and batch_size=1. class NoisyDataset(Dataset): def __init__(self, root_dir, crop_size=128, train_noise_model=('gaussian', 50), clean_targ=False): """ root_dir: Path of image directory crop_size: Crop image to given size clean_targ: Use clean targets for training """ self.root_dir = root_dir self.crop_size = crop_size self.clean_targ = clean_targ self.noise = train_noise_model[0] self.noise_param = train_noise_model[1] self.imgs = os.listdir(root_dir) def _random_crop_to_size(self, imgs): w, h = imgs[0].size #assert w >= self.crop_size and h >= self.crop_size, 'Cannot be croppped. Invalid size' if min(w, h) < self.crop_size: imgs[0] = tvF.resize(imgs[0], (self.crop_size, self.crop_size)) cropped_imgs = [] i = np.random.randint(0, h - self.crop_size + 1) j = np.random.randint(0, w - self.crop_size + 1) for img in imgs: if min(w, h) < self.crop_size: img = tvF.resize(img, (self.crop_size, self.crop_size)) cropped_imgs.append(tvF.crop(img, i, j, self.crop_size, self.crop_size)) return cropped_imgs def _add_noise(self, image): """ Added only gaussian noise """ w, h = image.size c = len(image.getbands()) if self.noise == 'gaussian': std = np.random.uniform(0, self.noise_param) _n = np.random.normal(0, std, (h, w, c)) noisy_image = np.array(image) + _n noisy_image = np.clip(noisy_image, 0, 255).astype(np.uint8) return Image.fromarray(noisy_image) def _add_text_overlay(self, image): """ Add text overlay to image """ assert self.noise_param < 1, 'Text parameter should be probability of occupancy' w, h = image.size c = len(image.getbands()) if platform == 'linux': serif = '/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf' else: serif = 'Times New Roman.ttf' text_img = image.copy() text_draw = ImageDraw.Draw(text_img) mask_img = Image.new('1', (w, h)) mask_draw = ImageDraw.Draw(mask_img) max_occupancy = np.random.uniform(0, self.noise_param) def get_occupancy(x): y = np.array(x, np.uint8) return np.sum(y) / y.size while 1: font = ImageFont.truetype(serif, np.random.randint(16, 21)) length = np.random.randint(10, 25) chars = ''.join(choice(ascii_letters) for i in range(length)) color = tuple(np.random.randint(0, 255, c)) pos = (np.random.randint(0, w), np.random.randint(0, h)) text_draw.text(pos, chars, color, font=font) # Update mask and check occupancy mask_draw.text(pos, chars, 1, font=font) if get_occupancy(mask_img) > max_occupancy: break return text_img def corrupt_image(self, image): if self.noise == 'gaussian': return self._add_noise(image) elif self.noise == 'text': return self._add_text_overlay(image) else: raise ValueError('No such image corruption supported') def __getitem__(self, index): """ Read a image, corrupt it and return it """ img_path = os.path.join(self.root_dir, self.imgs[index]) image = Image.open(img_path).convert('RGB') if self.crop_size > 0: image = self._random_crop_to_size([image])[0] source_img = tvF.to_tensor(self.corrupt_image(image)) if self.clean_targ: target = tvF.to_tensor(image) else: target = tvF.to_tensor(self.corrupt_image(image)) return source_img, target def __len__(self): return len(self.imgs) class ConvBlock(nn.Module): def __init__(self, ni, no, ks, stride=1, pad=1, use_act=True): super(ConvBlock, self).__init__() self.use_act = use_act self.conv = nn.Conv2d(ni, no, ks, stride=stride, padding=pad) self.bn = nn.BatchNorm2d(no) self.act = nn.LeakyReLU(0.2, inplace=True) def forward(self, x): op = self.bn(self.conv(x)) return self.act(op) if self.use_act else op class ResBlock(nn.Module): def __init__(self, ni, no, ks): super(ResBlock, self).__init__() self.block1 = ConvBlock(ni, no, ks) self.block2 = ConvBlock(ni, no, ks, use_act=False) def forward(self, x): return x + self.block2(self.block1(x)) class SRResnet(nn.Module): def __init__(self, input_channels, output_channels, res_layers=16): super(SRResnet, self).__init__() self.conv1 = nn.Conv2d(input_channels, output_channels, kernel_size=3, stride=1, padding=1) self.act = nn.LeakyReLU(0.2, inplace=True) _resl = [ResBlock(output_channels, output_channels, 3) for i in range(res_layers)] self.resl = nn.Sequential(*_resl) self.conv2 = ConvBlock(output_channels, output_channels, 3, use_act=False) self.conv3 = nn.Conv2d(output_channels, input_channels, kernel_size=3, stride=1, padding=1) def forward(self, input): _op1 = self.act(self.conv1(input)) _op2 = self.conv2(self.resl(_op1)) op = self.conv3(_op1 + _op2) return op
st100784
Solved by JuanFMontesinos in post #4 I guess, I’m not an expert in pytorch, that doing the cited piece of code you are saving the loss + the hist associated. if you wanna operate with the loss as a temporal recording you have to copy the data associated by doing tr_loss += _loss.data, even more i would do tr_loss += _loss.data.cpu() n…
st100785
@JuanFMontesinos sure. Actually I created a Train class to wrap everything up and I am testing it in jupyter notebook. Here is my Train class: import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F from data import NoisyDataset import torch.optim as optim from torch.optim import lr_scheduler from tqdm import tqdm from torch.utils.data import DataLoader class Train: def __init__(self, architecture, train_dir, val_dir, params): self.architecture = architecture.cuda() self.train_dir = train_dir self.val_dir = val_dir self.noise_model = params['noise_model'] self.crop_size = params['crop_size'] self.clean_targs = params['clean_targs'] self.lr = params['lr'] self.epochs = params['epochs'] self.bs = params['bs'] self.train_dl, self.val_dl = self.__getdataset__() self.optimizer = self.__getoptimizer__() self.scheduler = self.__getscheduler__() self.loss_fn = self.__getlossfn__(params['lossfn']) def train(self): for _ in range(self.epochs): tr_loss = 0 self.architecture.train(True) for _, (source, target) in tqdm(enumerate(self.train_dl)): source = source.cuda() target = target.cuda() _op = self.architecture(Variable(source)) _loss = self.loss_fn(_op, Variable(target)) tr_loss += _loss self.optimizer.zero_grad() _loss.backward() self.optimizer.step() val_loss = self.evaluate() self.scheduler.step(val_loss) print(f'Training loss = {tr_loss}, Validation loss = {val_loss}') def evaluate(self): val_loss = 0 self.architecture.train(False) for _, (source, target) in enumerate(self.val_dl): source = source.cuda() target = target.cuda() _op = self.architecture(Variable(source)) _loss = self.loss_fn(_op, Variable(target)) val_loss += _loss return val_loss def __getdataset__(self): train_ds = NoisyDataset(self.train_dir, crop_size=self.crop_size, train_noise_model=self.noise_model, clean_targ=self.clean_targs) train_dl = DataLoader(train_ds, batch_size=self.bs, shuffle=True) val_ds = NoisyDataset(self.val_dir, crop_size=self.crop_size, train_noise_model=self.noise_model, clean_targ=True) val_dl = DataLoader(val_ds, batch_size=self.bs) return train_dl, val_dl def __getoptimizer__(self): return optim.Adam(self.architecture.parameters(), self.lr) def __getscheduler__(self): return lr_scheduler.ReduceLROnPlateau(self.optimizer, patience=self.epochs/4, factor=0.5, verbose=True) def __getlossfn__(self, lossfn): if lossfn == 'l2': return nn.MSELoss() elif lossfn == 'l1': return nn.L1Loss() else: raise ValueError('No such loss function supported') In the jupyter I am just calling the class and the model: from train_utils import Train from model import SRResnet architecture = SRResnet(3, 64) params = { 'noise_model': ('gaussian', 25), 'crop_size': 64, 'clean_targs': False, 'lr': 0.001, 'epochs': 20, 'bs': 1, 'lossfn': 'l2' } trainer = Train(architecture, 'dataset/train', 'dataset/valid', params)
st100786
Shivam_Saboo: tr_loss += _loss I guess, I’m not an expert in pytorch, that doing the cited piece of code you are saving the loss + the hist associated. if you wanna operate with the loss as a temporal recording you have to copy the data associated by doing tr_loss += _loss.data, even more i would do tr_loss += _loss.data.cpu() not to overload the gpu and when u evaluate you should with torch.no_grad: else u will get out of memory too edit: and training and evaluating at the same time feels strange for me in addition, nn.module class has a training boolean by default. self.training if u set model.train() self.training=true and dropout/BN layers will be on if u set model.eval() self.training will be false for the whole nn. I would recommend to use that instatment instead of the self.architecture.train() I also saw you do the following _op1 = self.act(self.conv1(input)) _op2 = self.conv2(self.resl(_op1)) op = self.conv3(_op1 + _op2) i would recommend to use torch.add(op1,op2) since im not sure if op1+op2 properly create the graph
st100787
Thanks a lot. I did the following. Changed model.train(False) to model.eval(), changed the addition operation to torch.add() and used loss.data to add loss of each minibatch. Will use torch.no_grad() too but I right now have older version of PyTorch. Will update it(though it’s working without it). Can you stress more on : and training and evaluating at the same time feels strange for me Isn’t it a good practice to calculate validation loss after each training epoch?
st100788
I cannot properly answer that question. I wonder there may be some trouble with memory. There shouldn’t be, but who knows. Just pay attention to that
st100789
I am using torch.save() to save a model file. However, everytime I save it, it changes. Why so? netG_1 = torch.load('netG.pth') netG_2 = torch.load('netG.pth') torch.save(netG_1, 'netG_1.pth') torch.save(netG_2, 'netG_2.pth') Using md5sum *.pth: 779f0fefca47d17a0644033f9b65e594 netG_1.pth 476f502ec2d1186c349cdeba14983d09 netG_2.pth b0ceec8ac886a11b79f73fc04f51c6f9 netG.pth
st100790
You would need to look deeper in the serialization mechanism for tensors but it is possible that it uses their address in memory as an “id” to make sure to save each tensor only once. In that case, every time you load the model, it gets to a new place in memory and so "id"s will change.
st100791
The model is an instance of this class: github.com taoxugit/AttnGAN/blob/master/code/model.py#L397 self.img = nn.Sequential( conv3x3(ngf, 3), nn.Tanh() ) def forward(self, h_code): out_img = self.img(h_code) return out_img class G_NET(nn.Module): def __init__(self): super(G_NET, self).__init__() ngf = cfg.GAN.GF_DIM nef = cfg.TEXT.EMBEDDING_DIM ncf = cfg.GAN.CONDITION_DIM self.ca_net = CA_NET() if cfg.TREE.BRANCH_NUM > 0: self.h_net1 = INIT_STAGE_G(ngf * 16, ncf) self.img_net1 = GET_IMAGE_G(ngf)
st100792
As the model refers to a lot of stuff, I printed the final one here, using print(netG) G_NET( (ca_net): CA_NET( (fc): Linear(in_features=256, out_features=400, bias=True) (relu): GLU() ) (h_net1): INIT_STAGE_G( (fc): Sequential( (0): Linear(in_features=200, out_features=16384, bias=False) (1): BatchNorm1d(16384, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): GLU() ) (upsample1): Sequential( (0): Upsample(scale_factor=2, mode=nearest) (1): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (3): GLU() ) (upsample2): Sequential( (0): Upsample(scale_factor=2, mode=nearest) (1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (3): GLU() ) (upsample3): Sequential( (0): Upsample(scale_factor=2, mode=nearest) (1): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (3): GLU() ) (upsample4): Sequential( (0): Upsample(scale_factor=2, mode=nearest) (1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (3): GLU() ) ) (img_net1): GET_IMAGE_G( (img): Sequential( (0): Conv2d(32, 3, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (1): Tanh() ) ) (h_net2): NEXT_STAGE_G( (att): GlobalAttentionGeneral( (conv_context): Conv2d(256, 32, kernel_size=(1, 1), stride=(1, 1), bias=False) (sm): Softmax() ) (residual): Sequential( (0): ResBlock( (block): Sequential( (0): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): GLU() (3): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (4): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): ResBlock( (block): Sequential( (0): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): GLU() (3): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (4): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) ) (upsample): Sequential( (0): Upsample(scale_factor=2, mode=nearest) (1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (3): GLU() ) ) (img_net2): GET_IMAGE_G( (img): Sequential( (0): Conv2d(32, 3, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (1): Tanh() ) ) (h_net3): NEXT_STAGE_G( (att): GlobalAttentionGeneral( (conv_context): Conv2d(256, 32, kernel_size=(1, 1), stride=(1, 1), bias=False) (sm): Softmax() ) (residual): Sequential( (0): ResBlock( (block): Sequential( (0): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): GLU() (3): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (4): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): ResBlock( (block): Sequential( (0): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): GLU() (3): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (4): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) ) (upsample): Sequential( (0): Upsample(scale_factor=2, mode=nearest) (1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (3): GLU() ) ) (img_net3): GET_IMAGE_G( (img): Sequential( (0): Conv2d(32, 3, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (1): Tanh() ) ) )
st100793
Hello Forum Im currently building a CRNN (CNN followed by RNN) which needs to classify ship-types according to their movement/behavoir. Im using AIS data which is transformed into a [lat, lon, time] data sequence. The idea is to use the CNN as feature extraction network and then use the RNN to classify from found features. The network i have is unfortunately not working. I trained it on 1000 Cargo ship tracks, 1000 Passenger ship tracks and 1000 Fishing ship tracks. The result is an accurancy of 30% which is the same as the network essentially just guessing same class over and over. My Net is the following: First i have 3 convolutional layers, then 4 recurrent layers. class Net(nn.Module): def __init__(self): super(Net, self).__init__() ### RNN ### self.rnn1 = nn.GRU(input_size=32, #input is the output from CNN hidden_size=hidden_size, num_layers=1) self.rnn2 = nn.GRU(input_size=hidden_size, hidden_size=hidden_size, num_layers=1) self.rnn3 = nn.GRU(input_size=hidden_size, hidden_size=hidden_size, num_layers=1) self.rnn4 = nn.GRU(input_size=hidden_size, hidden_size=hidden_size, num_layers=1) self.activation = nn.ReLU() ### END ### self.dense1 = nn.Linear(hidden_size, 3) ### CNN ### self.conv1 = nn.Sequential( nn.Conv1d( in_channels=3, out_channels=8, kernel_size=5, stride=1, padding=2, ), nn.ReLU(), #nn.MaxPool1d(kernel_size=2), # reduce dimension of sequece by half ) self.conv2 = nn.Sequential( nn.Conv1d( in_channels=8, out_channels=16, kernel_size=5, stride=1, padding=2, ), nn.ReLU(), #nn.MaxPool1d(kernel_size=2), # reduce dimension of sequece by half ) self.conv3 = nn.Sequential( nn.Conv1d( in_channels=16, out_channels=32, kernel_size=5, stride=1, padding=2, ), nn.ReLU(), #nn.MaxPool1d(kernel_size=2), # reduce dimension of sequece by half ) def forward(self, x, hidden, batch_size): x = self.conv1(x.double()) #inputs (1,3,batch_size) x = self.conv2(x.double()) x = self.conv3(x.double()) #Reshape batch for RNN training: x = x.reshape(batch_size,1,32) x, hidden = self.rnn1(x, hidden) #inputs (seq_len,1,3) x = self.activation(x) x, hidden = self.rnn2(x, hidden) x = self.activation(x) x, hidden = self.rnn3(x, hidden) x = self.activation(x) x, hidden = self.rnn4(x, hidden) #x = x.select(0, maxlen-1).contiguous() x = x.view(-1, hidden_size) x = F.relu(self.dense1(x)) return x, hidden #Returns prediction for all batch_size timestamps. i.e [batch_size, 3] def init_hidden(self): weight = next(self.parameters()).data return Variable(weight.new(1, 1, hidden_size).zero_()) My optimizer and criterion: criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.0001, weight_decay=0.5) and my training phase: def train(): print("Training Initiated!") model.train() hidden = model.init_hidden() #Initiate hidden for step, data in enumerate(train_set_all): X = data[0] #Entire sequence y = data[1] #[1,0,0] or [0,1,0] or [0,0,1] y = y.long() #print(y.size()) ### Split sequence into batches: batch_size = 50 # split sequence into mini-sequences of size 50 max_batches = int(X.size(2)/batch_size) for nbatch in range(max_batches): model.zero_grad() output, hidden = model(X[:,:,nbatch*batch_size:batch_size+nbatch*batch_size], Variable(hidden.data), batch_size) loss = criterion(output, torch.max(y[:,nbatch*batch_size:batch_size+nbatch*batch_size,:].reshape(batch_size,3), 1)[1]) loss.backward() optimizer.step() print(step) my question is. Does it makes sense? I know this is quite a question. At the moment i use batches of 50 time samples. This is so that the convolutional part of the network have something to convolve around. Ideally i would just feed it a single timestamp at a time but the result was the same (30 % accurancy). Am i missing something between the networks? I.e. between the CNN and the RNN. Right now i just reshape the data so it fits the RNN requirements. Do i need anything else? I cant seem to find any good tutorials on CRNNs only a few examples of source codes. But i find those hard to rewrite into my example when i have no information other than the code. My labels are simply [0, 1, 0] or [1, 0, 0] or [0,0,1]. Is this correct? Should i use [1,2,3] or something of the like? And does it make sense to use the criterion that i use which i have labels as that? Is it possible to get a probability out as output from the network? Such that class 1 might be 20, class to might be 30 and class 3 might be 50? With all summing to 100? I think that would be ideal. Any help on CRNNs are highly appreciated.
st100794
Try increasing cnn layers since feature extraction is essential.Try using dropout
st100795
Thanks for your suggestion. Where should i place my nn.dropout() layer? at the very end? after all RNN layers or between CNN/RNN?
st100796
after every cnn layer’s activation or batch norm place dropout of 0.2 and rnn there is an argument for dropout use that
st100797
Vignesh: after every cnn layer’s activation or batch norm place dropout of 0.2 and rnn there is an argument for dropout use that Thanks ill try that
st100798
I have the following error: RuntimeError: While copying the parameter named loss.weight, whose dimensions in the model are torch.Size([20]) and whose dimensions in the checkpoint are torch.Size([20]). If the sizes agree, then what can be the issue ?
st100799
Could you give some information on how you saved the parameter and if possible a small code snippet which reproduces this error?