id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st45368
|
Yes you are correct, I am asking for the case 2.
(1) So, I am running a jupyter notebook on a remote server, is it possible to then say something like?
CUDA_VISIBLE_DEVICES=7,8 jupyter notebook --no-browser
(2) Also, do I understand it correctly that the above command will make sure that my notebook accesses the GPUs that have index 7 and 8 on the server (let’s say I have 9 GPUs then, otherwise there is no index 8 ), which I can check with e.g. nvidia-smi but inside my notebook they will have index 0 and 1?
(3) And then I use the command:
torch.nn.DataParallel(model, device_ids=0,1, output_device=None, dim=0)
to access the previously defined GPUs?
(4) And how do I need to define the device inside my notebook? When using a single GPU I can say:
device = torch.device('cuda') and then send everything to it with module.to(device)
What do I have to put in the brackets instead of ‘cuda’?
Sorry for all the questions, I am relatively new to using multiple GPUs on a remote server
|
st45369
|
I have one large file that has one measurement each second for 100,000 seconds. Each measurement captures 3 features.
I am going to create an LSTM that will look at 30 seconds in one go. i.e.
seq_len = 30, input_size = 3.
As I have a single file with continuous data measurements being taken for 100,000 seconds, after passing in the first set of data points in to this lstm of len 30, I am going to pass on the hidden state when examining time points 31 to 60.
If I wanted to batch this process, to look at two different 30 second windows at the same time, is there a DataLoader that I can use to ensure that between each seq_len, the data is correlated, but between different batches, the data is independent?
so my input size will be
(seq_len=30, batch=2, input_size=3)
two hidden states will be passed on to the next two batches, and the next two set of seq_lens are from time points that follow the first two sets of seq_lens.
|
st45370
|
I have 2 GPUs,
when I want to use one of GPUs to train, with the following code, both work.
CUDA_VISIBLE_DEVICES=0 python xxx.py,
CUDA_VISIBLE_DEVICES=1 python xxx.py,
However, when I want to use 2 GPUs to train, with the following code,
CUDA_VISIBLE_DEVICES=0,1 python xxx.py,
it doesn’t work anymore. Only the default GPU:0 is used for training, when the memory of GPU:0 run out of, the training will be terminated with error ‘out of memory’. The GPU:1 is lying idle and not be used. Why?
the GPU information is showed in the following:
±----------------------------------------------------------------------------+
| NVIDIA-SMI 440.64.00 Driver Version: 440.64.00 CUDA Version: 10.2 |
|-------------------------------±---------------------±---------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
|===============================+======================+======================|
| 0 Tesla K80 Off | 00006B71:00:00.0 Off | 0 |
| N/A 54C P0 82W / 149W | 8772MiB / 11441MiB | 40% Default |
±------------------------------±---------------------±---------------------+
| 1 Tesla K80 Off | 000096F1:00:00.0 Off | 0 |
| N/A 25C P8 32W / 149W | 11MiB / 11441MiB | 0% Default |
±------------------------------±---------------------±---------------------+
±----------------------------------------------------------------------------+
| Processes: GPU Memory |
| GPU PID Type Process name Usage |
|=============================================================================|
| 0 2495 C python 8759MiB |
±----------------------------------------------------------------------------+
Could someone explain this situation? and What should I do to love that?
Thanks in advance and really appreciate for any feedback.
|
st45371
|
that is a cuda enviroment variable.
It’s not pytorch.
What it means is that you can call any bash command preceded by that. It basically manages which devices the called process can see.
So in your case it means that your python kernel can only see one of the gpus. Both if you set 0,1. But it doesn’t mean that pytorch is gonna train on both automatically.
To train on several gpus you should use modules like https://pytorch.org/docs/stable/generated/torch.nn.DataParallel.html 6
|
st45372
|
Thanks for your information. Actually I have tried
model.cuda()
model = torch.nn.DataParallel(model, device_ids=[0, 1])
but there is always the following errors:
File “/home/speech/treelstm_nlg/HRED/ContextLSTMLayer.py”, line 21, in forward
output, (hn, cn) = self.rnn(x, (h_0, c_0))
File “/home/speech/treelstm_nlg/venv/lib/python3.6/site-packages/torch/nn/modules/module.py”, line 727, in _call_impl
result = self.forward(*input, **kwargs)
File “/home/speech/treelstm_nlg/venv/lib/python3.6/site-packages/torch/nn/modules/rnn.py”, line 579, in forward
self.check_forward_args(input, hx, batch_sizes)
File “/home/speech/treelstm_nlg/venv/lib/python3.6/site-packages/torch/nn/modules/rnn.py”, line 534, in check_forward_args
‘Expected hidden[0] size {}, got {}’)
File “/home/speech/treelstm_nlg/venv/lib/python3.6/site-packages/torch/nn/modules/rnn.py”, line 196, in check_hidden_size
raise RuntimeError(msg.format(expected_hidden_size, list(hx.size())))
RuntimeError: Expected hidden[0] size (1, 64, 300), got [1, 128, 300]
why for that?
By the way, what is the difference between DataParallel and DistributedDataParallel, I seems the official documents suggest more DistributedDataParallel. In my case, some computation code is written by myself, so I am not sure, which is the best choice.
Thanks in advance!! Really appreciate for any feedback.
|
st45373
|
Hmmm So basically it does a copy of the model in each gpu. Then, when you call forward, it takes the batch, created as many chunks as gpus a send them to the corresponding one.
it assumes the batch dimension is the dimension 0. I think this issue can happens due to he fact rnn operates as temporal dimension first. Soo how is the input to your network sorted?
WRT DistributedDP I don’t really know why. It wasn’t the case some versions ago. It seems the performance of DP is worse (https://pytorch.org/docs/stable/notes/cuda.html#cuda-nn-ddp-instead 1)
Anyway both will probably work in a similar way.
|
st45374
|
Hmmm then I don’t really know.
I mean, the module does nothing but splitting the batch into two chunks.
Are you sure the error doesn’t raise without it?
Can you try to post a standalone script?
|
st45375
|
I’m reading a code which has a class for Model and a class for Layer definition. The BaseClass of the Model is nn.Module and the BaseClass of Layer is Module from nn.modules.module. What is the difference?
This is the layer code 16 and this is the model code 11
Thanks
|
st45376
|
Solved by KFrank in post #6
Hi Mahsa!
Thanks for the link to the layer code. That clears things up.
Yes, the two Module classes are indeed one and the same.
Look specifically at this line in layers.py
from torch.nn.modules.module import Module
So let me go back to a version of my first reply to you – there is
a class t…
|
st45377
|
Hi Mahsa!
mahsa:
I’m reading a code which has a class for Model and a class for Layer definition. The BaseClass of the Model is nn.Module and the BaseClass of Layer is Module from nn.modules.module. What is the difference?
Thanks
If I understand python correctly (which I don’t) nn.Module and
nn.Modules.Module are the same class.
As I understand it the module (in the python sense) nn.Module
in effect does:
from torch.nn.Modules import Module
This makes the name Module (from nn.Modules) visible in nn.
So, if in your code you have import torch.nn as nn, you can
in your code then refer to the class torch.nn.Modules.Module
as nn.Module.
Best regards.
K. Frank
|
st45378
|
Thanks for your reply. I got a little bit confused. I though in the Model class, nn.Module is from nn package (actually torch.nn) an in the Layer class Module is from nn.Modules.Module. How are the same? Module and Modules aren’t different classes in nn?
|
st45379
|
Hello Mahsa!
mahsa:
Thanks for your reply. I got a little bit confused. I though in the Model class, nn.Module is from nn package (actually torch.nn) an in the Layer class Module is from nn.Modules.Module. How are the same? Module and Modules aren’t different classes in nn?
I’m a little bit confused, too.
Let me revise what I said.
I don’t think there is a torch.nn.Modules.Module. Compare the
documentation for torch.nn.Module:
https://pytorch.org/docs/stable/nn.html#torch.nn.Module 14
with this code:
Source code for torch.nn.modules.module 6
From this I conclude that the linked code is the code for the
class torch.nn.Module. I’m guessing that the url that refers
to “_modules/torch/nn/modules/module.html” is somehow
indicating how pytorch organizes its code, but does not mean
that the class’s full name is “torch.nn.Modules.Module”
(or “torch.nn.modules.Module”).
If this doesn’t make sense, could you link to the Layer code you
mentioned in your original post so we can see how it refers to
torch.nn.Modules.Module and try to figure out what is going on?
Best.
K. Frank
|
st45380
|
Hi Mahsa!
mahsa:
Thanks K Frank. I added the link of the codes.
Thanks for the link to the layer code. That clears things up.
Yes, the two Module classes are indeed one and the same.
Look specifically at this line in layers.py
from torch.nn.modules.module import Module
So let me go back to a version of my first reply to you – there is
a class torch.nn.modules.module.Module and the package
(python “module”) torch.nn imports it, making it visible as
torch.nn.Module.
To see what’s going on, run this script:
from torch.nn import Module as NnModule
print ('NnModule =', NnModule)
from torch.nn.modules.module import Module as MModule
print ('MModule =', MModule)
When I run this I get:
NnModule = <class 'torch.nn.modules.module.Module'>
MModule = <class 'torch.nn.modules.module.Module'>
So, the package torch.nn is, in effect, doing something like
from torch.nn.modules.module import Module
and this makes torch.nn.modules.module.Module visible as
torch.nn.Module.
(I was getting tangled up a little bit before with the
modules.module.Module and the capitalization.)
Best regards.
K. Frank
|
st45381
|
As @KFrank said, the two classes are indeed the same.
If you look at the “__ init__.py” files 2 of the “nn” module, you see that the first line
from .modules import *
imports all the names defined in the “__ all__” list in “modules” 's “__ init__.py” file 1 into the namespace of “nn”. And you can check that “Module”, which is imported from “module”
from .module import Module
, is contained in the “__ all__” list.
Hence, “nn.Module” is indeed “nn.modules.module.Module”
For details, you can see this python docs, 6.4. Packages 2
|
st45382
|
Hello all,
I have a retinanet model I am trying to train on a custom dataset which consists of around 2500 images in total. The problem is that it takes approximately 30 minutes per epoch(resnet 101 as a backbone). Is it supposed to be this slow?
I have PyTorch 1.7, Cuda 11.1 installed on the system with cuDNN8.0.5.
System specs - i7 9750 with RTX 2070. All hardware benchmarks run fine. Is the slow training due to cuda and cudnn mismatch and will it go away if I build from source?
|
st45383
|
I don’t know what you mean by “CUDA and cudnn mismatch”, but you could try to use e.g. the CUDA10.2 binaries and see, if you would get a similar performance.
Also note, that your training might suffer other bottlenecks such as the data loading, which should be visible by a low GPU utilization in nvidia-smi.
|
st45384
|
Hi, thanks for replying.
by mismatch I meant pytorch binaries are shipped with 11.0 whereas I have 11.1, 1.7 uses cuDNN version 8.0.3 whereas I have 8.0.5. I was wondering maybe that’s the reason for the slowdown.
During training, nvidia-smi shows GPU usage as 90%
|
st45385
|
Your local CUDA and cudnn versions won’t be used if you install the binaries, so you might indeed want to build from source and see if the performance improves.
|
st45386
|
Sorry for my poor English.
This is my code:
trainset = datasets.MNIST(‘data’, train=True, download=False, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset,batch_size=32, shuffle=True)
Now I want to choose a part of train sets(like 3000 images and labels) from shuffled datasets every epoch. I want to know how to shuffle the datasets and then choose index from 0 to 2999. Please help me
|
st45387
|
Solved by ptrblck in post #2
You could manually shuffle the indices using:
indices = torch.randperm(len(train_dataset))[:3000]
and pass these indices to a RandomSubsetSampler, which can then be passed to the DataLoader.
|
st45388
|
You could manually shuffle the indices using:
indices = torch.randperm(len(train_dataset))[:3000]
and pass these indices to a RandomSubsetSampler, which can then be passed to the DataLoader.
|
st45389
|
Sorry to distrub you.
There are 10 classes in MNIST datasets.Like 0,1,2,3… Now I want to choose 100 samples in each class and convert them to ‘trainset’ then use the new trainset like follow.
trainloader = torch.utils.data.DataLoader(trainset,batch_size=batch_size, shuffle=True)
Can you help me?
|
st45390
|
If you are fine with approx. 100 samples, which were randomly drawn, this code should work:
# Setup
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))])
dataset = torchvision.datasets.MNIST('./data/', train=True, transform=transform)
# Split the indices in a stratified way
indices = np.arange(len(dataset))
train_indices, test_indices = train_test_split(indices, train_size=100*10, stratify=dataset.targets)
# Warp into Subsets and DataLoaders
train_dataset = Subset(dataset, train_indices)
test_dataset = Subset(dataset, test_indices)
train_loader = DataLoader(train_dataset, shuffle=True, num_workers=2, batch_size=10)
test_loader = DataLoader(train_dataset, shuffle=False, num_workers=2, batch_size=10)
# Validation
train_targets = []
for _, target in train_loader:
train_targets.append(target)
train_targets = torch.cat(train_targets)
print(train_targets.unique(return_counts=True))
> (tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), tensor([ 99, 112, 99, 102, 97, 90, 99, 105, 98, 99]))
Otherwise you could probably use a loop for each class to get 100 random corresponding class indices and could then use the same Subset approach.
|
st45391
|
@ptrblck I’d like to access the classes of the dataloader, but currently have to switch between loader.dataset.classes and loader.dataset.dataset.classes, depending on whether I used Subset or not. Is there a way around this?
|
st45392
|
I don’t know what the best approach would be besides checking, if the loader.dataset is an instance of Subset.
|
st45393
|
@ptrblck Thanks. Currently, I’ve written the following utility function:
def get_classes(dataset):
while hasattr(dataset, 'dataset'):
dataset = dataset.dataset
return dataset.classes
From an API standpoint, might it not be better for Subset to inherit classes, targets (properly filtered according to the indices), and perhaps other relevant attributes from its parent?
|
st45394
|
That’s not necessarily that easy, if your original Datasets lazily loads the data.
Currently Subset only uses the passed indices to forward them to the underlying Dataset.
This works fine since Subset has no knowledge about the Dataset and just acts as a “filter” for the indices.
If you want to forward some dataset internals such as .classes, .targets etc., Subset would need to know what kind of Dataset you are using and which attributes to expose.
Your underlying dataset can of course be a custom Dataset, which doesn’t provide these attributes as they might be unknown during initialization.
|
st45395
|
I was trying to implement a simple CAE in Pytorch. I am seeing a lot of difference in train time in pytorch compared to tensorflow. Pytorch version is taking around 20 sec for 100 epochs whereas tensorflow version is taking around 5 sec for 100 epochs. Can anyone help me resolve this ? I have attached my code below.
Tensorflow code is similar to this https://github.com/panji1990/Deep-subspace-clustering-networks/blob/master/Pre-Train-Conv-AE-EYaleB.py 3
Also nvidia-smi shows 100% usage for pytorch version whereas it is around 45% for tensorflow version
class fullmodel(nn.Module):
def __init__(self,kernel_size,batch_size,num_class):
super(fullmodel, self).__init__()
self.batch_size = batch_size
self.enc1 = nn.Conv2d(1,10,kernel_size[0],padding = 2)
self.enc2 = nn.Conv2d(10,20,kernel_size[1],padding = 1)
self.enc3 = nn.Conv2d(20,30,kernel_size[2],padding = 1)
self.dec1 = nn.ConvTranspose2d(30,20,kernel_size = 3,padding = 1)
self.dec2 = nn.ConvTranspose2d(20,10,kernel_size = 3,padding = 1)
self.dec3 = nn.ConvTranspose2d(10,1,kernel_size = 5,padding = 2)
def forward(self,x):
enc_out = F.relu(self.enc3(F.relu(self.enc2(F.relu(self.enc1(x))))))
dec_out = F.relu(self.dec3(F.relu(self.dec2(F.relu(self.dec1(enc_out))))))
return enc_out,dec_out,
def train(model,data):
torch.backends.cudnn.benchmark = True
lr = 1e-3
num_epochs = 5000
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(device)
X = torch.from_numpy(data).float()
#data_train = torch.utils.data.DataLoader(dataset=X, batch_size=data.shape[0])
parameters = model.parameters()
model.apply(init_weights)
optim = torch.optim.Adam(model.parameters(), lr=lr)
model = model.to(device)
model = model.train()
X = X.to(device)
time1 = time.time()
for epoch in range(num_epochs):
avg_recon_loss = 0
latent,output = model(X)
recon_loss = 0.5*(torch.sum((output - X)**2))
optim.zero_grad()
recon_loss.backward()
optim.step()
avg_recon_loss += recon_loss
if (epoch+1)%100 == 0:
print("Iter : ",epoch+1)
print ("Loss : {:.4f}".format(avg_recon_loss/(38*64)))
print(time.time() - time1)
time1 = time.time()
if __name__ == "__main__":
data = sio.loadmat("../datasets/YaleBCrop025.mat")
imgs = data['Y']
I = []
Label = []
for i in range(imgs.shape[2]):
for j in range(imgs.shape[1]):
temp = np.reshape(imgs[:,j,i],[42,48])
Label.append(i)
I.append(temp)
I = np.array(I)
n_input = [42,48]
imgs = np.reshape(I, [I.shape[0], 1, n_input[0], n_input[1]])
kernel_size = [5,3,3]
classes = 38
batch_size = classes*64
model = fullmodel(kernel_size,classes,batch_size)
train(model,imgs)
|
st45396
|
Could you compare the number of parameters for both implementations?
Your TF reference uses placeholders, so that it’s not easy to compare the layer setup.
Also, you might want to remove cudnn.deterministic = True as this might pick a deterministic but slow algorithm.
|
st45397
|
The number of parameters in both pytorch and tensorflow versions are 14991. I removed the fc layers from tensorflow implementation (only has conv2d and transpose conv2d layers).
I also removed cudnn.deterministic = True. I literally have only conv2d and transpose conv2d layers in both.
I have included my main function in the code above. Do you think some unwanted broadcasting is happening? I don’t think there is anything wrong with this pytorch code.
|
st45398
|
Thanks for the information.
Note that CUDA operations are asynchronous, so you would have to synchronize the code via torch.cuda.synchronize() before starting and stopping the timer.
Could you add it and time the codes again?
I don’t know, how TF handles this case and how to synchronize TF code.
|
st45399
|
I tried with the changes you suggested. It is still the same result. Also I can visually notice the time difference because pytorch code is 4-5 times slower than tensorflow code.
My pytorch version is 1.4.0
Cuda version is 10.1.243
GPU is Geforce GTX 1080 ti
|
st45400
|
Thanks for the update. Are you using the same CUDA and cudnn versions for both frameworks?
If so, could you create profiles using nvprof for both models, please?
|
st45401
|
I am using the same CUDA and cudnn versions for both frameworks. I will create profiles using nvprof for both.
|
st45402
|
pytorch_profiler2880×1210 813 KB
Since I am not the admin of the remote server, I couldn’t directly run nvprof. I actually ran
with torch.autograd.profiler.profile(use_cuda=True) as prof:
model(imgs)
Something like this
I am not able to create profile for Tensorflow code as of now. It is not easy as Pytorch.
But is it okay with just this ?
|
st45403
|
@Sushruth_N were you able to identify the root cause of the difference? I am experiencing a similar problem.
|
st45404
|
In this page,TRANSFERING A MODEL FROM PYTORCH TO CAFFE2 AND MOBILE USING ONNX, the output is different.
# Verify the numerical correctness upto 3 decimal places
np.testing.assert_almost_equal(torch_out.data.cpu().numpy(), c2_out, decimal=3)
print("Exported model has been executed on Caffe2 backend, and the result looks good!")
I just copy the code, and the output is :
(mismatch 99.88728564342404%)
x: array([ 0.24 , 0.332, 0.502, ..., 0.025, -0.106, -0.055], dtype=float32)
y: array([ 0.24 , 0.665, 1.075, ..., 0.087, 0.369, -0.055], dtype=float32)
|
st45405
|
Hi. This question seems to have been asked a lot but I’m still facing some trouble. I’m trying to use two GPU’s using torch.nn.DataParallel but when I wrap my model nvidia-smi says I’m only using one.
The code I have looks something like:
import torch.nn as nn
model = SomeModel()
if args.multiple_gpu: # Boolean
os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'
model = nn.DataParallel(model)
model = model.to('cuda')
nvidia-smi says I’m only using GPU 0 and not 1. I feel like I’m overlooking something in plain sight but I can’t grasp what. Any opinions are appreciated, thanks.
|
st45406
|
You should specify device ids.
model = nn.DataParallel(model, device_ids=[0, 1])
pytorch.org
DataParallel — PyTorch 1.7.0 documentation 11
|
st45407
|
I’ve tried that as well, and by default device_ids is set as all available devices.
|
st45408
|
I tried the below snippet which is similar to yours but it works with multi-gpu on my device.
import torch.nn as nn
model = nn.Conv2d(3,3,1,1)
model = nn.DataParallel(model).cuda()
input = torch.randn(64,3,8,8).cuda()
output = model(input)
I’m not sure what the difference between mine and yours could be.
|
st45409
|
Hi,every.
I am trying to using weight decay to norm the loss function.I set the weight_decay of Adam(Adam) to 0.01(blue),0.005(gray),0.001(red) and I got the results in the pictures.
test loss2097×495 43.5 KB
It seems 0.01 is too big and 0.005 is too small or it’s something wrong with my model and data.
I use the unet as model and the data is DRIVE dataset.I use grayscale pictures as input and increase the dataset by CLAHE,gamma correction and flip,learning rate is 0.001.
And I always found my model get the best reslut in the beginning of the training!!
Thank you
|
st45410
|
I am having difficulty getting my LSTM based model to train properly, the loss stays fairly high. I have an implementation of the same model in Keras and I’m trying to convert it to PyTorch. In Keras, my LSTM layer looks like this (as a Sequential model):
model.add(LSTM(36))
and in PyTorch:
self.lstm = nn.LSTM( input_size = 1,hidden_size = 36,num_layers = 1)
In Keras, the default is not to return the hidden state, so in PyTorch I’m not sure how to handle that in the forward function, or when to initialize the hidden states. Right now I’m using this to initialize the hidden state:
def init_hidden(self):
return (
torch.zeros(1, 1, 36, device='cuda'),
torch.zeros(1, 1, 36, device='cuda'),
)
And I call this at the beginning of the forward() function. When I use the lstm layer it looks like this:
out, self.hidden = self.lstm(out, self.hidden)
So maybe the hidden states are being initialized too often? I’m using a batch_size of 4096 if that matters.
Thank you!
|
st45411
|
Say I want to check the gradient of f_\theta(x) wrt \theta, we should call gradcheck(f, x.requires_grad_()) rather than just gradcheck(f, x), why is this the case? The quantity we care about is df/d\theta, to do this, I guess Pytorch numerically check whether |f(x+h)-f(x)-grad(f)(x)h|/|h|->0? (or some other numerically efficient version). It seems redundant to let x require grad?
|
st45412
|
Hi,
Indeed the gradients are only checked for the Tensors that are explicit inputs to the function. So if none of them requires gradients, that means that no gradient needs to be checked.
You will need to give theta as an input to your function to be able to use gradcheck I’m afraid.
|
st45413
|
Hi albanD. Thanks for your reply. Here I use \theta to represent the parameters of the network f. So say if f=nn.Linear(a,b), then we can write f(x)=Wx, and here \theta will be W. It doesn’t make sense to pass W as an input to gradcheck(), no? Because the input to gradcheck() should be the input to the forward() function of f. Are you suggesting that gradcheck() calculates df/dx rather than df/d\theta?
|
st45414
|
Yes gradcheck only checks gradient for inputs to the function that are Tensor that require gradients.
Note that in this case, you can “cheat” by doing: gradcheck(lambda inp, *ignore: model(inp), (inp, *model.parameters()).
This will make all the parameters look like inputs for gradcheck. And all inplace changes to them must properly update the forward of the model (this will work with pytorch vanilla Module at least).
|
st45415
|
I am using windows and pycharm, Pytorch is installed by annaconda3 (conda install -c perterjc123 pytorch). My python is 3.6.2 and pytorch installed is pytorch 0.3.0.
I am trying to rerun this repository (https://github.com/vvanirudh/srnn-pytorch 242) but found the error “Torch not compiled with CUDA enabled”
I have no idea is my pytorch is not supported with CUDA or there is something I should change in the code.
|
st45416
|
Do you have an NVIDIA GPU? Have you installed cuda on this NVIDIA GPU? If not, then pytorch will not find cuda. It is not mandatory, you can use your cpu instead. Every time you see in the code something like tensor = tensor.cuda(), simply remove that line and the tensor will reside on the CPU. The problem is that it will be incredibly slow to the point of being unusable.
You can also explicitly check by doing
torch.cuda.is_available()
If it returns False, it means that CUDA is not available on your machine
|
st45417
|
Great thanks to your reply. I had GTX 1070 graphic card and it has GPU.
I followed the link to install cudatoolkit in python (https://developer.nvidia.com/how-to-cuda-python 1.3k) and run the sample test successfully. However, torch.cuda.is_available() still shows False. It will be appreciated If you could tell me how to make CUDA work with torch.
|
st45418
|
Which OS are you using?
Why did you use that command to install torch? On the website it’s written you should use
conda install pytorch torchvision cuda90 -c pytorch
for CUDA 9.0, otherwise
conda install pytorch torchvision -c pytorch
Try removing it and installing it with these two commands. Otherwise you can try installing from source, check out the instructions on the pytorch github page.
|
st45419
|
As I said in the post, I use Windows with Annaconda3. Thanks for the two command lines. However, the package is not for Windows (package missing in current channels).
|
st45420
|
Ah, I see. Then have you tried installing it from source? Where did you find the windows package? Maybe you can ask the author to see if there is CUDA support
|
st45421
|
I just made it work now! I checked the developed post (https://github.com/pytorch/pytorch/issues/494 1.2k), and some guy made it work and I installed it from his source. Only cuda80 works in my desktop. And also thanks for your reply!
|
st45422
|
When installing PyTorch on Windows, should I install CUDA for nVidia site or it will be installed by pip installer?
I’m using Windows 10 (Installing PyTorch 0.4.1 on Windows 10 [WinPython]).
|
st45423
|
pip install http://download.pytorch.org/whl/cu90/torch-0.4.1-cp36-cp36m-win_amd64.whl
pip install torchvision
just pip will do the job
|
st45424
|
I’m not sure you’re right.
If the user didn’t install system wide CUDA it seems it won’t work.
I couldn’t get official answer whether the pip install should take care of the CUDA or not.
|
st45425
|
Yes, you should install at least one system-wide CUDA installation on Windows when you use the GPU package. It’s recommended that you install the same version of CUDA that PyTorch compiles with. It will work even when the two versions mismatch. But you’ll then have to pay attention to the version of the GPU drivers.
Does PyTorch uses it own CUDA or uses the system installed CUDA?
Well, it uses both the local and the system-wide CUDA library on Windows, the system part is nvcuda.dll and nvfatbinaryloader.dll. They are located in the %systemroot%, so I’m afraid we could not put them in the package due to some potential permission issues. The reason why we use the local CUDA installation is to prevent dll load failure. e.g. Some users don’t have CUDNN installed. I don’t think the missing of any optional CUDA dependency should be a barrier to use our package on Windows.
Should pip install s take care of the CUDA or not?
No, at least the answer is no on Windows. We don’t use pip to install CUDA on Windows. We just use pip to select the package you want. For most users, it may be no differences using cuda80/cuda90. But if you are using some new or legacy cards, then you can only use specific CUDA distributions.
|
st45426
|
I’m not sure I understood all.
Could we get away with installing the CUDA Toolkit on Windows and have all installed by pip only for PyTorch?
I don’t need CUDA on my computer besides for PyTorch so I’d be happy if PyTorch could be independent and self sustained (All its dependencies supplied in the pip downloaded).
|
st45427
|
Once you install cuda, a quick way to test if CUDA is available is using the line below
python -c 'import torch; print(torch.cuda.is_available())'
|
st45428
|
That’s nearly an impossible task. Did you read my post? Some DLLs are installed to the system directory. pip or any python package cannot do this. Because there are permission issues.
|
st45429
|
@peterjc123, couldn’t we put the DLL’s in other folders on the path?
Like those dedicated to Python?
|
st45430
|
Well, I don’t know exactly the answer. Because I have never tried this before. But according to some posts, these two files will get updated with the Graphics driver. So the problem will become a little bit complex. For users that don’t have CUDA installed, I just don’t know if the DLLs will still work when drivers get updated. But we could try your suggestion because it doesn’t affect the users that have CUDA installed. See document 11 from MSDN. Anyway, thanks for your suggestion.
|
st45431
|
Yep,
I think it is the right policy to take.
First try to make it work out of the box independent of anything.
If it works, you reduced the the level of frustration for new users.
In case of any issue with CUDA still the first step would be - Install the latest CUDA drivers.
Thank You.
|
st45432
|
I tried everything to only the following steps works: The cuda 10 is too new for my graphic card.
(1)go to previous version of cuda & pytorch here:
pytorch.org
PyTorch 47
An open source deep learning platform that provides a seamless path from research prototyping to production deployment.
(2)following the page instruction and download *.whl file suitable for my python version and platform. for me it’s python 3.6 , windows
(3)install *.whl file
(4)test if torch.cuda.is_available() returns True
I am running windows 10 with Nvidia GTX 1070
|
st45433
|
Adam can adapt its learning rate by the gradient updating. I think we may not need the learning rate scheduler.
However, I worry that if with that kind of learning rate scheduler in Adam can jump out of the local minimal or get away from the local minimal
In transfer_learning_tutorial 49, it use momentum SGD with a learning scheduler.
|
st45434
|
Yes I have had such experience.
Now in my project, I split num_epochs into three parts.
num_epochs_1 warm up.
num_epochs_2 Adam for speeding up covergence.
num_epochs_3 momentum SGD+CosScheduler for training.
My friend used Adam without learning rate scheduler in his project, and he found that the loss started to rise after some epochs.
You can find some discuss here 211. Although Adam can adaptively adjust the learning rate, but such ability is limited.
At least, for me, I think momentum SGD is the most stable optimizer and Adam/AdamW is a good tick to speed up covergence.
All these are my personal experiences. Is it necessary to use a learning scheduler? Maybe as the answer in the link says,
It depends.
|
st45435
|
Pytorch Adam algorithm implementation follows changes proposed in Decoupled Weight Decay Regularization 168 which states:
Adam can substantially benefit from a scheduled learning rate multiplier. The fact that Adam
is an adaptive gradient algorithm and as such adapts the learning rate for each parameter
does not rule out the possibility to substantially improve its performance by using a global
learning rate multiplier, scheduled, e.g., by cosine annealing.
|
st45436
|
I am getting a confusing error that I’m not sure why is occurring. This is the error I am getting:
torch.Size([24047])
tensor([1315, 1318, 1472, 1454, 1318, 1337, 1453, 1454, 1317, 1310])
Traceback (most recent call last):
...
deg_inv = deg.pow(-1)
RuntimeError: Integers to negative integer powers are not allowed.
And this is part of the code:
from torch_scatter import scatter_add
from torch_geometric.utils import add_remaining_self_loops, add_self_loops, remove_self_loops
...
if edge_weight ==None:
edge_weight = torch.ones((edge_index.size(1), ), dtype=dtype,
device=edge_index.device)
fill_value = 1
edge_index, edge_weight = add_self_loops(
edge_index, edge_weight, fill_value, num_nodes)
row, col = edge_index
deg = scatter_add(edge_weight, row, dim=0, dim_size=num_nodes)
print(deg.size())
print(deg[:10])
deg_inv = deg.pow(-1)
I have not found anything related to this online. I’m not sure why this would be occurring?
|
st45437
|
Hi,
I think this means that the pow function does not support raising integer values to negative integer powers?
In particular, taking the inverse of an integer is not well defined because you don’t get an integer back.
I think you wnat to change your input to be floating point numbers for this to work fine: deg.float().pow(-1) (and the result will be a floating point number as well).
|
st45438
|
Hello, I am currently implementing an automated machine learning algorithm with weight inheritance. I implemented my NNs as networkx graphs. Since I mutate the graphs from one generation to another, I add new layers and hence need to pass those to the cuda device again. I do this in the a for loop over the nodes in the graph in the the forward pass. In each iteration of the loop, I first pass the nodes nn.module to the cuda device then forward pass the data through it. My issue is that I get the above mentioned error message at some point. Is there anyway to avoid this issue ?`
def forward(self, inputs):
# Evaluate the graph in topological ordering
topological_order = nx.algorithms.dag.topological_sort(self)
self.nodes[self.get_input_nodes()]['output'] = inputs
for node in topological_order:
# try:
node_info = self.nodes[node]
node_info['op'].to(device)
preds = list(self.predecessors(node))
if len(preds) > 0:
cell_input = [self.nodes[pred]['output'] for pred in preds]
if node_info['type'] == 'merge':
node_info['output'] = node_info['op'](cell_input)
else:
node_info['output'] = node_info['op'](cell_input[0])
node_info['params']['output_dim'] = node_info['output'].size()
return [self.nodes[node]['output'] for node in self.get_output_nodes()][0]`
|
st45439
|
I don’t get it at all but since you are adding new layers I imagine you have to pass them to the optimizer at some point right?
Soo the leaf tensor is the original nn.Module. Once you allocate it in cuda, the output of that allocation is a non-leaf tensor whose backward is something like “copy to the cpu leaf node”
Soooo I would tell you to pass the cpu module to the optimizer or to convert the one in cuda into a leaf tensor.
Anyway it would be nice if you paste a code to reproduce it.
|
st45440
|
What I do is the following:
First create some networks by hand and train them (works perfectly fine)
I create a deep copy of the networks, that I want to mutate by adding layers
then I create an evaluator, which trains the mutated child networks (here I get the error with the leaf nodes)
This is the code of the evaluator:
class Evaluator:
def __init__(self, graph: NodeOpGraph, train_loader, *args, **kwargs):
self.graph = graph
self.train_loader = train_loader
self.optimizer = torch.optim.Adam(self.graph.parameters())
self.criterion = torch.nn.BCELoss(reduction='none')
def train(self, n_samples_per_epoch, epochs=1, log_interval=10, verbose=True):
self.graph.train()
print('Device is {}'.format(device))
batch_size = next(self.train_loader)[0].shape[0]
n_steps_per_epoch = int(np.ceil(n_samples_per_epoch / batch_size))
print('BATCH SIZE:', batch_size)
print('N_STEPS:', n_steps_per_epoch)
for epoch in range(epochs):
if not verbose:
old_stdout = sys.stdout
sys.stdout = open(os.devnull, 'w')
print('EPOCH #', epoch)
total_loss = 0.
total_epoch_loss = 0.
total_size = 0
for step, (inputs, labels, sample_weights) in enumerate(self.train_loader):
s = inputs.shape
inputs = np.reshape(inputs, (s[0], s[3], s[1], s[2]))
self.optimizer.zero_grad()
inputs = torch.Tensor(inputs)
labels = torch.Tensor(labels)
sample_weights = torch.Tensor(sample_weights).to(device)
preds = self.graph(inputs.to(device))
preds = torch.reshape(preds, (preds.shape[0],))
loss = self.criterion(preds, labels.to(device))
loss = loss * sample_weights
loss = loss.mean()
loss.backward()
self.optimizer.step()
# Todo float(loss.item()) otherwise maybe memory issues
total_loss += loss.item()
total_epoch_loss += loss.item()
total_size += labels.size(0)
# if step % log_interval == log_interval-1:
print('Step {} Avg loss: {}'.format(str(step), str(total_loss / total_size)))
total_loss = 0.
if step >= n_steps_per_epoch:
break
if not verbose:
sys.stdout = old_stdout
print('*' * 25, '\nEpoch {} Avg loss: {}\n'.format(str(epoch), str(total_epoch_loss / total_size)), '*' * 25)
def eval(self):
pass
The problem is that part of the network is not on the GPU model by that point because of the adding a layer. Therefor I pass each node of the network graph first to the gpu. This works fine for the forward passes, but for the optimizer step it fails.
Is it because I passed the graph to gpu in the forward pass ?
|
st45441
|
When I first pass alll the nodes to cpu with the following code:
def to_cpu(self):
topological_order = nx.algorithms.dag.topological_sort(self)
for node in topological_order:
# try:
node_info = self.nodes[node]
node_info['op'].cpu()
When I call:
self.graph.to_cpu()
self.optimizer = torch.optim.Adam(self.graph.parameters())
I get the following error message:
UserWarning: The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad attribute won't be populated during autograd.backward(). If you indeed want the gradient for a non-leaf Tensor, use .retain_grad() on the non-leaf Tensor. If you access the non-leaf Tensor by mistake, make sure you access the leaf Tensor instead. See github.com/pytorch/pytorch/pull/30531 for more informations.
|
st45442
|
I would already thankful if you could give me any tips on how to locate the tensors causing this issue
|
st45443
|
Soo can you paste a standalone snippet with a toy example?
It seems you are wrapping everything with a nn.module class (graph).
Buut maybe node_info is a standard dict? It’s a bit difficult to say
I think you are doing something like
import torch
from torch import nn
class Toy(nn.Module):
def __init__(self):
super().__init__()
wrong=nn.Parameter(torch.Tensor([5]))
self.w = wrong.cuda()
self.good = nn.Parameter(torch.Tensor([5]))
def forward(self):
pass
m = Toy()
print(m.w.is_leaf,m.w.grad_fn)
print(m.good.is_leaf,m.good.grad_fn)
False <CopyBackwards object at 0x7f65a3de7f98>
True None
Think that this behaviour doesn’t have to happen inside init, it can be extrapolable to however you are instantiating new nodes.
|
st45444
|
#torch.manual_seed(seed)
tr_data_setup = DS(features, labels.reshape(-1,1))
tr_dataloader = DL(tr_data_setup, batch_size=64, shuffle=True, generator=torch.manual_seed(seed))
xx, yy = next(iter(tr_dataloader))
Why do I get two different results even though my seed is the same?
|
st45445
|
Solved by Alexey_Demyanchuk in post #5
Hey Prashanth, let me try to explain a concept of dataset and dataloader in pytorch as I understand it.
Dataset is a whole set of your data points (samples) you want to iterate through during training. It defines a logic on how to access the sample at some index idx. Dataloader - is a helper lets …
|
st45446
|
How are you creating the input data? Are you randomly sampling it or creating it in a deterministic manner?
Could you post a code snippet to reproduce this issue and explain your use case a bit more?
|
st45447
|
The data is deterministic. Features and Labels are taken from a csv file. As for the use case, I’m working on seed averaging a bunch of models on different splits of the data and would like the training results to be reproducible. I first realized something might be amiss since nn.BCELoss() would trigger a CUDA error if I didn’t explicitly set the generator.
The snippet below is taken from a test performed on “mnist_train_small.csv” provided in Colab which gave differing results as well.
class DS(Dataset):
def __init__(this, X=None, y=None, mode="train"):
this.mode = mode
this.X = X
if mode == "train":
this.y = y
def __len__(this):
return this.X.shape[0]
def __getitem__(this, idx):
if this.mode == "train":
return torch.FloatTensor(this.X[idx]), torch.LongTensor(this.y[idx])
else:
return torch.FloatTensor(this.X[idx])
data = pd.read_csv("/content/sample_data/mnist_train_small.csv")
print(data.head(5)) # First 5 labels 5, 7, 9, 5, 2
X = data.iloc[:, 1:].copy().values
y = data.iloc[:, 0].copy().values
dl_setup = DS(X, y.reshape(-1,1))
tY = []
for i in range(5):
tx, ty = dl_setup.__getitem__(i)
tY.append(ty)
tY # 5, 7, 9, 5, 2
dl = DL(dl_setup, batch_size=16, shuffle=False)
xx, yy = next(iter(dl))
print(yy[:5]) #5, 7, 9, 5, 2
torch.manual_seed(0)
dl = DL(dl_setup, batch_size=16, shuffle=True)
xx, yy = next(iter(dl))
print(yy[:5]) #3, 7, 7, 8, 3
dl = DL(dl_setup, batch_size=16, shuffle=True, generator=torch.manual_seed(0))
xx, yy = next(iter(dl))
print(yy[:5]) #0, 3, 0, 7, 9
|
st45448
|
Hey Prashanth, let me try to explain a concept of dataset and dataloader in pytorch as I understand it.
Dataset is a whole set of your data points (samples) you want to iterate through during training. It defines a logic on how to access the sample at some index idx. Dataloader - is a helper lets say from the smart guys in the pytorch which is helping you to iterate through the data by batches of some batch_size and doing a lot of intrinsically to make it fast and efficient.
While doing next method on iterable object in Python you are basically looping through it and each next is producing the next sample from your iterable the same way as for sample in samples: doing it.
Then iterating through dataloader it will provide you with a next batch every iteration as the concept is “model wants to see all the data during epoch”. Even more so shuffle=True will make sure data is reshuffled before every epoch, so you’ll have batches in different order on the second epoch even if set seed manually.
As for reproducibility, dataloader instantiated second time with the same seed (lets say for the next experiment) will provide you with the same sequence of data samples as the first instance of dataloader.
Consider these examples.
Setup:
import torch
from torch.utils.data import TensorDataset, DataLoader
t = torch.arange(100)
ds = TensorDataset(t)
First I iterate through dataloader for 2 “epochs”:
dl = DataLoader(ds, batch_size=16, shuffle=True, generator=torch.manual_seed(0))
# iterate through dataloader first time, print first 3 yy's
print("first run through dl")
for i, yy in enumerate(dl):
if i < 3:
print(yy[0][:5])
# iterate through dataloader second time, print first 3 yy's
print("second run through dl")
for i, yy in enumerate(dl):
if i < 3:
print(yy[0][:5])
It prints this:
first run through dl
tensor([33, 70, 17, 63, 71])
tensor([90, 64, 11, 30, 91])
tensor([43, 31, 92, 94, 19])
secondrun through dl
tensor([15, 9, 50, 34, 51])
tensor([82, 70, 73, 13, 57])
tensor([89, 23, 36, 55, 84])
In the next snippet I instantiate dataloader two times:
dl = DataLoader(ds, batch_size=16, shuffle=True, generator=torch.manual_seed(0))
# iterate through dataloader first time, print first 3 yy's
print("first run through dl")
for i, yy in enumerate(dl):
if i < 3:
print(yy[0][:5])
# instantiate for next experiment
dl = DataLoader(ds, batch_size=16, shuffle=True, generator=torch.manual_seed(0))
# iterate through dataloader second time, print first 3 yy's
print("secondrun through dl")
for i, yy in enumerate(dl):
if i < 3:
print(yy[0][:5])
and it prints this:
first run through dl
tensor([33, 70, 17, 63, 71])
tensor([90, 64, 11, 30, 91])
tensor([43, 31, 92, 94, 19])
second run through dl
tensor([33, 70, 17, 63, 71])
tensor([90, 64, 11, 30, 91])
tensor([43, 31, 92, 94, 19])
It is a lengthy post, I know But, hope it helps!
|
st45449
|
Thank You for the reply. I’ve used your code snippets.
from torch.utils.data import TensorDataset, DataLoader
t = torch.arange(100)
ds = TensorDataset(t)
# Setting Seed explicitly in dataloader
dl = DataLoader(ds, batch_size=16, shuffle=True, generator=torch.manual_seed(0))
print("first run through dl")
for i, yy in enumerate(dl):
if i < 3:
print(yy[0][:5])
print("second run through dl")
for i, yy in enumerate(dl):
if i < 3:
print(yy[0][:5])
first run through dl
tensor([33, 70, 17, 63, 71])
tensor([90, 64, 11, 30, 91])
tensor([43, 31, 92, 94, 19])
second run through dl
tensor([15, 9, 50, 34, 51])
tensor([82, 70, 73, 13, 57])
tensor([89, 23, 36, 55, 84])
# Setting Seed "globally"
torch.manual_seed(0)
dl = DataLoader(ds, batch_size=16, shuffle=True)
print("first run through dl")
for i, yy in enumerate(dl):
if i < 3:
print(yy[0][:5])
print("second run through dl")
for i, yy in enumerate(dl):
if i < 3:
print(yy[0][:5])
first run through dl
tensor([63, 70, 43, 75, 77])
tensor([78, 6, 23, 66, 44])
tensor([31, 84, 24, 73, 54])
second run through dl
tensor([71, 54, 40, 70, 80])
tensor([29, 90, 96, 56, 89])
tensor([92, 53, 41, 60, 78])
Both results are reproducible.If I understand correctly, the results happen to be different because the samples drawn, although use the same seed, are different instances and these instances are reproducible.
Edit:
Played around a bit. That explains it. Thank You.
torch.manual_seed(0)
x = torch.randn(5)
print(x)
print(torch.randn(5))
print(torch.randn(5))
# Reproducible
tensor([ 1.5410, -0.2934, -2.1788, 0.5684, -1.0845])
tensor([-1.3986, 0.4033, 0.8380, -0.7193, -0.4033])
tensor([-0.5966, 0.1820, -0.8567, 1.1006, -1.0712])
torch.manual_seed(0)
x = torch.randn(5)
print(x)
torch.manual_seed(0)
print(torch.randn(5))
torch.manual_seed(0)
print(torch.randn(5))
# Reproducible
tensor([ 1.5410, -0.2934, -2.1788, 0.5684, -1.0845])
tensor([ 1.5410, -0.2934, -2.1788, 0.5684, -1.0845])
tensor([ 1.5410, -0.2934, -2.1788, 0.5684, -1.0845])
|
st45450
|
a = torch.IntTensor([1,3,2,1,4,2])
b=[2,1,6]
I want to find index of values in list b, with the result index sorted
like output as tensor([0, 2, 3, 5])
I know how to do it separately:
torch.nonzero(a == 1).squeeze_(1)
–>tensor([0, 3])
torch.nonzero(a == 2).squeeze_(1)
–>tensor([2, 5])
torch.nonzero(a == 6).squeeze_(1)
–>tensor([], dtype=torch.int64)
but how can I do it at once? or in a better way.
Thanks.
|
st45451
|
According to https://stackoverflow.com/questions/64300830/pytorch-tensor-get-the-index-of-the-element-with-specific-values 1, this is a way to do it:
a = torch.IntTensor([1,3,2,1,4,2])
b=[2,1,6]
mask = torch.zeros(a.shape).type(torch.bool)
for e in b:
…mask = mask + (a == e)
torch.nonzero(mask).squeeze_(1) # tensor([0, 2, 3, 5])
|
st45452
|
I am trying to train an LSTM neural network. My data is of size (batch size, sequence length, features), so I have set “batch_first = True” when defining my LSTM class. I set a batch size of 30, hidden size of 200, and I am training a two layer bidirectional neural network. When I try to train it, however, I get “Expected hidden[0] size (4, 30, 200), got (30, 4, 200)” Size seems to be correct but it seems as though it is expecting a hidden size as if batch_first were set to False when in fact batch_first is set to True. What am I missing here?
Thanks for the help.
Please see my code below.
class lstm_net(nn.Module):
def __init__(self, input_size, hidden_size, output_size, bias = True):
super().__init__()
self.lstm = nn.LSTM(input_size, hidden_size, num_layers = 2, bidirectional = True, bias = bias, batch_first = True)
self.linear = nn.Linear(hidden_size, output_size, bias = bias)
def forward(self, input_seq, h_init, c_init):
output_seq, (h_last, c_last) = self.lstm(input_seq, (h_init, c_init))
scores = self.linear(output_seq)
return scores
# Training loop
net = lstm_net(2, 200, 2, bias = True)
bs = 30
lr = 1
criterion = nn.CrossEntropyLoss()
start = time.time()
for epoch in range(1, 11):
# Learning schedule
# TBD
# Setup optimizer
optimizer = optim.SGD(net.parameters(), lr = lr)
# Initialize stats to zeros to track network's progress
running_loss = 0
running_error = 0
num_batches = 0
# Shuffle indices to randomize training
shuffled_indices = torch.randperm(19481)
for count in range(0, 19481 - bs, bs):
# Initialize h and c to be zero
h = torch.zeros(bs, 4, 200)
c = torch.zeros(bs, 4, 200)
# Detach prior gradient
h = h.detach()
c = c.detach()
# Track changes
h = h.requires_grad_()
c = c.requires_grad_()
# Set gradient to 0
optimizer.zero_grad()
# Make minibatch
indices = shuffled_indices[count : count + bs]
minibatch_data = train_data[indices]
minibatch_label = train_label[indices]
print(minibatch_data.size())
# Track changes
minibatch_data.requires_grad_()
# Send minibatch through network
scores, (h, c) = net(minibatch_data, h, c)
# Compute loss of minibatch
loss = criterion(scores, minibatch_label)
# Backward pass
loss.backward()
# Do one step of stochastic gradient descent
normalize_gradient(net)
optimizer.step()
# Update summary statistics
with torch.no_grad():
running_loss += loss.item()
error = get_error(scores, minibatch_label)
running_error += error
num_batches += 1
# At the end of each epoch, print summary statistics
elapsed = time.time() - start
avg_loss = running_loss / num_batches
avg_error = running_error / num_batches
print('| EPOCH {} |'.format(epoch))
print('='*len('| EPOCH {} |'.format(epoch)))
print('')
print('Error: ', '{}%'.format(avg_error * 100), '\t Loss: ', avg_loss, '\t Time: ', '{} minutes'.format(elapsed / 60))
And the error I’m getting:
torch.Size([30, 90, 2])
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-25-ba433b2f7ded> in <module>
48
49 # Send minibatch through network
---> 50 scores, (h, c) = net(minibatch_data, h, c)
51
52 # Compute loss of minibatch
~\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\modules\module.py in __call__(self, *input, **kwargs)
539 result = self._slow_forward(*input, **kwargs)
540 else:
--> 541 result = self.forward(*input, **kwargs)
542 for hook in self._forward_hooks.values():
543 hook_result = hook(self, input, result)
<ipython-input-21-a7a31b056ff4> in forward(self, input_seq, h_init, c_init)
194 def forward(self, input_seq, h_init, c_init):
195
--> 196 output_seq, (h_last, c_last) = self.lstm(input_seq, (h_init, c_init))
197 scores = self.linear(output_seq)
198 return scores
~\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\modules\module.py in __call__(self, *input, **kwargs)
539 result = self._slow_forward(*input, **kwargs)
540 else:
--> 541 result = self.forward(*input, **kwargs)
542 for hook in self._forward_hooks.values():
543 hook_result = hook(self, input, result)
~\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\modules\rnn.py in forward(self, input, hx)
562 return self.forward_packed(input, hx)
563 else:
--> 564 return self.forward_tensor(input, hx)
565
566
~\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\modules\rnn.py in forward_tensor(self, input, hx)
541 unsorted_indices = None
542
--> 543 output, hidden = self.forward_impl(input, hx, batch_sizes, max_batch_size, sorted_indices)
544
545 return output, self.permute_hidden(hidden, unsorted_indices)
~\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\modules\rnn.py in forward_impl(self, input, hx, batch_sizes, max_batch_size, sorted_indices)
521 hx = self.permute_hidden(hx, sorted_indices)
522
--> 523 self.check_forward_args(input, hx, batch_sizes)
524 if batch_sizes is None:
525 result = _VF.lstm(input, hx, self._get_flat_weights(), self.bias, self.num_layers,
~\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\modules\rnn.py in check_forward_args(self, input, hidden, batch_sizes)
498
499 self.check_hidden_size(hidden[0], expected_hidden_size,
--> 500 'Expected hidden[0] size {}, got {}')
501 self.check_hidden_size(hidden[1], expected_hidden_size,
502 'Expected hidden[1] size {}, got {}')
~\AppData\Local\Programs\Python\Python37\lib\site-packages\torch\nn\modules\rnn.py in check_hidden_size(self, hx, expected_hidden_size, msg)
164 # type: (Tensor, Tuple[int, int, int], str) -> None
165 if hx.size() != expected_hidden_size:
--> 166 raise RuntimeError(msg.format(expected_hidden_size, tuple(hx.size())))
167
168 def check_forward_args(self, input, hidden, batch_sizes):
RuntimeError: Expected hidden[0] size (4, 30, 200), got (30, 4, 200)
|
st45453
|
Solved by rileypsmith in post #4
I ended up figuring this out. After closer reading of the docs, I noticed that it does specify that with batch_first = True, only the input and output tensors are reported with batch first. The initial memory states (h_init and c_init) are still reported with batch second.
This seems like a bit of …
|
st45454
|
As far as I know, the value of batch_first only affects the input and output but not the hidden state.
|
st45455
|
I apologize if this response sounds naive, but what exactly is meant by hidden[0] and how can I change it? At least as far as I can tell, the LSTM is set up properly and the inputs are given with batch first, as would be expected with batch_first = True, so how can I change the hidden[0] to the correct dimensions? Seems like this shouldn’t be needed–with batch_first = True and an input that does indeed have the batch first, it seems like it should work. Still, I am not an expert in PyTorch so there may be an additional step with the inputs or setting up the LSTM class that I am missing.
I appreciate your help. Thanks.
|
st45456
|
I ended up figuring this out. After closer reading of the docs, I noticed that it does specify that with batch_first = True, only the input and output tensors are reported with batch first. The initial memory states (h_init and c_init) are still reported with batch second.
This seems like a bit of a confusing way to do this in my opinion–seems like setting batch_first = True should make everything batch first but at least I figured it out.
Thanks for your help.
|
st45457
|
Yup, these are the little quirks one simply has to pick up along the road :). Happy coding!
|
st45458
|
I just came across the same problem. For the sake of consistency, I do agree. Hope Pytorch will update this in later versions.
|
st45459
|
I have this model:
class PriorBox4JIT(torch.nn.Module):
def __init__(self, cfg):
super(PriorBox4JIT, self).__init__()
self.cfg=cfg
self.idf = torch.nn.Identity()
def forward(self,image_size):
self_min_sizes = self.cfg['min_sizes']
self_steps = self.cfg['steps']
self_clip = self.cfg['clip']
self_image_size = image_size
self_feature_maps = self_image_size[1].to(dtype=torch.int64).tolist()
self_name = "s"
anchors = []
for k, f in enumerate(self_feature_maps):
min_sizes = self_min_sizes[k]
for i, j in product(range(f[0]), range(f[1])):
for min_size in min_sizes:
s_kx = min_size / self_image_size[0][1].item()
s_ky = min_size / self_image_size[0][0].item()
dense_cx = [x * self_steps[k] / self_image_size[0][1].item() for x in [j + 0.5]]
dense_cy = [y * self_steps[k] / self_image_size[0][0].item() for y in [i + 0.5]]
for cy, cx in product(dense_cy, dense_cx):
anchors += [cx, cy, s_kx, s_ky]
# back to torch land
output = torch.Tensor(anchors).view(-1, 4)
if self_clip:
output.clamp_(max=1, min=0)
return output
I pass inputs in vanilla mode (i.e no tracing) like so:
priorbox_jit = PriorBox4JIT(cfg)
inp0=torch.Tensor([im_height, im_width])
inp1=torch.Tensor( [ [ceil(im_height/step), ceil(im_width/step)] for step in cfg['steps'] ] )
inputs=(inp0, inp1)
priors_jit = priorbox_jit( inputs )
prior_data_jit = priors_jit.data
print("prior_data_jit.shape", prior_data_jit.shape)
and this returns me what I expect: prior_data_jit.shape torch.Size([8142, 4])
However, when I try to trace the same model like so:
traced_script_module2 = torch.jit.trace(priorbox_jit.eval(), inputs )
I get thrown an error:
TypeError: forward() takes 2 positional arguments but 3 were given
I am confused why this is - it seems to do the forward() correctly when I do not trace…
Any pointers would be great
|
st45460
|
Hello, dears
I’m trying to implement the code of The Annotated Transformer from Harvard NLP, everything is working well but I need to save and load my own mode instead of their (already) trained one, which is iwslt.pt.
model_opt = NoamOpt(model.src_embed[0].d_model, 1, 2000,
torch.optim.Adam(model.parameters(), lr=0, betas=(0.9, 0.98), eps=1e-9))
N_EPOCHS = 2
CLIP = 1
best_valid_loss = float('inf')
for epoch in range(N_EPOCHS):
model_par.train()
run_epoch((rebatch(pad_idx, b) for b in train_iter),
model_par,
MultiGPULossCompute(model.generator, criterion,
devices=devices, opt=model_opt))
model_par.eval()
valid_loss = run_epoch((rebatch(pad_idx, b) for b in valid_iter),
model_par,
MultiGPULossCompute(model.generator, criterion,
devices=devices, opt=None))
if valid_loss < best_valid_loss:
best_valid_loss = valid_loss
torch.save(model_par.state_dict(), 'model.pt')
print(valid_loss)
For loading model I use :
model = torch.load("model.pt")
I got an error of
AttributeError: 'collections.OrderedDict' object has no attribute 'encode'
Also, I used :
model.load_state_dict(torch.load('en-de-model.pt'))
I got an error : AttributeError: 'collections.OrderedDict' object has no attribute 'load_state_dict'
Could you help to find the optimal way to save and load my won model?
|
st45461
|
After saving the model state dict like this: torch.save(model_par.state_dict(), 'model.pt')
In general, you need to do these steps:
Initialize the new instance of the model the same way you initialize it before training and saving, like: model_par= MyFancyModelClass(some_args_here)
Load state dict into model: model_par.load_state_dict(torch.load('model.pt'))
|
st45462
|
I am new to PyTorch.
I am trying to freeze specific weights in my model. How do I do this?
Here is the output of param.grad
for param in model.parameters():
param.grad
tensor([[ 1.2880e+00, 1.9992e+00, -1.8617e-01, 9.7155e-04, 6.1021e-02,
-1.6990e-01, -1.6990e-01],
[ 1.2238e+00, 1.6739e+00, -1.5423e-01, 6.8004e-04, 4.8646e-02,
-1.3877e-01, -1.3877e-01],
[-1.4395e-01, 2.6961e-01, -3.0931e-01, 1.2276e-03, 4.1116e-02,
-9.4576e-02, -9.4576e-02],
[-1.4087e+00, -1.7222e+00, -1.0639e-01, 1.6479e-04, -1.9364e-02,
7.0537e-02, 7.0537e-02],
[-3.8626e+00, -5.9818e+00, -7.5635e-01, 1.4528e-04, -8.4420e-02,
2.8996e-01, 2.8996e-01],
[ 4.5561e-01, 2.6636e+00, 3.0582e-01, 1.1337e-03, 8.0234e-02,
-2.2834e-01, -2.2834e-01],
[ 9.2553e+00, -2.3199e+00, -4.4024e+00, 3.2237e-03, 1.1196e-01,
-2.6179e-01, -2.6179e-01],
[ 5.0038e-01, -2.0895e-01, -3.9626e-01, 4.9325e-04, 2.0533e-02,
-5.1361e-02, -5.1361e-02]])
tensor([[-0.0604, -0.0332, -0.1097, 0.1066, 0.0263, -0.0495, -0.0896, -0.0305],
[-0.0236, -0.0129, -0.0855, 0.0561, 0.0050, -0.0431, -0.0806, -0.0351],
[-0.0619, 0.0210, -0.0466, 0.1049, 0.0903, 0.0441, -0.0294, 0.0410],
[ 0.0039, 0.0439, 0.0502, -0.0047, 0.0523, 0.0802, 0.0768, 0.0853],
[ 0.1193, 0.1690, -0.0268, -0.0964, 0.0923, 0.1122, 0.3309, 0.3556],
[-0.1557, -0.0918, 0.0501, 0.1837, 0.1018, 0.0462, -0.1316, -0.0694],
[ 0.2985, 0.2872, -0.2841, -0.2909, -0.2793, -0.2900, 0.0360, -0.2768],
[ 0.0167, 0.0288, -0.0294, -0.0127, -0.0085, -0.0154, 0.0204, 0.0048]])
tensor([-0.1699, -0.1388, -0.0946, 0.0705, 0.2900, -0.2283, -0.2618, -0.0514])
tensor([-0.1699, -0.1388, -0.0946, 0.0705, 0.2900, -0.2283, -0.2618, -0.0514])
tensor([[-3.5904e+00, -3.2880e+00, 3.6735e+00, 3.5596e+00, 3.4067e+00,
3.9122e+00, 1.3480e+00, 3.1120e+00],
[ 1.0125e+00, 1.0352e+00, -3.3861e-01, -1.0392e+00, -2.5707e-02,
3.5781e-03, 2.3016e+00, 1.6572e+00],
[ 1.4970e+00, 1.7948e+00, -1.7893e+00, -1.2388e+00, -7.7342e-01,
-1.2879e+00, 4.3067e-01, -1.0760e-01],
[-6.6468e-02, -1.3030e-01, 1.3785e-01, 1.6426e-02, -2.2650e-02,
4.3137e-02, -3.3531e-02, -8.2672e-02],
[-3.2205e-02, -4.9927e-02, 8.5638e-02, 1.8152e-02, 4.9936e-02,
7.4584e-02, 1.0584e-01, 1.1505e-01]])
tensor([ 3.7052, 1.1885, -1.4792, 0.1808, 0.1393])
The particular weights I wish to freeze(set grad to zero) is the one in the 1st tensor, [:,5:].
Thanks
|
st45463
|
Solved by Alexey_Demyanchuk in post #2
Hey. It is not 100% clear for me what are you trying to achieve, but I answer as far as I understand.
Pytorch weights tensors all have attribute requires_grad. If set to False weights of this ‘layer’ will not be updated during optimization process, simply frozen.
You can do it in this manner, all …
|
st45464
|
Hey. It is not 100% clear for me what are you trying to achieve, but I answer as far as I understand.
Pytorch weights tensors all have attribute requires_grad. If set to False weights of this ‘layer’ will not be updated during optimization process, simply frozen.
You can do it in this manner, all 0th weight tensor is frozen:
for i, param in enumerate(m.parameters()):
if i == 0:
param.requires_grad = False
I am not aware of the method how you can do requires_grad = False for the slice of the weights. At least I can’t do it without pytorch complaining.
Anyway, you can zero some slice of the gradients before optimization step, so this exact slice of weights don’t changed after optimization step. Here is a dummy example:
import torch
m = torch.nn.Linear(4, 2)
opt = torch.optim.Adam(m.parameters())
x = torch.rand((1,4))
y = torch.tensor([[0, 1]], dtype=torch.float32)
crit = torch.nn.BCEWithLogitsLoss()
out = m(x)
loss = crit(y, out)
loss.backward()
for i, param in enumerate(m.parameters()):
if i == 0:
param.grad[:,1:] = torch.zeros_like(param.grad[:,1:])
opt.step()
print('after optimizer step')
for param in m.parameters():
print(param)
After doing this, I can see that weights tensor[0] slice[:,1:] didn’t change after optimizer step.
Hope it helps
|
st45465
|
Hi Alexey and Drezal!
Alexey_Demyanchuk:
I am not aware of the method how you can do requires_grad = False for the slice of the weights.
As Alexey notes, you can’t apply requires_grad to only part of a
tensor.
Anyway, you can zero some slice of the gradients before optimization step, so this exact slice of weights don’t changed after optimization step.
Please note that this approach – zeroing out parts of .grad before
calling opt.step() – doesn’t work in general. Some optimizers (e.g.,
when using momentum or weight decay) will change the weights
even if .grad is zero.
The more general approach will be to copy the weights you want
frozen, call opt.step() and then rewrite the frozen weights back
into your param.
Best.
K. Frank
|
st45466
|
Dear Alexey and KFrank,
I have tried both methods and they both worked!
Thank you for noting that zeroing out parts of .grad sometimes will not work.
I am using MSELoss() with ADAM Optimizer.
Regards,
Eric
|
st45467
|
KFrank:
Please note that this approach – zeroing out parts of .grad before
calling opt.step() – doesn’t work in general. Some optimizers (e.g.,
when using momentum or weight decay) will change the weights
even if .grad is zero.
Thanks, this is really important note!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.