id
stringlengths
3
8
text
stringlengths
1
115k
st82468
I think the easiest way would be to use torch.utils.checkpoint 111 to trade memory for compute. Manually pushing the values to the host and back to the device would probably make your training really slow. Accumulating gradients won’t help, as the same memory would be needed.
st82469
Check out Large Model Support for PyTorch: Wiki: https://github.com/mtbrandy/pytorch/wiki/Large-Model-Support 123 Code: https://github.com/mtbrandy/pytorch/tree/v1.1.0-LMS 63 This is the contribution proposal for the LMS feature that is currently available in the Watson Machine Learning solution. For information about that solution, see https://www.ibm.com/support/knowledgecenter/SS5SF7_1.6.1/navigation/wmlce_getstarted_pytorch.html 12
st82470
I’m having some trouble getting multi-gpu working across several V100s. Here’s code: BATCH_SIZE = 800 import torch import torchvision import torchvision.transforms as transforms from pathlib import Path transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) testset = torchvision.datasets.CIFAR10(Path.home()/"data", train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, batch_size=BATCH_SIZE, shuffle=False, num_workers=0) import torch.nn as nn import torch.nn.functional as F criterion = nn.CrossEntropyLoss() class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 20, 3) self.conv2 = nn.Conv2d(20, 80, 3) self.conv3 = nn.Conv2d(80, 160, 5) self.pool = nn.MaxPool2d(3, 3) self.fc1 = nn.Linear(5120*2, 50) self.fc2 = nn.Linear(50, 10) def forward(self, x): x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = F.relu(self.conv3(x)) x = self.pool(x) x = x.reshape(-1, 5120*2) x = F.relu(self.fc1(x)) x = self.fc2(x) return x dataiter = iter(testloader) inputs, labels = dataiter.next() inputs, labels = inputs.cuda(), labels.cuda() num_device = torch.cuda.device_count() multi_time = None print('making net') net = nn.DataParallel(Net().cuda(), device_ids=tuple(range(num_device))) print('made net') optim = torch.optim.SGD(net.parameters(), lr=1) # burn-in for i in range(100): print(i) out = net(inputs) print('got output') loss = criterion(out, labels) print('got loss') loss.backward() The output I get is making net made net 0 and then it hangs. I can see the appropriate amount of memory allocated on all my GPUs. If I interrupt the kernel, the message I get is: --------------------------------------------------------------------------- KeyboardInterrupt Traceback (most recent call last) <ipython-input-4-8bd966a1882f> in <module>() 8 for i in range(100): 9 print(i) ---> 10 out = net(inputs) 11 print('got output') 12 loss = criterion(out, labels) ~/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 475 result = self._slow_forward(*input, **kwargs) 476 else: --> 477 result = self.forward(*input, **kwargs) 478 for hook in self._forward_hooks.values(): 479 hook_result = hook(self, input, result) ~/anaconda3/lib/python3.6/site-packages/torch/nn/parallel/data_parallel.py in forward(self, *inputs, **kwargs) 121 return self.module(*inputs[0], **kwargs[0]) 122 replicas = self.replicate(self.module, self.device_ids[:len(inputs)]) --> 123 outputs = self.parallel_apply(replicas, inputs, kwargs) 124 return self.gather(outputs, self.output_device) 125 ~/anaconda3/lib/python3.6/site-packages/torch/nn/parallel/data_parallel.py in parallel_apply(self, replicas, inputs, kwargs) 131 132 def parallel_apply(self, replicas, inputs, kwargs): --> 133 return parallel_apply(replicas, inputs, kwargs, self.device_ids[:len(replicas)]) 134 135 def gather(self, outputs, output_device): ~/anaconda3/lib/python3.6/site-packages/torch/nn/parallel/parallel_apply.py in parallel_apply(modules, inputs, kwargs_tup, devices) 67 thread.start() 68 for thread in threads: ---> 69 thread.join() 70 else: 71 _worker(0, modules[0], inputs[0], kwargs_tup[0], devices[0]) ~/anaconda3/lib/python3.6/threading.py in join(self, timeout) 1054 1055 if timeout is None: -> 1056 self._wait_for_tstate_lock() 1057 else: 1058 # the behavior of a negative timeout isn't documented, but ~/anaconda3/lib/python3.6/threading.py in _wait_for_tstate_lock(self, block, timeout) 1070 if lock is None: # already determined that the C code is done 1071 assert self._is_stopped -> 1072 elif lock.acquire(block, timeout): 1073 lock.release() 1074 self._stop() KeyboardInterrupt: which makes me think that somehow a lock isn’t being properly released. Has anybody had success getting multiple V100s working? This exact same code works fine on a different machine with multiple 1080Tis.
st82471
Hey, could you tell me how to disable ACS? I also got hangs when I use dataparallel.
st82472
If you run sudo lspci -vvvv | grep -i plx you’ll get a listing of all the relevant PCI bridges. For example, 19:08.0. Then you can go through each one with sudo lspci -s 19:08.0 -vvv | grep -i acs and look at the ACSCtl line (the last line of output). All of the flags should have a - sign on them. If not, you can set them appropriately with sudo setpci -s 19:08.0 f2a.2=0000. Once you’ve done this for all of them, you should be able to use DataParallel.
st82473
^Small addition, in my case I found f2a.w=0000 worked instead of a specific number in place of ‘w’
st82474
class ModelOne(nn.Module): def __init__(self): super().__init__() self.weights = nn.Parameter(torch.randn(300, 10)) self.bias = nn.Parameter(torch.zeros(10)) def forward(self, x): return x @ self.weights + self.bias class ModelTwo(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(300, 10) def forward(self, x): return self.linear(x) if so, then why does mo = ModelOne() [len(param) for param in mo.parameters()] give [300, 10] while mt = ModelTwo() [len(param) for param in mt.parameters()] give [10, 10]
st82475
it turns out that [param.size() for param in mo.parameters()] gives [torch.Size([300, 10]), torch.Size([10])] while [param.size() for param in mt.parameters()] gives [torch.Size([10, 300]), torch.Size([10])] transpose when using nn.Linear
st82476
nn.Linear is transposing the weights 1 before multiplication so the two networks are equivalent. To match the params shapes and the behaviour of nn.Linear you have to do: class ModelOne(nn.Module): def __init__(self): super().__init__() self.weights = nn.Parameter(torch.randn(10, 300)) self.bias = nn.Parameter(torch.zeros(10)) def forward(self, x): return x @ self.weights.t() + self.bias
st82477
I am using LSTM with data parallel. What happens it first gives a warning RuntimeWarning: RNN module weights are not part of single contiguous chunk of memory. This means they need to be compacted at every call, possibly greatly increasing memory usage. To compact weights again call flatten_parameters(). self.num_layers, self.dropout, self.training, self.bidirectional) The according this post, I added the following in the forward function before calling the LSTM. self.lstm.flatten_parameters() But this time I got this error, set_storage is not allowed on Tensor created from .data or .detach() The error occurs at the last line of the flatten_parameters function in the PyTorch source code, image.png1038×873 45.6 KB
st82478
Hi Zheng Chen, did you manage to solve this issue? I’m running in similar problems when calling self.gru.flatten_parameters() The error occurs at inference while executing all code within with torch.no_grad():
st82479
Could solve this error by updating my dependencies. Upgrading/reinstalling my conda environment from PyTorch 1.1.0 to Pytorch 1.2.0 resolved this issue.
st82480
I am trying to do NN based on this article http://nlp.seas.harvard.edu/2018/04/03/attention.html 1 Or based on the standard nn.transformer module I have numbers instead of words. The size of one sequence is 5. At the output(I have three neurons), I need to predict three values ​​(0, 1, 2). That is, at each step I take a window of size 5 and predict 0 or 1 or 2. In fact, this is a classification into 3 classes. Can I use the standard nn.transformer module and use my data instead of words? Or what do you advise me to do? transformer.png972×616 6.53 KB
st82481
If you consider my example based on the nn.transformer module Instead of words, I use a vector of numbers of size 7. I want to send this vector instead of the word directly to the nn.transformer module The size of my sequence is always 5. How can I make a simple example to check the functionality of the code? I do not understand what E. is import torch import torch.nn as nn class Trans(nn.Module): def __init__(self, src_vocab, tgt_vocab): super(Trans, self).__init__() self.tr = nn.Transformer(src_vocab, tgt_vocab) def forward(self, src, tgt): out = self.tr(src, tgt) return out net = Trans(5,1) #src=5 (window), tgt=1 ('0' or '1' or '2') sr = torch.randn(5, 1, 7) #src: (S, N, E) E-?? tg = torch.tensor([0], dtype=torch.long) #tgt: (T, N, E) outputs = net(sr, tg) #output: (T, N, E)
st82482
Another addition to my question. If my question is not clear, you tell me. I would like to get a very simple example of how to solve this so that I can apply this with my real example. transformer2.png1967×587 10.5 KB
st82483
I have a CNN and a LSTM that I want to connect together to form some sort of ConvLSTM. The first layer in the CNN has a batchnorm2d layer which is then connected to a convolutional layer. class ConvNet(nn.Module): def __init__(self, num_classes=20,flatten_size=2*5, inputs=3, recurrent=False): super(ConvNet, self).__init__() self.layer1 = nn.Sequential( nn.BatchNorm2d(inputs), nn.Conv2d(inputs, 32, kernel_size=(3,3), padding=0,stride=1), nn.ReLU(), nn.MaxPool2d(2), nn.BatchNorm2d(32) ) ... My image data and CNN model are moved to gpu i.e using .to(device) - data.to(device), cnn.to(device). Calling the cnn with the input - cnn(input) results in the error - Expected tensor for argument #1 ‘input’ to have the same type as tensor for argument #2 ‘weight’; but type CUDAType does not equal CUDAType (while checking arguments for cudnn_batch_norm). I really do not understand it. Also, how is CUDAType not equal to CUDAType. Are there different CUDATypes?
st82484
Solved by ptrblck in post #11 After setting n_inputs=2560, the code runs fine on the CPU and the GPU and I get an output of shape [16, 4, 2560]. Could you check, if you are passing a ByteTensor as your input to the model? Make sure it’s a FloatTensor (or call .float() on it before passing to the model).
st82485
This error message sounds really weird. Could you post an executable code snippet to reproduce this message?
st82486
The CNN class from torch import nn import torchvision.transforms as transforms class ConvNet(nn.Module): def __init__(self, num_classes=20,flatten_size=2*5, inputs=3, recurrent=False): super(ConvNet, self).__init__() self.layer1 = nn.Sequential( nn.BatchNorm2d(inputs), nn.Conv2d(inputs, 32, kernel_size=(3,3), padding=0,stride=1), nn.ReLU(), nn.MaxPool2d(2), nn.BatchNorm2d(32) ) self.layer2 = nn.Sequential( nn.Conv2d(32, 32, kernel_size=(3,3), padding=0,stride=1), nn.ReLU(), nn.MaxPool2d(2), nn.BatchNorm2d(32) ) self.layer3 = nn.Sequential( nn.Conv2d(32, 64, kernel_size=(3,3), padding=0,stride=1), nn.ReLU(), nn.MaxPool2d(2), nn.BatchNorm2d(64) ) self.layer4 = nn.Sequential( nn.Conv2d(64, 64, kernel_size=(3,3), padding=0,stride=1), nn.ReLU(), nn.MaxPool2d(2), nn.BatchNorm2d(64) ) self.layer5 = nn.Sequential( nn.Conv2d(64, 128, kernel_size=(3,3), padding=0,stride=1), nn.ReLU(), nn.MaxPool2d(2), nn.BatchNorm2d(128) ) self.layer6 = nn.Sequential( nn.Conv2d(128, 256, kernel_size=(3,3), padding=0,stride=1), nn.ReLU(), nn.MaxPool2d(2), nn.BatchNorm2d(256) ) self.fc1Layer = nn.Sequential(nn.Linear(flatten_size*256, 132), nn.ReLU(), nn.BatchNorm1d(132)) self.fc2Layer = nn.Sequential(nn.Dropout(p=0.5), nn.Linear(132, 132), nn.ReLU(), nn.BatchNorm1d(132)) self.fc3Layer = nn.Sequential(nn.Linear(132, 132), nn.ReLU()) self.fc4Layer = nn.Sequential(nn.Dropout(p=0.2),nn.Linear(132, num_classes)) self.recurrent=recurrent def forward(self, x): print(type(x)) print('Before ', x.size()) out = self.layer1(x) print('After 1') out = self.layer2(out) print('After 2') out = self.layer3(out) print('After 3') out = self.layer4(out) print('After 4') out = self.layer5(out) print('After 5') out1 = self.layer6(out) print('After 6') #out = self.layer7(out) out1 = out1.reshape(out1.size(0), -1) out = self.fc1Layer(out1) out = self.fc2Layer(out) #out = self.fc3Layer(out) out = self.fc4Layer(out) if self.recurrent==True: return out1 else: return out for data, target in dataloader['validation']: data, target = data.to(device), target.to(device) output = model(data) loss = criterion(output) The model class combines the CNN and lstm. class Mixnet(nn.Module): def __init__(self, n_outputs, num_layers, hidden_dim, n_steps, cnn, num_classes=20,n_inputs=78*256): super(Mixnet, self).__init__() self.cnn=cnn self.bn = nn.BatchNorm1d(hidden_dim) self.n_steps = n_steps self.n_inputs = n_inputs self.n_outputs = n_outputs self.hidden_dim = hidden_dim self.num_layers = num_layers self.lstm = nn.LSTM(self.n_inputs, self.hidden_dim, self.num_layers, batch_first=True, dropout=0.5) self.FC = nn.Sequential(nn.Dropout(p=0.5), nn.Linear(self.hidden_dim, self.n_outputs)) def init_hidden(self,dim): return [torch.zeros(self.num_layers, dim, self.hidden_dim).to(dev), torch.zeros(self.num_layers, dim, self.hidden_dim).to(dev)] def forward(self, x): batch_size, timesteps, C, H, W = x.size() print('Batch size ', batch_size) print('Timesteps ', timesteps) print('Channels ', C) print('Height ', H) print('Width ', W) c_in = x.view(batch_size * timesteps, C, H, W) c_in.to(device) self.cnn.to(device) out1 = self.cnn(c_in) # This does not work out1 = out1.view(batch_size, timesteps, -1) X = out1 dim = X.size()[0] print(X.size()) lstm_out0, hidden = self.lstm(X) f=lstm_out0[:, -1, :] f = self.bn(f) out = self.FC(f) return out.view(dim, self.n_outputs) The idea is to run my batch through the CNN then connect the output to the lstm.
st82487
Thanks for the code. Could you also post the input shapes and arguments passed to Mixnet? I get a shape mismatch error, if I try to use torch.randn(1, 3, 224, 224) as the input.
st82488
Thanks a lot @ptrblck. Here is it - torch.Size([16, 4, 3, 257, 490]). In order : batch size, sequence, channels, height, width. The arguments are n_outputs=20 num_layers=2 hidden_dim=150 n_steps=3 cnn=ConvNet(recurrent=True) cnn = cnn.to(device) print('CNN runs on ', device) model=Mixnet( n_outputs, num_layers, hidden_dim, n_steps, cnn)
st82489
I still get a shape mismatch using: dev = 'cpu' cnn = ConvNet(recurrent=True).to(dev) model = Mixnet( n_outputs=20, num_layers=2, hidden_dim=150, n_steps=3, cnn=cnn).to(dev) x = torch.randn(16, 4, 3, 257, 490, device=dev) output = model(x) > RuntimeError: input.size(-1) must be equal to input_size. Expected 19968, got 2560
st82490
This implies that you got past the CNN. I think this error of input size is from the LSTM. I can not even get that far using my image batch data. Any reasons as to why that may be the case?
st82491
I would try to get the code running on the CPU first and check for these kind of errors or are you using the CPU as well at the moment?
st82492
To fix the error you got about input mismatch, you could change the MixNet parameter n_inputs to be 2560 instead of 78 * 256. I am using GPU. I would try using CPU right away. Thanks a lot.
st82493
The error I’m getting when using cpu is “RuntimeError: “batch_norm” not implemented for ‘Byte’”.
st82494
After setting n_inputs=2560, the code runs fine on the CPU and the GPU and I get an output of shape [16, 4, 2560]. Could you check, if you are passing a ByteTensor as your input to the model? Make sure it’s a FloatTensor (or call .float() on it before passing to the model).
st82495
@ptrblck, Thanks a lot. The issue was finally fixed by converting to a float. Thank you sooooo much @ptrblck
st82496
In Pytorch I want to use Data Augmentation to choose one class label. Somebody tell me how to, please. For example, 0 label class <- Use Data Augmentation 1 label class <- Not using
st82497
You could add a condition in your Dataset's __getitem__: class MyDataset(Dataset): def __init__(self, data, target, transform=None): ... self.transform = transform def __getitem__(self, index): x = self.data[index] y = self.target[index] if y == 0: x = self.transform(x) return x, y def __len__(self): return len(self.data) You could also pass different transformations and apply them based on the current target label.
st82498
Hi, I am new to PyTorch. I made my own custom model and now run with online training (batch size = 1). As a next step, I want extend the model to take mini-batch. Then I want to study about how to support mini-batch on PyTorch. Does it need to extend parameter size holding for all indentical one propagation? I think that it is natural to have amount of mini-batch size for input and its label. But regarding parameters, I think the model should not have the size because of use the model and parameter for identical inference after its deploying. Is my thinking a correct?
st82499
Yes, the size of the parameters is independent of the batch size. Your code is most likely already using “batched” inputs with a batch size of 1, so increasing the batch size should work out of the box.
st82500
@ptrblck -san, Again, thank you for your comment, before running, I did replace constant “1” in loading input with hyper-parameter being set to large number. And now it works (^ - ^). My model did not work on TensorFlow but now it works fine with PyTorch.
st82501
I have a 1060 6GB and after training the model about 4 gigabytes still remain occupied. I either need to do a pkill -u [username] and login again before I retrain the model. Is there any way that it clears itself or is there something I’m doing wrong ?
st82502
Are you seeing this zombie process after your script has finished? Is your script crashing at some point?
st82503
Let us assume I have a trained model saved with 5 hidden layers (fc1,fc2,fc3,fc4,fc5,fc6). Suppose I need to get output of Fc3 layer from the existing model, BY defining def get_activation(name): def hook(model, input, output): activation[name] = output.detach() return hook hidden_fc3_output = model.fc3.register_forward_hook(get_activation(‘fc3’)) … How can I use this hidden_fc3_output to pass it explicitly from fc4 layer to get the final fc6 output ?
st82504
hidden_fc3_output will be the handle to the hook and the activation will be stored in activation['fc3']. I’m not sure to understand the use case completely, but if you would like to pass this stored activation to fc4 and all following layers, you could create a switch in your forward method and pass it to the model. This would split the original forward path into two steps. You could of course still use the forward hook if needed. Have a look at this code snippet and let me know, if something would be useful or if I misunderstood your use case: class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.fc1 = nn.Linear(1, 1) self.fc2 = nn.Linear(1, 1) self.fc3 = nn.Linear(1, 1) self.fc4 = nn.Linear(1, 1) self.fc5 = nn.Linear(1, 1) self.fc6 = nn.Linear(1, 1) self.act = nn.ReLU() def forward_half1(self, x): x = self.act(self.fc1(x)) x = self.act(self.fc2(x)) x = self.act(self.fc3(x)) return x def forward_half2(self, x): x = self.act(self.fc4(x)) x = self.act(self.fc5(x)) x = self.fc6(x) return x def forward(self, x, path='all'): if path=='all': x = self.forward_half1(x) x = self.forward_half2(x) elif path=='half1': x = self.forward_half1(x) elif path=='half2': x = self.forward_half2(x) else: raise NotImplementedError return x model = MyModel() x = torch.randn(1, 1) out1 = model(x, path='half1') out2 = model(out1, path='half2') out = model(x) print(out2 == out) model.fc3.register_forward_hook(get_activation('fc3')) out1 = model(x, path='half1') print(out1 == activation['fc3']) out2 = model(activation['fc3'], path='half2') print(out2 == out)
st82505
Thanks ptrblck for the reply I was trying to understand the difference between defining (midoutput) architecture in forward definition and calling register_forward_hook function. Why is it that I get a difference in predicting output if I use register_forward_hook. It seems that model(x,path) is more accurate. Example - Actual Output - [8.1009,7.4015,7.7013] Predicted Output By model(model(x,path=‘half1’),path=‘half2’) – [8.1009,7.4015,7.7013] By register_forward_hook in fc3 layer and then calling model(activation[‘fc3’],path=‘half2’) – [8.3453,7.6397,7.9421] There is a huge difference in the predictions. The reason is activation [’‘fc3’’] and model(x,path=‘half1’) are not the same. Any specific reason for this? Regards, Nithin
st82506
In my example the hooked activation as well as the output using path='half1' yield the same result. Are you using any batchnorm layers or other layers with running stats? If so, note that the running estimates will be changes in each forward pass, so that the next one will yield different results. For the sake of debugging you could set the model to eval mode (model.eval()) and test it again.
st82507
Hello, I am using librosa to convert some greeting phases as audio files to an STFT spectrogram. I the used the ImageFolder command to load and covert the images to tensors using transforms.ToTensor() as transforms [code:] TRAIN_DATA_PATH = ‘…\librosa\images’ train_data = torchvision.datasets.ImageFolder(root=TRAIN_DATA_PATH, transform=TRANSFORM_IMG) train_data_loader = data.DataLoader(train_data, batch_size=BATCH_SIZE, shuffle=True, num_workers=4) [/code:] There are a few things I want to do but did not find clear cut explanations on them. I want to visualize each of the images from the data loader. Can someone explain with some code about how to do this? I tried looking in this forum but found a few ways. Can someone give me one standard way with an example?
st82508
I tried this from the udemy pytorch course but got an error dataiter = iter(train_data_loader) images, labels = dataiter.next() for idx in np.arange(2): ax = fig.add_subplot(2,20/2,idx+1, xticks=[],yticks=[]) ax.imshow(np.squeeze(images[idx])) Error: TypeError: Invalid shape (3, 256, 256) for image data
st82509
Solved by LeviViana in post #2 import torch a = torch.arange(3) b = a + 3 print((a == 1).nonzero().numel() > 0) # 1 is in a -> true print((b == 1).nonzero().numel() > 0) # 1 is in b -> false
st82510
import torch a = torch.arange(3) b = a + 3 print((a == 1).nonzero().numel() > 0) # 1 is in a -> true print((b == 1).nonzero().numel() > 0) # 1 is in b -> false
st82511
As title says. For example if my tensor represents a probability, how do I, in a simple way, ensure it’s always in the range of 0-1 through backpropagations?(not by implementing situation-specific tricks like logit transfer)
st82512
I’m trying to replicate the work of Han et al (Learning both Weights and Connections for Efficient Neural Networks, 2015), where model compression for the deep CNN models is achieved by pruning close-to-zero weights and then retrain the model. It has two training phases: in the first stage the model is trained as usual, which is used to find weights below a certain threshold; then those insignificant weights are pruned, resulting in a simpler model, and the rest parameters are kept for another fine-tuning training session. My idea of implementation using PyTorch is that given the trained model from the first stage, I set weights below the threshold to zero (memorized by pruned_inds_by_layer), and then start the second training stage, in which I don’t allow any gradient to be back-propagated to those zero-valued weights. But it seems modifying p.grad.data below doesn’t do the work. Those zero-valued weights still get gradients, making them non-zero again. Any idea how to solve this problem? optimizer.zero_grad() outputs = cnn(images) loss = criterion(outputs, labels) loss.backward() # zero-out all the gradients corresponding to the pruned connections for l,p in enumerate(cnn.parameters()): pruned_inds = pruned_inds_by_layer[l] p.grad.data[pruned_inds] = 0. optimizer.step()
st82513
I figure it out myself: I was using adam to optimize which accumulates gradients form previous steps and therefore setting gradients to zero by hand has no effect on the momentum term in adam. Using RMSprop solves this problem.
st82514
Not for my implementation. I was just creating a mask on the cnn module - weights are not actually pruned but just manually set to zero.
st82515
I see. I think, after zeroing the weights, new architecture definition has to be created manually, for instance number of neurons per layer and copying the parameters with a bit of engineering. However, the paper says that they train the connectivity between neurons of the previous and current layers. I guess it is a bit of different than your implementation, isn’t it?
st82516
I think you are right, the code I have here prunes the weight gradients after the backpropagation. Contributions from pruned weights are still included, which is incorrect. Well, it is a hacky attempt I had - to do it better we need to create masks for each layer using register_register_hook I think. Any thought?
st82517
I read the paper available in this link ( https://arxiv.org/pdf/1506.02626.pdf 105 ), and he mencioned weights are masked also. I think zero weights may be implemented in hardware without problems. I’m not sure about it. I’m trying to implement this method as well.
st82518
I am curious whether zeroing the gradients speeds up the operation, does the Pytorch implementation of .backward() support sparse weight update ? If there is no speed up, what stops you from zeroing the weights (instead of the gradients) after taking the optimization step ? in this case, the optimizer class doesn’t matter, unless you are trying to avoid accumulating meta information in the optimizer such as momentum. You can prune the gradients by changing the forward pass as follows. If you have W = Variable(torch.randn(10), requires_grad=True) and you would like the gradients of the first 5 coordinates only, maybe you can do something like this in the forward pass, loss = (torch.mv(X[:, :5], W[:5]) + torch.mv(X[:, 5:], Variable(W[5:].data)) - y)**2 loss = loss.sum() # Compute grad for W[:5] only loss.backward() which computes the gradient for W[:5] only.
st82519
Hello, I think this is a better way to do it (mentioned as the beginning): # zero-out all the gradients corresponding to the pruned connections for l,p in enumerate(cnn.parameters()): pruned_inds = pruned_inds_by_layer[l] p.grad.data[pruned_inds] = 0. Because I have the mask (zero-weights), so I can update only non zero weights. However, my weights continue updating. I will try other options as well
st82520
If the goal is to update few parameters, then the method mentioned in the top post should be very slow. That’s because when you call backwards() all the gradients are computed anyway so you lose the speed advantage of computing only few gradients. You can change the forward pass using the zero-weight mask so that only the gradients of the non-zero weights are computed.
st82521
On another note, I believe pruning the gradients using your code will result in the wrong update. That’s because gradients depend on each other. So if you zero some gradients for some parameters in some layer, then the gradients in the earlier layers should change (and might not necessarily be zero) due to the chain rule. Your code does not change the dependent gradients. So the code is probably slow and will result in the wrong update.
st82522
I implemented a similar version to gradients update correctly (based on the top publication) after set some weights to zero. This update works because gradient must be variables or None: for l,p in enumerate(net.parameters()): gradient_mask = (p!=0).data # Assuming some weights in 0 p.grad = Variable(gradient_mask.float() * p.grad.data) you are right in the first comment, and I am agree. The algorithm takes the same time as the non-pruned version, due to I continue computing the gradients in zero weights. However in this: I believe pruning the gradients using your code will result in the wrong update. My original model had 91.77% accuracy, after pruning, the my model had 71.78%. I retrained the model (without updating the zero weights and setting gradients to zero) and I got 92.18% for 25 epochs using lr=0.05 with SGD and learning rate is divided by 10 in 3, 10, 16 epoch. I’m not sure if it is a fine-tuning, but I improved the previous result. Moreover, could you explain a little bit more the example you gave? I get lose in some part when I try to employ it in my model. Thank you in advance
st82523
So we have an implementation of weights pruning on this repo 314. The idea is to create a wrapper on the linear or conv layer, and apply the mask on the forward pass. Since multiplying the mask is a differentiable operation (multiplying constant essentially), PyTorch AutoDiff will take care of the backward pass automatically. Well still you may not expect any acceleration, the goal of this implementation is to study the properties of pruned network.
st82524
Hi, is your code final by now? And why won’t it be faster? I have been struggling with similar question recently, I set the data below the threshold to zero and also set the gradient of them to zero. But based on your discussion, I think I should create mask for the loss instead? So now both my gradient is incorrect and the operation is super slow, any thoughts on that? Thanks a lot. My code is: 72
st82525
Unfortunatelly, I had the same time performance problem. I did not know how to solve it, but I worked
st82526
I actually don’t see any speedup from PyTorch on any network after zero-ing out the weights. I don’t know if the operations are meant to be constant in time regardless of the parameter values.
st82527
Did you find out the solution to the slow training? I meas setting gradient to zero takes a lot of time during training, especially when we are talking about setting Million parameters to Zero.
st82528
Hi @RahimEntezari, no, unfortunately , I didn’t try to solve that problem again. Check my github, I refer another interesting paper that reduces the model in a smaller one. I know my code is still a kind mess, but could give you maybe some ideas. GitHub emedinac/DeepCompression 45 This is my own implementation and understanding of the original paper paper - emedinac/DeepCompression
st82529
Hi, there is a nice repository for model compression in PyTorch here: https://github.com/opencv/openvino_training_extensions/tree/develop/pytorch_toolkit/nncf 215. Now it has two pruning methods and quantization support.
st82530
Hi. I wanna implement network pruning using PyTorch. I made a weight histogram to find out pruning point. And then make weight, which can be pruned by histogram, zero. At this point I have a few question. Is there any method to make weights zero? I made a for 2~4 loop… Here is my code for m in net.modules(): if isinstance(m, nn.Linear): wv_fc = m.weight.data if number_wv == 4: print("pruning FC1 weights") number = 0 for n in wv_fc: for i in range(0, 100): for j in range(0, 64*3*3): if m.weight.data[i][j] <= 0.0404 and m.weight.data[i][j] >= -0.0404: m.weight.data[i][j] = 0 print(m.weight.data[i][j]) number = number + 1 number_wv = number_wv + 1 else: print("pruning FC2 weights") number = 0 for n in wv_fc: for i in range(0, 10): for j in range(0, 100): if m.weight.data[i][j] <= 0.0404 and m.weight.data[i][j] >= -0.0404: m.weight.data[i][j] = 0 print(m.weight.data[i][j]) number = number + 1 number_wv = number_wv + 1 If I done masking, is there any simple method to freeze the zero weight specifically? Not per layer like "reqires_grad=FALSE" I wanna freeze only zero weights in entire network. In this context, freeze means that freezed weights cannot be trained anymore.
st82531
You can access parameters by doing a .parameters() So, model.children() gives you layers, and for each layer, layer.parameters() gives you access to each parameter. It’s a generator basically so it lets you run in a loop. Set the parameters to 0 and the requires_grad to False for any nodes you want to prune.
st82532
I have a tutorial which shows this in great detail. It doesn’t set the weight to zero and requires grad to False, but shows how to access the parameters. Here’s the github repo for the tutorial - https://github.com/Spandan-Madan/A-Collection-of-important-tasks-in-pytorch 103 In the tutorial go to cell 22 and modify the lines to be. for child in model.children(): for param in child.parameters(): param = torch.zeros(param.size()) param.requires_grad = False This will basically prune all nodes of the model. To specify which nodes are to be pruned just add if statements in the above code to prune only the required nodes! Hope this helps!
st82533
I think it is impossible to configure specific weights. The tutorial what you recommend is also about just layer configuration.
st82534
I modified the code like that for child in net.children(): for param in child.layer[0].parameters(): for i in range(0,16): for j in range(0,1): for k in range(0,5): for l in range(0,5): if param.data[i][j][k][l] <= 0.0404 and param.data[i][j][k][l] >= -0.0404: param.data[i][j][k][l] = 0 param[i][j][k][l].reguired_grand = False But I cause other error like that Traceback (most recent call last): File "main3.py", line 229, in <module> param[i][j][k][l].requires_grad = False RuntimeError: you can only change requires_grad flags of leaf variables. If you want to use a computed variable in a subgraph that doesn't require differentiation use var_no_grad = var.detach(). If i use detach(), there is no change…
st82535
You’ll need to use hooks to get access to intermediate gradients. Read this for an example - Why cant I see .grad of an intermediate variable?
st82536
That’s one way to do it. It’s a little inefficient as you’re still computing things just that they’re zero so they don’t add up to the equation. But yes it makes sense because it’s obviously impossible to drop specific elements of a matrix from the computation graph. If you get this to work, do drop a reply below I’m curious if this can be done
st82537
Hi, look at what is available here https://github.com/opencv/openvino_training_extensions/tree/develop/pytorch_toolkit/nncf 31. There are two pruning methods and quantization support.
st82538
Hi, I’m building an application where I receive images from a socket connection, then I process them and return back the results in another socket connection. All three steps are separated in a multiprocessing independent process. Furthermore, since the dataflow will be constant they operate parallel in while loops. In order to allow communication between the processes I use queues. I pass the queues as arg to the processes, and in some processes I use queue.put() while in others queue.get() (normal producer-consumer behaviour). I have an strange error, lets say the process that put the tensors from the socket into the queue is faster and puts 15 batches of images in the queue before the process with the pytorch model analyzes nothing. You would expect these 15 objects (cpu tensors) of the queue being different, however they are all the same which corresponds to the last objects. It’s like if the queue is filled in all their posititons with the last object it gets. If I send the images from the socket very slowly (with break points for instance) then this does not happen and everything is computed properly. Is this a know bug? Is there a limit size in terms of memory for the queues which I fill with my cpu tensors?
st82539
Why people did not use pytorch pretrained models (vgg, googlelenet) which are easy to use instead of building caffe library and use its pretrained models
st82540
Pretrained torchvision models are used in a lot of scripts. Where did you see Caffe models in PyTorch?
st82541
thank for answering my question. I see people using it in kaggle and some github repo which use caffe as feature extractor
st82542
Hello everyone, hope you are having a great day. How can I have layer wise training in Pytorch? I mean, suppose I have a network that trains like normal but parts of the network also gets optimized independently ? its something like this |________| |module1 | |________| |module2 | |________| |module3 | |________| It goes like this I feed the model like normal : for imgs, labels in dataloader: imgs = imgs.to(device) labels = labels.to(device) preds = model(imgs) loss = criterion(preds, labels) .... but what is not shown here is that each module can have its own criterion, each module receives a batch of images for example, runs the normal thing it does and it also trains until the loss reaches to a specific quantity then gets out of the loop for example and sends its outputs to the next layer, this goes on until the network predictions are made available which then the loss is calculated and the network weights is updated. Thank you all very much in advance
st82543
Hi, I’ve read the codes of PyTorch, the layers are mainly about “nn.linear()”, “nn.sequential()” and so on, but I want to build a layer that is completely artiifcial by myself, I’ve read the documents of PyTorch, but I havn’t an idea, how could it be solved? Please give an idea, thanks.
st82544
Hi, the “artificial” means that can edit the layers optionally, for example, can consuct a kind of novel neural network just like ResNet before, that is, could PyTorch construct a network optionally? And could PyTorch edit the neurons of the network? Thanks.
st82545
If I understand your question correctly, you would like to use something like a neural architecture search? If so, have a look at e.g. this DARTS implementation 5.
st82546
I’m trying to install Pytorch 1.2 on a laptop with Windows 10 Home (GTX 1050) in a new conda environment with Python 3.7, following the instructions from: pytorch.org PyTorch 2 An open source deep learning platform that provides a seamless path from research prototyping to production deployment. conda install pytorch torchvision cudatoolkit=10.0 -c pytorch I can only get a “false” when testing my cuda capabilities with torch.cuda.is_available() What can I do please? EDIT: It works using the “Cuda 9.2” option from the above-referred url: conda install pytorch torchvision cudatoolkit=9.2 -c pytorch -c defaults -c numba/label/dev
st82547
Hi, ↑ that is all. As a first penguin of the topic, my model is here; https://github.com/IAMAl/QNet My model is experiment to replace GRU cell with my proposal cell called Q-cell. I use MNIST as an experiment application.
st82548
Hello, I’m curious if its possible to do something like np.random.choice([a, b], p=[p_a, p_b]) using PyTorch where a and b are 1-d tensors of length L and p_a and p_b are probabilities used to sample elements from either tensor a or b into the resultant 1-d tensor. I think torch.multinomial([p_a, p_b], L) might be useful here - it returns a 1-d tensor length L of 0s and 1s based on the probabilities I give it but I’m drawing a blank of how to utilize this tensor to sample from my tensors a and b. Appreciate any help!
st82549
Solved by ptrblck in post #2 I’m not sure to completely understand the use case, but this code snippet should work, if you would like to sample either the element from a or b based on the probabilities: L = 10 a = torch.arange(L) b = torch.arange(L, 2*L) p_a = 0.2 probs = torch.empty(1, L).uniform_() idx = (probs >= p_a).to(t…
st82550
I’m not sure to completely understand the use case, but this code snippet should work, if you would like to sample either the element from a or b based on the probabilities: L = 10 a = torch.arange(L) b = torch.arange(L, 2*L) p_a = 0.2 probs = torch.empty(1, L).uniform_() idx = (probs >= p_a).to(torch.long) c = torch.stack((a, b)) result = torch.gather(c, 0, idx) print(c) > tensor([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]]) print(probs) > tensor([[0.8268, 0.0361, 0.2744, 0.4381, 0.7244, 0.8509, 0.5047, 0.0549, 0.2767, 0.3203]]) print(idx) > tensor([[1, 0, 1, 1, 1, 1, 1, 0, 1, 1]]) print(result) > tensor([[10, 1, 12, 13, 14, 15, 16, 7, 18, 19]])
st82551
Thank you - this is great! I ended up using the gather function(which I was previously unaware of) to sample from my a and b tensors after stacking them in dim=0 with the indices I got from torch.multinomial()
st82552
For instance is it common for some convolution layer to share weight with some other conv layer?
st82553
Traceback (most recent call last): File “/home/pi/tensorflow1/models/research/object_detection/Object_detection_webcam.py”, line 57, in label_map = label_map_util.load_labelmap(PATH_TO_LABELS) File “/home/pi/tensorflow1/models/research/object_detection/utils/label_map_util.py”, line 137, in load_labelmap with tf.gfile.GFile(path, ‘r’) as fid: Code: ######## Webcam Object Detection Using Tensorflow-trained Classifier ######### Author: Evan Juras Date: 1/20/18 Description: This program uses a TensorFlow-trained classifier to perform object detection. It loads the classifier uses it to perform object detection on a webcam feed. It draws boxes and scores around the objects of interest in each frame from the webcam. Some of the code is copied from Google’s example at https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb 16 and some is copied from Dat Tran’s example at https://github.com/datitran/object_detector_app/blob/master/object_detection_app.py 8 but I changed it to make it more understandable to me. Import packages import cv2 import numpy as np import tensorflow as tf import sys import os This is needed since the notebook is stored in the object_detection folder. sys.path.append("…") Import utilites from utils import label_map_util from utils import visualization_utils as vis_util Name of the directory containing the object detection module we’re using MODEL_NAME = ‘inference_graph’ Grab path to current working directory CWD_PATH = os.getcwd() Path to frozen detection graph .pb file, which contains the model that is used for object detection. PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,‘frozen_inference_graph.pb’) Path to label map file PATH_TO_LABELS = os.path.join(CWD_PATH,‘training’,‘labelmap.pbtxt’) Number of classes the object detector can identify NUM_CLASSES = 6 Load the label map. Label maps map indices to category names, so that when our convolution network predicts 5, we know that this corresponds to king. Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) Load the Tensorflow model into memory. detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_CKPT, ‘rb’) as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name=’’) sess = tf.Session(graph=detection_graph) Define input and output tensors (i.e. data) for the object detection classifier Input tensor is the image image_tensor = detection_graph.get_tensor_by_name(‘image_tensor:0’) Output tensors are the detection boxes, scores, and classes Each box represents a part of the image where a particular object was detected detection_boxes = detection_graph.get_tensor_by_name(‘detection_boxes:0’) Each score represents level of confidence for each of the objects. The score is shown on the result image, together with the class label. detection_scores = detection_graph.get_tensor_by_name(‘detection_scores:0’) detection_classes = detection_graph.get_tensor_by_name(‘detection_classes:0’) Number of objects detected num_detections = detection_graph.get_tensor_by_name(‘num_detections:0’) Initialize webcam feed video = cv2.VideoCapture(0) while(True): # Acquire frame and expand frame dimensions to have shape: [1, None, None, 3] # i.e. a single-column array, where each item in the column has the pixel RGB value ret, frame = video.read() frame_expanded = np.expand_dims(frame, axis=0) # Perform the actual detection by running the model with the image as input (boxes, scores, classes, num) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: frame_expanded}) objects = [] threshold = 0.89 for index, value in enumerate(classes[0]): object_dict = {} if scores[0,index] > threshold: object_dict[category_index.get(value).get('name')] = scores[0,index] avbn = (category_index.get(value).get('name')) print(avbn) # Draw the results of the detection (aka 'visulaize the results') vis_util.visualize_boxes_and_labels_on_image_array( frame, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=8, min_score_thresh=0.85) # All the results have been drawn on the frame, so it's time to display it. cv2.imshow('Object detector', frame) # Press 'q' to quit if cv2.waitKey(1) == ord('q'): break Clean up video.release() cv2.destroyAllWindows()
st82554
Your issue seems to be related to TensorFlow, so I doubt many users can help you in this PyTorch discussion board. I would recommend to ask a question on StackOverflow.
st82555
In the code below I am doing a normal training loop with batchsize 128 . the model outputs a 128x1 vector as predicticed result which i am comparing with a 128x1 target variable and computing L1 loss and backpropagating. However after 1 epoch i am getting the following warning followed by cuda out of memory error /home/ec2-user/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/nn/modules/loss.py:91: UserWarning: Using a target size (torch.Size([59336])) that is different to the input size (torch.Size([59336, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size. return F.l1_loss(input, target, reduction=self.reduction) Now how is the target size becoming 59336 when it should be128x1 , I am not able to understand . If possible any help would be appreciated for no in range(1): model = ModelCombination(count,non_numeric_feats,numeric_feats,emb_dims,latent_dim, int(full_data['price_band_index'].max())+1,price_diff,price_max) model.to(device) learning_rate = 0.001 criterion = torch.nn.L1Loss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, betas=(0.9, 0.999),weight_decay=1e-5) patience = 20 best = 1e5 early_stop_counter = 0 train_data , valid_data = train_test_split(final_train,shuffle=True,test_size=0.2) final_train1 = torch.tensor(train_data[['ASIN_index','price_band_index', 'demand','price']].to_numpy(),dtype=torch.float32) valid_train1 = torch.tensor(valid_data[['ASIN_index','price_band_index', 'demand','price']].to_numpy(),dtype=torch.float32) final_test1 = torch.tensor(final_test[['ASIN_index','price_band_index', 'demand','price']].to_numpy(),dtype=torch.float32) train_dataset = torch.utils.data.TensorDataset(final_train1) # Data set only on ASIN Index train_loader = torch.utils.data.DataLoader(train_dataset,batch_size=128) # batches are 128 ASIN_index valid_dataset = torch.utils.data.TensorDataset(valid_train1) # Data set only on ASIN Index valid_loader = torch.utils.data.DataLoader(valid_dataset,batch_size=len(valid_dataset)) for epoch in range(100): for i,j in enumerate(train_loader): batch_demand = j[0][:,2] batch_price = j[0][:,3] batch_asin = torch.tensor(j[0][:,0],dtype=torch.int64) batch_price_index = torch.tensor(j[0][:,1],dtype=torch.int64) num_fts = numeric_matrix[batch_asin] non_num_fts = non_numeric_matrix[batch_asin] d_hat=model(batch_asin.to(device),batch_price_index.to(device),batch_demand.to(device),batch_price.to(device),num_fts.to(device),non_num_fts.to(device)) loss = criterion(d_hat.flatten(),batch_demand.to(device)) # Scaling demand by number of sigmoids #print(loss) optimizer.zero_grad() loss.backward() optimizer.step() #print("learning_rate",optimizer.state_dict()["param_groups"][0]['lr']) #scheduler.step() ## Decrease Learning Rate val_mape,val_loss = evaluate_valid(valid_loader,model) #val_mape,val_loss = np.round(val_mape,5),np.round(val_loss,5) if val_mape.item() < best: best = val_mape.item() early_stop_counter = 0 torch.save({ 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'loss': loss, }, "MEAN_V3"+str(no)+".pth") print("Best yet",no,best,val_mape) fname.write("Best yet"+str(no)+"\t"+str(best)+"\t"+str(val_mape.item())+"\n") early_stop_counter+=1 print("Train Loss ",no,epoch,loss,val_mape.item(), val_loss,np.round(optimizer.state_dict()["param_groups"][0]['lr'],5)) if early_stop_counter>=patience: print("Breaking Training Loop for Model",no) break
st82556
Hi, I am working on someone’s code in torch 0.3. I want to count number of padding so I wrote: ys = valid_decoder_inputs[1:,:].view(-1) #true target not_padding = ys.ne(PAD_IDX) no_not_padding = not_padding.sum().item() However torch 0.3 doesn’t support item(). Can you help of how to write this line of code in torch 0.3?
st82557
Solved by ptrblck in post #2 You could replace it with x.sum().data[0]. The probably better approach would be to port the code to the latest PyTorch version, as you might encounter already solved bugs etc.
st82558
You could replace it with x.sum().data[0]. The probably better approach would be to port the code to the latest PyTorch version, as you might encounter already solved bugs etc.
st82559
I have the following code: for i in range(num_models): model = ConvNet() model.cuda() model = nn.DataParallel(model, device_ids=[0]) ... I suspect that these lines don’t actually reinitialize the model with random weights. I believe this because I observed better results for models which are trained in later iterations of the for-loop than if the same models were trained individually without any for-loop, leading me to think that some sort of transfer learning is taking place. Is this a possibility? How could I reinitialize the weights of the model to be random with every iteration of the for-loop?
st82560
The model is randomly initialized in each loop. You could run a quick test and compare (some) parameters of the new model to the last trained one (use .clone() to get the real value instead of a reference).
st82561
Two model:Net_D,Net_C Net_D class Net_D(nn.Module): def __init__(self): super(Net_D, self).__init__() model = models.resnet50(pretrained=False) model.fc = nn.Linear(hidden_dim, num_D_class) model = remove_last(model) self.resnet = model ........ class Net_C(nn.Module): def init(self): super(Net_C, self).init() model = self.load_state_dict(torch.load("best.mdl") model.fc = nn.Linear(hidden_dim, num_C_class) model = remove_last(model) self.resnet = model … Two training code: train_D.py, train_C.py part code for train_D.py torch.save(model.state_dict(), 'best.mdl') part code for train_C.py model = Net_C() model.to(device) print('Model is built ...') 。。。。。。 I run the train_D.py successfuly and I got the best.mdl file. But when I try to run train_C.py to pretrain the best model, I got the following error info: RuntimeError: Error(s) in loading state_dict for Fusion_Net_C: Unexpected key(s) in state_dict: "resnet.0.weight", "resnet.1.weight", "resnet.1.bias",...... But I found there are actually such keys above. Any help, thanks.
st82562
Your Net_C doesn’t seem to initialize the resnet50 model, which was used in Net_D. Could you explain your use case a bit, e.g. why you need a new model architecture?
st82563
Thank you very much for your reply. My work is to train two tasks, which are related but different. In fact,I can say the relation between the two tasks is hierarchical. I planed to train taskone( which is task D) firstly and save the model, and then do some modification to the model D to train task two(which is task C). and the code “self.resnet = model” is what I try to init the resnet.
st82564
The state_dict will contain all parameters and buffers of the model. In the case of Net_D it will contain the parameters/buffers of the internal resnet50 as well as your custom linear layer. I’m not sure, what remove_last does, but if it removes the last linear layer, your custom one will most likely be gone. In Net_C you are calling self.load_state_dict immediately in the __init__ method, which won’t work, as your model does not have any parameters or buffers yet. If you just want to initialize the linear layer and load its state_dict, you could use this approach 2.
st82565
Hi, I try to make custom model which includes; class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.w = [torch.randn((NUM_INPUT), requires_grad=True) for _ in range(NUM_HIDDEN)] for index in range(NUM_HIDDEN): self.parameters = nn.ParameterList([self.w[index]]) I did the “nn.ParameterList()” because of error “no parameter” is occurred. But, running makes an error of; TypeError: cannot assign 'torch.FloatTensor' object to parameter '0' (torch.nn.Parameter or None required) Why this error is occurred, and then how to solve it?
st82566
I did; for index in range(NUM_HIDDEN): self.parameters = nn.Parameter(self.w[index]) Then it worked.
st82567
as thisissue 5 say that: every time you move model to different device, you should build optimizer again, so model = Model() model.cuda() optimizer = optim.Adam(model.parameters()) for d, gt in trn_dataloader: # train ... optimizer.step() model.cpu() # move to cpu # eval or do other things ... model.cuda() # but finnally, move back does optimizer run as expected?