id
stringlengths
3
8
text
stringlengths
1
115k
st99368
hi, guys I wanna make a execute file from my project. My project is consist of PyTorch, PyQt. So I tried to use pyinstaller. I saw the some warning messages. Warning messages are below. It can be easily fixed.(I installed PGI compiler) 37453 WARNING: lib not found: pgf90.dll 37541 WARNING: lib not found: pgc14.dll 37639 WARNING: lib not found: pgf90rtl.dll 38158 WARNING: lib not found: ATen.dll 38242 WARNING: lib not found: shm.dll 38340 WARNING: lib not found: nvToolsExt64_1.dll But I could not make a execute file, which is due to this error message. FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\xxx\AppData\Local\Temp\_MEI191242\torch\_thnn\…\lib\THNN.h’ I would like to finally create an executable using PyTorch and PyQt.
st99369
I have made execute file from PyTorch,but when I double-click execute file, it can run. It shows failed to execute script. Have you met this problem?
st99370
No. I still haven’t solved this problem. I tried so many times, but failed. At last, I tried a simple example, the py file only consist of three lines of code: import torch a = torch.zeros(2, 3) print(a) After I used this simple py file to create an executable, when I double-click execute file, it couldn’t run. It still showed “failed to execute script”. Could you tell me you how to solve it?
st99371
Environments: ubuntu 16.04 + anaconda 2 + pytorch 0.4.0 I’m trying to build a cpp extension for point cloud iterative closest point using the icp function in pcl-1.7 http://pointclouds.org/documentation/tutorials/iterative_closest_point.php 15. The data transforming from at::tensor to pcl::Pointcloud is fine. However, as soon as I declare a new icp object, there will be a segmentation fault. image.png1694×739 335 KB This line triggers the fault: pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp; The setup.py file is: setup( name='icp_cpp', version='1.0', ext_modules=[ CppExtension( name='icp_cpp', sources = ['icp_op.cpp'], library_dirs=['/usr/lib/x86_64-linux-gnu'], libraries=[*pcl related libraries*], include_dirs=["/usr/include/pcl-1.7/", "/usr/include/eigen3"])], cmdclass={ 'build_ext': BuildExtension }) I also tried to add more arguments to the CppExtension as https://github.com/strawlab/python-pcl/blob/master/setup.py 2. But it doesn’t help. To repeat the bug, you can clone the related files from https://github.com/onlytailei/icp_extension 5. There should be pcl and eigen in the system sudo apt-get install libpcl-all sudo apt-get install libeigen3-dev Then build the extension through: python setup install.py Comment/Uncomment line 72 1 in icp_op.cpp pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp; And rebuild the extension, you will see the difference. python icp_test.py
st99372
Random guess: maybe PCL is stealing the ownership of a Torch Tensor, and that is causing the segfault?
st99373
Thanks! The problem is that I only declare a new icp object like pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp; As soon as you uncomment this one, the segfault happen. I’m not starting to input any point cloud to it. In the pure cpp example 11, everything is fine.
st99374
Do you have the segfault if you comment out everything in https://github.com/onlytailei/icp_extension/blob/master/icp_op.cpp#L29-L65 10 ?
st99375
Let’s move the discussion to https://github.com/pytorch/extension-cpp/issues/20 146
st99376
I have tensor which looks like tensor([[1., 1., 0., 1., 0., 0., 1., 1., 0., 1.], [1., 1., 0., 1., 0., 0., 1., 1., 0., 0.], [1., 1., 0., 1., 0., 0., 0., 0., 0., 1.]]) Whats the best way to find the indices of last one in each row? In the above case, it should return [9, 7, 9]
st99377
Suppose your tensor is a. Then you can do sorted_tensor, sort_idx = a.sort(1) out = sort_idx[:, -1]
st99378
I want to perform certain post-processing on each of the MNIST digits but I get OSError: [Errno 24] Too many open files. I am using pytorch==0.4.1. Have tried this both for python 2.7 and 3.6. I have also tried the other suggestions mentioned in this 8 i.e I have rebooted my ubuntu server as well as tried setting ulimit but I get ulimit: value exceeds hard limit when I try to set something above 4096. Although, I get the output as unlimited when I run ulimit. Is there any other solution for this?. My code to get the train and the test loaders: import torch from torch.utils.data import DataLoader from torchvision.utils import save_image import torchvision.datasets as dset import torchvision.transforms as transforms trans = transforms.ToTensor() train_set = dset.MNIST(root=root, train=True, transform=trans, download=True) test_set = dset.MNIST(root=root, train=False, transform=trans) train_loader = DataLoader(dataset=train_set, batch_size=1, shuffle=True, num_workers=4) test_loader = DataLoader(dataset=test_set, batch_size=1, shuffle=True, num_workers=4)
st99379
I was able to have a workaround by increasing the hard limit by following the directions as mentioned here 288.
st99380
When dealing with a binary classification problem, we can use either logistic loss or hinge loss to train our model, implemented with CrossEntropyLoss() or MarginRankingLoss() respectively, if I don’t misunderstand. In both cases, we can use the same network, say a single FC to project the inputs to outputs y_est of shape (batch_size, 2), where 2 comes from the binary classification. For CrossEntropyLoss(), we simply argmax the outputs per sample in a batch to yield our predictions: index 0 and 1 for class label 0 and 1, respectively. On the other hand, do we do the same for MarginRankingLoss()? The target argument in the function (y in the formula below) should be either 1 or -1 (instead of 1 and 0), can we also argmax and say that index 0 and 1 as -1 and 1, respectively? loss(x,y)=max(0,−y∗(x1−x2)+margin) I am also wondering if it is correct to regard x1 and x2 as the y_est[:,0] and y_est[:,1].
st99381
Hi, in my understanding, x1 and x2 corresponds to distance between positive(same-class) pair and negative pair. Before you apply MarginRankingLoss(), you have to compute those distances from batch. For example, we have X1c,X2c,X3,X4 (X1c,X2c belong to class c and others are not). In the binary classification phase, we apply usual classification to X1~X4. In the ranking phase, at first, distance Dp = d(f(X1c) - f(X2c)), Dn = (f(X1c) - f(X4)) are computed, where f() returns model output, d() returns distance between two feature vectors. Then loss computation would be as follows: loss = max(0, Dp - Dn + m) In your case, if you fix x1 as Dp and x2 as Dn, y should be always 1
st99382
I have an impression of your description more like hinge loss for triplet. What I was referring to does not have to worry about pairs; apologize if I didn’t make clear. Particularly, I used MarginRankingLoss() as hinge loss for binary classification as answered here 19. So I am wondering how to make equal the formula in the OP (eq. 1, I believe that it is y E {-1, 1} not t) and the one from the doc 4 (eq. 2): max(0, 1 - t * y) where t E {-1, 1} (1) max(0, -y * (x1 - x2) + 1) (2) so I make x1 and x2 as y_est[:,0] and y_est[:,1], respectively. I also tried to set x2 to zeros but I am not sure about it.
st99383
If I have a tensor that is of shape [96, 16, 160] that is the output from a model I’m trying to train, and my targets are in a tensor of shape [96, 16, 1] (where there are 160 different classes, hence the appearance of 160 in the first, and 1 in the second), what’s the proper method for putting these two tensors into a loss function? Should I just use .view(-1, 160) and .view(-1, 1)?
st99384
Solved by ptrblck in post #5 features stands here for out class logits, i.e. you have 160 classes? If so, you could view the seq_len and batch_size together, in case you want a prediction for each seq timestamp: x = torch.randn(96, 16, 160) y = torch.empty(96, 16, dtype=torch.long).random_(160) criterion = nn.CrossEntropyLos…
st99385
Oops, just realized that .view(-1,1) will not work for target values input into CrossEntropyLoss function. It returns an Error and states that multiclass classification is not supported. So… Would this be the proper approach: loss = lossFunction(output.view(-1, 160), targets.view(-1))
st99386
Depending what dim0 and dim1 are representing, this might be a valid approach. I assume dim0 is the batch size, so what is dim1? nn.CrossEntropyLoss takes an input of shape [N, C, additional dims] and a target of [N, additional dims]. Could you explain the dimensions so that we can reshape them if necessary?
st99387
The dimensions are [seq_len, batch, features] as per the documentation re: RNN input. Although I’m still a little unclear on the proper usage of seq_len as well, or rather, how this is treated internally. Thanks,
st99388
features stands here for out class logits, i.e. you have 160 classes? If so, you could view the seq_len and batch_size together, in case you want a prediction for each seq timestamp: x = torch.randn(96, 16, 160) y = torch.empty(96, 16, dtype=torch.long).random_(160) criterion = nn.CrossEntropyLoss() loss = criterion(x.view(-1, 160), y.view(-1))
st99389
Hi, I decided to publish a tiny module which I find very helpful when creating and debugging procedurally generated and executed models. GitHub jatentaki/torch-localize 2 Decorators for better tracebacks in PyTorch. Contribute to jatentaki/torch-localize development by creating an account on GitHub. Feedback is welcome, both in terms of the actual code and everything else - it’s the first module I am publishing, so my understanding of setuptools and licensing is rough.
st99390
Hi, is it possible like in tensorflow to specify after how many epochs the learning rate gets decayed? I looked into the documentation and noticed the current implementation only decays the learning rate after each epoch! and there is no way to specify anything else there! I thought maybe I can use a condition in training section and write sth like : if (epoch %2 == 0): scheduler.step() but I noticed since the implementation always uses the last epoch , but i’m not sure if it would yeild a different result ? More information : Actually the reason I’m asking this is I want to implement the same setting Tensorflow uses to train MobileNet. Here is thetensorflow’s setting : --model_name="mobilenet_v2" --learning_rate=0.045 * NUM_GPUS #slim internally averages clones so we compensate --preprocessing_name="inception_v2" --label_smoothing=0.1 --moving_average_decay=0.9999 --batch_size= 96 --num_clones = NUM_GPUS # you can use any number here between 1 and 8 depending on your hardware setup. --learning_rate_decay_factor=0.98 --num_epochs_per_decay = 2.5 / NUM_GPUS # train_image_classifier does per clone epochs And this is the training script, As you can see different hyperparameters are given. what I’m specifically asking about is the Exponential learning rate, which its implementation is given here : decayed_learning_rate = learning_rate * decay_rate ^ (global_step / decay_steps) based on this 4 , global step is basically a counter for number of batches read so far(i.e it holds the total number of steps during training). So basically tensorflow uses the iterations and Pytorch uses epoch. my first question is, would it not make the outcome different? I tried to do the exp scheduler using iterations like this : def exp_lr_scheduler(optimizer, iter, lr_decay_iter=6400, max_iter=2400000, gamma=0.96): """Exponential decay of learning rate :param iter is a current iteration :param lr_decay_iter how frequently decay occurs, default is 6400 (batch of 64) :param max_iter is number of maximum iterations :gamma is the ratio by which the decay happens """ if iter > max_iter: return optimizer #learning rate lr=0 # fetch the last lr (in the beginning it would be the initial learning rate) for param_group in optimizer.param_groups: lr = param_group['lr'] lr = lr * gamma ** (iter / lr_decay_iter) for param_group in optimizer.param_groups: param_group['lr'] = lr return lr However,Since I do not have a global iteration, can I simply multiply epoch by the current iteration and use that? meaning : def exp_lr_scheduler(optimizer, iter, lr_decay_iter=6400, max_iter=2400000, gamma=0.96): """Exponential decay of learning rate :param iter is a current iteration :param lr_decay_iter how frequently decay occurs, default is 6400 (batch of 64) :param max_iter is number of maximum iterations :gamma is the ratio by which the decay happens """ if iter > max_iter: return optimizer #learning rate lr=0 # fetch the last lr (in the beginning it would be the initial learning rate) for param_group in optimizer.param_groups: lr = param_group['lr'] lr = lr * gamma ** ((epoch * iter) / lr_decay_iter) for param_group in optimizer.param_groups: param_group['lr'] = lr return lr What should I do here. which way is the correct one? can anybody please help me on this ?
st99391
Hello , I have created a neural network like this : F1 = feedforward netwrok --> RNN --> F2 = feedforward netwrok and I want to train them but I’m having issues with my optimizer # MLP_in----------------------------------------------------------------------- model_in = MLPModel(input_dim, args.hidden_dim_1_in, args.hidden_dim_2_in, args.hidden_dim_3_in, args.output_dim_in) if torch.cuda.is_available(): model_in.cuda() # RNN-------------------------------------------------------------------------- model_RNN = LSTMModel(input_dim, args.hidden_dim, args.layer_dim, args.output_dim_rnn) if torch.cuda.is_available(): model_RNN.cuda() # MLP_OUT----------------------------------------------------------------------- model_out = MLPModel(args.output_dim_rnn, args.hidden_dim_1_out, args.hidden_dim_2_out, args.hidden_dim_3_out, args.output_dim) if torch.cuda.is_available(): model_out.cuda() optimizer = torch.optim.SGD(model.parameters() , lr=learning_rate) should I replace model.parameters() with their sum ? or there is another method to do this ? And thank you.
st99392
Solved by ptrblck in post #2 You could pass the parameters together with: params = list(model_in.parameters()) + list(model_RNN.parameters()) + list(model_out.parameters()) optimizer = optim.SGD(params, lr=learning_rate)
st99393
You could pass the parameters together with: params = list(model_in.parameters()) + list(model_RNN.parameters()) + list(model_out.parameters()) optimizer = optim.SGD(params, lr=learning_rate)
st99394
I construct a optimizer like that, but it raise an error when I apply the function torch.nn.utils.clip_grad_norm_ to the optimizer. I have tried two ways, params = list(model1.parameters())+list(model2.parameters()) optimizer = optim.SGD(params, lr=learning_rate) torch.nn.utils.clip_grad_norm_(optimizer,clip_value) the error message is TypeError: ‘SGD’ object is not iterable 2)torch.nn.utils.clip_grad_norm_(optimizer,clip_value) AttributeError: ‘SGD’ object has no attribute ‘parameters’ is there any way to do this?
st99395
clip_grad_norm expects parameters, not an optimizer. Try to pass params or model.parameters() to it.
st99396
I am trying to limit the range of values that a tensor can take in the forward pass like this: class ScaleRange(nn.Module): def __init__(self, max_): super(ScaleRange, self).__init__() self.max = max_ self.inv_scale = 255.0/max_ self.scale = max_/255.0 self.clamp = nn.Hardtanh(min_val=0.0, max_val=self.max) def forward(self, x): out = self.clamp(x) with torch.no_grad(): out = torch.mul(out, self.inv_scale) out = torch.floor(out) out = torch.mul(out, self.scale) return out Here I take the input tensor, clamp it to (0, max), then scale it by 255/max, floor the result, and then scale it back again by max/255, thus restricting the range of values to (0, 1.0). Is this the correct way to do this?
st99397
I don’t think your code is doing, what you try to achieve. Let’s think about what each line of code is doing. Assuming you have a random tensor and set max_ to a random value, e.g. 2. The fclamp operation would therefore cut all values below 0.0 and above 2.0: x = torch.randn(10) * 10 max_val = 2. clamp = nn.Hardtanh(min_val=0.0, max_val=max_val) x = clamp(x) print(x) > tensor([2.0000, 0.0000, 2.0000, 2.0000, 0.0000, 0.0000, 0.0000, 0.4396, 2.0000, 2.0000]) x holds currently values in [0, max_]. Scaling it with 255./max_ will let x be in the range [0, 255.]: inv_scale = 255./max_val out = x * inv_scale print(out) > tensor([255.0000, 0.0000, 255.0000, 255.0000, 0.0000, 0.0000, 0.0000, 56.0499, 255.0000, 255.0000]) Now the floor basically just has an effect on values between 0. and 255., as the min and max values are already “floored”: out = torch.floor(out) print(out) > tensor([255., 0., 255., 255., 0., 0., 0., 56., 255., 255.]) Multiplying it with scale = (max_/255.) will just set the range again back to [0, max_]: scale = max_val/255. out = out * scale print(out) > tensor([2.0000, 0.0000, 2.0000, 2.0000, 0.0000, 0.0000, 0.0000, 0.4392, 2.0000, 2.0000]) We are basically back at the clamped tensor with a little difference due to the floor op. If you want to scale your tensor to the range [0, 1], you could subtract the minimal values and divide by the maximal: x = torch.randn(10) x -= x.min() x /= x.max()
st99398
Hi, I have coded the ShallowNet for Saliency prediction. The code seems to work fine. The authors of the ShallowNet paper says the model needs to be trained for 1000 epochs. When I put my model for training, my initial validation loss was 0.024888 but after the 1st epoch it became 0.009461 and in the subsequent epochs it reduces marginally. My question are :- Is it advisable to continue training till 1000 epochs. Does the model still learns even though the validation error seems to have saturated. The authors have implemented using caffe and I am trying to write it in pytorch. Is it possible that the change of framework could effect the hyperparameters. In the paper the authors have reduced the momentum term from 0.9 to 0.999 over the 1000 epochs. I guess there is no scheduler for momentum like we have for LR in pytorch. How it can be done. Thank you in advance for your valuable time and helping me learn. warm regards, Goutam Kelam
st99399
I have a question on the concurrency of caffe2 calling into Gloo. I see this max_concurrent_distributed_ops in caffe2’s resnet50-trainer.py example. I tuned it to a larger number but the concurrent calls to Gloo’s reduction algorithm, namely CudaHalvingDoubling is at most 12. I’d like to understand how we can get faster training by turning this value up a bit more. Is this due to the dependency not being resolved, so that only 12 gradients can be worked on at the same time? Is there another limit to tweak (maybe the GPU has some concurrency limit?) Please advice! Thanks!
st99400
Hi, currently I have implemented following Dataset class that accepts input and output data for creating batches for training. class My_dataset(Dataset): def __init__(self, data_in, data_out): self._data_in = data_in self._data_out = data_out def __len__(self): return len(self._data_in) def __getitem__(self, index): return self._data_in[index], self._data_out[index] Now I would like to add a few helper variables that has the same length with data to improve training results and they should also be split into same batches with input and output data. Does anyone know if it is possible to create a subclass of Dataset that accepts variable number of arrays in the constructor (e.g. it could be called as My_dataset(data_in, data_out, helper_1), My_dataset(data_in, data_out, helper_1, helper_2), etc) and generates batches accordingly? Thank you!
st99401
Solved by Wei_Chen in post #2 Never mind, it is solved: class My_dataset(Dataset): def __init__(self, *data): # accept variable number of arrays to construct dataset self._data = data def __len__(self): return len(self._data[0]) def __getitem__(self, index): …
st99402
Never mind, it is solved: class My_dataset(Dataset): def __init__(self, *data): # accept variable number of arrays to construct dataset self._data = data def __len__(self): return len(self._data[0]) def __getitem__(self, index): return [item[index] for item in self._data]
st99403
Hi, Note that this is actually already implemented in TensorDataset, see the implementation here 1
st99404
I tried to use the C++ example from the docs but when I run the build I get the error that torch::data does not exist. Any help on this? I could not find docs on using the dataloader serializer for C++
st99405
Hi, Thanks for the report. It turns out that the PR adding support for torch::data hasn’t been merged yet, see https://github.com/pytorch/pytorch/pull/11918 3 I’ll let Peter (the author of C++ extensions) know so that he can update / merge the code.
st99406
import torch import torch.nn as nn from torch.autograd import Variable from keras.models import * from keras.layers import * from keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D from keras.models import Model, load_model from keras import backend as K K.set_image_dim_ordering('th') import keras.backend as K K.set_image_data_format('channels_last') K.set_learning_phase(1) torch.backends.cudnn.enabled = True #print(the_model) class PytorchToKeras(object): def __init__(self,pModel,kModel): super(PytorchToKeras,self) self.__source_layers = [] self.__target_layers = [] self.pModel = pModel self.kModel = kModel K.set_learning_phase(0) def __retrieve_k_layers(self): for i,layer in enumerate(self.kModel.layers): if len(layer.weights) > 0: self.__target_layers.append(i) def __retrieve_p_layers(self,input_size): input = torch.randn(input_size) input = Variable(input.unsqueeze(0)) hooks = [] def add_hooks(module): def hook(module, input, output): if hasattr(module,"weight"): self.__source_layers.append(module) if not isinstance(module, nn.ModuleList) and not isinstance(module,nn.Sequential) and module != self.pModel: hooks.append(module.register_forward_hook(hook)) self.pModel.apply(add_hooks) self.pModel(input) for hook in hooks: hook.remove() def convert(self,input_size): self.__retrieve_k_layers() self.__retrieve_p_layers(input_size) for i,(source_layer,target_layer) in enumerate(zip(self.__source_layers,self.__target_layers)): weight_size = len(source_layer.weight.data.size()) transpose_dims = [] for i in range(weight_size): transpose_dims.append(weight_size - i - 1) self.kModel.layers[target_layer].set_weights([source_layer.weight.data.numpy().transpose(transpose_dims), source_layer.bias.data.numpy()]) def save_model(self,output_file): self.kModel.save(output_file) def save_weights(self,output_file): self.kModel.save_weights(output_file) """ We explicitly redefine the architecture since Keras has no predefined """ def basic_block(X, filters): X = ZeroPadding2D((1, 1))(X) X = Conv2D(filters, kernel_size=(3, 3), strides=(2, 2), use_bias=False)(X) X = Activation('relu')(X) X = ZeroPadding2D((1, 1))(X) X = Conv2D(filters, kernel_size=(3, 3), strides=(1, 1), use_bias=False)(X) return X def convolutional_block(X, filters): X_shortcut = X X = basic_block(X, filters) ### Shortcut Path ### X_shortcut = Conv2D(filters, kernel_size=(1, 1), strides=(2, 2), use_bias=False)(X_shortcut) # Final step: Add shortcut value to main path X = Add()([X, X_shortcut]) return X def ResNet(input_shape=(224, 224, 3)): # Define the input as a tensor with shape input_shape X_input = Input(input_shape) # Zero Padding X = ZeroPadding2D((3, 3))(X_input) # Stage 1 X = Conv2D(4, (7, 7), strides=(2, 2), use_bias=False)(X) X = Activation('relu')(X) X = ZeroPadding2D((1, 1))(X) X = MaxPooling2D((3, 3), strides=(2, 2))(X) # Stage 2 X = basic_block(X, filters=4) # Stage 3 X = convolutional_block(X, filters=6) X = convolutional_block(X, filters=98) X = convolutional_block(X, filters=160) # Stage 4 X = AveragePooling2D((3, 3))(X) # Output Layer X = Flatten()(X) X = Dense(16, activation='softmax')(X) model = Model(inputs=X_input, output=X, name='HuaweiNet') return model keras_model = ResNet() path = "/neutrino/models/pretrained/huawei/huawei_0000_4_4_6_98_160.pth" the_model = torch.load(path) the_model.state_dict() #Time to transfer weights converter = PytorchToKeras(the_model,keras_model) converter.convert((3,224,224)) #Save the weights of the converted keras model for later use converter.save_weights("huaweinet.h5") I have been getting this error. Traceback (most recent call last): File "/tmp/pycharm_project_896/agents/pytorch2keras.py", line 155, in <module> converter.convert((3,224,224)) File "/tmp/pycharm_project_896/agents/pytorch2keras.py", line 60, in convert self.__retrieve_p_layers(input_size) File "/tmp/pycharm_project_896/agents/pytorch2keras.py", line 54, in __retrieve_p_layers self.pModel(input) File "/usr/local/lib/python2.7/dist-packages/torch/nn/modules/module.py", line 357, in __call__ result = self.forward(*input, **kwargs) File "/usr/local/lib/python2.7/dist-packages/torch/nn/parallel/data_parallel.py", line 71, in forward return self.module(*inputs[0], **kwargs[0]) File "/usr/local/lib/python2.7/dist-packages/torch/nn/modules/module.py", line 357, in __call__ result = self.forward(*input, **kwargs) File "/tmp/pycharm_project_896/agents/training_agent.py", line 148, in forward x = self.fc(x) File "/usr/local/lib/python2.7/dist-packages/torch/nn/modules/module.py", line 357, in __call__ result = self.forward(*input, **kwargs) File "/usr/local/lib/python2.7/dist-packages/torch/nn/modules/linear.py", line 55, in forward return F.linear(input, self.weight, self.bias) File "/usr/local/lib/python2.7/dist-packages/torch/nn/functional.py", line 835, in linear return torch.addmm(bias, input, weight.t()) RuntimeError: size mismatch at /pytorch/torch/lib/THC/generic/THCTensorMathBlas.cu:247 Can anyone help me? Thanks in advance
st99407
I’m not sure, how your PyTorch model is defined as you’ve only posted the Keras model. From the error message it seems you have a size mismatch in your linear layers somewhere. If you run your model on the CPU, you will most likely get a better error message.
st99408
Thansk for replying. Found the error. Solved it. The PyTorch model is a custom pretrained model storing everything. But I am getting the following error. RuntimeError: can’t convert CUDA tensor to numpy (it doesn’t support GPU arrays). Use .cpu() to move the tensor to host memory first. File "/tmp/pycharm_project_896/agents/pytorch2keras.py", line 152, in <module> converter.convert((3,224,224)) File "/tmp/pycharm_project_896/agents/pytorch2keras.py", line 72, in convert self.kModel.layers[target_layer].set_weights([source_layer.weight.data.numpy().transpose(transpose_dims), source_layer.bias.data.numpy()]) RuntimeError: can't convert CUDA tensor to numpy (it doesn't support GPU arrays). Use .cpu() to move the tensor to host memory first. Any help is appreciated. Thank You
st99409
Hi, tensor on your GPU is not torch.tensor. So you need to use .cpu() before you call .numpy(). Please check related topic for detail: Convert to numpy cuda variable How to convert cuda variables to numpy? Shortly, it would be like: ... data.cpu().numpy()
st99410
I followed the topic. I wasn’t able to get the result I needed. It ended up giving me more errors. The code I am using to convert is as above. I have attached the error details too. Could you please help me in adding the line as required? I am still new to PyTorch. Thank You.
st99411
So basically, I am training humans and seperate them from animals(cats) I have training data full of humans,cats and val data humans,cats. I use imagefolder btw. However, I wanted to try sth new: In train folder, I put “human” folder that has human pictures. In val folder, I also put “human” folder that has cat pictures instead. So I expected that to have 0% accuracy, because of overfitting and not accurate image clusters. If I had human folder with human pics in train AND human,cat in val the accuracy is 50% which is normal. The rest of the classifications is fine as well. However, that thing really gave me weird feelings on my model. Thanks!
st99412
I’m not sure if I understand the problem correctly. As far as I’ve understood it, you have clean training data and mixed-up Val data. Now your validation accuracy does represent the Val data classes, i.e. 50% accuracy for 50% wrong images. Could you explain your issue a bit more?
st99413
oh sorry I will try to be elaborate: I had several test scenarios and I use imagefolder style and use resnet: 1st scenario: train: ./human has human ./cat has cat val ./human has human ./cat has cat accu: 100% I think thats alright. 2nd scenario: train: ./human has human val ./human has human ./cat has cat accu: 50% thats alright too, given that its trained on human 3nd scenario: train: ./human has human val “./human has cat” OR(other scenario not together) “./cat has cat” accu: 100% I didnt get this part.
st99414
Thanks for the clarification. I guess it might be just a mix-up with the class indices. In your 2nd scenario, your model is only trained on one class, which means it will output only class0. Since your validation data contains human and cat classes, your accuracy will be 50% if you have a balanced dataset. In your 3rd scenario, it looks like you only have one single class in your validation dataset, which corresponds to class0. Since your training data only consists of one class, your model just outputs class0 for every sample it gets, which will yield an accuracy of 100% regardless of the actual class in your validation set.
st99415
Hi Everyone - I created the following simple module to turn any block into a resnet block class ResBlock(nn.Module): r""" ResBlock Args: block: block or list of layers multiplier <float [RES_MULTIPLIER]>: ident multiplier crop: <int|bool> if <int> cropping=crop else if True calculate cropping else no cropping Links: TODO: I THINK I GOT THE IDEA FROM FASTAI SOMEWHERE """ def __init__(self, block, in_ch, out_ch, multiplier=RES_MULTIPLIER, crop=True): super(ResBlock, self).__init__() self.block=self._process_block(block) self.in_ch=in_ch self.out_ch=out_ch self.multiplier=multiplier self.crop=crop if self.in_ch!=self.out_ch: self.ident_conv=nn.Conv2d( in_channels=self.in_ch, out_channels=self.out_ch, kernel_size=1) else: self.ident_conv=False def forward(self, x): block_out=self.block(x) if self.crop: x=self._crop(x,block_out) if self.ident_conv: x=self.ident_conv(x) return (self.multiplier*x) + block_out def _process_block(self,block): if isinstance(block,list): return nn.Sequential(*block) else: return block def _crop(self,x,layers_out): if not isinstance(self.crop,int): # get cropping out_size=layers_out.size()[-1] x_size=x.size()[-1] self.crop=(x_size-out_size)//2 return x[:,:,self.crop:-self.crop,self.crop:-self.crop] Using it I found that my the number of parameters in my model were almost doubling! After playing around a bit I realized it was because the conv-blocks in my model were being set as model properties before passing them into ResBlock. In case that isn’t clear there is an oversimplified example below where ResBlock has been replaced with PassThrough and the model is a single Conv2d layer. My question is then, are Net2 and Net3 below really different? or is this a bug with torchsummary 1? I acknowledge that the Net3 version is probably just bad practice but I wanted to understand what pytorch is doing and if these really are different networks. Here’s the oversimplified code: SIZE=32 import torch.nn as nn from torchsummary import summary class PassThrough(nn.Module): """ return the original block/layer without any changes This module does nothing. In a real world scenario it would be replaced with something more interesting like a resnet wrapper for a conv_block. """ def __init__(self,block): super(PassThrough, self).__init__() self.block=block def forward(self,x): return self.block(x) class Net1(nn.Module): """ a dumb test """ def __init__(self): super(Net1, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) def forward(self, x): return self.conv1(x) print('\n'*3,'Net1') summary(Net1(),input_size=(3,SIZE,SIZE)) class Net2(nn.Module): """ This Network, as expected, is the same as Net1 but you see the PassThrough wrapper in the summary """ def __init__(self): super(Net2, self).__init__() c1=nn.Conv2d(3, 6, 5) self.conv1 = PassThrough(c1) def forward(self, x): return self.conv1(x) print('\n'*3,'Net2') summary(Net2(),input_size=(3,SIZE,SIZE)) class Net3(nn.Module): """ This Network shows each conv block twice. Is this real or a bug with torchsummary? """ def __init__(self): super(Net3, self).__init__() self.c1=nn.Conv2d(3, 6, 5) self.conv1 = PassThrough(self.c1) def forward(self, x): return self.conv1(x) print('\n'*3,'Net3') summary(Net3(),input_size=(3,SIZE,SIZE)) Here’s the output Net1 ---------------------------------------------------------------- Layer (type) Output Shape Param # ================================================================ Conv2d-1 [-1, 6, 28, 28] 456 ================================================================ Total params: 456 Trainable params: 456 Non-trainable params: 0 ---------------------------------------------------------------- Input size (MB): 0.01 Forward/backward pass size (MB): 0.04 Params size (MB): 0.00 Estimated Total Size (MB): 0.05 ---------------------------------------------------------------- Net2 ---------------------------------------------------------------- Layer (type) Output Shape Param # ================================================================ Conv2d-1 [-1, 6, 28, 28] 456 PassThrough-2 [-1, 6, 28, 28] 0 ================================================================ Total params: 456 Trainable params: 456 Non-trainable params: 0 ---------------------------------------------------------------- Input size (MB): 0.01 Forward/backward pass size (MB): 0.07 Params size (MB): 0.00 Estimated Total Size (MB): 0.09 ---------------------------------------------------------------- Net3 ---------------------------------------------------------------- Layer (type) Output Shape Param # ================================================================ Conv2d-1 [-1, 6, 28, 28] 456 Conv2d-2 [-1, 6, 28, 28] 456 PassThrough-3 [-1, 6, 28, 28] 0 ================================================================ Total params: 912 Trainable params: 912 Non-trainable params: 0 ---------------------------------------------------------------- Input size (MB): 0.01 Forward/backward pass size (MB): 0.11 Params size (MB): 0.00 Estimated Total Size (MB): 0.12 ---------------------------------------------------------------- Thanks!
st99416
Solved by InnovArul in post #2 Yes. seems to be a bug in torchsummary. The below code prints only the shape from a single cnv layer. print([p.shape for p in Net3().parameters()]) I had created an issue in Github for you.
st99417
Yes. seems to be a bug in torchsummary. The below code prints only the shape from a single cnv layer. print([p.shape for p in Net3().parameters()]) I had created an issue in Github for you. github.com/sksq96/pytorch-summary Issue: Shared module weights are counted twice 36 opened by InnovArul on 2018-10-04 https://discuss.pytorch.org/t/repeated-model-layers-real-or-torchsummary-bug/26489
st99418
Thanks! On this topic does anyone know if there is discussion of adding a something like torchsummary to the pytorch code base? I’ve seen others ask on the forums but haven’t seen any definitive response or reason for its absence.
st99419
I have heard of this discussion and if I remember correctly the reason for it’s absence is the pytorch philosophy itself: with Pytorch you are able to dynamically create a computation graph (which might also change during time). This philosophy makes it impossible to summarize a graph in a proper way (since you don’t know whether the graph changes or not).
st99420
that make sense… kinda. i guess i’d argue that its an extremely useful tool for the vast majority of architectures so its a mistake to through it out completely, but i get the point. thanks!
st99421
You could check, whether it is possible/easier to create a summary from a model traced with torch.jit since this will also create a somewhat static graph.
st99422
In numpy, when i have a 3D tensor X with shape [A, B, C] and a 2D tensor Y with shape [C, D], then np.dot(X, Y) gives a 3D tensor with shape [A, B, D]. In PyTorch, i can do this as below. result = torch.mm(X.view(-1, C), Y) result = result.view(-1, B, D) Is there simpler way to handle this?
st99423
do you mean entrywise product? you want broadcast like numpy? maybe you can try expand_as 231 and unsqueeze 95 Y.unsqueeze(0).expand_as(X) * X
st99424
Y.unsqueeze(0) has a shape (1, C, D) so that it can not be expanded as X which has a shape (A, B, C). What i want to do is to broadcast 2D matrix multiplication as below. def matmul(X, Y): results = [] for i in range(X.size(0)): result = torch.mm(X[i], Y) results.append(result) return torch.cat(results)
st99425
@yunjey at the moment there is no simpler way. we plan to add broadcast semantics into pytorch
st99426
@chenyuntc, what you suggest would work but it’s an elementwise multiplication. @yunjey for the dot product, in pytorch it seems to only support 2D tensors. So yes, for the moment you have to vectorize (A and B) into one vector (for instance using view, or you can also use resize for almost simpler code: result = torch.mm(X.resize_(A*B,C), Y).resize_(A,B,D)
st99427
I created operators for pytorch with broadcasting - you can grab them from Tip: using keras compatible tensor dot product and broadcasting ops
st99428
Also, you be able to do that with batched matrix multiply: result = torch.bmm(X, Y.unsqueeze(0).expand(X.size(0), *Y.size())) We’ll be adding broadcasting very soon.
st99429
@alexis-jacq don’t use resize_ on tensors that you want to use later! The contents of the tensor are unspecified after you call it.
st99430
@yunjey, numpy-compatible dot was recently published on the forums Tip: using keras compatible tensor dot product and broadcasting ops by @jphoward.
st99431
For future viewers: There is a function in torch einsum: output= torch.einsum("abc,cd->abd", (X, Y))
st99432
Hi All, I want to sample a small part of data from a massive, imbalance dataset, and then split it as training part and validation part. For the sample part, I know the WeightedRandomSampler is the best choice. For the split part, I use SubsetRandomSampler before. But I don’t know how to sample then split because the WeightedRandomSampler will return a dataloader, which cannot put into the SubsetRandomSampler as a sampled dataset. So, how to do that? Thanks!
st99433
Solved by ptrblck in post #2 For the SubsetRandomSampler you would need to provide indices, so we have to get the balanced indices from WeightedRandomSampler. One way would be to create the sampler and instead of returning the data we could return the indices and store them somehow. This doesn’t really sound like a good approa…
st99434
For the SubsetRandomSampler you would need to provide indices, so we have to get the balanced indices from WeightedRandomSampler. One way would be to create the sampler and instead of returning the data we could return the indices and store them somehow. This doesn’t really sound like a good approach, so let’s instead directly get the indices using torch.multinominal. I assume you have already the sample weights for your dataset. This line of code will return len(target) balanced indices: indices = torch.multinomial(weights, num_samples=len(target), replacement=True) Once you have these indices you can split them and feed to the SubsetRandomSampler. If you want to split them in a stratified manner, you can use sklearn.model_selection.train_test_split 9 with stratify=target[indices]. As a small side note: WeigthedRandomSampler is of class Sampler and will be fed to a DataLoader.
st99435
oh yes, you are right! I should read the code more carefully. For images, I found a ugly way to do this: sample_idx = torch.randperm(len(dataset))[:sample_size] dataset.samples = np.array(dataset.samples)[sample_idx.tolist()].tolist() But your way is cleaner and more standard. Thanks!
st99436
Hello, i used VGG 16 to train medical images and after training i got that: vgg_accuracy.png3840×2160 306 KB vgg_loss.png3840×2160 664 KB is that overfitting?
st99437
Hi, Guys. I am new in deep learning area. Now I am reproducing a paper’s codes. since they use several GPUs, there is a command “torch.nn.DataParallel(model, device_ids= args.gpus).cuda()” in codes. But I only have one GPU, what should I change this code to match up my GPU? Thank you!
st99438
Hi, currently I’m having trouble performing all_reduce operations on nn.Module's internal buffers, in multi-node multi-gpu scenario using DistributedDataParallel: E.g., I have a module named Foo, with registered buffer buf_bar. During training, I want to average it on all running instances. Say, I have 2 servers each equipped with 8 gpus; if I don’t use DistributedDataParallel and just launch 16 jobs assigning to each gpus, I can simply write: rank = dist.get_rank() world_size = dist.get_world_size() class Foo(nn.Module): def __init__(...): # ... self.register_buffer("buf_bar", Tensor(*size).to(f"cuda:{rank % world_size}")) # ... def forward(x): # calculates `buf_bar` and div by `world_size` dist.all_reduce(self.buf_bar) # continue training using reduced `buf_bar` Since each gpu has its unique rank, this works just fine. However, if I wrap Foo with DistributedDataParallel and launch 2 jobs, each job sees 8 gpus, as suggested in official documents, then above code locks durning training, since the rank becomes node-wise and each tensor’s device should be indexed by two-level: rank and device_id. I think the solution should be using all_recude_multi_gpu outside of Foo.forward. I’ve briefly gone though DistributedDataParallel, seems it’s using hooks for reduce ops. However, the all_reduce op is in the middle of the Foo's forward process, so register_forward/backward_hook may not help. Can anyone give suggestions? Thank you a lot~
st99439
I do not understand what does “Sets the seed for generating random numbers to a random number on all GPUs” mean, and what is the difference between torch.cuda.mamual_seed_all and torch.cuda.seed_all.
st99440
Hi, I’m learning how to make Convolutional neural networks right now and I ran into something unexpected. I get the an error when I pass an MNIST image to a convolutional layer. I have pytorch 0.4.1 with no cuda on my laptop I made my own module to let me choose a variable number of convolutional layers and linear fully connected layers. I am prettymuch following this tutorial : http://adventuresinmachinelearning.com/convolutional-neural-networks-tutorial-in-pytorch/ Code: class CNN2d(torch.nn.Module): def __init__(self, convolution_args, pool_args, linear_args, activation_functions, softmax=False): """convolution_args, pool_Args, linear_args are lists of *args for the Conv2d, MaxPool, and Linear modules and activation_functions is a ModuleList of activation functions (not including softmax)""" super(CNN2d, self).__init__() assert len(convolution_args) == len(pool_args) l = len(convolution_args) assert all([convolution_args[j][1] == convolution_args[j+1][0] for j in range(l-1)]) self.convolutions = torch.nn.ModuleList([torch.nn.Conv2d(*arg) for arg in convolution_args]) self.pools = torch.nn.ModuleList([torch.nn.MaxPool2d(*arg) for arg in pool_args]) k = len(linear_args) assert all([linear_args[j][1] == linear_args[j+1][0] for j in range(k-1)]) assert len(activation_functions) == len(linear_args) - 1 self.linears = torch.nn.ModuleList([torch.nn.Linear(*arg) for arg in linear_args]) self.activation_functions = activation_functions self.softmax = softmax def forward(self, x): y = x n = len(self.convolutions) l = len(self.linears) relu = torch.nn.ReLU() dropout = torch.nn.Dropout() for i in range(n): conv = self.convolutions[i] pool = self.pools[i] y = conv(y) y = relu(y) y = pool(y) y.reshape(y.size(0),-1) y = dropout(y) for j in range(l-1): linear = torch.nn.Linear(*self.linears[j]) actv = self.activation_functions[j] y = actv(linear(y)) y = self.linears[-1](y) if self.softmax == True: sm = torch.nn.Softmax(dim=1) y = sm(y) return y I put this module in my own module that I will load as nnet. The error is on the y = conv(y) line. Now I start to use it with the MNIST data: import matplotlib.pyplot as plt import torch import torchvision batch_size = 30 epochs = 5 learning_rate = 0.001 train_set = torchvision.datasets.MNIST(root = '/home/carson/Desktop/Archive/Computing/Projects/Python/Data', train=True, transform=torchvision.transforms.ToTensor(), download=True) test_set = torchvision.datasets.MNIST(root = '/home/carson/Desktop/Archive/Computing/Projects/Python/Data', train=False, transform=torchvision.transforms.ToTensor(), download=True) train_loader = torch.utils.data.DataLoader(dataset=train_set, batch_size=batch_size, shuffle=True) test_loader = torch.utils.data.DataLoader(dataset=test_set, batch_size=batch_size, shuffle=False) Ok, so I am about to define my network, I want the [input, output, kernel_size, stride, padding] of the first convolution layerlayer to be [1,32,5,1,2], just like in the tutorial. convolution_args = [[1,32,5,1,2], [32,64,5,1,2]] pool_args = [[2,2], [2,2]] linear_args = [[7*7*64,1000],[1000,10]] activation_functions = torch.nn.ModuleList([torch.nn.ReLU()]) model = nnet.CNN2d(convolution_args, pool_args, linear_args, activation_functions) loss_function = torch.nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) So far so, good, the next step gives the runtime error: loss_items = list() for t in range(epochs): for i, (images, labels) in enumerate(train_loader): encoder = nnet.encoding_function(10) labels = encoder(labels) images = images.reshape(-1,28*28) outputs = model(images) loss = loss_function(outputs, labels) if i%1000 == 0: loss_items.append(loss.item()) optimizer.zero_grad() loss.backward() optimizer.step() error message: --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-5-a61d0e8b1d76> in <module>() 8 9 images = images.reshape(-1,28*28) ---> 10 outputs = model(images) 11 12 ~/.local/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 475 result = self._slow_forward(*input, **kwargs) 476 else: --> 477 result = self.forward(*input, **kwargs) 478 for hook in self._forward_hooks.values(): 479 hook_result = hook(self, input, result) ~/Desktop/Archive/Computing/Projects/Python/ai/neural_network.py in forward(self, x) 93 conv = self.convolutions[i] 94 pool = self.pools[i] ---> 95 y = conv(y) 96 y = relu(y) 97 y = pool(y) ~/.local/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 475 result = self._slow_forward(*input, **kwargs) 476 else: --> 477 result = self.forward(*input, **kwargs) 478 for hook in self._forward_hooks.values(): 479 hook_result = hook(self, input, result) ~/.local/lib/python3.6/site-packages/torch/nn/modules/conv.py in forward(self, input) 299 def forward(self, input): 300 return F.conv2d(input, self.weight, self.bias, self.stride, --> 301 self.padding, self.dilation, self.groups) 302 303 RuntimeError: Expected 4-dimensional input for 4-dimensional weight [32, 1, 5, 5], but got input of size [30, 784] instead So I tried to do an example to see what is going on, but I did not get the same error arg = [1,32, 5, 1, 2] net = torch.nn.Conv2d(*arg) for i, (image, label) in enumerate(train_loader): if i == 0: net(image) No error, so I have no idea what to do about this.
st99441
Solved by ptrblck in post #2 Since you have a CNN you should pass your input as images. Try to remove the image = images.reshape(-1, 28*28) line and run it again. Your code already flattens the activation after the conv and before the linear layers.
st99442
Since you have a CNN you should pass your input as images. Try to remove the image = images.reshape(-1, 28*28) line and run it again. Your code already flattens the activation after the conv and before the linear layers.
st99443
How can I handle data imbalance by updating the loss functions or by biasing the batch pass? It will be great if some excerpts of the code can be provided.
st99444
You could pass a weight Tensor to your loss (e.g. NLLLoss) with your class weights. It should have the length of your classes C.
st99445
I believe that if you use the weight Tensor then shuffle=True is not an option as far as I saw a few days ago though I would hope to be corrected.
st99446
The weight in a loss function has no impact on the shuffle option from a DataLoader. Could it be you are referring to the sampler argument in DataLoader? The doc 14 states that shuffle cannot be set when a sampler was given. To sample in a balanced way, you could you a WeightedRandomSampler with its class weights. However, a weighted loss should work regardless of the sampling method.
st99447
Absolutely, you are correct and my apologies for poor, presumptuous reading and false statements. Perhaps, after my time spent to view the Sampler only to find out it could not be used as per my setup I was hoping to save someone else said time. If balancing data through loss functions works as well and allows shuffling why would this method rather than the Sampler be available, short of rolling one’s own?
st99448
No worries, sometimes it’s quite easy to mix something up. Especially when the arguments have the same name. Well, the weights in the loss function perform a class weighting, i.e. samples get multiplied with the respective class weight. Have a look at the formula in the docs 45. The WeightedRandomSampler draws samples according the the weights, so that some classes are sampled more often than others. In the case of an imbalanced setup, you could try either of these approaches.
st99449
@ptrblck @smth I found it is time-consuming on calculating weights for this WeightedRandomSampler(weights, sample_size). As people said, len(weights) == len(dataset). so if the dataset is huge (10^9), this part is inefficient for index in range(len(dataset)): reciprocal_weights.append(class_prob[dataset[index][1]]) weights = (1 / torch.Tensor(reciprocal_weights)) Is it really necessary to calculate all weights (10^9) if my sample_size is just very small (e.g. 1000)? I don’t think so, especially the weights array usually is just a vector with lots of redundancy which can be express as the sparse vector.
st99450
The for loop might indeed be slow. Could you try to use direct indexing like in this example 68? Currently the weights are passed to torch.multinominal, so I guess there is no easy alternative at the moment. I get your issue and like the idea of just providing class weights. Let me think about a good approach.
st99451
Is there any stable pytorch implementation of Mask-RCNN? I have seen many projects on github, but all of them are left incomplete. I want to use it for medical imaging segmentation problem.
st99452
So, when the first half of my EACH and EVERY training mini-batches are from class C0 and the second from class C1, my neural net trains up to 60% accuracy and then crashes to flat 50%! I finally figured out it is because my batches are ordered. For instance, they look like (C0, C0, C0, C1, C1, C1). To resolve this, the input tensor to the model must be shuffled, (C0, C1, C0, C1, C1, C0). Why would this matter? Doesn’t the weight/learning update step stem from the average of the losses of datapoints in a mini-batch? If that’s true, why would the order of classes in the training minibatch matter so much?
st99453
Because the estimate of the expected gradients is biased if your data is ordered. Have a look at Chapter 8 - Deep Learning book 5: It is also crucial that the minibatches be selected randomly. Computing an unbiased estimate of the expected gradient from a set of samples requires that those samples be independent. We also wish for two subsequent gradient estimates to be independent from each other, so two subsequent minibatches of examples should also be independent from each other. I can’t explain it that well as Ian Goodfellow does, but I understand it from a point of view, where you force your model to a minimum for the current class. All weight updates aim towards the minimum of class0, until you finally provide samples for class1. This minimum of class1 might be slightly different. If your parameters are already in a “class0 valley” it might be hard for your model to escape it. That’s probably a very shallow view on the training and loss function, but it helps me visualizing, what could be happening.
st99454
@ptrblck, thanks for replying but I think you misunderstood my question. My dataLoader does NOT load all class0 first, then all class1. Each mini-batch contains class0 AND class1, something like this (C0, C0, C0, C1, C1, C1). The weights should be updated based on the average loss. However, this doesn’t result in proper training. Rather, they must be shuffled, e.g. (C0, C1, C0, C1, C1, C0). Is pytorch creating mini-mini-batches from the mini-batches I feed to the model?
st99455
it might be the reason if you are using Batchnorm as well as 2 GPUs. As far as I know batch norm is local per GPU. Is it the case?
st99456
Another reason is that shuffling the data and then taking a random set of samples as the mini-batch samples offers some “implicit regularization”. And this method is considerably effective if the mini-batch sizes are very small (for e.g. 8, 16, or 32)
st99457
If you are curious enough to test this hypothesis, try to remove batchnorm in your network and train again to see whats happening.
st99458
@miladiouss whats your batch_size?? If its like 32 and you are distributing the data to 2 GPUS, the effective batch_size would be 16 . Here, since the batch_size is small, the parameters of BatchNorm layers are highly biased towards the mini-batches. This might be the reason. Try other norms like SwitchNorm in case of small batch_size
st99459
Thanks @Vikas_Sangwan and everyone else. So, my batch size is 64 and I had 2 classes and 2 GPUs. And it seems the issue is from batch normalization. For now, I am shuffling my minibatches so each GPU gets the same number of each class. I will try other normalization methods and write an update at some time. Thanks for the help everyone.
st99460
I have seen a lot of pytorch code that defines a training function to take in the input and do the training but yet does not have a return statement (instead just modifies the model in place). Is it typically better practice to do this as opposed having a return statement that takes in a model and returns a model ?
st99461
I know that Caffe2 supports batch training (multi-batch size > 1). Does Caffe2 support multi-batch inference? If so, where can I find an example in Python?
st99462
Could anyone explain what might cause swap to be used a lot when using pin_memory, and what are some common ways to fix the problem? Is it due to trying to pin too much memory? Or some other cause? If you have multiple data workers, does each have it’s own memory pin (which might be part of the issue leading to pinning too much memory)? Additionally, the documentation 12 says once you pin a tensor or storage, you can use asynchronous GPU copies. Just pass an additional non_blocking=True argument to a cuda() 1 call. This can be used to overlap data transfers with computation. If I am not using non_blocking CUDA calls after using pin_memory does that, there is still an advantage to using pin_memory, correct?
st99463
I downloaded the c++ preview build of pytorch and am trying to do multiple indexing via the [] operator: in python it would be: data = torch.rand(3,3,3) data[tensor([0,1]), tensor([1,2])] Anyone know the syntax for this functionality in C++? in C++ the [] operator only supports a single int.
st99464
Found it for anyone wondering. Just call index: Tensor data = at::rand(3,3,3); dim1 = at::tensor(({0, 1}, torch::kInt64); dim2 = at::tensor(({1, 2}, torch::kInt64); data.index({dim1, dim2});
st99465
Hey there, I have faced an issue with using the WeightedRandomSampler where even with the assigned weights the majority class is being resampled more heavily than the remaining classes. Is there a capacity to the weighted random sampler beyond which resampling doesn’t reweight the samples any more?
st99466
Solved by ptrblck in post #6 I used 0.4.0 and tried to stay as close to your code as possible. This code works on my machine: data = torch.randn(1000, 1) target = torch.cat(( torch.zeros(998), torch.ones(1), torch.ones(1)*2 )).long() cls_weights = torch.from_numpy( compute_class_weight('balanced', np.unique(t…
st99467
If you left the argument replacement´ asTrue`, I assume the limit of the weights is just the floating point precision to represent the weight. What are the current values you are using?