id
stringlengths
3
8
text
stringlengths
1
115k
st117368
Hi, Are there any implementations of deconvolution, or class model visualizations in pytorch ? Thanks
st117369
we dont have deconvolution in the sense of traditional signal processing. For visualization / saliency etc. look at https://github.com/leelabcnbc/cnnvis-pytorch/blob/master/test.ipynb 73
st117370
Hi, I am a theano user and new to pytorch. I was wondering if there’s any way to automatically move everything (modules, loss, variables) to gpu without calling .cuda() for each of them. In theano it could be easily done by setting the environmental variable THEANO_FLAGS=device=gpu. It would be great if pytorch has similar mechanisms. Thanks!
st117371
You can rewrite the Variable class to automatically use cuda: class Variable(autograd.Variable): def __init__(self, data, *args, **kwargs): data = data.cuda() super(Variable, self).__init__(data, *args, **kwargs) Won’t help w models tho obv.
st117372
If you judiciously use things like tensor.new you should be able to reduce the number of .cuda() calls to two: one for your data and one for the model.
st117373
I have a suggestion. tensor.new() looks unobvious in the code. Maybe torch could mimic numpy and provide torch.empty_like(tensor), torch.ones_like(tensor) and torch.zeros_like(tensor) instead? Or maybe new() does something more sophisticated?
st117374
One option is something like torch.zeros(...).type_as(tensor), But I agree that those convenience functions would be appreciated.
st117375
I wrote a custom dataloader by following the examples in pytorch. This is the code I have written import torch import torch.utils.data import numpy as np # reads the binary file and return the data in ascii format def _read_binary_file(fname, dim): with open(fname, 'rb') as fid: data = np.fromfile(fid, dtype=np.float32) assert data.shape[0] % dim == 0.0 data = data.reshape(-1, dim) return data, data.shape[0] class LoadDataset(torch.utils.data.Dataset): """ Custom dataset compatible with torch.utils.data.DataLoader """ def __init__(self, x_files_list, y_files_list, in_dim, out_dim): """Set the path for data Args: x_files_list: list of input files with full path y_files_list: list of target files with full path x_dim: input dimension y_dim: output dimension """ self.x_files_list = x_files_list self.y_files_list = y_files_list self.in_dim = in_dim self.out_dim = out_dim def __getitem__(self, index): """Returns one data pair (x_data, y_data).""" x_file = self.x_files_list[index] y_file = self.y_files_list[index] x_data, no_frames_x = _read_binary_file(x_file, self.in_dim) y_data, no_frames_y = _read_binary_file(y_file, self.out_dim) assert (no_frames_x == no_frames_y) return (torch.Tensor(x_data), torch.Tensor(y_data)) def __len__(self): return len(self.x_files_list) def get_loader(x_files_list, y_files_list, in_dim, out_dim, batch_size, shuffle, num_workers): # Custom dataset data = LoadDataset(x_files_list=x_files_list, y_files_list=y_files_list, in_dim=in_dim, out_dim=out_dim) # Data loader # This will return (x_data, y_data) for every iteration # x_data: tensor of shape (batch_size, in_dim) # y_data: tensor of shape (batch_size, out_dim) data_loader = torch.utils.data.DataLoader(dataset=data, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers) return data_loader if __name__ == "__main__": x_files_list_file = '/work/shared/vocomp/x_files_list' y_files_list_file = '/work/shared/vocomp/y_files_list' in_dim = 335 out_dim = 262 with open(x_files_list_file, 'r') as fid: x_files_list = [l.strip() for l in fid.readlines()] with open(y_files_list_file, 'r') as fid: y_files_list = [l.strip() for l in fid.readlines()] x_files_list = x_files_list[0:len(y_files_list)] data_loader = get_loader(x_files_list, y_files_list, in_dim, out_dim, 64, False, 1) for i, (x_data, y_data) in enumerate(data_loader): print i, x_data.size(), y_data.size() Output is File "dataprovider_pytorch.py", line 80, in <module> for i, (x_data, y_data) in enumerate(data_loader): File "/l/SRC/python/lib/python2.7/site-packages/torch/utils/data/dataloader.py", line 174, in __next__ return self._process_next_batch(batch) File "/l/SRC/python/lib/python2.7/site-packages/torch/utils/data/dataloader.py", line 198, in _process_next_batch raise batch.exc_type(batch.exc_msg) RuntimeError: Traceback (most recent call last): File "/l/SRC/python/lib/python2.7/site-packages/torch/utils/data/dataloader.py", line 32, in _worker_loop samples = collate_fn([dataset[i] for i in batch_indices]) File "/l/SRC/python/lib/python2.7/site-packages/torch/utils/data/dataloader.py", line 81, in default_collate return [default_collate(samples) for samples in transposed] File "/l/SRC/python/lib/python2.7/site-packages/torch/utils/data/dataloader.py", line 68, in default_collate return torch.stack(batch, 0) File "/l/SRC/python/lib/python2.7/site-packages/torch/functional.py", line 56, in stack return torch.cat(list(t.unsqueeze(dim) for t in sequence), dim) RuntimeError: inconsistent tensor sizes at /data/users/soumith/builder/wheel/pytorch-src/torch/lib/TH/generic/THTensorMath.c:2548
st117376
As the error says: RuntimeError: inconsistent tensor sizes at /data/users/soumith/builder/wheel/pytorch-src/torch/lib/TH/generic/THTensorMath.c:2548 Tensors from the returned data loader are of various different sizes, so the collate function is not able to concatenate them into a mini-batch
st117377
Hi, now I need to sum all probability with same index together for my modified pointer network. which means prob = Variable(torch.Tensor(len, batch)) indices = Variable(torch.LongTensor(len, batch)) output = Variable(torch.zeros(len, batch,vsize)) for pos in range(len): for b in range(batch): output[pos][b][indices[pos,b]] += prob[pos][b] but this implementation is too brutal, How can I do this without for-loop? thanks very much!
st117378
I think you can do this using index_add_ http://pytorch.org/docs/tensors.html?highlight=index_add#torch.Tensor.index_add_ 537 output.index_add_(2, indices.view(-1), prob)
st117379
For torch.autograd Variable, there’s the ‘gradient’ input param for the .backward() function. I don’t quite understand what this ‘gradient’ input param stands for, and why this param is needed?
st117380
To call .backward() you need gradient wrt the output. It is needed as part of the chain rule / backpropagation algorithm.
st117381
Note that if you’re calling it on a loss/cost variable, you don’t need to provide an argument since autograd will assume a tensor of ones.
st117382
A more precise mathematical definition would be to say that what we often refer to as “gradients” are Jacobian-vector products, and the gradient is the vector you want to multiply with it (for the loss it’s initialized as [1] by default, so it gives the Jacobian itself).
st117383
apaszke: A more precise mathematical definition would be to say that what we often refer to as “gradients” are Jacobian-vector products, and the gradient is the vector you want to multiply with it (for the loss it’s initialized as [1] by default, so it gives the Jacobian itself). Hi, I implement a skip-gram model using pytorch. However, I find the backward speed depends on the embedding size. The larger is the embedding size, the slower is the backward speed. So I’m wondering if the backward will calculate the gradient of each variable, even the variable that is not used in this step? For example, I have an Embedding variable which is 10,000*100. When I used 10th and 20th embedding, will backward function calculate the gradient only for this two embeddings or will it calculate the gradient for all 10,000 embeddings?
st117384
I also have trouble with this. It says that the argument of backward should be the gradients w.r.t. the output. But consistently across the documentation it is never mentioned of what the gradient w.r.t. the output (must be a conspiracy to drive me crazy). Clearly you can define the gradient as an operator but then you don’t get numbers (like 1). Can the thing of which you take the gradient w.r.t. the output not be stated concisely? Does it depend on some usecase? If I just have y=f(x) for example how do I derive the 1 that is assumed?
st117385
Is it the gradient of the eventual downstream loss with respect to the current layer? So that in the case of a scalar loss which is also the “most downstream output/loss” we get dloss/dloss =1 but if we want to get backward() from some middle layer we have to provide the gradient of the downstream loss w.r.t. all the outputs of this middle layer (evaluated at the current values of those outputs) in order to get well defined numerical results. This makes sense to me and actually occurs in backprop. In more technical terms. Let y be an arbitrary node in a computational graph If we call y.backward(arg) the argument arg to backward should be the gradient of the root of the computational graph with respect to y evaluated at a specific value of y (usually the current value of y). If y is a whole layer, this means that arg should provide a value for each neuron in y. If y is th final loss it is also the root of the graph and we get the usual scalar one as the only reasonable argument arg. Am I getting there?
st117386
Yes, that’s correct. We only support differentiation of scalar functions, so if you want to start backward form a non-scalar value you need to provide dout / dy
st117387
I know this does not work right now. But would there be something (computationally) equivalent to detaching a node that is already in the backpropagation graph so that computation does not flow backwards through it? Right now calling detach_() only affects computations defined/run after the call. Any ideas on how to do this? e.g. this could be used on an RNN where the loss at each time step gets always propagated K steps backwards, instead of 1 step for the first, 2 steps for the second…
st117388
Can you try, save all the hidden vectors in a list, and use detach_() to detach those vectors which are out of K steps. It may not free the all the memory, but I guess it will prevent from backpropogating through early steps.
st117389
I have tried exactly that but no, it seems what matters is the “detached” state at the time of operating with a Variable, not if it gets detached afterwards. By doing it I get always increasing execution times, which probably means I’m backpropagating through the full history of the graph. This is the critical section of the code I’m running (basically char_rnn). next_sequential_sample() generates one character at a time. from collections import deque train_length = 100 hidden_deque = deque(maxlen=train_length) criterion = nn.NLLLoss() optimizer = optim.Adam(rnn.parameters()) def train(n_steps=train_length, hidden_init=None): hidden = hidden_init or rnn.initHidden() for i in range(n_steps): sample = next_sequential_sample() input_line_tensor, target_line_tensor = Variable(torch.unsqueeze(onehot_torch(sample[0]), 1)), Variable(torch.from_numpy(sample[1])) if len(hidden_deque) == hidden_deque.maxlen: h_to_detach = hidden_deque.popleft() for h in h_to_detach: h.detach_() hidden_deque.append(hidden) output, hidden = rnn(input_line_tensor[0], hidden) loss = criterion(output, target_line_tensor[0]) optimizer.zero_grad() loss.backward(retain_graph=True) optimizer.step() return (hidden[0], hidden[1]) n_train_calls = 100 print_every = 1 hidden = None for train_iter in range(1, n_train_calls + 1): hidden = train(train_length, hidden_init=hidden) @apaszke mentioned in Delete variable from the graph that they would add this soon, but I’m not sure if there has been any progress on it.
st117390
In the optim class, we always call optimizer.step() which I assume computes the loss after a minimization process. If we want to maximize a cost function, do we simply negate optimizer.step()?
st117391
Hi, What is the difference between torch.nn.sigmoid and torch.nn.functional.sigmoid ? Thanks, Lucas
st117392
torch.nn.Sigmoid is a nn.Module, which behaves like a class, while torch.nn.functional.sigmoid is a function. You can use any of them, and indeed, torch.nn.Sigmoid uses the functional interface internally 19 (or almost). It’s a matter of taste when using one or the other. For example, if you just want to write a basic fully-connected network, it might be easier to use a nn.Sequential and append some modules to it, like model = nn.Sequential( nn.Linear(2, 2), nn.Sigmoid(), nn.Linear(2, 2) ) in which case the nn.Module interface is simpler. On the other hand, if you are writing some more complex functions, it might be easier to just go for the functional interface, as this avoids you from having to create a class for it. For example # this is a function that will be differentiated def my_function(x): x1 = x ** 2 x2 = F.sigmoid(x ** 3) return x1 + x2
st117393
input = Variable(torch.LongTensor([-1, -1, 0, 1])) input2 = Variable(torch.LongTensor([[0, 0], [1, 1], [2, 2], [3, 3]])) temp = input < 1 print input2[temp, :] I got RuntimeError: inconsistent tensor size at /b/wheel/pytorch-src/torch/lib/TH/generic/THTensorMath.c:193 if input2 is 1-d, say input[temp] there is no problem. Is there a way to do what I want?
st117394
The current way of doing what you want is the following: input = Variable(torch.LongTensor([-1, -1, 0, 1])) input2 = Variable(torch.LongTensor([[0, 0], [1, 1], [2, 2], [3, 3]])) temp = input < 1 indices = temp.data.nonzero()[:,0] print(input2[indices]) Note that with broadcasting and advanced indexing 97, we will get even close to numpy indexing semantics
st117395
Hi all, I’m using Pytorch to build my own model but meet some problem. I found many Loss has the param size_average, such as torch.nn.CrossEntropyLoss(weight=None, size_average=True). Loss func takes Input: (N,C) and Target: (N) then returns a single value, which I suppose is averaged on batch_size N. size_average (bool, optional): By default, the losses are averaged over observations for each minibatch. However, if the field sizeAverage is set to False, the losses are instead summed for each minibatch. But when I set size_average=False, it still returns a single value instead of a batch_size loss. So I wonder what this param size_average do? How can I access losses of batch by individual? Thanks a lot!
st117396
Currently, all losses in pytorch returns a single number, which is either the sum of the losses per element, or the average. Obtaining losses per element is not yet implemented in pytorch, and is being tracked in https://github.com/pytorch/pytorch/issues/264 508
st117397
Hi all, I am new to artificial neural network. Currently I am trying to solve a regression problem with 3 input variables but the ouptput dimension is around 40. I cannot get any acceptable fitting results after several trials. Is there any general rules in dealing with this kind of regression problem, such as how to choose activation function, number of layers and neurons in each layer? I used 3 layers with about 500 neurons in each layer, and Relu activation in all layers. It seems to improve very little when I increase the model complexity. Apart from neural network, is there any other tools suitable for this problems? Thanks
st117398
Wow, 3 inps -> 40 outputs! For sanity check, have you tried training 40 independent linear regression models (using sklearn may be)?
st117399
Thanks for your kind reply. Using several independent model should be a solution, but there is some inner relations among the elements in the output vector, which I wish to modify the error function to account for this. Currently I simply use the square error. I am wondering if there is some fundamental limit when mapping small number of input to large number of output when doing regression using neural networks?
st117400
maweibest: I used 3 layers with about 500 neurons in each layer, and Relu activation in all layers. It seems to improve very little when I increase the model complexity. That’s a lot actually. Get nn.Linear(3, 40) (which is same as 40 independent regressors) working and incrementally add hidden layers with a few number of units. I don’t expect MLPs to ‘just work’.
st117401
Thank you chsasank. You mean that MLP can not well handle the regression with oupt dimension much larger than the input? Why? Any other suggestions about my problem? I am looking forward to your kind reply.
st117402
Hi, I’m trying to plot the kernels in my first layer but they don’t look right. I used a pre trained AlexNet and there’s definitely structure but the colours seem off. Here is a fairly minimal example: import torchvision.models as models import torchvision.transforms as transforms import torch.nn as nn import torch import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def plot_kernels(tensor, num_cols=6): num_rows = 11 fig = plt.figure(figsize=(num_cols,num_rows)) i = 0 for t in tensor: ax1 = fig.add_subplot(num_rows,num_cols,i+1) pilTrans = transforms.ToPILImage() pilImg = pilTrans(t) ax1.imshow(pilImg, interpolation='none') print(tensor[i]) ax1.axis('off') ax1.set_xticklabels([]) ax1.set_yticklabels([]) i+=1 plt.subplots_adjust(wspace=0.1, hspace=0.1) plt.show() alexnet = models.alexnet(pretrained=True) i = 0 for m in alexnet.modules(): if isinstance(m, nn.Conv2d): if i == 0: plot_kernels(m.weight.data.clone().cpu()) plt.savefig('result.png') Which results in: result.png600×1100 37.3 KB So I guess it has something to do with the structure so I produced this example: import torchvision.models as models import torchvision.transforms as transforms import torch.nn as nn import torch import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def plot_kernels(tensor, num_cols=6): num_rows = 1 fig = plt.figure(figsize=(num_cols,num_rows)) i = 0 for t in tensor: ax1 = fig.add_subplot(num_rows,num_cols,i+1) pilTrans = transforms.ToPILImage() pilImg = pilTrans(t) ax1.imshow(pilImg, interpolation='none') ax1.axis('off') ax1.set_xticklabels([]) ax1.set_yticklabels([]) i+=1 plt.subplots_adjust(wspace=0.1, hspace=0.1) plt.show() tensor = torch.FloatTensor([[ [[0, 0, 0], [0, 0, 0], [0,0,0]], [[0, 0, 0], [0, 0, 0], [0,0,0]], [[1, 1, 1], [1, 1, 1], [1,1,1]], [[0, 0, 0], [0, 0, 0], [0,0,0]], [[0, 0, 0], [0, 0, 0], [0,0,0]], [[1, 1, 1], [1, 1, 1], [1,1,1]], [[0, 0, 0], [0, 0, 0], [0,0,0]], [[0, 0, 0], [0, 0, 0], [0,0,0]], [[1, 1, 1], [1, 1, 1], [1,1,1]], ],[ [[1, 1, 1], [1, 1, 1], [1,1,1]], [[0, 0, 0], [0, 0, 0], [0,0,0]], [[0, 0, 0], [0, 0, 0], [0,0,0]], [[0, 0, 0], [0, 0, 0], [0,0,0]], [[1, 1, 1], [1, 1, 1], [1,1,1]], [[0, 0, 0], [0, 0, 0], [0,0,0]], [[0, 0, 0], [0, 0, 0], [0,0,0]], [[0, 0, 0], [0, 0, 0], [0,0,0]], [[1, 1, 1], [1, 1, 1], [1,1,1]] ], ]) plot_kernels(tensor) plt.savefig('result.png') Which produces this result: (I can’t post a second image as I’m a new user ) I guess I expected a blue square and then either a black square with a white diagonal? What I get is vertical stripes of red, green then blue. I could see how they might be horizontal instead but I didn’t expect vertical ones? Is this the right way to save the weights to look at their structure? How can I plot these weights with accurate colour? Thanks!
st117403
I figured this out. You have to normalise the tensor between 0 and 1: # Normalise maxVal = tensor.max() minVal = abs(tensor.min()) maxVal = max(maxVal,minVal) tensor = tensor / maxVal tensor = tensor / 2 tensor = tensor + 0.5 Gets a nice result: result.png600×1100 33 KB and matches the weights here: http://cs231n.github.io/understanding-cnn/ 66
st117404
I study reinforcement learning and I want to implement a simple actor-critic approach. my question about freezing parameters: I have a critic network: critic = Critic() critic_old = critic(Variable(torch.Tensor(observation).view(1,4))) critic_new = critic(Variable(torch.Tensor(observation).view(1,4))) Then I compute critic loss: critic_loss = ((reward+(gamma*critic_new)) - critic_old)**2 So, in this case, I don’t want to backpropagate through critic_new only through critic_old. so critic_new should be like a fixed scalar. How can I do this?
st117405
Should just be something like critic_loss = ((reward+(gamma*critic_new.detach())) - critic_old)**2
st117406
Thank you! I Have one more question: As I understand these two blocks of code are the same. critic = Critic() critic_old = critic(Variable(torch.Tensor(observation).view(1,4))) critic_new = critic(Variable(torch.Tensor(observation).view(1,4))) critic_loss = ((reward+(gamma*critic_new.detach())) - critic_old)**2 . critic = Critic() critic_old = critic(Variable(torch.Tensor(observation).view(1,4))) critic_new = critic(Variable(torch.Tensor(observation).view(1,4), volatile = True)) critic_new.volatile = False critic_loss = ((reward+(gamma*critic_new)) - critic_old)**2 Am I correct?
st117407
github.com pytorch/pytorch/blob/master/torch/nn/parallel/parallel_apply.py#L22 8 for result in results: if isinstance(result, Variable): return result if isinstance(obj, dict): results = map(get_a_var, obj.items()) for result in results: if isinstance(result, Variable): return result return None def parallel_apply(modules, inputs, kwargs_tup=None, devices=None): assert len(modules) == len(inputs) if kwargs_tup is not None: assert len(modules) == len(kwargs_tup) else: kwargs_tup = ({},) * len(modules) if devices is not None: assert len(modules) == len(devices) else: devices = [None] * len(modules) This seems to constrain input to variables or a list (or nested list) of variables. I suppose that at least allowing dictionary of variables as input should increase flexibility (which indeed works for single GPU case). I created an issue for it. If you think this bug should be resolved, I would be happy to send a pull request.
st117408
I build three versions of the same network achitecture( i am not sure now). And trained them on the same dataset( i swear) using the same solver Adam with default hyper parameters. The caffe and keras version works really well, but the pytorch version just doesn’t work. the loss will go down, but rises at the end of every epoch. This is strange. What’s wrong with my code? time_step = 150 batch_size = 256 input_dim = 6 lstm_size1 = 100 lstm_size2 = 512 fc1_size = 512 class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.lstm1 = nn.LSTM(input_dim, lstm_size1, dropout=0.3) self.lstm2 = nn.LSTM(lstm_size1, lstm_size2, dropout=0.3) self.fc1 = nn.Linear(lstm_size2, fc1_size) self.fc2 = nn.Linear(fc1_size, 3755) def forward(self, x, num_strokes, batch_size): x = torch.nn.utils.rnn.pack_padded_sequence(x,num_strokes) hidden_cell_1 = (Variable(torch.zeros(1, batch_size, lstm_size1).cuda()), Variable(torch.zeros(1, batch_size, lstm_size1).cuda())) allout_1, _ = self.lstm1(x, hidden_cell_1) hidden_cell_2 = (Variable(torch.zeros(1, batch_size, lstm_size2).cuda()), Variable(torch.zeros(1, batch_size, lstm_size2).cuda())) _, last_hidden_cell_out = self.lstm2(allout_1, hidden_cell_2) last_hidden_cell_out = Variable(last_hidden_cell_out[0].data) x = last_hidden_cell_out.view(batch_size, lstm_size2) x = self.fc1(x) x = F.relu(x) x = F.dropout(x, p = 0.3) x = self.fc2(x) # out = F.log_softmax(x) return x The mainly training part: optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # one sample is of size [150, 6], so data is of size [256, 150, 6], i need to transpose data to get T*B*L data = torch.transpose(data, 0, 1) data, target = Variable(data), Variable(target) optimizer.zero_grad() out = model(data, num_strokes, batch_size) loss = F.cross_entropy(out, target) loss.backward() optimizer.step() The key point here is that my data is padded to 150, which means one sample maybe only have a length of 35 and of size [35, 6], i padded it to [150, 6], so only 35 lines at the begining are none zero. the rest 115 lines are all zeros. So i use: x = torch.nn.utils.rnn.pack_padded_sequence(x,num_strokes) where x is sorted by data lengths, and num_strokes indicates their lengths in descent order. Am i using it in the right way? Could any help me? I really don’t know why after debug for several days
st117409
Hello @Nick_Young. I have a similar problem like you but the difference is that I have never trained any network. What I have done was to transfer weights in keras to pytorch. The result are so different. I swear I check every line of code to verify are there any bugs are not. Do you find any difference between keras and pytorch?
st117410
Well, for one with this line last_hidden_cell_out = Variable(last_hidden_cell_out[0].data) you are detaching the computational graph for everything that happened to compute last_hidden_cell_out. Therefore, the parameters for lstm1 and lstm2 never get updated. What was the point for this, is this intentional?
st117411
got it! should be: x = last_hidden_cell_out[0].view(batch_size, lstm_size2) and it finally worked! Thank you so much!!!
st117412
There are some mistakes in the offical doc. it says that h_n and c_n are tensors, but they turn out to be Variables. and the shapes of weights: for weight_ih and weight_hh, they are transposed.
st117413
Variables are tensors just with pytorch Variable wrapper around them so you can auto compute their gradients
st117414
I’m trying to understand how the adam optimizer 12 was implemented in pytorch. Basically, I would like to penalize the returned loss with an l_2 norm of some noise variable (for use in a specific problem). The way the loss is written is not as intuitive as the paper seems to argue. What’s the advisable way to do this?
st117415
Is there a way to return classification results as confidence scores from a pyTorch Variable? I can easily retrieve topk results from Variable but they’re just floats with various negative/positive values (e.g. [-0.201, 5.627, 0.982, 3.221]. I’m looking to get the confidence instead (where all numbers sum up to 1.0 e.g. [0.84, 0.11, 0.026, 0.024]) Does anyone know how to obtain/compute this? Thanks
st117416
You are looking for softmax. Most(all?) pretrained in torch vision don’t have final softmax.
st117417
I want to plot my history losses with matplot. But my loss data are returned as Variables from loss function. What’s the way of plotting with PyTorch?
st117418
You get the value of a Variable using its parameter “data” : loss = criterion( output, target) loss_value = loss.data[0]
st117419
I’m trying to make a simple feed forward network with sparse weights. Using pytorch v0.1.12, python 3 [cuda80] I am unable to do a simple forward pass in the two ways shown below, both produce the same error. The shape of x is [10,100] and the sparse tensor w1 is of shape [100,500]. I expect a dense tensor of shape [10,500]. x = Variable(torch.from_numpy(p_in).type(dtype), requires_grad=False) #where weights[0] is of type torch.sparse.FloatTensor w1 = Variable(weights[0].type(dtype_sparse), requires_grad=True) #this is where the error occurs l3 = torch.mm(x, w1) #also used this: l3 = x.mm(w1) The output of this is: TypeError Traceback (most recent call last) in () ----> 8 l3 = torch.mm(x, w1) /home/lina/anaconda2/envs/py3/lib/python3.5/site-packages/torch/autograd/variable.py in mm(self, matrix) 525 def mm(self, matrix): 526 output = Variable(self.data.new(self.data.size(0), matrix.data.size(1))) –> 527 return self._static_blas(Addmm, (output, 0, 1, self, matrix), False) 528 529 def bmm(self, batch): /home/lina/anaconda2/envs/py3/lib/python3.5/site-packages/torch/autograd/variable.py in _static_blas(cls, args, inplace) 518 if num_args == 4: 519 alpha = args[1] –> 520 return cls(alpha, beta, inplace)(*(args[:1] + args[-2:])) 521 522 def _blas(self, cls, args, inplace): /home/lina/anaconda2/envs/py3/lib/python3.5/site-packages/torch/autograd/_functions/blas.py in forward(self, add_matrix, matrix1, matrix2) 26 output = self._get_output(add_matrix) 27 return torch.addmm(self.alpha, add_matrix, self.beta, —> 28 matrix1, matrix2, out=output) 29 30 def backward(self, grad_output): TypeError: torch.addmm received an invalid combination of arguments - got (int, torch.FloatTensor, int, torch.FloatTensor, torch.sparse.FloatTensor, out=torch.FloatTensor), but expected one of: (torch.FloatTensor source, torch.FloatTensor mat1, torch.FloatTensor mat2, *, torch.FloatTensor out) (torch.FloatTensor source, torch.SparseFloatTensor mat1, torch.FloatTensor mat2, *, torch.FloatTensor out) (float beta, torch.FloatTensor source, torch.FloatTensor mat1, torch.FloatTensor mat2, *, torch.FloatTensor out) (torch.FloatTensor source, float alpha, torch.FloatTensor mat1, torch.FloatTensor mat2, *, torch.FloatTensor out) (float beta, torch.FloatTensor source, torch.SparseFloatTensor mat1, torch.FloatTensor mat2, *, torch.FloatTensor out) (torch.FloatTensor source, float alpha, torch.SparseFloatTensor mat1, torch.FloatTensor mat2, *, torch.FloatTensor out) (float beta, torch.FloatTensor source, float alpha, torch.FloatTensor mat1, torch.FloatTensor mat2, *, torch.FloatTensor out) didn’t match because some of the arguments have invalid types: (int, torch.FloatTensor, int, torch.FloatTensor, torch.sparse.FloatTensor, out=torch.FloatTensor) (float beta, torch.FloatTensor source, float alpha, torch.SparseFloatTensor mat1, torch.FloatTensor mat2, *, torch.FloatTensor out) didn’t match because some of the arguments have invalid types: (int, torch.FloatTensor, int, torch.FloatTensor, torch.sparse.FloatTensor, out=torch.FloatTensor)
st117420
Solved by lmnt in post #2 Seems it is just not currently possible to do dense X sparse > dense (please correct me if wrong) Workaround is to just have sparsity manually. I.e. make the “sparse” matrix dense, and multiplying by a mask of 1s and 0s each trial. Main goal here was to have a dense input layer mm by a sparse weigh…
st117421
Seems it is just not currently possible to do dense X sparse > dense (please correct me if wrong) Workaround is to just have sparsity manually. I.e. make the “sparse” matrix dense, and multiplying by a mask of 1s and 0s each trial. Main goal here was to have a dense input layer mm by a sparse weight matrix to produce a dense next layer. Then of course to apply backprop to these sparse layers, and needed the sparse values to not be updated. By multiplying by the mask, those unwanted changes resets values to 0.
st117422
I have an issue when I try to resume snapshot of a saved model. I am training a model in GPU 0. For evaluation, I load the model snapshot in GPU 1. Since my model barely fits in GPU 0, I do not have any more space left on GPU 0. When I try to load the snapshot in GPU 1, it seems that a part of the model is instantiated in GPU 0, despite me giving the GPU flag: model.cuda(1). Is there a way to load the snapshot only in GPU 1 without using any part of GPU 0 ?
st117423
I realized this could be done using the CUDA_VISIBLE_DEVICES flag and calling model.cuda() within the code. Closing this.
st117424
(e) .env  In [1]  from torch.autograd import Variable │ │ (e) .env  In [2]  import torch │ │ (e) .env  In [3]  a = Variable(torch.Tensor(1)) │ (e) .env  In [4]  a.ne(0) │ Out[4]  Variable containing: 1 │ [torch.ByteTensor of size 1] │ │ (e) .env  In [5]  a.ne(0).sum() │ Out[5]  │ Variable containing: │ 1 │ [torch.ByteTensor of size 1] │ (e) .env  In [6]  a.data.ne(0).sum() Out[6]  1 │ (e) .env  In [7]  However, the document about Tensor says Tensor’s sum return float 5.
st117425
Solved by spruceb in post #2 The sum of a Tensor is a float, but a Variable containing a Tensor is not a Tensor. Think of Variable like a wrapper that can hold most numeric objects. Operations performed on a Variable produce the expected result, but wrapped in a Variable.
st117426
The sum of a Tensor is a float, but a Variable containing a Tensor is not a Tensor. Think of Variable like a wrapper that can hold most numeric objects. Operations performed on a Variable produce the expected result, but wrapped in a Variable.
st117427
Hi all, I customize a Loss module for seq2seq model. Since inputs are padded to max_seq_len for batch training, so I need a loss that can pass in mask in order to ignore PAD loss. import torch.nn as nn import torch from torch.autograd import Variable def _assert_no_grad(variable): assert not variable.requires_grad, \ "nn criterions don't compute the gradient w.r.t. targets - please " \ "mark these variables as volatile or not requiring gradients" class SequenceLoss(nn.Module): def __init__(self, average_cross_timesteps=True, average_cross_batch=True): super(SequenceLoss, self).__init__() self.average_cross_timesteps = average_cross_timesteps self.average_cross_batch = average_cross_batch self.loss_func = nn.CrossEntropyLoss(size_average=False) def forward(self, input, target, weight): batch_size = input.size()[0] max_seq_len = input.size()[1] _assert_no_grad(target) _assert_no_grad(weight) num_classes = input.size()[-1] logits_flat = input.view(-1, num_classes) targets_flat = target.view(-1) logits_flat_list = torch.split(logits_flat, 1, dim=0) targets_flat_list = torch.split(targets_flat, 1, dim=0) tmp = [self.loss_func(logits_flat_list[i], targets_flat_list[i]).data for i in range(batch_size*max_seq_len)] crossent = Variable(torch.cat(tmp, dim=0), requires_grad=True) #Variable(torch.Tensor(tmp)) crossent = crossent * weight.view(-1) if self.average_cross_timesteps and self.average_cross_batch: # char level ppl crossent = torch.sum(crossent) total_size = torch.sum(weight) total_size += 1e-12 # to avoid division by 0 for all-0 weights crossent = crossent / total_size else: sequence_length = input.size()[1] crossent = crossent.view(batch_size, sequence_length) if self.average_cross_timesteps and not self.average_cross_batch: crossent = torch.sum(crossent, 1) total_size = torch.sum(weight, 1) total_size += 1e-12 crossent = crossent / total_size if not self.average_cross_timesteps and self.average_cross_batch: # return crossent = [time_steps] crossent = torch.sum(crossent, 0) total_size = torch.sum(weight, 0) total_size += 1e-12 crossent = crossent / total_size return crossent And loss doesn’t go down in training process. I don’t know where the problem is. Could anybody give me some advice?
st117428
I installed PyTorch on Win10 by conda install -c peterjc123 pytorch=0.1.12 but it didn’t include some functions. Will it update?
st117429
I wrote simple script which converts a lasagne model (saved in h5 format) to a pytorch model (the architecture has only convolutional layers - https://github.com/madratman/lasagne_to_pytorch/blob/master/convert_lasagne_to_pytorch.py 66), but am getting erroneous (read blank) predictions I also was checking the model weights of https://github.com/Lasagne/Recipes/blob/master/modelzoo/vgg16.py 3) and comparing them to torch vision’s vgg16, and saw that after the 2nd conv layer, the mean weight of each conv layer is different by an order of 10. I guess for VGG, it’s due to different input ranges (in pytorch, it’s 0-1 and in lasagne, it’s just subtraction from mean image but not scaling to 0-1) But for my architecture, I fail to understand how could the two give different results. The code is here https://github.com/madratman/lasagne_to_pytorch/blob/master/convert_lasagne_to_pytorch.py 66 model in lasagne https://github.com/madratman/lasagne_to_pytorch/blob/master/models/lasagne/dilated_3.py 12 model in pytorch https://github.com/madratman/lasagne_to_pytorch/blob/master/models/pytorch/dilated_3.py 10 Could a reason be that torch and lasagne have different ways to add relu?! (lasagne allows it as an option in the conv layer itself.) I won’t mind writing a generic model converter if I get past this
st117430
either the memory layout of the inputs/weights (BCHW vs BHWC for example), or the normalization, I would suspect. Start with a single-layer model, and slowly go towards complex models.
st117431
Hey @smth So I compared the weights and activations from of pytorch and lasagne VGG16 models converted from caffe. They are the same. My custom model has dilation layers and they are the ones which are resulting in different activations. Still investigating.
st117432
dilation might be subtly different in lasagne than in pytorch. maybe some boundary conditions (ceil / floor)
st117433
Yeah, screw that. I just wrote a semantic segmentation training pipeline in pytorch and got things working It’s pretty awesome Thanks for the help
st117434
I’m playing with rnn-char example from here: https://github.com/spro/practical-pytorch/blob/master/char-rnn-generation/char-rnn-generation.ipynb 3 Here’s the simplified code I’m running: gist.github.com https://gist.github.com/michaelklachko/fa485c27f83477981889d8a2fde0af4d 10 GRU based char-rnn model import random import torch import torch.nn as nn from torch.autograd import Variable text = open('input.txt', 'r').read() file_len = len(text) all_chars = ''.join(set(text)) n_chars = len(all_chars) This file has been truncated. show original When I run it on GPU, memory usage is almost 12GB (Pascal Titan X). GPU utilization is ~20%. I added ‘requires_grad=False’ to the input Variable, but that didn’t help. Any ideas why so much memory is in use? Is this normal for a RNN network of this size (3 layer GRU with hidden_size=500, and input_size=100?
st117435
x and y are two matrices. I want to find the indices of nonzero entries in a column of y (let’s say the first column), and take the corresponding rows of x. In numpy, I can do: x[y[:,0] > 0] In theano: x[(y[:,0]>0).nonzero()] What is the most appropriate way to do this in Pytorch? I can do: m = y[:,0] > 0 x[m.unsqueeze(1).expand_as(x)].resize(m.long().sum().data[0], x.size()[1]) But I assume there should be a much easier way. Thanks.
st117436
Yeah, we’ve added the ability to select based on the long tensor a few days ago. I think it’s in the new binaries, so once you reinstall pytorch this should work: x[(y[:, 0] > 0).nonzero().squeeze()]
st117437
And in the future, we’re going to support automatic broadcasting so the numpy way should work in some time too.
st117438
I just reinstalled from scratch , but it cannot find nonzero() function. I am getting the following message: File “/home/yusuf/anaconda2/envs/pytorch-bin-env/lib/python2.7/site-packages/torch/autograd/variable.py”, line 86, in _getattr_ raise AttributeError(name) AttributeError: nonzero I also have a version that I built from source, and I get the same error from it, too. How can I get the right version? Thanks.
st117439
It will work on tensors only right now, as we don’t have nonzero() implemented for Variables. I’ll add that soon. I’m afraid for now you need to do it like you originally wrote, sorry for the trouble!
st117440
Hi, I tried to use resnet from torchvision.models on GPU, then I got an error below. Does anyone know solutions? I’m using the latest PyTorch and torchvision in conda. code from torchvision.models import resnet18 model = resnet18() model.cud() input = Variable(input).cuda() output = model(input) output Traceback (most recent call last): File "tinyimagenet.py", line 82, in <module> train(model, optimizer, train_loader) File "tinyimagenet.py", line 35, in train output = model(input) File "/home/user/.anaconda/lib/python3.6/site-packages/torch/nn/modules/module.py", line 206, in __call__ result = self.forward(*input, **kwargs) File "/home/user/.anaconda/lib/python3.6/site-packages/torchvision-0.1.8-py3.6.egg/torchvision/models/resnet.py", line 139, in forward File "/home/user/.anaconda/lib/python3.6/site-packages/torch/nn/modules/module.py", line 206, in __call__ result = self.forward(*input, **kwargs) File "/home/user/.anaconda/lib/python3.6/site-packages/torch/nn/modules/conv.py", line 237, in forward self.padding, self.dilation, self.groups) File "/home/user/.anaconda/lib/python3.6/site-packages/torch/nn/functional.py", line 40, in conv2d return f(input, weight, bias) RuntimeError: expected CPU tensor (got CUDA tensor) Thank you.
st117441
sorry, this issue has already been issued (https://github.com/pytorch/pytorch/issues/1472 703 )
st117442
In the real code, I forgot to do input = Variable(input).cuda() but did just Variable(input).cuda().
st117443
Hi, I have been using pack_padded_sequence for packing padded and sorted variable-length of input with RNN and LSTM. I would like to customize a layer or a network to work with this kind of packed input. For example, if I just want to do a maxpooling or an averaging pooling over a packed input on the dimension where we have variable-length. def pad_tensor(tensor, length): return torch.cat([tensor, tensor.new(length - tensor.size(0), *tensor.size()[1:]).zero_()]) def pad_tensor_list(tensor_list): tensor_length = [x.size(0) for x in tensor_list] return torch.cat([torch.unsqueeze(pad_tensor(tensor, max(tensor_length)), 0) for tensor in tensor_list], 0), tensor_length # assume the tensor is sorted tensor_list = [] tensor_list.append(torch.Tensor(7, 16)) tensor_list.append(torch.Tensor(5, 16)) tensor_list.append(torch.Tensor(3, 16)) # pad the tensor padded_tensor, tensor_length = pad_tensor_list(tensor_list) # pack the padded tensor packed_input = pack_padded_sequence(padded_tensor, list(tensor_length), batch_first=True) # customized layer ... maxpooling_for_packed(packed_input) I understand that we can basically skip packing the input and iterate through the 1st dimension of the tensor and index_select the original length of the tensor, and then apply max or mean pooling on selected tensors. I am wondering whether if there is a way to design a max, mean pooling or other layers that can natively and efficiently work with packed input. If so, how would you suggest me do it?
st117444
Hi. I am starting with PyTorch and trying to write a simple classification code. I am using CIFAR10 dataset to train the model. This part of the code downloaded the dataset and stores it. elif self.dataset_train == 'cifar10': self.dataset_train = datasets.CIFAR10(root=self.args.dataroot, train=True, download=True, transform=transforms.Compose([ transforms.Scale(self.resolution), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), ]) ) And this create the dataloader. dataloader_train = torch.utils.data.DataLoader(self.dataset_train, batch_size=self.args.batch_size, shuffle=True, num_workers=int(self.args.nthreads)) However, when I am using the dataloader to iterate through the dataset, using just a for loop (in a different function with parameter name as dataloader) like this: for i, data in enumerate(dataloader, 0): input, label = data ... I am getting the following error: /home/rahul/CANVAS/pytorchnet/train.py(84)train() -> for i, data in enumerate(dataloader, 0): (Pdb) n –Return– /home/rahul/CANVAS/pytorchnet/train.py(84)train()->None -> for i, data in enumerate(dataloader, 0): (Pdb) n TypeError: TypeErro…nt’\n’,) /home/rahul/CANVAS/pytorchnet/main.py(62)() -> loss_train = trainer.train(epoch, loader_train) (Pdb) n –Return– /home/rahul/CANVAS/pytorchnet/main.py(62)()->None -> loss_train = trainer.train(epoch, loader_train) (Pdb) n Traceback (most recent call last): File “main.py”, line 62, in loss_train = trainer.train(epoch, loader_train) File “/home/rahul/CANVAS/pytorchnet/train.py”, line 84, in train for i, data in enumerate(dataloader, 0): File “/home/rahul/anaconda2/lib/python2.7/site-packages/torch/utils/data/dataloader.py”, line 212, in next return self._process_next_batch(batch) File “/home/rahul/anaconda2/lib/python2.7/site-packages/torch/utils/data/dataloader.py”, line 239, in _process_next_batch raise batch.exc_type(batch.exc_msg) TypeError: Traceback (most recent call last): File “/home/rahul/anaconda2/lib/python2.7/site-packages/torch/utils/data/dataloader.py”, line 41, in _worker_loop samples = collate_fn([dataset[i] for i in batch_indices]) File “/home/rahul/anaconda2/lib/python2.7/site-packages/torchvision-0.1.8-py2.7.egg/torchvision/datasets/cifar.py”, line 99, in getitem img = self.transform(img) File “/home/rahul/anaconda2/lib/python2.7/site-packages/torchvision-0.1.8-py2.7.egg/torchvision/transforms.py”, line 29, in call img = t(img) File “/home/rahul/anaconda2/lib/python2.7/site-packages/torchvision-0.1.8-py2.7.egg/torchvision/transforms.py”, line 139, in call ow = int(self.size * w / h) TypeError: unsupported operand type(s) for /: ‘tuple’ and ‘int’ When I try to debug using pdb, I see that inside the PyTorch’s dataloader.py file, the batch becomes an instance of ExceptionWrapper. It is not clear as exactly what am I doing wrong as I have run the same kind of loops on dataloader previously with CIFAR10. Please help!
st117445
The problem is with your Scale transform. I’m guessing self.resolution is a tuple? For some reason the documentation for torchvision is for the newest version, in which Scale does take a tuple, but the most recent release (which you presumably have) only takes a single int. That being the desired size of the smaller edge. You should either change to that (if possible, since it does require the scaled version to have the same aspect ratio), or install torchvision from HEAD.
st117446
Hi, I am looking for equivalent function for numpy.where(condition[, x, y]). What I am hoping is to have a function for elementwise condition for each element on x & y depends on the boolean matrix “condition”. But I can’t find it in current pytorch function. Is there any possibility to be included in the future ? Thanks
st117447
@norm_inf You’re trying to implement SELU github.com/pytorch/pytorch Add SELU (Scaled ELU) 105 opened Jun 10, 2017 closed Jun 11, 2017 ethancaballero Here's TF example: https://github.com/bioinf-jku/SNNs/blob/master/selu.py#L20-L25 Ideally it would be done in C in TH backend. However, it could also be done in python if a...
st117448
@ethancaballero I am trying to implement different elementwise penalty. Currently, I am using hack like this Variable(condition.float()) * x + Variable((condition != 1).float()) * y I just read about SELU things after your post, You can try using that tricks for where substitute. But I think native Torch implementation must be faster & better than this hack.
st117449
Really want to learn pytorch mainly because of the programming style. However, going through the tutorials, I’ve realized the tutorials & documentation on the website and the github is not updated. For example: doesn’t even exist… even after replacing ‘grad_fn’ with ‘creator’, the ‘next_function’ doesn’t exist. Does anyone have any good UPDATED learning material for PyTorch? Or is there a certain version of PyTorch I need install instead of the conda python 3.6 version?
st117450
Hi, Tutorials are not outdated. In fact, they are more update and even with master pytorch. Unfortunately, latest pytorch release doesn’t include a recent refactoring which rename these functions. You will face no issues if you install pytorch from source. Please sift though issues and/or raise an issue at tutorials repo if you face any problems.
st117451
Thank you Sasank! So do you suggest me uninstall the version I have now (linux, conda, 3.6, cpu) and just download it from source? Or downgrade to an earlier release until the latest release is stable?
st117452
Hi all, I am confused by the output format of bidirectional RNN. Is the forward and backward output concatenated on the last dimesion? Can I assume the first hidden_size of the last dimension of the output tensor is from the forward part? Thanks!
st117453
Yes the outputs of the two directions are concatenated on the last dimension, so to get all forward outputs out[:, :, :hidden_size] and backwards out[:, :, hidden_size:]
st117454
Hi, I met an interesting problem. When I ran two replicates of my model on two GPUs with CUDA_VISIBLE_DEVICES macro and initialized them with same random seed, the speed of the two training process deteriorates after several iterations. This phenomenon appears when I use ROI pooling layer implemented by longcw’s faster RCNN 9. I guess it may be related the implementation of the ROI pooling layer. When initialized with the same seed, some GPU operations will lead conflicts. Is there anyone knowing why? Best, Yikang
st117455
So if you run a single process it’s ok, but if you start two it will run slower? Maybe the GPUs are competing for the PCIe bandwidth
st117456
Thank you very much. Maybe it is due to the competition of PCle bandwidth. But at the beginning tens of thousands of iterations, there is no such problem. Do you know what I can do to avoid the problem?
st117457
Hey @yikang-li did you train longcw’s code on a custom dataset? If so what were the changes that you made?
st117458
This code (FASTER RCNN in PyTorch) works perfectly fine for the PASCAL_VOC dataset but it fails in custom dataset with following error. File “train.py”, line 127, in net(im_data, im_info, gt_boxes, gt_ishard, dontcare_areas) File “/usr/local/lib/python2.7/dist-packages/torch/nn/modules/module.py”, line 206, in call result = self.forward(*input, **kwargs) File “/data/code/faster_rcnn_pytorch/faster_rcnn/faster_rcnn.py”, line 219, in forward roi_data = self.proposal_target_layer(rois, gt_boxes, gt_ishard, dontcare_areas, self.n_classes) File “/data/code/faster_rcnn_pytorch/faster_rcnn/faster_rcnn.py”, line 287, in proposal_target_layer proposal_target_layer_py(rpn_rois, gt_boxes, gt_ishard, dontcare_areas, num_classes) File “/data/code/faster_rcnn_pytorch/faster_rcnn/rpn_msr/proposal_target_layer.py”, line 66, in proposal_target_layer np.hstack((zeros, np.vstack((gt_easyboxes[:, :-1], jittered_gt_boxes[:, :-1])))))) File “/usr/local/lib/python2.7/dist-packages/numpy/core/shape_base.py”, line 234, in vstack return _nx.concatenate([atleast_2d(_m) for _m in tup], 0) ValueError: all the input array dimensions except for the concatenation axis must match exactly github.com/longcw/faster_rcnn_pytorch Train new dataset: zeros after conv3 in vgg16 8 opened May 25, 2017 kduy I am trying to train the model with my own dataset. Sometimes , I got this error File "train.py", line 127,...
st117459
In order to partition an image into smaller patches, during training, in Theano we can take advantage of theano.tensor.nnet.neighbours package that contains images2neibs, neibs2images. How can it be performed in PyTorch? Cheers
st117460
No, I’m afraid we don’t have any operation like that. You can open a feature request in the main repository if you want.
st117461
You can hack up a conv operation to do this. If you want a patch of say 8x8 just do a 8x8x64 convolution with zero padding and let the kernel be 1’s in different positions with all zeros. After you do this your 1x1x64 will be your 8x8 patches. This will probably be very inefficient with maximally sparse convolutions, but unless you intend to do this in an iterative manner it shouldn’t be noticeable. And should be faster than any loop you can cook up probably. With some extra effort you can make a better array programming solution, something involving reshapes and permutes probably.
st117462
This is actually equivalent to im2col and col2im in the main repo. Just need to wrap it in python with a nice interface.
st117463
@apaszke Is the function added as of now? (Since the last update on this thread was in March!)
st117464
Hi, I’m new to pytorch and have been following the many tutorials available. In the seq2seq tutorial, the encoder’s foward() method iterates over all GRU’s layer. I’m somewhat confused by this : I thought the RNN constructor took the amount of layers as a parameter. I therefore assumed you would not need to explicitly iterate over the RNN’s layers. My question is : is this the proper way of coding a multi-layers rnn ? If not, how should one proceed ? Thanks, Lucas (link to tutorial : http://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html 356)
st117465
I think layers is a parameter of RNN, in this tutorial, it just explicitly show you how multi layer RNN works, you can just give a layer parameter to RNN.
st117466
This is non-standard (you could call it a mistake), but it works well - essentially reusing a single RNN layer multiple times as a form of shared weights. If you use the n_layers parameter of an RNN each layer has its own weights, which is the normal way to do it.
st117467
Hey guys, I’ve been trying out pytorch for a while and have a somewhat contrived used case: I am trying to change the shape of the weight tensor inside Conv2d layers in order to do some filter pruning on a pre-trained model: I wrote some code to change the shape of all the conv layers in the model. for layer in model.modules(): if isinstance(layer, nn.Conv2d): print("Pruning Conv-{}".format(index)) filters = layer.weight.data.numpy() new_filters = prune_layer(filters) # reshape the tensor # Update layer with new tensor layer.weight.data = torch.from_numpy(new_filters).float() layer.out_channels = new_filters.shape[0] The problem I have is that since the out_channels of the ith layer change, I also need to adjust the in_channels of the ith+1 layer and from modules() I can’t guarantee that the order of the nn.Conv2d modules is the same as the one defined in the forward function, so I might end up changing the channels for the wrong layers. Is there a better approach to this? Am I doing it completely wrong? Thanks for the help!