id
stringlengths
3
8
text
stringlengths
1
115k
st101700
I have tried a few things but with no success. Tried “conda install pytorch torchvision -c pytorch” Failed because "PackagesNotFoundError: The following packages are not available from current channels: pytorch" Tried “pip install pytorch” That failed as well after downloading the tar.gz file and attempting a build (which failed). The error notice ended with “Exception: You should install pytorch from http://pytorch.org 15”. Been working with Linux for many years but not sure how to navigate with pip and conda package utilities. Help is appreciated. Thank You Tom
st101701
Two things you could try: Build from source (pytorch in github 67) Install from here : pip install https://files.pythonhosted.org/packages/ca/0d/f00b2885711e08bd71242ebe7b96561e6f6d01fdb4b9dcf4d37e2e13c5e1/torchvision-0.2.1-py2.py3-none-any.whl. This will install pytorch 0.4.1 also.
st101702
Hi and thank you for the reply, Although I have other computers that do run Linux natively, with a GXT960 graphics card, here, I am on a relatively new Dell laptop running windows 10 (weening myself off the “big” tower). So, probably no dedicated GPU. Running python in a jupyter notebook (browser). python -V python 3.6.6 :: Anaconda custom (64 bit) Thank You Tom
st101703
Please help me assemble list of PyTorch tensor operations which are useful You can refer to NumPy or SciPy or any other libraries operation here docs.google.com Numpy operations that should be in PyTorch 16 Sheet1 Category, Operation, Use, Numpy equivalent, Sematics and input args Data Processing, torch. savetxt, Save tensor into file, np. savetxt, delimiter, new line Matrix Ops
st101704
Hey there, so I’ve been using PyTorch (0.3.1) for a while now and have tried to fix the following issue for some time now: When I run a training script simulatenously (i.e. in two separate terminal instances) with different parameters, but same overall structure, on two separate 1080Tis, I get a full system freeze under Ubuntu 16.04 which I can’t leave without a force shutdown. Alse, there is no prior error message. This doesn’t happen when I utilize either one of the GPUs alone. Since I have encountered this issue, I have tried multiple things to fix this: [1] Upgraded PSU to 1200W [2] Set shared memory to high values. [3] Use torch.multiprocessing.set_start_method(‘spawn’) [4] Varied # of workers. Except for 0 workers, the error still occurs. Unfortunately, using the 0 worker option is not a feasible option for me. This most likely points to a multiprocessing issue; but I don’t know enough in that regard to investigate deeper. Also, its hard to tell since, again, no error message is thrown. [5] Tested Ubuntu 18.04 - Same issue [6] Tested PyTorch 0.4 - Same issue [7] Worked my way through most of the nvidia-drivers. Since this is most likely (although not necessarily) a specific issue either with my PC or my training script, I don’t expect full solutions in that regard. But pointers to options that could be helpful and that I haven’t looked into would be nice :). Note: The training script structure is fairly straightforward: Initialize Dataloader with paths to image files -> Iterate over them one by one.
st101705
Could you try to run your script via CUDA_VISIBLE_DEVICES=YOUR_GPU_ID python script.py? This will make sure the current script only sees the specified GPU. Let me know, if that helps.
st101706
I’ve been doing that internally via os.environ["CUDA_VISIBLE_DEVICES"]= <device_num> in the script itself. Does it make a difference to instead declare it when calling the script? Nonetheless, I’ll still give it a try
st101707
So unfortunately, as expected, choosing the device outside of the actual python script did not change anything, the system still crashed :/. Maybe any other suggestions?
st101708
I think we should narrow down the error. Could you try to run the scripts without the GPUs? If that still hangs, could you use num_workers=0 in your DataLoaders and run it again?
st101709
I actually haven’t tried running without a GPU yet! I’ll see what that gives me. Sidenote: I’ve already testednum_workers=0 (with GPU) and it works.
st101710
Are you working on windows? Edit: just saw you wrote ubuntu. Have you tried covering your script with if __name__ == "__main__" :
st101711
Thanks for the suggestion! Fortunately (or unfortunately) I’ve already tried putting my main function and all relevant setting into if __name__ == "__main__", but it didn’t seem to help.
st101712
Could you check your shared memory limit? This github issue 10 deals probably with the same problem.
st101713
And did you try adding freeze-support like this? from multiprocessing import freezele_support ... if __name__ == "__main__" : freeze_support() ... EDIT: what happens if you combine both scripts into a single script and parallelize it by hand (spawning some processes yourself)?
st101714
@ptrblck: I’ve checked that issue and tested everything listed there, but increasing the shared memory did not solve this issue. @justusschock: So as it turns out, when I put my complete script into a main()-handle (which I thought I had already tried but apparently not :)) I do not get a full system freeze any longer! However, scripts similarly stop running, with either one of these errors being thrown: RuntimeError: cuda runtime error (4) : unspecified launch failure at /opt/conda/conda-bld/pytorch_1518243271935/work/torch/lib/THC/generated/../generic/THCTensorMathPointwise.cu:630 during optimizer.step(). DataLoader worker (pid 15189) is killed by signal: Segmentation fault or Illegal Instruction which happens arbitrarily, also either during optimizer.step(). Full errors are appended. Any ideas what could cause this/what generally leads to errors like this? — FULL ERRORS — EXAMPLE 1 ERROR: Unexpected segmentation fault encountered in worker Traceback (most recent call last): File "script.py", line 590, in <module> main() File "script.py", line 540, in main trainer(epoch) File "script.py", line 395, in trainer optimizer.step() File "/home/user/software/miniconda3/envs/D3L/lib/python3.6/site-packages/torch/optim/adam.py", line 72, in step denom = exp_avg_sq.sqrt().add_(group['eps']) File "/home/user/software/miniconda3/envs/D3L/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 175, in handler _error_if_any_worker_fails() RuntimeError: DataLoader worker (pid 9437) is killed by signal: Segmentation fault. EXAMPLE 2 THCudaCheck FAIL file=/opt/conda/conda-bld/pytorch_1518243271935/work/torch/lib/THC/generic/THCTensorMathPairwise.cu line=81 error=4 : unspecified launch failure | 418/2092 [02:38<10:34, 2.64it/s] Traceback (most recent call last): File "script.py", line 590, in <module> main() File "script.py", line 540, in main trainer(epoch) File "script.py", line 395, in trainer optimizer.step() File "/home/user/software/miniconda3/envs/D3L/lib/python3.6/site-packages/torch/optim/adam.py", line 69, in step exp_avg.mul_(beta1).add_(1 - beta1, grad) RuntimeError: cuda runtime error (4) : unspecified launch failure at /opt/conda/conda-bld/pytorch_1518243271935/work/torch/lib/THC/generic/THCTensorMathPairwise.cu:81 EXAMPLE 3 Traceback (most recent call last): File "script.py", line 590, in <module> main() File "script.py", line 540, in main trainer(epoch) File "script.py", line 395, in trainer optimizer.step() File "/home/user/software/miniconda3/envs/D3L/lib/python3.6/site-packages/torch/optim/adam.py", line 72, in step denom = exp_avg_sq.sqrt().add_(group['eps']) File "/home/user/software/miniconda3/envs/D3L/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 175, in handler _error_if_any_worker_fails() RuntimeError: DataLoader worker (pid 6114) is killed by signal: Illegal instruction.
st101715
It seems to be an issue with how you update the parameters. Could you post a small code snippet?
st101716
Ok so the reply took some time as running two full networks on CPU only in parallel takes some time. Nevertheless, doing so shows the following: When running the same script in parallel (see bottom of paragraph) in cpu-only mode (so simple discarding any .cuda()-commands, for 4 days straight & 12 epochs in total), there is NO freezing/hang-up. When using GPUs, I get a freeze after roughly 1.5 hours or 10 epochs. This is weird, since the script stays the same in both cases (with the exception of whether or not a GPU is used). Below you can see the relevant functions I use, invoked subsequently: General Setup UNet = network_library.UNet(**Network_Parameters) UNet.weight_init('he_normal') Base_Loss_t = auxiliaries.Loss_Provider('dice_loss') optimizer = torch.optim.Adam(UNet.parameters(), lr=opt.lr, weight_decay=opt.l2_reg) scheduler = lr_scheduler.StepLR(optimizer, step_size=30, gamma=0.2) DataLoader-Setup train_dataset = Dataset_2D(path_to_data_files) train_data_loader = DataLoader(train_dataset, num_workers=6, batch_size=8, pin_memory=False, shuffle=True) Note: I don’t think there is any error with the Dataloader now since it works fine using CPUs only. Training Function def training(epoch): _ = UNet.train() mini_dice1 = [] mini_dice2 = [] mini_loss = [] mini_time = [] train_data_iter = tqdm(train_data_loader, position=1) inp_string = 'Epoch {} || Loss: --- | Dice: ---'.format(epoch) for slice_idx, full_file_dict in enumerate(train_data_iter): train_data_iter.set_description(inp_string) train_iter_start_time = time.time() training_slice = full_file_dict["input_slice"] training_slice = Variable(training_slice).type(torch.FloatTensor).cuda() #--- Run Training --- network_output = UNet(training_slice) ### BASE LOSS feed_dict = {'input':network_output} feed_dict['target'] = Variable(full_file_dict['ground_truth_mask']).cuda() loss = Base_Loss_t(**feed_dict) optimizer.zero_grad() loss.backward() optimizer.step() mini_dice1.append(np.round(get_cuda(network_output))) mini_dice2.append(full_file_dict['ground_truth_mask'].numpy()) mini_loss.append(loss.data.cpu().numpy()[0]) mini_time.append(np.round(time.time()-train_iter_start_time,4)) I do hope I made some obvious mistake, but any help is appreciated!
st101717
Since the error might occur inside your dataloader, it would be interesting what kind of data you read and maybe to see your dataset code. I’ve skimmed through your train code and it looks fine to me.
st101718
I’ll post the dataset code later - just a quick question: Doesn’t the script running in CPU-mode only show that everything regarding the dataloader should be fine? Or am I missing something?
st101719
To be honest: I don’t know. Your error looks pretty strange, but since it might be related to your data it can’t be wrong to have a look on your data loading. Do you set your CUDA_VISIBLE_DEVICES before or after importing torch or modules, that use torch?
st101720
Ok sure :). Well I’ve tried both, setting CUDA_VISIBLE_DEVICES=0 or 1 when calling it via CUDA_VISIBLE_DEVICES=0 python script.py and after importing torch via os.environ(). Also as a side note: For whatever reasons, I don’t get a error raise anymore, but go straight to system freezes… it’s really weird
st101721
Well so I have tried: [1] Moving everything to Windows, but same problem there - no frozen system, but bluescreen. [2] Tested under Pytorch 0.4.1 - Same Problem. [3] Set integrated GPU as display card and use NVIDIA Gpus only for PyTorch - Same Problem. So I can pretty much rule out OS-problems. Also, I don’t think there is a hardware issue, since the PSU should be powerful enough. So in a last hope, I’ve attached a functional version of the dataset. I hope there is some error in there :D. In it, I accumulate every relevant path to my data files in a dictionary and, well, load it in _getitem_(). """==================================""" """====== Load Basic Libraries ======""" """==================================""" import numpy as np import os, sys, time, csv, itertools, copy from tqdm import tqdm, trange import torch import torch.nn as nn from torch.utils.data import Dataset sys.path.insert(0, '../Helper_Functions') sys.path.insert(0, '../Network_Library') import helper_functions as hf import Network_Auxiliaries as aux import scipy.ndimage.measurements as snm import skimage.transform as st import pandas as pd """""""""""""""""""""""""""""""""""" """===== Dataset 4 Training ===""" """""""""""""""""""""""""""""""""""" class Dataset_Training(Dataset): def __init__(self, base_path, train_val_split=0.8, perc_data=1., standardize=True, augment=False, crop=[224,224], seed=1): self.rng = np.random.RandomState(seed) ### Read in CSVs containing paths to data slices (0.5MB numpy files .npy) v = pd.read_csv(base_path+"Assign_2D_Volumes.csv",header=0) l = pd.read_csv(base_path+"Assign_2D_LiverMasks.csv",header=0) n = pd.read_csv(base_path+"Assign_2D_LesionMasks.csv",header=0) wle = pd.read_csv(base_path+"Assign_2D_LesionWmaps.csv",header=0) ### Get unique data volumess self.available_volumes = sorted(list(set(np.array(v["Volume"]))),key=lambda x: int(x.split('-')[-1])) self.rng.shuffle(self.available_volumes) self.available_volumes = self.available_volumes[:int(len(self.available_volumes)*perc_data)] self.available_volumes = self.available_volumes[:int(len(self.available_volumes)*train_val_split)] ### Create path dictionary roi_vicinity = 4 self.training_volumes = {key:{"LesWmap_Paths":[], "LesMask_Paths":[],"LivMask_Paths":[],"Has Lesion":[], "Vol_Paths":[],"LesSlices":[], "LivSlices":[]} for key in self.available_volumes} iter_vals = tqdm(v["Volume"]) iter_vals.set_description('Reading and assigning training data paths') for i,vol in enumerate(iter_vals): if np.sum(l["Has Mask"][i:i+roi_vicinity]) and vol in self.available_volumes: self.training_volumes[vol]["Vol_Paths"].append(v["Slice Path"][i]) self.training_volumes[vol]["LivMask_Paths"].append(l["Slice Path"][i]) self.training_volumes[vol]["LesMask_Paths"].append(n["Slice Path"][i]) self.training_volumes[vol]["Has Lesion"].append(n["Has Mask"][i]) self.training_volumes[vol]["LesWmap_Paths"].append(wle["Slice Path"][i]) for i,vol in enumerate(self.available_volumes): if np.sum(self.training_volumes[vol]["Has Lesion"]): self.training_volumes[vol]["LesSlices"] = list(np.where(self.training_volumes[vol]["Has Lesion"])[0]) self.training_volumes[vol]["LivSlices"] = list(set(np.arange(0,len(self.training_volumes[vol]["Has Lesion"])))-set(self.training_volumes[vol]["LesSlices"])) else: self.training_volumes[vol]["LesSlices"] = [] self.training_volumes[vol]["LivSlices"] = list(np.arange(0,len(self.training_volumes[vol]["Has Lesion"]))) self.n_files = np.sum([len(self.training_volumes[key]["Vol_Paths"]) for key in self.training_volumes.keys()]) ### Other input arguments self.standardize = standardize self.augment = augment self.crop_size = crop self.n_crops = n_crops self.channel_size = channel_size def __getitem__(self, idx): #>> Data Volume Array Of Interest VOI = self.available_volumes[self.rng.randint(0,len(self.available_volumes))] #>> There are two types of Slices - randomly pick one chosen_slice_from_VOI = self.rng.randint(0,3)>0 and len(self.training_volumes[VOI]["LesSlices"])>0 #>> Pick a random slice from either category if chosen_slice_from_VOI: SOI = self.rng.choice(self.training_volumes[VOI]["LesSlices"]) else: SOI = self.rng.choice(self.training_volumes[VOI]["LivSlices"]) #>> Load Slice of Interest V2O = np.expand_dims(np.expand_dims(np.load(self.training_volumes[VOI]["Vol_Paths"][SOI]),0),0) #>> Perform data standardization if required V2O = hf.normalize(V2O, supply_mode="orig") #>> Load The Respective Target Mask Les2O = np.load(self.training_volumes[VOI]["LesMask_Paths"][SOI]) Les2O = np.expand_dims(np.expand_dims(Les2O,0),0) #>> Load An Additional Crop Mask Liv2O = np.expand_dims(np.expand_dims(np.load(self.training_volumes[VOI]["LivMask_Paths"][SOI]),0),0) #>> And A Used Cost Map Wmap2O = np.expand_dims(np.expand_dims(np.load(self.training_volumes[VOI]["LesWmap_Paths"][SOI]),0),0) #>> Images Are Too Big So They Get Cropped. files_to_crop = [V2O, Les2O, Wmap2O] #>> But First, I Augment Them (rotation & zooming with scipy.ndimage.interpolation.rotate/zoom) files_to_crop = list(hf.augment_2D(files_to_crop, copy_files=True, seed=self.rng.randint(0,1e8), is_mask = [0,1,0])) #>> Crop Images - Function slices random subarray from input arrays in files_to_crop. Liv2O provides the regions in which to crop. crops_for_picked_batch = hf.get_crops_per_batch(files_to_crop, Liv2O, crop_size=self.crop_size) V2O = crops_for_picked_batch[0] Les2O = crops_for_picked_batch[1] Wmap2O = crops_for_picked_batch[2] return_dict = {"vol":V2O[0,:], "lesmask":Les2O[0,:], "wmap": Wmap2O[0,:].astype('float')} return return_dict def __len__(self): return int(self.n_files) """""""""""""""""""""""""""""""""""" """===== Dataset 4 Validation ===""" """""""""""""""""""""""""""""""""""" class Dataset_Validation(Dataset): def __init__(self, base_path, tv_split=0.85, standardize=True, seed=1, is_training=False, perc_data=1.): self.tv_split = tv_split self.standardize = standardize self.rng = np.random.RandomState(seed) ### Read in CSVs to data files (npy-files, 0.5MB) v = pd.read_csv(base_path+"Assign_2D_Volumes.csv",header=0) l = pd.read_csv(base_path+"Assign_2D_LiverMasks.csv",header=0) n = pd.read_csv(base_path+"Assign_2D_LesionMasks.csv",header=0) ### Get unique volumes self.available_volumes = sorted(list(set(np.array(v["Volume"]))),key=lambda x: int(x.split('-')[-1])) self.rng.shuffle(self.available_volumes) self.available_volumes = self.available_volumes[:int(len(self.available_volumes)*perc_data)] self.available_volumes = self.available_volumes[int(len(self.available_volumes)*tv_split):] self.available_volumes.sort() self.validation_volumes = {key:{"LesMask_Paths":[],"LivMask_Paths":[],"Vol_Paths":[]} for key in self.available_volumes} iter_vals = tqdm(v["Volume"]) iter_vals.set_description('Reading and assigning validation data paths') for i,vol in enumerate(iter_vals): if vol in self.available_volumes: if l['Has Mask'][i]: self.validation_volumes[vol]["Vol_Paths"].append(v["Slice Path"][i]) self.validation_volumes[vol]["LivMask_Paths"].append(l["Slice Path"][i]) self.validation_volumes[vol]["LesMask_Paths"].append(n["Slice Path"][i]) self.volume_separators = [len(self.validation_volumes[vol]["Vol_Paths"]) for vol in self.validation_volumes.keys()] self.validation_data = {"vol":[], "lesmask":[], "livmask":[]} for vol in self.available_volumes: for i in range(len(self.validation_volumes[vol]["Vol_Paths"])): vol_slices = self.validation_volumes[vol]["Vol_Paths"][i] liv_slices = self.validation_volumes[vol]["LivMask_Paths"][i] les_slices = self.validation_volumes[vol]["LesMask_Paths"][i] self.validation_data["vol"].append(vol_slices) self.validation_data["livmask"].append(liv_slices) self.validation_data["lesmask"].append(les_slices) self.n_files = len(self.validation_data["vol"]) def __getitem__(self, idx): #>> Slice of Interest V2O = np.expand_dims(np.expand_dims(np.load(self.validation_data["vol"][idx]),0),0) #>> Data Standardization V2O = hf.normalize(V2O, supply_mode="orig") Les2O = np.expand_dims(np.expand_dims(np.load(self.validation_data["lesmask"][idx]),0),0) Liv2O = np.expand_dims(np.expand_dims(np.load(self.validation_data["livmask"][idx]),0),0) return_dict = {"vol":V2O[0,:], "lesmask":Les2O[0,:], "livmask":Liv2O[0,:]} return return_dict def __len__(self): return self.n_files
st101722
Your code looks fine to me. What kind of data do you use? I want to try it myself. Have you tried to replace your loaded data with random data (just to ensure that the error is not the loading part)?
st101723
Hey there awesome People! I am wondering what is the best way to put meta data as extra information into my CNN. I thought of normalizing it and concatenating the tensor of meta data with the output-tensor of my last Conv2D Layer so the Fully connected layers can take advantage of this meta-data. Is this common practice in PyTorch? Thanks a lot! Raph
st101724
Hi, What kind of metadata do you have? For the case that you deal with numerical metadata: You could surely do this. Another approach would be to repeat your Metadata until it has the same dimensions as your images and start feeding it into your Conv layers. This would have the benefit, that you do not have a mixture of abstract/learned features and “handcrafted” features/Metadata. Your network would learn to build abstract features out of your metadata as well. However, your approach could work too. In my opinion it is something like a philosophical decision.
st101725
I have a 2 GPUs so I want to use data parallelism. In my prototype I build a method within the model itself so I can call model.dosomething(), this works if I only use 1 gpu E.g. using model.cuda(). Now that my model is done testing I want to utilize the power of 2 GPUs. I can no longer do model.dosomething() because model is now a type of <class 'torch.nn.parallel.data_parallel.DataParallel'>. How can I remedy this beside rewrite the entire model again?
st101726
Solved by JuanFMontesinos in post #2 Do model.module.something()
st101727
I am trying to build an LSTM model that will predict future values of a time series, using past values as well as other features (these other features being the key). For example, I have a time series Y: Y = [1, 2, 3, 1, 2, 3] that also has a bunch of features associated with each time point: X1 = [5,5,4,3,3,3] X2 = [2,2,1,2,2,2] I’m having the damnedest time figuring out how to extrapolate the LSTM example with Sin wave function prediction with my scenario, where the input layer should contain cells for both past values and their associated features. Does anybody have a link to an example of time series prediction using both autoregressive AND other features in PyTorch?
st101728
Hey I’m facing a similar problem right now, did you find any way of solving this issue? i.e. combining previous predictions with current input features?
st101729
The simplest approach would be to use torch.cat them together along the feature dimension (dim=2). Have a linear layer with the appropriate number of outputs towards the top of the model. Then on prediction, you can torch.cat the outputs of the model with the next timestep’s extrinsic features. Best regards Thomas
st101730
This is an older example from Pytorch 3.0 but it might help… So, torch.cat all your timeseries into a tensor (batch, time, features) where feature has dim of 2 in your case, then… class SimpleLSTM(nn.Module): def __init__(self, input_dims, sequence_length, cell_size, output_features=1): super(SimpleLSTM, self).__init__() self.input_dims = input_dims self.sequence_length = sequence_length self.cell_size = cell_size self.lstm = nn.LSTMCell(input_dims, cell_size) self.to_output = nn.Linear(cell_size, output_features) def forward(self, input): h_t, c_t = self.init_hidden(input.size(0)) outputs = [] for input_t in torch.chunk(input, self.sequence_length, dim=2): h_t, c_t = self.lstm(input_t.squeeze(2), (h_t, c_t)) outputs.append(self.to_output(h_t)) return torch.stack(outputs, dim=2) def init_hidden(self, batch_size): hidden = Variable(next(self.parameters()).data.new(batch_size, self.cell_size), requires_grad=False) cell = Variable(next(self.parameters()).data.new(batch_size, self.cell_size), requires_grad=False) return hidden.zero_(), cell.zero_() the self.to_output set to nn.Linear(2,1) should reduce your features down to 1 number… the rest of my lstm code at https://github.com/DuaneNielsen/DualAttentionSeq2Seq 45
st101731
Hi, I have a time series forecasting model that uses both normal (i.e. global) parameters like weights, and some per series parameters. Additionally, I train a number of NNs concurrently - they are receiving different subsets of the dataset (allocation happens once an epoch). So, to speed things up, I am using multiprocessing, one process per network. In the main program I create trainers, one per network, and pass them to the worker process. I use .share_memory() on both global and per series parameters. I am passing the trainer to the worker. At the end of training, inside the worker function, I save the trainer state (trainer.state), pass it back to the main program and update the trainer state here, like: trainer.state=state_retunerned But the accuracy of the fit is below the one I am getting on a single-threaded C++/Dynet. I am thinking that this may be because I use several trainers (one per net) to update the same per-series parameters. In C++/Dynet I have a separate trainer dealing with per-series-parameters, but I do not see how I could make it in Pytorch, in other words: how to share a trainer in a multiprocessing? A trainer is an object that does not support share_memory() function. So, let me ask again: how to share a trainer? Regards, Slawek
st101732
I train a model on two gpus, and then save the model like this: net = nn.DataParallel(net) ..... torch.save(net, save_path) Then I load the model and run inference with single gpu: CUDA_VISIBLE_DEIVCES=0 python infer.py the infer.py is like this: im = cv2.imread('./cropped.jpg') im = cv2.resize(im, (224, 224)).transpose(2, 0, 1) im = torch.tensor([im, im, im], dtype = torch.float32) model_path = './res/model.pytorch' model = torch.load(model_path) model.eval() out = model(im).detach().cpu().numpy() I met the error message like this: test() File "infer.py", line 25, in test out = model(im).detach().cpu().numpy() File "/home/zhangzy/.local/lib/python2.7/site-packages/torch/nn/modules/module.py", line 491, in __call__ result = self.forward(*input, **kwargs) File "/home/zhangzy/.local/lib/python2.7/site-packages/torch/nn/parallel/data_parallel.py", line 110, in forward inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids) File "/home/zhangzy/.local/lib/python2.7/site-packages/torch/nn/parallel/data_parallel.py", line 121, in scatter return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim) File "/home/zhangzy/.local/lib/python2.7/site-packages/torch/nn/parallel/scatter_gather.py", line 36, in scatter_kwargs inputs = scatter(inputs, target_gpus, dim) if inputs else [] File "/home/zhangzy/.local/lib/python2.7/site-packages/torch/nn/parallel/scatter_gather.py", line 29, in scatter return scatter_map(inputs) File "/home/zhangzy/.local/lib/python2.7/site-packages/torch/nn/parallel/scatter_gather.py", line 16, in scatter_map return list(zip(*map(scatter_map, obj))) File "/home/zhangzy/.local/lib/python2.7/site-packages/torch/nn/parallel/scatter_gather.py", line 14, in scatter_map return Scatter.apply(target_gpus, None, dim, obj) File "/home/zhangzy/.local/lib/python2.7/site-packages/torch/nn/parallel/_functions.py", line 73, in forward streams = [_get_stream(device) for device in ctx.target_gpus] File "/home/zhangzy/.local/lib/python2.7/site-packages/torch/nn/parallel/_functions.py", line 100, in _get_stream if _streams[device] is None: IndexError: list index out of range What is wrong with this code then?
st101733
Solved by justusschock in post #7 Your Problem lies within your saving/loading code: You save your model via torch.save(net, save_path) where net is an instance of nn.DataParallel I would recommend to change a few things: You should only save the state dict instead of your model. See this post for further details You should …
st101734
I would say that u are calling out.cpu() but you never used gpu() for doing so, you have do use model = torch.load(model_path).cuda()
st101735
I dont think it is the root cause, because I add the cuda() and the error still exists.
st101736
That error sounds like there is no gpus available. Have you noticed you wrongly wrote CUDA_VISIBLE_DEIVCES instead of CUDA_VISIBLE_DEVICES ? If it’s a transcription error can u try torch.cuda.is_available() and torch.cuda.device_count() to check if you have available gpus/cuda when you are running that? You should also to consider you have to allocate (as i said) both, model and input, in gpu by calling .cuda() method.
st101737
I have access to my gpus, the program works when I run python infer.py, but it will not work if I run CUDA_VISIBLE_DEVICES python infer.py. The root of this problem seems to be that I train my model with two gpus (nn.DataParallel), but I run test on a single gpu.
st101738
hmmm It could be, when you use data parallel state dict create a submodule called module. Try to save the state_dict instead of the model and before saving it allocate model in cpu and load state dict instead of that
st101739
Your Problem lies within your saving/loading code: You save your model via torch.save(net, save_path) where net is an instance of nn.DataParallel I would recommend to change a few things: You should only save the state dict instead of your model. See this 142 post for further details You should not save the stat dict of your DataParallel instance but your model’s state dict since the data parallel is simply a wrapper and also contains things like the used GPUs and copies of your model. You can access the model by calling net.module just as @JuanFMontesinos mentioned. Taking these steps into account you would save your model with code like this: net = nn.DataParallel(net) ..... torch.save(net.module.state_dict(), save_path) and load your model like this: model = YourNetworkClass() # create an instance of your network model.load_state_dict(torch.load(save_path)) If you want to infer on multiple GPUs or continue training on multiple GPUs you would have to wrap your model again with nn.DataParallel. Also a good practice would be to move the model to cpu before saving it’s state_dict and move it back to GPU afterwards. This way the state dict will also be loaded to CPU instead of being loaded to GPU directly (which happens if you save the state_dict of a GPU-Model since you would save CUDA-Tensors). Loading a model on CPU is better practice since you could also deploy it to machines wich aren’t CUDA-capable.
st101740
I noticed that in version 0.4.1 of Pytorch the nn.Upsample is being replace by F.interpolate However due to that change, reusable blocks that contain a nn.Upsample step become difficult (or at least less elegant) to refactor: self.block = nn.Sequential( nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False), ConvRelu(in_channels, middle_channels), ConvRelu(middle_channels, out_channels), ) As a result I need to put to introduce a wrapper function or put an extra line of code in the forward method for every used block. It doesn’t seem to add to the maintainability of the model. I was wondering is there a more elegant way to refactor the above that I missed? Or perhaps in the future a nn.interpolate will be introduced? (similar to having both nn.ReLU and F.relu)
st101741
Hello, index_select allows me to retrieve rows of a tensor by specifying their respective indices. Now suppose my tensor is very large and I want almost all of these indices. Instead of specifying all row indices I want, is their a function where I specify all rows I do not want instead?
st101742
May be you can do like this x = torch.randn(3, 4) x=torch.FloatTensor(np.delete(x.data.numpy(), 1, 0)) print(x)
st101743
Hi, any idea how can I check what project actually look like in hyperplane or hypersphere?
st101744
You can go up to three. Matplotlib can do it. Obviously you can’t see in anything higher. There are several dimensional reduction techniques used for data viz, like PCA, LLE, t-SNE, etc., all that have downsides stemming from the fact that the task is not well determined. Roughly what you want is that close points in high-dim stay close in the projection, and vice-versa for far-away points. This is what t-SNE does, but is randomized and returns different results given seed.
st101745
I don’t what exactly you are looking for.But according to me have a look at the link below which will provide hyperplane for any datasets with simple change and have by default MNIST within itself. https://github.com/plotly/dash-tsne 16 Screen Shot 2018-08-11 at 1.03.01 AM.png2142×1268 386 KB
st101746
I have the tensor of N×3×128×128 which stands for a batch of images,which range is [-1,1]. Now I want to input it to the pretrained VGG16 to extract feature. However, It requires range [0, 1] , size >224 and mean=[0.485, 0.456, 0.406] ,std=[0.229, 0.224, 0.225]. What can I use to do the aboving process based a batch?(especially for the normalization about the mean and std)?Thanks!
st101747
def rescale(x,max_range,min_range): max_val = np.max(x) min_val = np.min(x) return (max_range-min_range)/(max_val-min_val)*(x-max_val)+max_range x=(rescale(x,1,0)-mean)/std but do it per channnel
st101748
If you got an Image of size 128x128. To resize it to 224x224. Import Image and ImageOps from PIL img = Image.open(path).convert(“RGB”) img = ImageOps.fit(img, (224,224), Image.ANTIALIAS) Assuming you had done all this and finally got tensor to 3x224x224 before loading as batches you could possibly do - ((Tensor*2.)+2.)/2. This should get the tensor in [0,1] range.
st101749
For each channel of tensor of N×3×128×128, it has a size of N×128×128. How can I normalize every element of the tensor with corresponding mean=[0.485, 0.456, 0.406] ,std=[0.229, 0.224, 0.225] respectively? I do not want to process it one by one. thanks
st101750
Thanks. The input tensor is an intermediate variable rather than read in by PIL. I want to resize and normalize it with the shape of N×3×128×128 directly.
st101751
What I am not understanding is why are you so specific in converting it to the mean and std. I think that mean and std are according to your images and are used to bring the input to zero mean and stddev 1.
st101752
My network is as follows, sorry for my simple drawing. IMG_3729.jpeg4032×3024 1.86 MB where: G1, G2 are 2 generators and fake_B_temp is output of G1 and fake_B is output of G2. The loss of G1 is: $B%WQ7%K[%GOJ(U(G8L28P2.png776×110 20.8 KB and the loss of G2 is the L1 loss too. Thus, I have 2 backward() in my net to update G1 and G2 respectively. I have make the output of G1: fake_B_temp to fake_B_temp.detach() to stop the gradient from G2. My optimize_parameter function is: I want to know iwhether I do is right? Is there any problem or better way to improve?Thanks!
st101753
I am trying to implement a simple auto encoder in PyTorch and (for comparison) in Tensorflow. As I noticed some performance issues in PyTorch, I removed all the training code and still get ~40% more runtime for the PyTorch version. Here’s the basic training setup: loader = DataLoader(dataset, batch_size=64, shuffle=True, num_workers=8, pin_memory=True) iterator = iter(loader) model = ConvolutionalAE(384).to(device) for i in range(5): x = next(iterator).to(device) model(x) times = [] x_prefetched = next(iterator).to(device) for _ in range(100): start = time() x = x_prefetched x_prefetched = next(iterator).to(device, non_blocking=True) model(x) times.append(time() - start) print(np.mean(times), '+-', np.std(times)) Some things I’ve tried: The “prefetching” shown above didn’t really make a difference loading the data into CPU memory doesn’t make a difference, so I am sure it’s GPU bound (seeing 95% GPU load). When I increase the input size to 128 I get a CUDA out of memory error, which doesn’t happen with the Tensorflow version The full code can be found here 9 for the PyTorch version and here 8 for the TF version. Edit: When I only run the convolutional part (without the transpose convolutions) both versions perform very similar. So is there anything specific with the transpose convolutions in pytorch?
st101754
Could you change the for loop to: for data in loader: ... model(data) ... and time it again? I’m not sure about the OOM issue.
st101755
Thanks for the reply. Tried that before. I included the prefixing as that was one of the things I suspected made the pytorch version slow. Adding the prefetching made it slightly faster. As noted above, I now suspect the transpose convolution to be the culprit.
st101756
Hi everyone, I’m working with a multilabel dataset for image retrieval, but the precision value is getting very low. I have already tested the loss functions that Pytorch offers to solve this problem: BCEWithLogitsLoss and MultiLabelSoftMarginLoss. However, the performance of both functions is poor. As I see that there are some people with the same problem I would like to know if there is anyone here in the forum who has already worked with the multilabel problem and has achieved good results and could provide a tutorial on how to handle the multilabel problem in Pytorch. Or if there is already a tutorial in this sense could make available here. Thank you
st101757
It is not easy to answer your question/request as there are a lot of problems that might cause this low precision (I guess you are calculating the mAP). First, you have to make sure your code is correct, then, you have to check the data-loaders, are you loading the data correctly? I usually do this in the debug-mode, and check if everything is correct, you may also need to do some exploratory analysis on your images; for example, do some histogram statistics, visual inspection on randomly picked samples, and check if they are correctly labeled, etc. One thing that might really be helpful to know is how much your mAP results differ from chance-level? Have other people reported better results than yours on the same dataset? If so, there must be a bug or more in your code or the way of doing things (algorithms), etc. To get feedback on the multi-label classification, maybe you could post how are you doing it and maybe you will have some feedback from the forum.
st101758
Thanks for the feedback. I’m trying to adapt this implementation https://github.com/flyingpot/pytorch_deephash 17 from a 2015 method for image retrieval, now using it for a multilabel dataset (the NUS-WIDE). I’m using the same dataset preprocessing used in this implementation https://github.com/jiangqy/ADSH-AAAI2018/tree/master/ADSH_pytorch 24 which gets an approximately 80% mAP, however it implements a specific function of its method. Briefly, what an image retrieval method that uses deep learning does is take the representation of the image generated by the network, it applies some kind of binarization (in the case of this method it does a simple rounding up or down to generate codes of 0s and 1s), then use this code to calculate similarity between the images to make retrieval. I’ve already checked the dataloader and it looks okay, but now I’ll check again with more caution. If you have any suggestions, I thank you.
st101759
I would then check if the training set is balanced, and try to play with the binary encoder. I do not think the loss is the issue here.
st101760
Hello, I am trying to use the trained torchvision Resnet in caffe2. I’ve renamed all layers and weights as necessary to load the weights and gotten pretty good results, although the accuracy in caffe2 is just lower than that of pytorch. I’ve found that the first conv gives the same results in either framework, but the first batch norm does not. How does pytorch’s “running_var” correspond to caffe2’s “_riv” running inverse variance? I think this is the problem. I’ve tried copying the same weight as well as taking its reciprocal (is that what inverse is supposed to mean?).
st101761
x = [1,2,3;4,5,6;7,8,9] and y = [1,2,3], I want to get y[0]*x, y[1]*x and y[2]*x by vectorization operation.
st101762
Just transform y in a 3x9 matrix y0 0 0 y1 0 0 y2 0 0 0 y0 0 0 y1 0 0 y2 0 0 0 y0 0 0 y1 0 0 y2 and do torch.mm(x,y) you will get result = (x*y0 | x*y1 | x*y2)
st101763
You could also use broadcasting, which will save some memory: x * y.view(-1, 1) > tensor([[ 1., 2., 3., 4., 5., 6., 7., 8.], [ 2., 4., 6., 8., 10., 12., 14., 16.], [ 3., 6., 9., 12., 15., 18., 21., 24.]])
st101764
I am suffering from a very strange problem and I have to ask someone who might be familiar with it. Briefly speaking, 0% gpu-util with a lot of gpu memory (see figure below). Screenshot from 2018-08-09 00-15-32.png766×180 21.3 KB The code I am running is protonets 4 which uses the fancy torchnet frame. I have a Quadro P4000 on my local desktop and a Tesla V100 on the server cluster. The code works well with 50% gpu-util on my local desktop but cannot reach even 1% gpu-util on the cluster with the V100. It turns out the code on the cluster is at least 10 times slower than on the local machine. After a lot of configurations, both the cluster node and my location desktop have the same settings: python 3.6.5, cuda 9.0, pytorch 0.4.0. The configuration thus is probably not an issue. I am pretty sure I have applied cuda() to all the possible models, tensors, and you can see that they are indeed loaded into the gpu-memory (2503/16160 MiB, in the picture). But why can’t they go through the computation in gpu? I initially doubt whether torchnet support V100 or not. But after running a simple example, I found the example ran well on V100. PS: I didn’t change anything in the source code of the protonets. But it just cannot work on V100, while work well on P4000.
st101765
Print output.device to see it output is allocated to cuda:0 or cpu If it’s allocated in cpu u probably did something wrong. It may also be a cuda drivers problem or dunno. Not so much info
st101766
Yes, I have checked all the inputs and outputs before and after computations. They are all allocated to cuda:0.
st101767
Are u working in PC, cluster? u may have wrongly exported environment variables?
st101768
I am working on cluster. The key env vars are set to be the same, specified above. But it is just having trouble running on gpu’s on cluster. cuda: 9.0 pytorch: 0.4.0 python 3.6.5 I think these are the only vars important to the training, right?
st101769
Not Really, in professional clusters (ones managed by an administrator) there are usually several versions of cuda and cudnn. It may happen (it happened to me) that when you are exporting environment variables you do it wrongly or pointing to wrong versions. You have to check which version of pytorch you have (it means, which cuda version the pytorch version you installed is compatible with, I guess there are installations for cuda 8 9 9.1 and 9.2 right now) and check what is there available in you cluster. When you run a job you typically have to export those variables Those are CUDA_HOME LD_LIBRARY And depending on your cluster some other related to python, pytorch etcetera… it depens a lot on the cluster. Go to the shell and check if those variables exist. If error is due to hardware compatibility there is no so much you can do. But I guess in the end pytorch layer rely on cuda, and I don’t think cuda drives does not work with those powerful gpus.
st101770
Thanks, Juan. I set up the same environments and finally figured out why. I wrote four versions of the code and modify different suspicious parts. I found that function “TransformDataset” from the new pytorch framework torchnet seems incompatible with the gpu V100. As long as I use some conventional dataset class like TensorDataset or run the code on P4000, everything works well. It is quite strange. But since torchnet is new, I think such incompatibility is understandable.
st101771
I follow the tutorial to train a cnn model on CIFAR10, and when I use this model to validate on test_data, I got different accuracy when I use different batch_size on test_data, is it normal? As you can see below, as the batch_size increased to 280, the accuracy of this model has declined. I use batch size of 64 to train this model, I don’t know why just changing the batch size of test data will get different accuracy. # Validate on test_data model.eval() def test_accu(batch_size): test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False) correct_count = 0.0 for i, data in enumerate(test_loader, 0): img, labels = data x = Variable(img) y = Variable(labels) if torch.cuda.is_available(): x = x.cuda() y = y.cuda() outs = model(x) _, pred = torch.max(outs, -1) correct_count += (pred == y).sum().data[0] return correct_count for i in range(200, 500, 10): correct_count = test_accu(i) print('BatchSize: {}, Accu: {}'.format(i, correct_count/len(test_data))) BatchSize: 200, Accu: 0.90894 BatchSize: 210, Accu: 0.90894 BatchSize: 220, Accu: 0.90894 BatchSize: 230, Accu: 0.90894 BatchSize: 240, Accu: 0.90894 BatchSize: 250, Accu: 0.90894 BatchSize: 260, Accu: 0.90894 BatchSize: 270, Accu: 0.90382 BatchSize: 280, Accu: 0.4891 BatchSize: 290, Accu: 0.08974 BatchSize: 300, Accu: 0.06414 BatchSize: 310, Accu: 0.08462 BatchSize: 320, Accu: 0.11022 BatchSize: 330, Accu: 0.13582 BatchSize: 340, Accu: 0.1563 BatchSize: 350, Accu: 0.17678 BatchSize: 360, Accu: 0.19726 BatchSize: 370, Accu: 0.21774 BatchSize: 380, Accu: 0.23822 BatchSize: 390, Accu: 0.25358 BatchSize: 400, Accu: 0.26894 BatchSize: 410, Accu: 0.2843 BatchSize: 420, Accu: 0.29966 BatchSize: 430, Accu: 0.31502 BatchSize: 440, Accu: 0.32526 BatchSize: 450, Accu: 0.34062 BatchSize: 460, Accu: 0.35086 BatchSize: 470, Accu: 0.36622 BatchSize: 480, Accu: 0.37646 BatchSize: 490, Accu: 0.3867
st101772
once the model is in .eval() mode, the BatchSize should not matter. This is weird. If you give a script that I can run and reproduce this, I’m happy to look into it. I think it’s just a user-error somewhere.
st101773
Hi smth, I use this script to train the model, https://github.com/lynic/notebooks/blob/master/ml/pytorch/CIFAR10_CNN.ipynb 156 EPOCHES I set to 20, and I use pytorch 0.1.12 with cuda 8.0 . Then I use the code in question description to test the model, seems batch_size really impact the results.
st101774
This was a subtle issue. Change this line: correct_count += (pred == y).sum().data[0] to correct_count += (pred == y).double().sum().data[0] The problem is that pred == y returns a ByteTensor, which has only an 8-bit range. Hence, after a particular batch-size, the sum was overflowing, and hence the wrong results.
st101775
wow, that is a subtle bug, anyway to prevent these kinds of issues from happening better? I imagine this kind of issue will pop up often.
st101776
Hi! I am also having a similar issue with my code. Testing with different batch sizes is giving me different results. I am doing it like this… (inside my test loader code, after prediction…) pred = pred.view(-1) label = label.view(-1) correct_count += (pred == label).double().sum().item() total_count += pred.size(0) and at the end of the loop over test loader I do this… mean_accuracy = correct_count * 100 / total_count I have tried so many different test sizes and found out that test accuracy is max, 96% with a test batch size of 512 and above and keeps declining with decrease in batch size until batch size 1 gives me 11% accuracy and I have a total of 10 classes, which means I could achieve this with random weights as well. I can’t figure out what I am doing wrong?
st101777
Hi everybody, I tried to implement custom layers like LSoftmax (arXiv), PNN required components (arXiv) and so forth in pytorch style, but model loading and prediction work significantly slower (400-500% execution time decrease). So, my question is: Is there any efficient way to implement custom features to make them work fast?
st101778
You should paste your code. I guess pytorch operators use cuda and they should be fast enough, however, if you are using python tools such as for loops lists and all these stuff it’s probable your code were not optimal. Developers are amazing coding with pytorch operators so they may help you to optimize. I think you can also implement things on C but I have not experience about it
st101779
Doubts about creating an LSTM that predicts NBA player positions Hi, I’m really new in Pytorch but I this summer I wanted to do something cool with it. I wanted to predict the position of a particular player based on historical position information of all players in course using data that comes from real NBA games (https://github.com/linouk23/NBA-Player-Movements 11). To do it I think that the best option is using an LSTM because the previous information about the positions is important to be able to predict it. The point is that I watched the example that Pytorch gives about LSTM (the one about recreating the sine wave) and there are some things that are not clear for me. Firstly, you have to know that as an input data for training I thought about tensors of (team_id, player_id, x, y) of each moment and use the (x,y) values as an output of the training. And whenever I wanted to test it I would delete a player position by (-1,-1) and see if I get a correct value. I still do not know if this would be the best model to do what I want to do so I am open to suggestions. class RNN(nn.Module): def __init__(self, input_size, hidden_size, num_layers): super(RNN, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.input_size = input_size self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True) self.out = nn.Linear(hidden_size) def forward(self, x): # Set initial hidden and cell states h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) # Forward propagate LSTM out, hidden = self.lstm(x, (h0, c0)) # out: tensor of shape (batch_size, seq_length, hidden_size) # Decode the hidden state of the last time step out = self.fc(out[:, -1, :]) return out #HYPER-PARAMETERS sequence_length = 28 input_size = 4 hidden_size = 128 num_layers = 1 batchsize = 1 #number of sequences I want to process in parallel num_epochs = 1 #train the data 1 time learning_rate = 0.01 #learning rate model = RNN(input_size, hidden_size, num_layers) #Loss, optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) Here I posted a snippet of my code because some of the questions are related to issues that can be seen in the code. Do I have to specify the number of classes for the output?, as I said before I am talking about positions so I think that it doesn’t really makes sense Should I create an init_hidden_layer? If so, why? Which would be the best parameters to initialize my model? Some of them like sequence_length or number of layers seem to be a little bit arbitrary. I do have a function that returns me Variables of the input/output of the training and the testing. But how am I supposed to use them in my model? def grouplen(sequence, chunk_size): return list(zip(*[iter(sequence)] * chunk_size)) def load_data_sets(): filename = "train.p" train_list= pickle.load(open(filename , "rb" )) train_data=[] train_position=[] for event in train_list: for moment in event.moments: for player in moment.players: train_data.append(player.get_info()) train_position.append(player.x) train_position.append(player.y) #has team,id,x,y for every player for every moment train_data = grouplen(train_data,4) torch.set_printoptions(precision=8) train_data = torch.tensor(np.array(train_data)) train_data = Variable(train_data) #train_position has every player position every event train_position = grouplen(train_position,2) train_position = torch.tensor(np.array(train_position)) train_position = Variable(train_position) data = pickle.load(open("test_data.p" , "rb" )) for j in range(151): test_data=[] test_position=[] for i in range(6): for obj in vars(data[j][i])["players"]: test_data.append(obj.get_info()) test_position.append(player.x) test_position.append(player.y) #test_data has team,id,x,y for every player for every moment with (-1,-1) test_data = grouplen(test_data,4) test_data = torch.tensor(np.array(test_data)) test_data = Variable(test_data) #test_position has x,y for every player for every moment with (-1,-1) test_position = grouplen(test_position,2) test_position = torch.tensor(np.array(test_position)) test_position = Variable(test_position) return train_data,train_position,test_data,test_position Is there something you would change? Thanks in advance, as you may have seen I am really new in the topic but I really want to learn a lot.
st101780
Hi, I try to implement asymmetric threshold Function: Forward path computes as ordinary threshold, and Backward path computes as a derivative from Sigmoid function. So, I need to call only backward path of nn.functions.sigmoid in my backward path. How can I do It? I think that it’s will be more faster than self implemented derivative of Sigmoid, Thanks in advance!
st101781
Hi, To do so, you want to create your own Function 13 where you reimplement the sigmoid backward. It should be fairly easy as it is: grad_output * (1 - output) * output where output is the output of the forward pass and grad_output is the grad given as parameter for the backward.
st101782
So, Yes I did it: def where(cond, x_1, x_2): cond = cond.float() return (cond * x_1) + ((1-cond) * x_2) class Threshold(torch.autograd.Function): @staticmethod def forward(ctx, x): ctx.save_for_backward(x) _zeros = torch.zeros_like(x) _ones = torch.ones_like(x) return where(x > 0, _ones, _zeros) @staticmethod def backward(ctx, grad_output): x, = ctx.saved_variables _slope = 100 grad_input = _slope * torch.exp(- _slope * x) / torch.pow((1 + torch.exp(- _slope * x)), 2) return grad_input * grad_output But I got a NaN values in gradients (I think it’s problem related with large slope of sigmoid, but I have not good ideas how to fix it)
st101783
I would do it slightly differently: class AsymThreshold(torch.autograd.Function): @staticmethod def forward(ctx, *args, **kwargs): output = torch.nn.functional.threshold(*args, **kwargs) ctx.save_for_backward(output) return output @staticmethod def backward(ctx, grad_output): output, = ctx.saved_variables return grad_output * (1. - output) * output
st101784
Hi everyone, I am attempting to do seq2seq translation, and wanted to learn how to use torch text. I am trying to load some text from a file into a single torchtext dataset and then create an iterator for it, but am only getting one big batch returned when I try to iterate. My code: spacy_fr = spacy.load('fr') def tokenize_fr(text): return [tok.text for tok in spacy_fr.tokenizer(text)] FR_TEXT = data.Field(lower=True, tokenize=tokenize_fr, init_token='<sos>', eos_token='<eos>') fm = LanguageModelingDataset("french.txt", FR_TEXT) FR_TEXT.build_vocab(fm) fm_iter = data.Iterator(fm, batch_size=10) iteration = next(iter(fm_iter)) And when I run print(iteration) I get: Variable containing: 2 131 40 ⋮ 4 3 3 [torch.cuda.LongTensor of size 1462273x1 (GPU 0)] (additional info: The “french.txt” file contains 155000 lines of text separated by newline characters.) My understanding is that I should have 10 batches, but I only get one long one. Have been racking my brain over this for ages, examining the source code, can anyone tell me what I am doing wrong? Thank you!
st101785
My input A is C×H×W. And I want to use torch.nn.Upsample to resize it. I know the format should be Batch×C×H×W ,so I do: self.upsample = torch.nn.Upsample(size=[128,128], mode=‘bilinear’) A = torch.unsqueeze(A, 0) (to get 1×C×H×W) A = self.upsample(A) However, it reports: raise NotImplementedError(“Got 3D input, but bilinear mode needs 4D input”) NotImplementedError: Got 3D input, but bilinear mode needs 4D input What is wrong with my code?Can someone help me? Thanks!
st101786
Your code is fine. Could you check again that you are not passing another tensor to self.upsample? This works: A = torch.randn(3, 10, 10) upsample = nn.Upsample(size=24, mode='bilinear') A = torch.unsqueeze(A, 0) A = upsample(A) print(A.shape)
st101787
Sure. Could you print the shape of patch_up_A_temp right before the call to self.upsample?
st101788
Seems to be right. Could you call self.upsample outside of the “batch loop”?: x = torch.randn(1, 3, 55, 42) model.upsample(x)
st101789
The size of tensors among the bacth I want to resize are different. For each one I have to resize it respectively. I can not resize them for one batch directly. Any way to solve it?
st101790
I’m not sure I understand this issue. Your tensors have a different spatial shape for every batch? This should not be a problem as upsample will reshape it to [batch, channels, 128, 128]. Could you explain the tensor shapes a bit more?
st101791
For example, the input is 16×3×128×128 (batchsize=16).For each one among the batch ,I will crop one patch of different size respectively, that is my patch_up_A_temp. And I want to resize all the patch to the same size(64,64) and finally, for this batch, I get an output of 16×3×64×64.
st101792
for j in range(sequence['input'].size(2) - 1): inputs = sequence['input'][:, :, j:j+2, :, :].cuda(args.gpu, non_blocking=True) t = sequence['target'][:, :, j+1, :, :].cuda(args.gpu, non_blocking=True) I am trying to iterate over a Tensor but I get the following error: RuntimeError: invalid argument 3: Source tensor must be contiguous at ../src/THC/generic/THCTensorCopy.c:114 Do you know which is the problem?
st101793
I guess the problem is, that indexing makes the tensors non-contiguous (meaning they are not in neighboring memory cells). You could give it a try with for j in range(sequence['input'].size(2) - 1): inputs = sequence['input'][:, :, j:j+2, :, :].contiguous().cuda(args.gpu, non_blocking=True) t = sequence['target'][:, :, j+1, :, :].contiguous().cuda(args.gpu, non_blocking=True) This snippet may realllocate some memory. Usually contiguous tensors become non-contiguous by some view/reshaping-operations (and maybe indexing)
st101794
Thanks, using contiguous() helped solving the error. I should check what is actually doing because I have the feeling that it is going to slow down the training. If every time I index the Tensor it reallocates memory in order to make it contiguous there is something wrong going on.
st101795
have a tensor named input with dimensions 16x3x64x64. It is a minibatch of 16 RGB images, each 64x64 pixels. I’d like to crop each image down to a patch . Then I want to resize all the patches to the same size(32×32). So the output tensor I want would have dimensions 64x3×32x32. I’d like to crop each image based on the point of lefttop and rightdown . They are given by a 4-dimensional numpy array named box [x1,y1,x2,y2] with dimensions 64x4. I try crop the input with: for i in range (batchsize): output[i] = input[ i, : , box[i, 0]:box[i, 2], box[i, 1]:box[i, 3] ] Then I translate the tensor output to numpy and resize it. Finally I translate it back to the tensor to forward. However, when I do this,it tells: TypeError: only integer tensors of a single element can be converted to an index. I really do not know where is wrong. And Is there an efficient way to do the process I say (crop the tensor and resize based on a batch) in pytorch (on the gpu)? And if I translate the tensor to numpy, does it influence the gradient? Thanks for any help!
st101796
I think you could use torchvision like torchvision.transforms.FiveCrop to transform input image
st101797
thanks,but the input tensor is a intermediate variable ,not read in by PIL, I feel I can not do this.
st101798
Are you sure that your box[i, j] is a single element tensor? And I don’t understamd why you have to convert your data into numpy.array first when torch.Tensor could use indexing too
st101799
Because I want to resize the tensor from random size to (32×32). (.view() may not work)However, I do not know if there is a function in pytorch? I want to translate to numpy and call the cv2.resize to do it. And then I have to translate it back to the tensor to forward in GPU. Maybe I am wrong.Or how can I resize the tensor directly?