id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st101400 | Hi,
I am confused about the implementation of multi-layer bidirectional LSTM in pytorch.
Say we have
model1 = nn.LSTM(input_size=2, hidden_size=3, num_layers=2, bidirectional=True)
model1 would be a 2-layer bidirectional lstm. For the first layer, since the hidden size is 3 and it is bidirectional, the output of first layer will have size of 6. Therefore the input size of second layer should be 6 and output size should be 6*2=12.
If i do:
for name,para in model1.named_parameters():
print(name)
print(para.size())
It prints:
weight_ih_l0
torch.Size([12, 2])
weight_hh_l0
torch.Size([12, 3])
bias_ih_l0
torch.Size([12])
bias_hh_l0
torch.Size([12])
weight_ih_l0_reverse
torch.Size([12, 2])
weight_hh_l0_reverse
torch.Size([12, 3])
bias_ih_l0_reverse
torch.Size([12])
bias_hh_l0_reverse
torch.Size([12])
weight_ih_l1
torch.Size([12, 6])
weight_hh_l1
torch.Size([12, 3])
bias_ih_l1
torch.Size([12])
bias_hh_l1
torch.Size([12])
weight_ih_l1_reverse
torch.Size([12, 6])
weight_hh_l1_reverse
torch.Size([12, 3])
bias_ih_l1_reverse
torch.Size([12])
bias_hh_l1_reverse
torch.Size([12])
The output matches my expectation. However, when I really feed the network with data, it gives me outputs having size of 6:
from torch.autograd import Variable
random_input = Variable(torch.FloatTensor(5, 1, 2).normal_(), requires_grad=False)
out, _ = model1(random_input)
out.size()
The code gives torch.Size([5, 1, 6])
Could someone please explain why that is the case? Thanks in advance! |
st101401 | it"s right, the “12” is not the output size,
- x: Input data of shape (N, T, D)
- h0: Initial hidden state of shape (N, H)
- Wx: Weights for input-to-hidden connections, of shape (D, 4H)
- Wh: Weights for hidden-to-hidden connections, of shape (H, 4H)
- b: Biases of shape (4H,) |
st101402 | Is it possible to import data using torchtext that is not tab- or comma-separated? For example, I have a dataset where the fields are separated using " ||| " |
st101403 | a = torch.zeros((1,1,100))
a.expand(1,2,100)
Works
a = torch.zeros((1,2,100))
a.expand(1,4,100) gives error
RuntimeError: The expanded size of the tensor (4) must match the existing size (2) at non-singleton dimension 1
Why is this?
Also i am trying to do batched beam search, my batch size=2 and beam size=2. When it comes out from encoder, hidden dimension is 1x2x100 [as i dont consider beam there]. Now as it has to be fed into the decoder with two initial states for two sentences, i need to make it 1x4x100. Is the approach right? |
st101404 | Here is my answers (suggestions only):
x = torch.tensor([[1], [2], [3]])
x.size()
=torch.Size([3, 1])
x.expand(3, 4)
tensor([[ 1, 1, 1, 1],
[ 2, 2, 2, 2],
[ 3, 3, 3, 3]])
From the above example its clear that it returns new view of the exists.
In the first case, it didn’t throw any error because it’s just of shape [1,1,100] from which you can produce anything as its single shape almost with no dimensions.
Not the same in the second case.
Decoder and Encoder(My Thinking)
Hidden dimension is 1x2x100 : 2 indicates the batch size I think and you don’t need to pass anything 14100 as the pytorch net itself will handle this. |
st101405 | Hi, Thanks Jaya !
For the Decoder and Encoder , i also thought this initially
But going forward we would have 2 hidden states for each sentence [as there are two sources per sentence[beam size=2] each giving a new hidden state . Which dimension would pytorch put the 4 hidden states into?
I would need to feed four hidden states [2 sentences;2 beam size] which axis’s dimension should be increased? |
st101406 | Hi
Is anyone working on textual entailment using WikiQA? are there any tutorials or notes on how to do this using pytorch?
Thank you |
st101407 | Hi,
I’m facing a similar issue already reported here by another user. I’m running PyTorch to train a ResNet model on Linux Ubuntu 16 TLS VM hosted on Google Cloud (one GPU K80). It works fine for a few minutes (several epochs) and then it reboots the host. No warning, no error, just crash with reboot. It’s quite random. Sometime it works 30 minutes without any problem.
What could be done? Do I need to update to cuDNN 7.1.3 (I’m using 7.0.5)?
Python : 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 18:10:19)
Numpy : 1.14.2
PyTorch : 0.4.1
torch.version.cuda = 9.0.176
torch.backends.cudnn.version = 7102
torch.cuda.device_count() = 1
torch.cuda.current_device() = 0
Thanks. |
st101408 | Hi,
I am finding a weird behavior using tensors for indexing, so wanted some insight.
x=torch.tensor([[1,2],[3,4],[5,6]])
Now,
x[torch.tensor([[0],[1]])]
tensor([[[ 1, 2]],
[[ 3, 4]]])
but what I expect is as
x[[[0],[1]]]
tensor([ 2])
How can I get this result using tensor indexing. Thank you. |
st101409 | According to My thinking
x[torch.tensor([[0],[1]])] == x[tensor([[0],[1]]) = x[[0,1]]=
tensor([[[1, 2]],
[[3, 4]]])
This is because the torch considers the subscript as x[x-dimension][y-dim] which in our case is x[[[0],[1]] which is still x-dimension with no y-dimension x[[0],[1]][No-y-dimension]
so it will return those values which are columns [1,2][3,4] |
st101410 | Thanks @jmandivarapu1.
Can I use indexing by tensors to get the same result as when indexing by list, i.e. like x[[[0],[1]]]. |
st101411 | Hi,
I’ve created a custom linear layer and am now testing it by running the forward() function on tensors of different sizes. I’m finding that for certain dimensional sizes, the forward pass throws a size mismatch error. For example, running forward on a (2, 10) tensor (and using 2 input features and 10 output features) works properly, while running forward on a (3, 10) tensor with 3 input features and 10 output features does not work.
Any insight on what to check for would be greatly appreciated.
Thanks!
Edit: Issue resolved, made a typo initializing the tensor sizes I was testing with. |
st101412 | Hi all,
I’m working on a project and have extracted the trained layer weights, manipulated them, and am trying to figure out how to replace the trained weights with the manipulated weights I have. Can anyone please help?
Thanks! |
st101413 | Do you still have the state_dict and could load it or do you have the parameters as tensors after your manipulation?
In the former case, you could just try model.load_state_dict(manipulated_state_dict),
while this code might help setting the weights for the latter case:
lin = nn.Linear(in_features=10, out_features=2, bias=False)
x = torch.ones(1, 10)
output = lin(x)
with torch.no_grad():
# Manipulate your weight here
lin.weight += 1 # or e.g. lin.weight = nn.Parameter(lin.weight / 2. + 1)
output = lin(x) |
st101414 | I am trying to do batched beam search in seq2seq, my batch size=2 and beam size=2. When it comes out from encoder hidden dimension is 1x2x100 [as i don’t consider beam there]. Now as it has to be fed into the decoder with two initial states for two sentences.Do I need to make it 1x4x100 ?
We would have 2 hidden states for each sentence [as there are two sources per sentence[beam size=2] each giving a new hidden state . Which dimension would pytorch put the 4 hidden states into?
I would need to feed four hidden states [2 sentences;2 beam size] which axis’s dimension should be increased?
Should the hidden state be made 1x4x100 for feeding to decoder?
I saw the documentation for hidden and it said (num_layersxnum_directions, batch_size, input_size), so i think it should be (1,2x2 [batch_sizexbeam_size],100) |
st101415 | Issue description
Hello there.I’m using Jupyter Notebook, Linux Mint x64 and I have a huge problem with Pytorch. When I running this code - kernel dies.Perfect running on Win 8.1 x64,no problem. I tryed different types of installing - pip,conda, source code from github.Nothing. Please, explain me why this happen all times and how to fix it
Code example
import torch
from torch import nn
import torch.nn.functional as F
from notmnist import load_notmnist
X_train, y_train, X_test, y_test = load_notmnist(letters='AB')
X_train, X_test = X_train.reshape([-1, 784]), X_test.reshape([-1, 784])
model = nn.Sequential()
model.add_module('l1', nn.Linear(784, 1))
model.add_module('l2', nn.Sigmoid())
x = torch.tensor(X_train[:3], dtype=torch.float32)
y = torch.tensor(y_train[:3], dtype=torch.float32)
y_predicted = model(x)[:, 0]
System Info
PyTorch version: 0.5.0a0+b640264
Is debug build: No
CUDA used to build PyTorch: None
OS: Linux Mint 19 Tara
GCC version: (Ubuntu 7.3.0-16ubuntu3) 7.3.0
CMake version: version 3.10.2
Python version: 3.6
Is CUDA available: No
CUDA runtime version: No CUDA
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
Versions of relevant libraries:
[pip] Could not collect
[conda] pytorch-cpu 0.4.1 py36_cpu_1 pytorch
[conda] torch 0.5.0a0+b640264
[conda] torchvision-cpu 0.2.1 py36_1 pytorch
If you need any logs - please tell me where I can found it |
st101416 | Could you export the notebook as a script and run it in your terminal?
This will most likely return an error message instead of just a kernel restart. |
st101417 | I assume you are running and editing your notebook in a browser. You can export it via:
File -> Download as -> Python (.py)
Alternatively you might use
jupyter nbconvert --to script your_notebook.ipynb |
st101418 | Translate from russian - Invalid instruction (the memory stack is flushed to disk)
изображение.jpg1366×768 297 KB |
st101419 | Could you run your script with pdb 8 to get the stack trace?
The error message would probably translate to illegal instruction (core dumped). |
st101420 | I’m sorry for so much screenshoots, but here everything
изображение.jpg1366×768 455 KB
изображение.png1366×768 322 KB
изображение.png1366×768 356 KB
изображение.png1366×768 348 KB
изображение.png1366×768 300 KB |
st101421 | This sounds similar to Unable to sum the result of an equality test 8.
Do you know what model CPU you have on the Linux Mint machine? |
st101422 | Also, it looks like you have both the nightly PyTorch build (0.5.0a0) and PyTorch-CPU (0.4.1) installed. I’m not sure which version you are running. Can you uninstall the older pytorch-cpu build?
conda uninstall pytorch-cpu |
st101423 | I read the topic about Unable to sum the result of an equality test 7
So on my cpu pytorch can not be started? |
st101424 | Your CPU should be OK. It looks like there is a bug in PyTorch, but I am not sure which PyTorch version you are using.
Please try the following. First fully uninstall PyTorch:
conda uninstall -y pytorch-cpu
conda uninstall -y pytorch
Next try the nightly CPU build from yesterday:
pip install https://download.pytorch.org/whl/nightly/cpu/torch_nightly-2018.8.14.dev1-cp36-cp36m-linux_x86_64.whl
Please let me know if this works. |
st101425 | Can you try running your script under gdb and report the backtrace?
$ gdb --args python my_script.py
...
Reading symbols from python...done.
(gdb) run
...
(gdb) backtrace
... |
st101426 | изображение.jpg1366×768 475 KB
изображение.png1366×768 419 KB
изображение.png1366×768 447 KB |
st101427 | Thanks, this is very helpful. Can you also run disas and report the output?
$ gdb --args python my_script.py
...
Reading symbols from python...done.
(gdb) run
...
(gdb) disas
... |
st101428 | OK, it looks like the FMA4 vmfaddps instruction is the problem. I’m a bit confused because your CPU should support that instruction.
Can you report the cpu flags: grep flags < /proc/cpuinfo
Can you report the kernel version: uname -a
Are you running in a virtual machine? |
st101429 | "If you need to move a model to GPU via .cuda(), please do so before constructing optimizers for it. Parameters of a model after .cuda() will be different objects with those before the call.
In general, you should make sure that optimized parameters live in consistent locations when optimizers are constructed and used."
We tried to test this using the code below, but for us it shows that pre and post weights are different, so we believe optimizer is still working, even if .cuda is called after creating optimizer object. So what does this note affect?
import torch
import numpy as np
import torch.nn as nn
import torch.optim as optim
net = nn.Linear(1, 2)
net1 = nn.Linear(1, 2)
net1.load_state_dict(net.state_dict())
pre, pre1 = net.weight.clone(), net1.weight.clone()
net.cuda()
optimizer = optim.SGD(net.parameters(), lr=10)
optimizer_1 = optim.SGD(net1.parameters(), lr=10)
net1.cuda()
inp = torch.autograd.Variable(torch.randn(1, 1)).cuda()
out = torch.autograd.Variable(torch.randn(1, 2)).cuda()
loss = torch.nn.functional.mse_loss(net(inp), out)
loss1 = torch.nn.functional.mse_loss(net1(inp), out)
optimizer.zero_grad()
loss.backward()
optimizer.step()
optimizer_1.zero_grad()
loss1.backward()
optimizer_1.step()
post, post1 = net.weight.clone(), net1.weight.clone()
print pre, pre1
print post, post1 |
st101430 | would mentioning which optimizers does it affect will be helpful in docs? If so, I can check which optimizers are being affected and submit a pull request to modify the docs? |
st101431 | Now there is only 1 or 2 being affected IIRC, and those can be worked around. I’d happy to accept a PR that “fixes” those optimizers and remove that note from doc. |
st101432 | I wonder which dataset is the pretrained model in pytorch? ILSVRC-2012? ILSVRC-2014? or others? |
st101433 | The pre-trained models were trained on ImageNet-12:
discussion in other thread 27 |
st101434 | I wonder why the top-5 and top-1 error is significantly higher than the same model in caffe? |
st101435 | linyu:
I wonder why the top-5 and top-1 error is significantly higher than the same model in caffe?
I wonder why the top-5 and top-1 error is significantly higher than the same model in caffe? |
st101436 | For example, in https://github.com/BVLC/caffe/wiki/Model-Zoo#resnets-deep-residual-networks-from-msra-at-imagenet-and-coco-2015 4, the top-5 of vgg-16 is 7.4%, but 9.62% and 8.5%(with bn) in pytorch. |
st101437 | I’m not sure, but I assume the site reports the multi-scale evaluation instead of the single-scale one.
You can see the different error rates in Table 3 and 4 in their paper 6.
Table 3 comes pretty close to the pre-trained models. |
st101438 | What is the simplest way to get pytorch crashes C++ callstack ?
[edit: found this which seems to help https://stackoverflow.com/questions/28108851/catching-segfault-with-debugger-in-python 6 ]
Is the only way to build pytorch yourself, and even then, is there any flag that needs to be set to make sure that “debug symbols” are available?
I’m aiming towards getting crash messages like the text at the bottom of my question.
I can see that gdb is being used here, any tips/pointers on the steps needed to make gdb kick in when the crash happens?
Epoch: [268][670/782] Time 0.354 (0.331) Data 0.001 (0.001) Loss 0.0003 (0.0014) Prec@1 100.000 (99.984) Prec@5 100.000 (100.000)
Thread 6 "python" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fff22ba1700 (LWP 23233)]
std::__push_heap<__gnu_cxx::__normal_iterator<torch::autograd::FunctionTask*, std::vector<torch::autograd::FunctionTask, std::allocator<torch::autograd::FunctionTask> > >, long, torch::autograd::FunctionTask, torch::autograd::CompareFunctionTaskTime> (__first=..., __holeIndex=5, __topIndex=__topIndex@entry=0, __value=..., __comp=__comp@entry=...)
at /home/why/anaconda3/gcc/include/c++/bits/stl_heap.h:182
182 while (__holeIndex > __topIndex
(gdb) bt
#0 std::__push_heap<__gnu_cxx::__normal_iterator<torch::autograd::FunctionTask*, std::vector<torch::autograd::FunctionTask, std::allocator<torch::autograd::FunctionTask> > >, long, torch::autograd::FunctionTask, torch::autograd::CompareFunctionTaskTime> (__first=...,
__holeIndex=5, __topIndex=__topIndex@entry=0, __value=..., __comp=__comp@entry=...) at /home/why/anaconda3/gcc/include/c++/bits/stl_heap.h:182
#1 0x00007fffecd33480 in std::push_heap<__gnu_cxx::__normal_iterator<torch::autograd::FunctionTask*, std::vector<torch::autograd::FunctionTask> >, torch::autograd::CompareFunctionTaskTime> (__comp=..., __last=..., __first=...)
at /home/why/anaconda3/gcc/include/c++/bits/stl_heap.h:221
#2 std::priority_queue<torch::autograd::FunctionTask, std::vector<torch::autograd::FunctionTask, std::allocator<torch::autograd::FunctionTask> >, torch::autograd::CompareFunctionTaskTime>::push(torch::autograd::FunctionTask&&) (
__x=<unknown type in /home/why/anaconda3/lib/python3.6/site-packages/torch/_C.cpython-36m-x86_64-linux-gnu.so, CU 0x2314a43, DIE 0x23cd8e1>, this=0x7fff2be84fe0) at /home/why/anaconda3/gcc/include/c++/bits/stl_queue.h:507
#3 torch::autograd::ReadyQueue::push (this=0x7fff2be84fe0, item=...) at torch/csrc/autograd/engine.cpp:128
#4 0x00007fffecd364ed in torch::autograd::Engine::thread_main (this=0x7fffee562680 <engine>, graph_task=0x0) at torch/csrc/autograd/engine.cpp:199
#5 0x00007fffecd329d4 in torch::autograd::Engine::thread_init (this=this@entry=0x7fffee562680 <engine>, device=device@entry=-1) at torch/csrc/autograd/engine.cpp:150
#6 0x00007fffecd5bf0a in torch::autograd::python::PythonEngine::thread_init (this=0x7fffee562680 <engine>, device=-1) at torch/csrc/autograd/python_engine.cpp:34
#7 0x00007ffff7b0dc80 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#8 0x00007ffff73376ba in start_thread (arg=0x7fff22ba1700) at pthread_create.c:333
#9 0x00007ffff67553dd in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:109 |
st101439 | @colesbury gave some intructions in this thread 45. Maybe you can use it to debug your issue. |
st101440 | Hi there, I’m new to PyTorch. Just checked the DistributedDataParallel code, and have some questions related:
def _register_grad_hooks(self):
self._grad_accs = [] # need to keep them in scope
for device_idx, module in enumerate(self._module_copies):
for p in module.parameters():
if p.requires_grad:
p_tmp = p.expand_as(p)
grad_acc = p_tmp.grad_fn.next_functions[0][0]
grad_acc.register_hook(self._make_param_hook(p, device_idx))
self._grad_accs.append(grad_acc)
see code 8
Could someone explain how this works? namely, why does it create a new tensor and register hooks on the new tensor’s grad_fn.next_functions[0][0] (what is this function)?
What’s the difference between this and directly register hooks on the original tensor register_hook 8
Thanks. |
st101441 | As for the register_hook function:
It stated that the hook will be called after the gradient is computed, this is true for CPU and GPU use the same stream to compute, but how about I use the grad in a new stream on GPU, is it possible the grad is not fully computed as stated in Horovod 13? |
st101442 | I have 20,580 images about dogs downloaded from http://vision.stanford.edu/aditya86/ImageNetDogs/ 21
In the dataset, I have 120 classes, and each class has images between 120 and 180.And I use 16,418 (about 80% of the dataset) as the train dataset.
During my training, the train accuracy could be 0.96, but the val accuracy is only 0.7(after 50 epochs). It is obviously that overfitting happened.
So I tried seveal ways to improve the problem:
Reduce the size of my network.I switched from using a pretrained(Imagenet) Resnet50 to Resnet18, but it improved a little.
Data augmentation.For the train dataset, I used random horizontal flip,random brightness,random shift and random ratation. In the end, I resized the image to 384384,but it does not help too much with overfitting(Because the size of images are different,some are 180120,some are 500*400, and so on).
Add weight decay.I tried 1e-5,5e-4,1e-4,1e-3 weight_decay,and 1e-5 and 1e-4 could improve a little.The train accuracy is 0.85,and the val accuracy is 0.65(after 7 epochs).
I am confused about how to prevent overfitting. I even doubt if the dataset is suitable for classfication.
Hope your advice.
Thanks. |
st101443 | I guess this is more of a generic answer then specific to PyTorch, but two things come to mind:
If you reuse a pre-trained network, ensure that when you train on your images you “freeze” most of the earlier layers. So only train the last few layers (typically the fully connected layers) and don’t update the weights of the earlier layers. Possible you are already doing this, but if not I would suggest to try this first.
I like to use dropouts as a way to prevent overfitting. The default dropout value of 0.5 is in my personal experience a good starting point. You could add them at the end between the fully connected layers. |
st101444 | Thanks for your advice.
I just use the pre-trained weight to initialize the new network , and retrain the network instead of freeze most of the earlier layers.
By now, I haven’t applied dropout in the network.
Thanks for your advice again, I will update my result after the two tries. |
st101445 | Yes, you are right.
I tried the two ways that you advised, the results are improved a lot.
Now I have two results:
I freeze all the earlier layers, only update the last fully connected layers(Resnet 18). No dropout.Train accuracy:0.80; Val accuracy:0.76
I freeze all the earlier layers, only update the last fully connected layers(Resnet 34). And I also add a dropout layer (p = 0.5) before the fullly connected layers. Train accuracy:0.90; Val accuracy:0.81
The two are all better than my first result. Thanks for your advice. |
st101446 | Good to hear that it improved the accuracy score of the validation set (and I assume reduced the training time significantly since the back-propagation involves fewer learnable parameters). |
st101447 | may i see your resnet18 code? i need it so much , because my resnet18 did not work well. |
st101448 | Hi,
When we pass a number to any torch function, e.g. addcmul, internally the cpp calls have a datatype called real. Does the code internally transfer the real value to the GPU at runtime if the other tensors are in the GPU?
Regards
Nabarun |
st101449 | “real” is the type of your data. It could be float, double, int, etc. There is code in THC that acts on real. I’m not sure if that answers your question, please feel free to post a followup. |
st101450 | I will try to put my question in more simple terms:
Let’s say I want to multiply the loss with a weight before doing backward which I modify after every batch.
For example, in below pseudo code, assume all tensors are in GPU and w is just a variable (not a torch tensor)
w = 5
loop for all batches:
loss = get_loss(inp)
loss = w * loss
loss.backward()
opt.step()
w += 1
In this scenario, how is w handled on the GPU. I mean, does it involve a GPU transfer for every iteration since the value of w keeps changing? |
st101451 | My program always stops with no error, just being at a standstill, after working some epochs. And the same program works well in another dataset. By the way, GPU just run this only program. Does anybody know why? Could you give me some advice? I really appreciate that. |
st101452 | Is your script not responding or does it crash with some error message?
Which OS are you using?
Are you using multi-processing, e.g. for data loading (num_workers>=1)?
Is the error reproducible or does it occur randomly? |
st101453 | It hasn’t any error message. Just like being suspended at random epochs.
But it works well in another dataset.
I don’t use any multi-processing, and my OS is Ubuntu 16.04. |
st101454 | I have a tensor like [[1,2],[3,4],[0,2],[2,0]] . I want to find along the columns the indices of the rows which have a particular value. For eg for 0, it should give me [2,3] as 2nd row has value 0 in first column and third for second column. I want to do it for a tensor. How do I go about this? |
st101455 | Solved by jmandivarapu1 in post #3
Method 1:
x=torch.Tensor([[1,2],[3,4],[0,2],[2,0]])
np.transpose(np.argwhere(x==0))
returns
tensor([[2, 0],
[3, 1]]) |
st101456 | You could use binary masking and argmax afterwards:
mask = (tensor==0)
flattened_indices = mask.argmax() |
st101457 | Method 1:
x=torch.Tensor([[1,2],[3,4],[0,2],[2,0]])
np.transpose(np.argwhere(x==0))
returns
tensor([[2, 0],
[3, 1]]) |
st101458 | I use nn.CrossEntropyLoss() to train my classfication model, but when I test the model I got some outputs are negative. Is it normal? I want to get probablity distribution for every class ? what should i do? |
st101459 | class DenseNet(nn.Module):
“”“Densenet-BC model class
Args:
growth_rate (int) - how many filters to add each layer (k in paper)
block_config (list of 4 ints) - how many layers in each pooling block
num_init_features (int) - the number of filters to learn in the first convolution layer
bn_size (int) - multiplicative factor for number of bottle neck layers
(i.e. bn_size * k features in the bottleneck layer)
drop_rate (float) - dropout rate after each dense layer
num_classes (int) - number of classification classes
“””
def __init__(self,
sample_size,
sample_duration,
growth_rate=32,
block_config=(6, 12, 24, 16),
num_init_features=64,
bn_size=4,
drop_rate=0,
num_classes=1000):
super(DenseNet, self).__init__()
self.sample_size = sample_size
self.sample_duration = sample_duration
# First convolution
self.features = nn.Sequential(
OrderedDict([
('conv0',
nn.Conv3d(
3,
num_init_features,
kernel_size=7,
stride=(1, 2, 2),
padding=(3, 3, 3),
bias=False)),
('norm0', nn.BatchNorm3d(num_init_features)),
('relu0', nn.ReLU(inplace=True)),
('pool0', nn.MaxPool3d(kernel_size=3, stride=2, padding=1)),
]))
# Each denseblock
num_features = num_init_features
for i, num_layers in enumerate(block_config):
block = _DenseBlock(
num_layers=num_layers,
num_input_features=num_features,
bn_size=bn_size,
growth_rate=growth_rate,
drop_rate=drop_rate)
self.features.add_module('denseblock%d' % (i + 1), block)
num_features = num_features + num_layers * growth_rate
if i != len(block_config) - 1:
trans = _Transition(
num_input_features=num_features,
num_output_features=num_features // 2)
self.features.add_module('transition%d' % (i + 1), trans)
num_features = num_features // 2
# Final batch norm
self.features.add_module('norm5', nn.BatchNorm2d(num_features))
for m in self.modules():
if isinstance(m, nn.Conv3d):
m.weight = nn.init.kaiming_normal(m.weight, mode='fan_out')
elif isinstance(m, nn.BatchNorm3d) or isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
# Linear layer
self.classifier = nn.Linear(num_features, num_classes)
def forward(self, x):
features = self.features(x)
out = F.relu(features, inplace=True)
last_duration = int(math.ceil(self.sample_duration / 16))
last_size = int(math.floor(self.sample_size / 32))
out = F.avg_pool3d(
out, kernel_size=(last_duration, last_size, last_size)).view(
features.size(0), -1)
out = self.classifier(out)
return out
model = densenet.densenet201(sample_size=112, sample_duration=16, num_classes=400)
and I want to enter a sequence of behaviors **
** torch.Size([20, 3, 16, 112, 112]) batch :20 channel:3 sequence :16 and112x112
**but **
ValueError: expected 4D input (got 5D input)
**and **
Batch dimension becomes 1 torch.Size([1, 3, 16, 112, 112]) and squeeze(0)
**torch.Size([ 3, 16, 112, 112]) **
**But still Error: expected stride to be a single integer value or a list of 2 values to match the convolution dimensions, but got stride=[1, 2, 2]
Traceback (most recent call last):
File “desnext.py”, line 556, in
train()
File “desnext.py”, line 335, in train
output1 = net(X)
File “/home/linbb/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py”, line 491, in call
result = self.forward(*input, **kwargs)
File “/home/linbb/anaconda3/lib/python3.6/site-packages/torch/nn/parallel/data_parallel.py”, line 112, in forward
return self.module(*inputs[0], **kwargs[0])
File “/home/linbb/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py”, line 491, in call
result = self.forward(*input, **kwargs)
File “/home/linbb/C3D_siamese/model/densenet.py”, line 206, in forward
features = self.features(x)
File “/home/linbb/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py”, line 491, in call
result = self.forward(*input, **kwargs)
File “/home/linbb/anaconda3/lib/python3.6/site-packages/torch/nn/modules/container.py”, line 91, in forward
input = module(input)
File “/home/linbb/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py”, line 491, in call
result = self.forward(*input, **kwargs)
File “/home/linbb/anaconda3/lib/python3.6/site-packages/torch/nn/modules/batchnorm.py”, line 45, in forward
self._check_input_dim(input)
File “/home/linbb/anaconda3/lib/python3.6/site-packages/torch/nn/modules/batchnorm.py”, line 193, in _check_input_dim
.format(input.dim()))
ValueError: expected 4D input (got 5D input)
and i found nn.Conv3d(
3,
num_init_features,
kernel_size=7,
stride=(1, 2, 2),
padding=(3, 3, 3),
bias=False)) |
st101460 | Solved by ptrblck in post #2
I’m not sure how _Denseblock is defined, but assuming you are using nn.Conv3d layers, this line might be the issue:
self.features.add_module('norm5', nn.BatchNorm2d(num_features))
Should this be BatchNorm2d or rather BatchNorm3d?
Or is the transition layer flattening your output already? |
st101461 | I’m not sure how _Denseblock is defined, but assuming you are using nn.Conv3d layers, this line might be the issue:
self.features.add_module('norm5', nn.BatchNorm2d(num_features))
Should this be BatchNorm2d or rather BatchNorm3d?
Or is the transition layer flattening your output already? |
st101462 | class _DenseBlock(nn.Sequential):
def __init__(self, num_layers, num_input_features, bn_size, growth_rate,
drop_rate):
super(_DenseBlock, self).__init__()
for i in range(num_layers):
layer = _DenseLayer(num_input_features + i * growth_rate,
growth_rate, bn_size, drop_rate)
self.add_module('denselayer%d' % (i + 1), layer) |
st101463 | I have 3 tensors, say T, Idx, V, where V is a K-long 1D tensor, T has arbitrary shape and numbers and Idx has the same shape as T, but contains index entries of V (that is, it has integers from 1 to K as elements). Now I would like to scatter each element of V into T as respectively stated in Idx. How can I do this? |
st101464 | I’m not sure how you would like to scatter the values into T, as I think just indexing V[Idx] might give you the output:
K = 10
V = torch.randn(K)
T = torch.randn(5, 5)
Idx = torch.empty(T.size(), dtype=torch.long).random_(K)
V[Idx]
Would this work for you? |
st101465 | Hi,
I’m working on switching over some code I have from Keras to Pytorch, and I’m trying to get a network training on CIFAR-100. So far, I’ve been bogged with issues telling me, in some way or another, that my output and target sizes are mismatched or that the batch size and target size are mismatched. The only architecture that works and trains on CIFAR-100 is the one from the “Training a classifier” tutorial (https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html 1)
I can manipulate the number of filters and the model will still successfully train, but changing the kernel size or adding/taking away layers break it so that it won’t train on CIFAR 100 and instead throws an error.
I’ll attach my code for your perusal. Please inform me of any fixes you know!
import torch
import torchvision
import torchvision.transforms as transforms
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR100(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=50,
shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR100(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=50,
shuffle=False, num_workers=2)
classes = (str(i) for i in range(100))
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 60, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(60, 160, 5)
#self.conv3 = nn.Conv2d(160, 160, 5)
self.fc1 = nn.Linear(160 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 100)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
#x = F.relu(self.conv3(x))
x = x.view(-1, 160 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
from torch.autograd import Variable
batch_size=50
for epoch in range(2): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# get the inputs
inputs, labels = data
inputs, labels = Variable(inputs), Variable(labels)
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
prediction = outputs.data.max(1)[1]
accuracy = prediction.eq(labels.data).sum()/batch_size*100
if i % 1000 == 0:
print('Train Step: {}\tLoss: {:.10f}\tAccuracy: {:.10f}'.format(i, loss.data[0], accuracy))
print('Finished Training')
I’ve attached code that runs successfully for me on both Ubuntu 16.04 and Google Colab notebooks. If I uncomment the self.conv3 lines in both init and forward, then the code breaks. If I change the kernel size in any of the convolution lines, the code breaks.
Thanks in advance for your help!
Edit: I can also add/take away Linear layers without any ill effects. |
st101466 | You issues are related to the changed activation size, if you manipulate the conv layers.
If you want to keep the output shapes, you would have to set the padding value for your layers, as it’s currently 0 by default.
E.g. for your current setup with kernel_size=5 and stride=1, you would need to add padding=2 to keep the shape. |
st101467 | I want to implement a typical attention mechanism and I need to compute the dot product between a sequence of vectors and a query vector. I was wondering, which is the best way to implement this operation with batched data.
Suppose that I have the following data:
import torch
batch_size = 32
seq_length = 50
dim = 100
sequence = torch.randn(batch_size, seq_length, dim)
query = torch.randn(batch_size, dim)
What i need as an output is a tensor with dimenionality (batch_size, seq_length).
Edit:
What i am doing now is this:
energies = torch.matmul(sequence, query.unsqueeze(2)) |
st101468 | I think torch.bmm does what you want. But you’ll need to unsqueeze the query first.
i.e.,
query = query.unsqueeze(2)
result = torch.bmm(sequence,query)
and shape of result would be : batch_size, seq_length,1 |
st101469 | Thanks. What is the difference between torch.matmul(sequence, query.unsqueeze(2)) and torch.bmm(sequence,query.unsqueeze(2))? I get the same results, but performance-wise is there any difference? |
st101470 | In thory matmal supports brodcasting so it shouldn’t make copies of the tensor (more memory efficent).
There was a bug report filed for that recently, not sure if it was fixed.
You can time a for loop on both and see what you get. I think the timing will be the same but the memory consumption will be less for matmul (important for big matrices) |
st101471 | I am beginner in pytorch and I tried to use ONNX to transform my Pytorch mode and i have the error : ONNX export failed: Couldn’t export Python operator GridSampler. I tried to solve the problem using https://github.com/onnx/tutorials/blob/master/tutorials/PytorchAddExportSupport.md 115
But it doesn’t work. |
st101472 | I’d like to make an autograd function which will map all values based on a lookup table where each input value bin is mapped to a fixed output value from a lookup table. The mapping table may also depend on a dimension index of the tensor.
What could be a way to achieve that?
(in numpy I would keep using something like searchsorted to find the input value index in the bins, and then return the output value at the index) |
st101473 | My problem is that when I use nn.ReLU my network learns nicely. But when I use nn.Sigmoid then the weights are not updated at all.
after loss.backward() the list(model.parameters())[0].grad shows all 0. while with nn.ReLU they are 0.0000
My input data is OneHot encoded and target is normalize to be between 0 and 1
EDIT:
When i remove the additional layer, then ( w2, b2) then sigmoid also starts to learn. The the fact it has two layers stops it from learning. But why?
class LinearRegressionModel(nn.Module):
def __init__(self, input_dim, output_dim):
torch.manual_seed(1)
super(LinearRegressionModel, self).__init__()
self.input_dim = input_dim
self.output_dim = output_dim
self.w = torch.nn.Parameter(torch.empty(input_dim, 20).uniform_(0, 1))
self.b = torch.nn.Parameter(torch.empty(20).uniform_(0, 1))
self.w2 = torch.nn.Parameter(torch.empty(20, output_dim).uniform_(0, 1))
self.b2 = torch.nn.Parameter(torch.empty(output_dim).uniform_(0, 1))
def activation(self):
return torch.nn.Sigmoid()
def forward(self, x):
x = x.view((x.shape[0], 1, self.input_dim))
exp_w = self.w.expand(x.shape[0], self.w.size(0), self.w.size(1))
out = torch.add(torch.bmm(x, exp_w), self.b)
exp_w2 = self.w2.expand(out.shape[0], self.w2.size(0), self.w2.size(1))
out = self.activation()(torch.add(torch.bmm(out, exp_w2), self.b2))
return out.view(x.shape[0]) |
st101474 | I printed out sum of the wights before and after and they are equal.
I’m not sure what else could I do to debug this. |
st101475 | I am testing seq2seq model on my training data as a sanity check. I implemented masked backpropagation for taking into consideration batching different length sentences together. But even if i remove the masking ,the NN will eventually do well on the training data. So my question is how do i figure out by evaluation if my masking is correct based on the performance seen? Thanks
I commented masking and in the same number of iterations the loss reduced lesser. Is that a valid sanity check?
Also in general is there any other method of validating your implementation other than testing on training data |
st101476 | I am studying the data loading tutorial 19. I am wondering if there is similar utility as repeat() in TensorFlow 3. It is necessary when the size of the dataset is smaller than my training iterations.
Thank you in advance. |
st101477 | Solved by 1Konny in post #2
AFAIK, there are many ways to achieve your goal. Here are two examples.
dloader = DataLoader(dset, batch_size=batch_size, drop_last=True, shuffle=True)
loader = iter(dloader)
while True:
try:
img, label = loader.next()
except StopIteration:
loader = iter(dloader)
im… |
st101478 | AFAIK, there are many ways to achieve your goal. Here are two examples.
dloader = DataLoader(dset, batch_size=batch_size, drop_last=True, shuffle=True)
loader = iter(dloader)
while True:
try:
img, label = loader.next()
except StopIteration:
loader = iter(dloader)
img, label = loader.next()
# ...
and
dloader = DataLoader(dset, batch_size=batch_size, drop_last=True, shuffle=True)
epoch = 3
for e in range(epoch):
for img, label in dloader:
# ... |
st101479 | Hello,
I want to change dynamically bias=True to False after defining the full-layers. How I should do it. |
st101480 | I am not sure if it can be done via nn.Linear class.
But you can define your own custom module with nn.functionalal 2 module.
Somewhere on these lines:
def mylinear(nn.Module):
def __init__(self, nin, nout):
self.W = nn.Parameter(torch.zeros(nin, nout))
self.B = nn.Parameter(torch.zeros(nout))
def forward(self, x, condition):
if condition:
### No bias if condition true
return nn.functional.linear(x, self.W, None)
else:
return nn.functional.linear(x, self.W, self.B)
I think it should do the job |
st101481 | Hi, there
I currently ran into a problem below:
THCudaCheck FAIL file=/opt/v0.4.0/aten/src/THC/THCGeneral.cpp line=702 error=48 : no kernel image is available for execution on the device
Traceback (most recent call last):
File “/var/dl/runtime/script/main.py”, line 102, in
train(model, train_loader, eval_loader, args.epochs, args.output, optim, epoch)
File “/var/dl/runtime/script/tesla_test.zip/train.py”, line 94, in train
File “/opt/conda/envs/pytorch-py3.6/lib/python3.6/site-packages/torch/nn/modules/module.py”, line 491, in call
result = self.forward(*input, **kwargs)
File “/var/dl/runtime/script/tesla_test.zip/test_base_model.py”, line 48, in forward
File “/opt/conda/envs/pytorch-py3.6/lib/python3.6/site-packages/torch/nn/modules/module.py”, line 491, in call
result = self.forward(*input, **kwargs)
File “/var/dl/runtime/script/tesla_test.zip/language_model.py”, line 43, in forward
RuntimeError: cuda runtime error (48) : no kernel image is available for execution on the device at /opt/v0.4.0/aten/src/THC/THCGeneral.cpp:702
When the exact same code ran on local, which is cuda 8.0 environment. It can finish without any error.
However, when I ran on platform, which is cuda 9.0. It gave me such error.
I was wondering what is the difference between the program that can run on 8.0 or 9.0. Don’t it use the same api?
I’am here to ask how can I find the changes that needed to be apply to my program so that it is compatible to 9.0 |
st101482 | I found the reason.
Other discussion say that compatibility should bigger than 3.0, K20 is 3.5.
I thought that would be ok. However, I guess other factor will affect this.
The result is because of the old GPU. Cuda 8.0 on K20 should do the work.
If your device is cuda 9.0 and you don’t have the permission to degrade this version.
I suggest you change your GPU. |
st101483 | I see in some caffe file that some convolution layers are initialized like this:
layer {
bottom: "conv1_1"
top: "conv1_2"
name: "conv1_2"
type: "Convolution"
param {
lr_mult: 1
decay_mult: 1
}
param {
lr_mult: 2
decay_mult: 0
}
convolution_param {
weight_filler {
type: "msra"
}
bias_filler {
type: "constant"
}
num_output: 64
pad: 1
kernel_size: 3
}
}
However, I found pytorch provides kaiming_normal and kaiming_uniform. What is the pytorch way to initialize the convolution layer equally as the caffe way ? |
st101484 | I like to do all my data transforms in numpy. E.g. random crops of very large images/arrays is very simple and fast when using the mmap mode of np.load (no need to load entire array into memory). Who honestly likes PIL?? And anyway it’s useless outside of 2D.
Also not being able to multiply numpy types (e.g. np.log(2)) with torch tensors is a nuisance… yes, I can import math but who actually uses that instead of numpy??
There’s just so much good stuff in numpy and scipy! |
st101485 | I don’t understand your first point. What prevents you from using NumPy to do your data transformations? You can convert between PyTorch tensors and NumPy arrays without having to copy the data using Tensor.numpy() and torch.from_numpy.
We plan to improve operations that mix PyTorch tensors and NumPy types (especially scalars), but it’s probably a month or two away. |
st101486 | As colesbury said, you can do it. You can build your own data loader using the torch.utils.data.Dataset class. You can change the getitem and add your own data transformation using Numpy or any other library. You have more information of how to do it here:
https://pytorch.org/tutorials/beginner/data_loading_tutorial.html#dataset-class 3 |
st101487 | Sure, and that’s what I’ve been doing (apologies for being unclear). It’s just a shame that the built in transforms are all PIL (but I guess that’s just torchvision, not core pytorch?).
Anyway, that was just my late night ranting… I love PyTorch! |
st101488 | A: a 5x11x4 tensor where there are 5 sentences in a batch and 11 is the vocab size for log softmax.
B: a 5x4 tensor which represents the target sentence
I have the lengths of sentences in my batch to be 3,2,1,4 [Max is 4]
Now i want to prevent backprop happening in the portion of sentences beyond the length.
I can think of a way:
I can have a 5x11x4 tensor constructed such that the third dimension is 1 for the length of sentence times and 0 otherwise.
Then i can multiply this element wise with my original tensor and then apply the NLLloss function. This way backprop cannot affect the gradient in those elements.
Does this seem fine or is any other method recommended? |
st101489 | Also ,Even if I calculate the loss matrix first and then make the relevant entries 0 before summing it up, it would be correct right? Thanks |
st101490 | The trick is to build a submatrix with only the entries that correspond to actual words. You can reshape the array to flatten the words and sentences, and only keep the subset. Then the nll only applies to those entries and backprop will do the correct thing. |
st101491 | Even if I flatten the array , how can I eliminate the other entries as earlier it was 5x11x4 . Now it will be 55x4 . Now out of these I want some sentences as 4 is the maximum length. So out of the dimension of 4 I want 2,3,3,4,3 for the 5 sentences in my batch. Do you have an example here please? Thanks |
st101492 | I understand your idea ,but am confused about the approach as shown in my comment below |
st101493 | Sorry, to be clearer, you are flattening the 1st and 3rd dimensions together, then selecting the valid indices to keep. Look at torch.take(), which can be applied after you flatten the array. You’ll have to create a second array with the valid indices to use it. |
st101494 | So you mean, if originally it is 5x11x4 and 5x1x4 is the targets. I can have 20x11 and 20x1 and then if i have the first sentence of 3 words and second of 4 , select indices 0,1,2,4,5,6,7 from both vectors [These need to be calculated based on sentence lengths ]and apply the loss function ? Thanks a lot ! |
st101495 | Hi,
I was wondering if anyone could help me solve this problem. Say I have a minibatch of inputs:
x = torch.randn(N, C_in, iH, iW)
Along with that, I have N unique sets of filters:
W = torch.randn(N, C_out, C_in, kH, kW)
What I’d like is something like:
y = F.batch_conv2d(x, W)
# let's say iH=5, iW=5, kH=1, kW=1, C_out=3, N=10
assert(y.shape == (10, 3, 5, 5))
I’ve tried searching the forum for something similar, but the closest I’ve seen is someone wanting to partition filters along the input channels (i.e. depthwise convolutions, so they ended up using groups). I need the split to be in the minibatch dimension.
Another thing I’ve tried is to use F.conv3d with the minibatch being moved into the iT dimension, but this dimension isn’t preserved in the output since it wasn’t designed for this use case.
Any ideas? |
st101496 | I think I’ve come up with a solution by stacking along the channel dimension and misusing groups:
>>> x1.shape
(1, 3, 5, 5)
>>> x = torch.cat([x1,x2,x3,x4], dim=1)
>>> x.shape
(1, 12, 5, 5)
>>> w = torch.randn(12, 3, 1, 1)
>>> y = F.conv2d(x, w, groups=4)
>>> y.shape
(1, 12, 5, 5)
>>> y.view(4,3,5,5)
I’m not 100% sure this is the right thing to do, so I’d still appreciate any thoughts. |
st101497 | Hello,
I have a 3-D weight tensor W with dimensionality (C,H,H) and 2-D input x (C,H).
My goal is to calculate a sum. \sum_i W_i * x_i and have an output (C,H).
How I can implement it in pytorch? Could not make it work with torch.mul |
st101498 | Could you elaborate a little more on what you want?
octopusyo:
\sum_i W_i * x_i
What is the size of W_i? Wouldn’t it be (H, H)? This doesn’t lead to the correct output size you want so that’s probably not the case. einsum probably does what you want, though: https://pytorch.org/docs/stable/torch.html?highlight=einsum#torch.einsum 1 |
st101499 | Yes, its (H,H) and x_i would be (H,1) so multiplication should work somehow. Just to add a bit of context I am trying to implement time convolution (https://arxiv.org/pdf/1803.05563.pdf 1, section 3.1). the goal is to take a set of vectors (seq_length,H), for each of this vectors extract context (C,H) dimensionality and apply W matrix in a way to combine this context tensor into a vector (H,). In other words, W represents weights combining context vector and is convolved (or maybe proper to say correlated) through the whole sequence. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.