id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st49168 | There is a KL divergence function registered for KL(Uniform || Normal), but not for KL(Uniform || MultivariateNormal). Is there any fundamental reason for this, or it just hasn’t been implemented yet?
Both KL(Normal || Uniform) and KL(MultivariateNormal || Uniform) are infinite since Uniform will have bounded support and you’ll divide by zero anywhere outside that region. I’m just trying to understand if there’s anything that should prevent the KL(Uniform || MultivariateNormal) case. I haven’t tried working through the math yet, I also haven’t found any good references on these derivations. Any pointers are appreciated. |
st49169 | Hello, I am using squeeze() before calculating loss. My code is given below and giving an error
ValueError: Target size (torch.Size([1, 256, 383])) must be the same as input size (torch.Size([1, 1, 256, 383]))
def training_step(self, batch, batch_nb):
x, y = batch
y_hat = self.forward(x)
y_label = y.squeeze(axis = 1)
loss = F.cross_entropy(y_hat, y_label) if self.n_classes > 1 else \
F.binary_cross_entropy_with_logits(y_hat, y_label)
tensorboard_logs = {'train_loss': loss}
return {'loss': loss, 'log': tensorboard_logs}
But, when I am changing the y_label to y only for logist binary_cross_entropy_with_logitsy_hat, y)
Working fine!
Why y_label is showing the error for logits but working fine for cross_entropy.
However, if I do not use squeeze() it gives the same error for both loss functions.
For your kind information
x torch size torch.Size([1, 3, 256, 383])
y torch size torch.Size([1, 3, 256, 383])
y_label torch size torch.Size([1, 256, 383])
Thanks in advance. |
st49170 | Solved by KFrank in post #2
Hi Akib!
cross_entropy() and binary_cross_entropy_with_logits take
targets (your y_label) with differing shapes, and, in fact, with
different numbers of dimensions.
If input (your y_hat) has shape [nBatch, nClass, height, width],
cross_entropy_loss() expects a target with shape
[nBatch, heigh… |
st49171 | Hi Akib!
akib62:
ValueError: Target size (torch.Size([1, 256, 383])) must be the same as input size (torch.Size([1, 1, 256, 383]))
…
But, when I am changing the y_label to y only for logist binary_cross_entropy_with_logitsy_hat, y)
Working fine!
Why y_label is showing the error for logits but working fine for cross_entropy.
cross_entropy() and binary_cross_entropy_with_logits take
targets (your y_label) with differing shapes, and, in fact, with
different numbers of dimensions.
If input (your y_hat) has shape [nBatch, nClass, height, width],
cross_entropy_loss() expects a target with shape
[nBatch, height, width] (no nClass dimension), whose values
are integer class labels that run from 0 to nClass - 1, while
binary_cross_entropy_with_logits() expects a target of shape
[nBatch, nClass, height, width] (the same shape as the input),
whose values are probabilities, that is floats that run from 0.0 to 1.0
(and can be exactly 0.0 and 1.0 in the most common use case).
(Note, using binary_cross_entropy_with_logits() with an nClass
dimension is appropriate for the multi-label, multi-class use case. In
the more common single-label, two-class (binary) use case, you would
not use an nClass dimension, neither nClass = 1 nor nClass = 2.)
y torch size torch.Size([1, 3, 256, 383])
y_label torch size torch.Size([1, 256, 383])
As a side comment, this isn’t consistent with:
y_label = y.squeeze(axis = 1)
In your y, axis = 1 (usually called dim) has size 3, so squeeze()
does nothing, and y_label will have shape [1, 3, 256, 383].
(If y had, instead, shape [1, 1, 256, 383], squeeze (axis = 1)
would, in fact, remove the axis = 1 singleton dimension.)
A comment on your approach: What I think you’re trying to do is
switch to binary_cross_entropy_with_logits when you have
a two-class (binary) problem. While, in principle, your scheme could
be made to work with some complexity and attention to detail, I
don’t think it’s worth the bother.
If you know that you have a binary problem, just build that into your
code. The output of your model (y_hat) and your target will both
have shape [nBatch, height, width] (note no nClass dimension),
and you will use binary_cross_entropy_with_logits().
If you want to write code that can be used for a multi-class problem,
but will work for various numbers of classes, including nClass = 2,
just implement the general multi-class solution using
cross_entropy_loss(). (Again, in this case, the output of your
model should have shape [nBatch, nClass, height, width],
and your target should have shape [nBatch, height, width].)
cross_entropy_loss() works just fine for the nClass = 2 (binary)
case, and any minor efficiency gains you might get by switching
to binary_cross_entropy_with_logits() when nClass = 2
just aren’t worth the hassle.
Best.
K. Frank |
st49172 | Hi @KFrank, if I want to use the MSE loss instead of cross_entropy then how I have to write the code?
More specifically, are there any variants for MSE loss. For example, we are using cross_entrpoy for binary-class classification and logits for multi-class classification.
So, MSE loss has 2 types (one for binary class nad another for multi-class)?
Sorry, for this kind of silly questions! |
st49173 | Hi Akib!
akib62:
if I want to use the MSE loss instead of cross_entropy then how I have to write the code?
It is a BAD idea to use MSELoss for classification. Here is the
reason: MSELoss cares about how far the prediction is from the
target. But in a classification problem you generally don’t have
that notion of distance.
If a tree is 60 years old, I have done better if I predict it to be 55
years old than if I predict it to be 40 years old. Both predictions
are wrong, but the 40-years-old prediction is worse. MSELoss
takes this into account.
But if I classify a bird as fish, that’s wrong, but no better or worse
than classifying the bird as a reptile. There’s no sense of distance
or some concept of a class being closer to some classes and farther
from others. (Conceptually there could be, but there is not in the
typical pytorch classification use case.)
However …
If you want to use MSELoss for classification, you would convert
your integer class labels to floats (so target would be a FloatTensor
of shape [nBatch], with no nClass dimension). Your model would
have a single output so it would output batch predictions of shape
[nBatch, 1] which you would squeeze() to get shape [nBatch].
Your (floating-point) target would have values running from 0.0
to nClass - 1. If your target value were, say, 2.0, then a predicted
value of 2.0 would be perfect, and MSELoss would return 0.0. A
prediction of 1.95 or 2.05 would be quite good, while a prediction
of 0.0 (or even -1.0) or 4.0 would be worse.
But for a classification problem, for a target of 2.0, would you
really consider a prediction of 0.0 to be worse than a prediction of
1.0, or are they both just wrong because they both predict the wrong
class?
Best.
K. Frank |
st49174 | Hi @KFrank thank you very much. No, I am not thinking to use MSE for classification problems. I am thinking it to use for regression related problem. |
st49175 | Which one is a better practice to detach a tensor without expanding CPU memory too much? x.detach() or x.cpu() ?
I found out that if I perform x.cpu(), my memory expand quickly and soon reach memory limit error in slurm. |
st49176 | Hi,
The two have very different (and non-overlapping) effect:
x.cpu() will do nothing at all if your Tensor is already on the cpu and otherwise create a new Tensor on the cpu with the same content as x. Note that his op is differentiable and gradient will flow back towards x!
y = x.detach() breaks the graph between x and y. But y will actually be a view into x and share memory with it. |
st49177 | I have parameterized a filtering problem, so that I essentially only have to make a product and sum between two arrays. I want to do this on the GPU, using pytorch to accelerate this.
Right now my code is:
kernels_cuda = torch.cuda.FloatTensor(kernels) # (32,32,159,21,21,21) float32 array
sub_matrices_cuda = torch.cuda.FloatTensor(sub_matrices) # (32,32,159,21,21,21) float32 array
out = (sub_matrices_cuda*kernels_cuda).sum(dim=[3,4,5]).cpu().numpy()
torch.cuda.synchronize()
This takes about 3.0s right now, and almost all the time is spent on sending the data to the GPU. Is there anyway I can speed up my code?
My hardware is: Titan RTX, Intel Xeon W2133 and 2666 MHz DDR4 RAM. I have the feeling, that I should be able to exceed this on this hardware? |
st49178 | Hi,
According to this thread 1, each worker loads a single batch. The more number of workers essentially means it preloads “future” data in memory.
If that’s the case, then is there any benefit of using the iter/next 2 approach to read batches from a loader?
image806×176 47.2 KB |
st49179 | If you are using the iter/next approach, the DataLoader iterator might already start preloading the data once you call the next op on it, so you could potentially overlap the loading of the first batches with other operations in your main script.
Such an approach can be seen here 4. |
st49180 | Thanks @ptrblck, I can confirm that in the iter/next approach, the dataloader behaves as expect and preloads future batches when number of workers > 0. My observation is based on a vanilla dataloader from torch. |
st49181 | There may exist a problem of torch.nn.functional.embedding
print(torch.nn.functional.embedding(torch.LongTensor([[0,2,0,5]]), torch.rand(10, 3), padding_idx=0))
The output embedding vectors are not zero if the corresponding index=0. |
st49182 | Solved by RoySadaka in post #2
@zqu1992
I can confirm that, and this also happens with the nn.embedding version:
predefined_weights = torch.rand(10, 3)
emb = torch.nn.Embedding(num_embeddings=10, embedding_dim=3, padding_idx=0, _weight=predefined_weights)
emb(torch.LongTensor([[0,2,0,5]]))
It “pads” with the vector at idx=0 … |
st49183 | @zqu1992
I can confirm that, and this also happens with the nn.embedding version:
predefined_weights = torch.rand(10, 3)
emb = torch.nn.Embedding(num_embeddings=10, embedding_dim=3, padding_idx=0, _weight=predefined_weights)
emb(torch.LongTensor([[0,2,0,5]]))
It “pads” with the vector at idx=0 from predefined_weights instead of a zero vector.
From the code, it looks like it zeros-out the vector in padding_idx in reset_parameters but only
if _weight is None
otherwise, it uses the given _weight parameter.
IMO, the behavior is fine and the documentation should adjust, cause if you provide your own weights, you should get full control over the weights, including the padding vector.
Roy. |
st49184 | Thanks a lot.
I agree the predefined weight can better control the behavior.
But the relevant definition of the argument _weight should be added in the official document anyway. |
st49185 | Would you mind creating an issue on GitHub with this suggestion?
Also, would you or @RoySadaka be interested in providing the PR for it? |
st49186 | opened:
github.com/pytorch/pytorch
padding_idx and provided weights in nn.Embedding and nn.functional.embedding 15
opened
Oct 20, 2020
RoySadaka
1) nn.Embedding documentation says:
padding_idx (int, optional): If given, pads the output with the embedding vector at :attr:padding_idx
(initialized to zeros) whenever it... |
st49187 | Hello, community!
I’m writing pytorch code that uses a lot of logarithms, and it’s slower than ideal. When writing raw CUDA code, I’ve been able to speed things up using CUDA intrinsics, which gives approximate logarithms at the cost of a small amount of accuracy:
docs.nvidia.com
CUDA Math API :: CUDA Toolkit Documentation 1
Is there any way to use these approximations within pytorch? I couldn’t see any options for torch.log, but maybe the functionality is elsewhere. |
st49188 | You could create a custom CUDA extension as described here 1 and use it in your PyTorch model. |
st49189 | Hello everyone. How can I use callback in pytorch for saving end of epoch in google colab? |
st49190 | Higher-level APIs such as Ignite or Lightning provide these type of hooks, so you should check them out. |
st49191 | class RNNnet(nn.Module):
def init(self,input_size,hidden_size,output_size,n_layers=1):
super(self).init()
self.input_size=input_size
self.hidden_size=hidden_size
self.output_size=output_size
self.n_layers=n_layers
self.encoder=nn.Embedding(input_size,hidden_size)
self.gru=nn.GRU(input_size,hidden_size,n_layers)
self.decoder=nn.Linear(hidden_size,output_size)
def forward(self,input,hidden):
input=self.encoder(input.reshape(1,-1))
output,hidden=self.gru(input.view(1,1,-1),hidden)
output=self.decoder(output.view(1,-1))
return output,hidden
def init_hidden(self):
return torch.zeros(self.n_layers,1,self.hidden_size) |
st49192 | What is your question about this module?
Note, you can find general information in the docs 2. |
st49193 | I have an RTX 3080 and I want to use it to train a deep learning model. Both CUDA and Pytorch I installed are version 10.2. However, when I train this deep learning model, it freezes when loaded into CUDA. Is there any solution? |
st49194 | Solved by ptrblck in post #2
If you’ve installed the CUDA10.2 binaries, the first CUDA operation would call into the JIT and compile the kernels for your compute architecture.
You could use the nightly binaries, which are build with CUDA11 and support sm_80 via:
conda install pytorch torchvision cudatoolkit=11.0 -c pytorch-ni… |
st49195 | If you’ve installed the CUDA10.2 binaries, the first CUDA operation would call into the JIT and compile the kernels for your compute architecture.
You could use the nightly binaries, which are build with CUDA11 and support sm_80 via:
conda install pytorch torchvision cudatoolkit=11.0 -c pytorch-nightly |
st49196 | I created a model like resnet but for tabular data here is model architecture
class Model(nn.Module): # <-- Update
def __init__(self, num_features, num_targets, hidden_size):
super(Model, self).__init__()
head1 = nn.Sequential(
nn.BatchNorm1d(num_features),
nn.Dropout(0.2),
nn.utils.weight_norm(nn.Linear(num_features, hidden_size)),
nn.ReLU()
)
head2 = nn.Sequential(
nn.BatchNorm1d(hidden_size),
nn.Dropout(0.25),
nn.utils.weight_norm(nn.Linear(hidden_size, hidden_size)),
nn.ReLU()
)
head3 = nn.Sequential(
nn.BatchNorm1d(hidden_size),
nn.Dropout(0.3),
nn.utils.weight_norm(nn.Linear(hidden_size, num_targets))
)
def forward(self, x):
head1_out = head1(x)
concat_1 = torch.cat((x, head1_out), dim=1)
head2_out = head2(concat)
concat_2 = torch.cat((x, head2_out), dim=1)
out = head3(concat_2)
return out
When I initialize it it doesn’t give me any error but doesn’t show any output either.
Any help or suggestions would be appreciated.
Thanks. |
st49197 | Solved by Hacking_Pirate in post #6
I figured it out. I had to write self.head1. |
st49198 | Could you explain what kind of output you are expecting and how you are initializing the model?
If you are using:
model = Model(num_features, num_targets, hidden_size)
then model should be the object of your custom Model class. |
st49199 | Yes, this is how I am initializing it. And I am working with a multilabel classification problem |
st49200 | I don’t know exactly what the issue is.
Could you explain, if you are seeing any errors or what you would expect, which is not working at the moment? |
st49201 | Oh sorry, I completely missed this issue and couldn’t figure out what the problem is.
I’m glad you’ve figured it out. |
st49202 | I have a feature map of size NxCxWxH, where N is the batch size, C is the number of channels, and W and H are width and the height respectively.
Lets consider features (a_i) from this feature map. Each feature has a dimension of Cx1x1. I need to find out the following for each of the feature: \sum_j a_i*a_j.
So the output I am expecting is Nx1xWxH, where each element represents the sum of the dot product between the feature at that location and all the other features. How to do it? |
st49203 | Create a map sized CxWxH of the feature a_i repeated WxH times, then calculate a dot product along the channel dimension between that and your original feature map of size CxWxH (let’s call it A):
A_rep = a_i.repeat((1,W,H))
result = (A_rep*A).sum(axis=0)
I ignored N for simplicity but the concept is similar with N>1 |
st49204 | I’m using Linux, Ubuntu 18.04 with python3.6.9 and have a problem with the torch.max() function when using torch==1.6.0.
With torch==1.5.0. It works correctly:
steph@steph-desktop:~$ python3
Python 3.6.9 (default, Jul 17 2020, 12:50:27)
[GCC 8.4.0] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
import torch
torch.version
‘1.5.0’
a=torch.randn(1,3,5)
a.max(1)
torch.return_types.max(
values=tensor([[ 1.4852, 1.0638, -0.7425, -0.4036, 0.8044]]),
indices=tensor([[1, 2, 0, 0, 2]]))
quit()
Then I pip3 uninstall torch==1.5.0 and pip3 install torch==1.6.0 --user
Then I do the same thing as above:
steph@steph-desktop:~$ python3
Python 3.6.9 (default, Jul 17 2020, 12:50:27)
[GCC 8.4.0] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
import torch
torch.version
‘1.6.0’
a=torch.randn(1,3,5)
a.max(1)
Illegal instruction (core dumped)
Then I pip3 unstall torch==1.6.0 and pip3 install torch==1.5.0 --user again.
steph@steph-desktop:~$ python3
Python 3.6.9 (default, Jul 17 2020, 12:50:27)
[GCC 8.4.0] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
import torch
torch.version
‘1.5.0’
a=torch.randn(1,3,5)
a.max(1)
torch.return_types.max(
values=tensor([[ 0.2041, 1.7543, 0.4384, 0.7029, -0.3107]]),
indices=tensor([[1, 1, 1, 0, 0]]))
quit()
steph@steph-desktop:~$
That is, we are back to normal.
Then I went on Google colab. Created a jupyter notebook. Imported torch. The imported version is torch==1.6.0. And there… it works.
So, is it a problem on my side or is it a problem with the torch==1.6.0 version for linux? |
st49205 | Hi,
It does work fine on my side as well…
Do you have any specific configurations on your machine for libraries like openMP, blas, libc?
Also what kind of CPU do you have?
Can you try with a different version of python to see if it changes anything as well? |
st49206 | Moving from python3.6.9 to python3.7.5 doesn’t help.
With torch==1.6.0 and python3.7.5:
steph@steph-desktop:~$ python3.7
Python 3.7.5 (default, Nov 7 2019, 10:50:52)
[GCC 8.3.0] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
import torch
torch.version
‘1.6.0’
a=torch.randn(1,3,5)
a.max(1)
Illegal instruction (core dumped)
While with torch==1.5.0 and python3.7.5:
steph@steph-desktop:~$ python3.7
Python 3.7.5 (default, Nov 7 2019, 10:50:52)
[GCC 8.3.0] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
import torch
torch.version
‘1.5.0’
a=torch.randn(1,3,5)
a.max(1)
torch.return_types.max(
values=tensor([[ 1.0653, 1.4195, 2.4267, -0.1173, 1.0128]]),
indices=tensor([[1, 0, 1, 0, 1]]))
quit()
steph@steph-desktop:~$
LIBRARIES, KERNEL AND PROCESSOR:
Libraries:
(No “fancy” installs for these libraries)
libc6: version 2.27-3ubuntu1.2
libopenmp: version 2.1.1-8
liblas3: version 3.7.1-4ubuntu1
Kernel:
steph@steph-desktop:~$ uname -a
Linux steph-desktop 5.4.0-42-generic #46~18.04.1-Ubuntu SMP Fri Jul 10 07:21:24 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
For the cpu:
Indeed, the problem might well be my (a bit old) processor which doesn’t support the SSE4 instruction set but only SSE2.
Does the processor have to support the SSE4 instruction set for torch.max() function to work properly?
I know that I can’t install tensorflow because of incompatibility of my cpu with SSE4.
steph@steph-desktop:~$ lscpu
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 6
On-line CPU(s) list: 0-5
Thread(s) per core: 1
Core(s) per socket: 6
Socket(s): 1
NUMA node(s): 1
Vendor ID: AuthenticAMD
CPU family: 16
Model: 10
Model name: AMD Phenom™ II X6 1065T Processor
Stepping: 0
CPU MHz: 1560.909
CPU max MHz: 2900.0000
CPU min MHz: 800.0000
BogoMIPS: 5827.05
Virtualization: AMD-V
L1d cache: 64K
L1i cache: 64K
L2 cache: 512K
L3 cache: 6144K
NUMA node0 CPU(s): 0-5
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm 3dnowext 3dnow constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf pni monitor cx16 popcnt lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt cpb hw_pstate vmmcall npt lbrv svm_lock nrip_save pausefilter |
st49207 | Hi,
Can you please try running your code with ATEN_CPU_CAPABILITY=default?
Also, if you have gdb installed on your machine, can you please run:
gdb /usr/bin/python -ex "set args -c 'import torch;print(torch.rand(1,2,5).max(1))'" -ex "run" -ex "bt"
And share the output here? |
st49208 | Hi,
Regarding ATEN_CPU_CAPABILITY:
steph@steph-desktop:~$ export ATEN_CPU_CAPABILITY=default
steph@steph-desktop:~$ echo $ATEN_CPU_CAPABILITY
default
steph@steph-desktop:~$ python3.7
Python 3.7.5 (default, Nov 7 2019, 10:50:52)
[GCC 8.3.0] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
import torch
torch.version
‘1.6.0’
a=torch.randn(1,3,5)
a.max(1)
Illegal instruction (core dumped)
Regarding gdb output:
For python3.7.5 and torch==1.6.0 the gdb output is:
steph@steph-desktop:~$ gdb python3.7 -ex “set args -c ‘import torch;print(torch.rand(1,2,5).max(1))’” -ex “run” -ex “bt”
GNU gdb (Ubuntu 8.1-0ubuntu3.2) 8.1.0.20180409-git
Copyright © 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later …
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type “show copying”
and “show warranty” for details.
This GDB was configured as “x86_64-linux-gnu”.
Type “show configuration” for configuration details.
For bug reporting instructions, please see:
.
Find the GDB manual and other documentation resources online at:
.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Registered pretty printers for UE4 classes
Reading symbols from python3.7...(no debugging symbols found)...done.
Starting program: /usr/bin/python3.7 -c 'import torch;print(torch.rand(1,2,5).max(1))'
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
[New Thread 0x7fffa5778700 (LWP 3552)]
[New Thread 0x7fffa4f77700 (LWP 3553)]
[New Thread 0x7fffa2776700 (LWP 3554)]
[New Thread 0x7fff9df75700 (LWP 3555)]
[New Thread 0x7fff9b774700 (LWP 3556)]
Thread 1 “python3.7” received signal SIGILL, Illegal instruction.
0x00007fffe4c04409 in at::TensorIteratorConfig::declare_static_shape(c10::ArrayRef, long) ()
from /home/steph/.local/lib/python3.7/site-packages/torch/lib/libtorch_cpu.so
#0 0x00007fffe4c04409 in at::TensorIteratorConfig::declare_static_shape(c10::ArrayRef, long) ()
from /home/steph/.local/lib/python3.7/site-packages/torch/lib/libtorch_cpu.so
#1 0x00007fffe54e66f7 in at::native::(anonymous namespace)::max_kernel_impl ()
from /home/steph/.local/lib/python3.7/site-packages/torch/lib/libtorch_cpu.so
#2 0x00007fffe449d83e in void at::native::DispatchStub<void ()(at::Tensor&, at::Tensor&, at::Tensor const&, long, bool), at::native::max_stub>::operator()<at::Tensor&, at::Tensor&, at::Tensor const&, long&, bool&>(c10::DeviceType, at::Tensor&, at::Tensor&, at::Tensor const&, long&, bool&) () from /home/steph/.local/lib/python3.7/site-packages/torch/lib/libtorch_cpu.so
#3 0x00007fffe4499bd2 in at::native::max_out(at::Tensor&, at::Tensor&, at::Tensor const&, long, bool) ()
from /home/steph/.local/lib/python3.7/site-packages/torch/lib/libtorch_cpu.so
#4 0x00007fffe449a77f in at::native::max(at::Tensor const&, long, bool) ()
from /home/steph/.local/lib/python3.7/site-packages/torch/lib/libtorch_cpu.so
#5 0x00007fffe48d3047 in at::TypeDefault::max_dim(at::Tensor const&, long, bool) ()
from /home/steph/.local/lib/python3.7/site-packages/torch/lib/libtorch_cpu.so
#6 0x00007fffe4751544 in c10::impl::wrap_kernel_functor_unboxed_<c10::impl::detail::WrapFunctionIntoRuntimeFunctor_<std::tuple<at::Tensor, at::Tensor> ()(at::Tensor const&, long, bool), std::tuple<at::Tensor, at::Tensor>, c10::guts::typelist::typelist<at::Tensor const&, long, bool> >, std::tuple<at::Tensor, at::Tensor> (at::Tensor const&, long, bool)>::call(c10::OperatorKernel*, at::Tensor const&, long, bool) () from /home/steph/.local/lib/python3.7/site-packages/torch/lib/libtorch_cpu.so
#7 0x00007fffe47ebf54 in at::max(at::Tensor const&, long, bool) ()
from /home/steph/.local/lib/python3.7/site-packages/torch/lib/libtorch_cpu.so
#8 0x00007fffe648b9e2 in torch::autograd::VariableType::max_dim(at::Tensor const&, long, bool) ()
from /home/steph/.local/lib/python3.7/site-packages/torch/lib/libtorch_cpu.so
#9 0x00007fffe4751544 in c10::impl::wrap_kernel_functor_unboxed_<c10::impl::detail::WrapFunctionIntoRuntimeFunctor_<std::tup—Type to continue, or q to quit—
le<at::Tensor, at::Tensor> ()(at::Tensor const&, long, bool), std::tuple<at::Tensor, at::Tensor>, c10::guts::typelist::typelist<at::Tensor const&, long, bool> >, std::tuple<at::Tensor, at::Tensor> (at::Tensor const&, long, bool)>::call(c10::OperatorKernel, at::Tensor const&, long, bool) () from /home/steph/.local/lib/python3.7/site-packages/torch/lib/libtorch_cpu.so
#10 0x00007fffe4974944 in at::Tensor::max(long, bool) const ()
from /home/steph/.local/lib/python3.7/site-packages/torch/lib/libtorch_cpu.so
#11 0x00007ffff3de9d33 in torch::autograd::THPVariable_max(_object*, _object*, _object*) ()
from /home/steph/.local/lib/python3.7/site-packages/torch/lib/libtorch_python.so
#12 0x00000000004d6194 in _PyMethodDescr_FastCallKeywords ()
#13 0x0000000000551d89 in _PyEval_EvalFrameDefault ()
#14 0x000000000054b302 in _PyEval_EvalCodeWithName ()
#15 0x0000000000530aef in PyRun_StringFlags ()
#16 0x000000000063138d in PyRun_SimpleStringFlags ()
#17 0x000000000065473d in ?? ()
#18 0x000000000065486e in _Py_UnixMain ()
#19 0x00007ffff7a05b97 in __libc_start_main (main=0x4b84d0 , argc=3, argv=0x7fffffffdba8, init=,
fini=, rtld_fini=, stack_end=0x7fffffffdb98) at …/csu/libc-start.c:310
#20 0x00000000005df80a in _start ()
(gdb) quit
A debugging session is active.
Inferior 1 [process 3542] will be killed.
Quit anyway? (y or n) y
steph@steph-desktop:~$
While with python3.7.5 and torch==1.5.0 installed, the gdb output is:
steph@steph-desktop:~$ gdb python3.7 -ex “set args -c ‘import torch;print(torch.rand(1,2,5).max(1))’” -ex “run” -ex “bt”
GNU gdb (Ubuntu 8.1-0ubuntu3.2) 8.1.0.20180409-git
Copyright © 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later (link)
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type “show copying”
and “show warranty” for details.
This GDB was configured as “x86_64-linux-gnu”.
Type “show configuration” for configuration details.
For bug reporting instructions, please see:
(link).
Find the GDB manual and other documentation resources online at: (link)
For help, type “help”.
Type “apropos word” to search for commands related to “word”…
Registered pretty printers for UE4 classes
Reading symbols from python3.7…(no debugging symbols found)…done.
Starting program: /usr/bin/python3.7 -c ‘import torch;print(torch.rand(1,2,5).max(1))’
[Thread debugging using libthread_db enabled]
Using host libthread_db library “/lib/x86_64-linux-gnu/libthread_db.so.1”.
[New Thread 0x7fffa59f8700 (LWP 3197)]
[New Thread 0x7fffa51f7700 (LWP 3198)]
[New Thread 0x7fffa09f6700 (LWP 3199)]
[New Thread 0x7fff9e1f5700 (LWP 3200)]
[New Thread 0x7fff9b9f4700 (LWP 3201)]
[New Thread 0x7fff92dcd700 (LWP 3203)]
[New Thread 0x7fff925cc700 (LWP 3204)]
[New Thread 0x7fff91dcb700 (LWP 3205)]
[New Thread 0x7fff915ca700 (LWP 3206)]
[New Thread 0x7fff90dc9700 (LWP 3207)]
torch.return_types.max(
values=tensor([[0.3803, 0.9634, 0.5299, 0.9652, 0.6461]]),
indices=tensor([[1, 1, 0, 0, 0]]))
[Thread 0x7fff9b9f4700 (LWP 3201) exited]
[Thread 0x7fff90dc9700 (LWP 3207) exited]
[Thread 0x7fff915ca700 (LWP 3206) exited]
[Thread 0x7fff91dcb700 (LWP 3205) exited]
[Thread 0x7fff925cc700 (LWP 3204) exited]
[Thread 0x7fff92dcd700 (LWP 3203) exited]
[Thread 0x7fff9e1f5700 (LWP 3200) exited]
[Thread 0x7fffa09f6700 (LWP 3199) exited]javascript:;
[Thread 0x7fffa51f7700 (LWP 3198) exited]
[Thread 0x7fffa59f8700 (LWP 3197) exited]
[Inferior 1 (process 3187) exited normally]
No stack.
(gdb) quit |
st49209 | Thank you for the quick reply. Can you please also issue disassemble command when exception is hit in gdb, by executing:
gdb python3.7 -ex “set args -c ‘import torch;print(torch.rand(1,2,5).max(1))’” -ex “run” -ex “bt” -ex “disassemble” |
st49210 | Sorry, the file was incomplete…
So, here it is again:
Dropbox
dump_2.txt 4
Shared with Dropbox |
st49211 | Thank you for the detailed repro instructions, filed https://github.com/pytorch/pytorch/issues/43300 42 |
st49212 | I’ll keep an eye on github about this issue.
Thank you very much for having spent some time on this.
Best regards,
Stéphane |
st49213 | Did anyone fix this?
Have the same problem, torch==1.6.0 and core dumps when using torch.max() |
st49214 | The issue should be fixed in version 1.7
See https://github.com/pytorch/pytorch/issues/43300 20 |
st49215 | Hi,
Looking for ways to convert a custom tensorflow trained model to pytorch equivalent that can be fine-tuned further in pytorch.
Thanks |
st49216 | I don’t know if there are tools to convert the TF model automatically to PyTorch and think you would have to rewrite it manually in PyTorch.
A definition of a custom model can be found in this tutorial 365 and might be a good starter.
Once the model architecture is created in PyTorch, you could convert the pretrained weights from TF to PyTorch. @tom and I did the same for the StyleGAN model in this notebook 483 so you could take a look at the implementation. |
st49217 | Hi @ptrblck, thanks that helped. I was able extract the sequence of layer information and corresponding weights using tf.all_variables().
The following are the components I am trying to transfer weights from tensorflow to pytorch now,
TF layers and weights:
Batchnorm layer: BatchNorm/beta:0, BatchNorm/moving_mean:0 and moving_variance:0
Conv layer: Conv/weights:0 and Conv/biases:0
Conv2d_transpose layer: Conv2d_transpose_1/weights:0 and Conv2d_transpose_1/biases:0
Can I just create the same sequence of layers in pytorch and assign these? Will there be computational flow differences between pytorch and tensorflow?
Wondering if you have idea on conversion for those particular layers. |
st49218 | The notebook also shows how to transfer these parameter to PyTorch.
In particular, check out weight_translate, which permutes the conv filters etc. to match the expected shape for PyTorch layers. |
st49219 | In the following,
x_6 = torch.cat((x_1, x_2_1, x_3_1, x_5_1), dim=-3)
Sizes of tensors x_1, x_2_1, x_3_1, x_5_1 are
torch.Size([1, 256, 7, 7])
torch.Size([1, 256, 7, 7])
torch.Size([1, 256, 7, 7])
torch.Size([1, 256, 7, 7]) respectively.
The size of x_6 turns out to be torch.Size([1, 1024, 7, 7])
I couldn’t understand this concatenation along a negative dimension(-3 in this case).
What exactly is happening here?
How does the same go if dim = 3?
Is there any constraint on dim for a given set of tensors? |
st49220 | Solved by ptrblck in post #2
Negative dimensions start from the end, so -1 would be the last dimension, -2 the one before etc.:
[1, 256, 7, 7]
pos dim: 0, 1, 2, 3
neg dim: -4, -3, -2, -1
If you are passing dimensions outside of this range, you should get an error:
IndexError: Dimension out of range (expected to be… |
st49221 | Negative dimensions start from the end, so -1 would be the last dimension, -2 the one before etc.:
[1, 256, 7, 7]
pos dim: 0, 1, 2, 3
neg dim: -4, -3, -2, -1
If you are passing dimensions outside of this range, you should get an error:
IndexError: Dimension out of range (expected to be in range of [-4, 3], but got -5)
dim=3 would correspond to dim=-1. |
st49222 | On a single machine I started getting random segmentation faults which causes a core dump. I have seen some segmentation faults in other scenarios which were caused by invalid array indexing in the C++ backbone. I don’t think my problem is caused by this though because it is happening randomly in stably training models. I have seen it happen the same way while training many different models too so I am sure it is not something to do with a specific implementation. Here is an example of the output I am seeing…
d=1.01e+7, loss=2.15e+10]
17%|██████████████████▌
| 8384/50000 [03:29<17:17, 40.11it/s, bpd=9.33, loss=1.99e+4]Segmentation fault (core dumped)
that is a tqdm progress bar just followed with the core dump and no error message. I am not sure how to diagnose what is happening here. Could this be a hardware issue?
Versions:
Pytorch: 1.6.0
OS: Ubuntu 20.04
GPU: GeForce GTX 1080TI 11GB |
st49223 | deltaskelta:
Could this be a hardware issue?
Might be the case, but I would start by trying to isolate a particular software setup which might be causing this issue.
E.g. could you run the same workload in an Ubuntu18.04 docker container and check, if the behavior stays the same?
If so, could you run it with:
gdb --args python script.py args
run
...
bt
and post the backtrace here? |
st49224 | def build_model(n_features, n_features_2, n_labels, label_smoothing = 0.0005):
input_1 = layers.Input(shape = (n_features,), name = 'Input1')
input_2 = layers.Input(shape = (n_features_2,), name = 'Input2')
head_1 = Sequential([
layers.BatchNormalization(),
layers.Dropout(0.2),
layers.Dense(512, activation="elu"),
layers.BatchNormalization(),
layers.Dense(256, activation = "elu")
],name='Head1')
input_3 = head_1(input_1)
input_3_concat = layers.Concatenate()([input_2, input_3])
head_2 = Sequential([
layers.BatchNormalization(),
layers.Dropout(0.3),
layers.Dense(512, "relu"),
layers.BatchNormalization(),
layers.Dense(512, "elu"),
layers.BatchNormalization(),
layers.Dense(256, "relu"),
layers.BatchNormalization(),
layers.Dense(256, "elu")
],name='Head2')
input_4 = head_2(input_3_concat)
input_4_avg = layers.Average()([input_3, input_4])
head_3 = Sequential([
layers.BatchNormalization(),
layers.Dense(256, kernel_initializer='lecun_normal', activation='selu'),
layers.BatchNormalization(),
layers.Dense(n_labels, kernel_initializer='lecun_normal', activation='selu'),
layers.BatchNormalization(),
layers.Dense(n_labels, activation="sigmoid")
],name='Head3')
output = head_3(input_4_avg) |
st49225 | Solved by ptrblck in post #2
For a general introduction to writing custom PyTorch models, have a look at this tutorial.
To convert the TF model to PyTorch you should initialize all modules in the __init__ method of your custom model and use these modules in the forward method.
The layers are almost equivalently named, i.e. la… |
st49226 | For a general introduction to writing custom PyTorch models, have a look at this tutorial 3.
To convert the TF model to PyTorch you should initialize all modules in the __init__ method of your custom model and use these modules in the forward method.
The layers are almost equivalently named, i.e. layers.BatchNormalization (assuming it’s working on temporal data) would correspond to nn.BatchNorm1d, while e.g. layers.Dense corresponds to nn.Linear.
The “functional” layers, such as layers.Concatenate can be applied in the forward pass of your model using:
input_3_concat = torch.cat((input_2, input_3)) |
st49227 | I want to build a CNN for classifying time series data with high accuracy. The data has been windowed into chunks of 12 time steps, it looks like this:
[0. , 0.00167084, 0.00568087, ..., 0.60016708, 0.55238095,
0.68421053],
[0.00167084, 0.00568087, 0.146533 , ..., 0.55238095, 0.68421053,
0.6566416 ],
Consider my use of CNN for such data an experiment.
Here are 2 architectures that I have tried. But they have poor accuracy.
#Architecture 1:
init:
self.conv1 = nn.Conv1d(1,3, kernel_size = 2, stride = 1, padding =1)
self.bn1 = nn.BatchNorm1d(3)
self.maxpool1 = nn.MaxPool1d(kernel_size=2, stride=2, padding=1)
self.dropout1 = nn.Dropout(0.3)
self.conv2 = nn.Conv1d(3, 5, kernel_size=2, stride=2, padding=1)
self.bn2 = nn.BatchNorm1d(5)
self.dropout2 = nn.Dropout(0.3)
self.conv3 = nn.Conv1d(5, 5, kernel_size=2, stride=1, padding=1)
self.bn3 = nn.BatchNorm1d(5)
self.dropout3 = nn.Dropout(0.3)
self.fc = nn.Linear(5, num_classes)
forward:
x = self.conv1(x)
x = self.bn1(x)
x = F.relu(x)
x = self.maxpool1(x)
x = self.dropout1(x)
x = self.conv2(x)
x = self.bn2(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.conv3(x)
x = self.bn3(x)
x = F.relu(x)
x = self.dropout3(x)
x = torch.mean(x, dim = 2)
x = self.fc(x)
#Architecture 2: similar to PyTorch MNIST example
init:
self.conv1 = nn.Conv1d(1,3, kernel_size = 2, stride = 1, padding =1)
self.conv2 = nn.Conv1d(3, 5, kernel_size=2, stride=2, padding=1)
self.maxpool1 = nn.MaxPool1d(kernel_size=2, stride=2, padding=1)
self.dropout1 = nn.Dropout(0.3)
self.dropout2 = nn.Dropout(0.3)
self.fc1= nn.Linear(20, 12)
self.fc2= nn.Linear(12, num_classes)
forward:
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = self.maxpool1(x)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
Could anyone suggest what I am doing fundamentally wrong here?
P.S. I want to classify them into 3 classes |
st49228 | I can’t see any fundamental flaws in your models.
You could e.g. apply the relu before the batchnorm layers in your first model, but this might not change too much.
I would recommend to try to overfit a small dataset, e.g. just 10 samples, and make sure your model is able to do so by playing around with the hyperparameters.
If that’s not working, there might be another issue in your training routine, such as forgetting to zero out the gradients. |
st49229 | I will give that a try
@ptrblck What are your thoughts on using batch norm as well as dropout? I read that batch norm acts like a regularizer so that we dont need dropout. |
st49230 | I’ve read the same a couple of times, but would recommend to run a few experiments to make sure this claim isn’t only valid for some mentioned use cases. |
st49231 | Hi,
I am trying to train a model using k80.
I get this error
RuntimeError: CUDA out of memory. Tried to allocate 1.38 GiB (GPU 0; 11.17 GiB total capacity; 10.05 GiB already allocated; 514.31 MiB free; 10.28 GiB reserved in total by PyTorch)
I tried training the model with a much smaller batch size, but the training becomes extremely slow (2hrs per epoch)
Is there a way to fix this issue?
Following is my code:
def train_epoch(model, training_data, optimizer, pred_loss_func, opt):
""" Epoch operation in training phase. """
model.train()
total_event_ll = 0 # cumulative event log-likelihood
total_time_se = 0 # cumulative time prediction squared-error
total_event_rate = 0 # cumulative number of correct prediction
total_num_event = 0 # number of total events
total_num_pred = 0 # number of predictions
for batch in tqdm(training_data, mininterval=2,
desc=' - (Training) ', leave=False):
""" prepare data """
event_time, time_gap, event_type = map(lambda x: x.to(opt.device), batch)
""" forward """
optimizer.zero_grad()
enc_out, prediction = model(event_type, event_time) #BR: Output predictions
""" backward """
# negative log-likelihood
event_ll, non_event_ll = Utils.log_likelihood(model, enc_out, event_time, event_type)
event_loss = -torch.sum(event_ll - non_event_ll)
# type prediction
pred_loss, pred_num_event = Utils.type_loss(prediction[0], event_type, pred_loss_func)
# time prediction
se = Utils.time_loss(prediction[1], event_time)
# SE is usually large, scale it to stabilize training
scale_time_loss = 100
loss = event_loss + pred_loss + se / scale_time_loss
loss.backward()
""" update parameters """
optimizer.step()
""" note keeping """
total_event_ll += -event_loss.item()
total_time_se += se.item()
total_event_rate += pred_num_event.item()
total_num_event += event_type.ne(Constants.PAD).sum().item()
# we do not predict the first event
total_num_pred += event_type.ne(Constants.PAD).sum().item() - event_time.shape[0]
del event_time
del time_gap
del event_type
# del se
# del pred_loss
# del pred_num_event
# del event_loss
rmse = np.sqrt(total_time_se / total_num_pred)
return total_event_ll / total_num_event, total_event_rate / total_num_pred, rmse |
st49232 | Hello, I am relatively new to Pytorch and I am trying to train a stateful LSTM Autoencoder. But while training I run into the following error
“RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time”
Even after setting retain_graph=True I run into another error
“RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation.”
A solution that I found on the forum is to use detach() at the end of every forward pass. However, I am unsure if detaching the hidden state from the computation graph would only retain the hidden state from the previous time step alone. If this is the case how do I backpropagate across batches?
class Encoder(nn.Module):
def __init__(self, inputDimension, outputDimension):
super(Encoder, self).__init__()
self.inputDimension = inputDimension
self.outputDimension = outputDimension
#batch size (numLayers, batchSize, hidden_layer size)
self.hidden1 = (torch.zeros(1,1,64), torch.zeros(1,1,64))
self.hidden2 = (torch.zeros(1,1,self.outputDimension), torch.zeros(1,1, self.outputDimension))
self.lstm1 = nn.LSTM(self.inputDimension, 64, num_layers=1)
self.lstm2 = nn.LSTM(64, self.outputDimension, num_layers=1)
def forward(self, inputs):
x,self.hidden1= self.lstm1(inputs, self.hidden1)
x,self.hidden2= self.lstm2(x, self.hidden2)
return x
class Decoder(nn.Module):
def __init__(self, inputDimension, outputDimension):
super(Decoder, self).__init__()
self.inputDimension = inputDimension
self.outputDimension = outputDimension
self.hidden3 = (torch.zeros(1, 1, 64), torch.zeros(1, 1, 64))
self.lstm1 = nn.LSTM(self.inputDimension, 64, num_layers=1)
self.lin1 = nn.Linear(64, self.outputDimension)
def forward(self, inputs):
#no need to reshape input as the output of Encoder is a 3D tensor
x,self.hidden3= self.lstm1(inputs, self.hidden3)
x = x.view(-1, torch.prod(torch.tensor(x.shape)[1:]))
x = self.lin1(x)
return x
class LSTM_Autoencoder(nn.Module):
def __init__(self,inputDimension, outputDimension):
super(LSTM_Autoencoder, self).__init__()
self.inputDimension = inputDimension
self.outputDimension = outputDimension
self.encoder = Encoder(inputDimension, outputDimension)
self.decoder = Decoder(outputDimension, inputDimension)
def forward(self, inputs):
inputs = inputs.view(len(inputs), 1, -1)
x = self.encoder(inputs)
x = self.decoder(x)
return x
Any clarification provided is much appreciated. |
st49233 | I would like to know what are all the possible distributions I can use out of the box in the kl_divergence function. Is there a quick way to figure this out? Thanks! |
st49234 | Solved by Adam_Conkey in post #3
Thank you for the suggestion @googlebot. Based on that I wrote this function that does what I want:
from torch.distributions.kl import _KL_REGISTRY
def view_kl_options():
names = [(k[0].__name__, k[1].__name__) for k in _KL_REGISTRY.keys()]
max_name_len = max([len(t[0]) for t in names])
… |
st49235 | Thank you for the suggestion @googlebot. Based on that I wrote this function that does what I want:
from torch.distributions.kl import _KL_REGISTRY
def view_kl_options():
names = [(k[0].__name__, k[1].__name__) for k in _KL_REGISTRY.keys()]
max_name_len = max([len(t[0]) for t in names])
for arg1, arg2 in sorted(names):
print(f" {arg1:>{max_name_len}} || {arg2}")
This gives an output like:
Bernoulli || Bernoulli
Bernoulli || Poisson
Beta || Beta
Beta || ContinuousBernoulli
Beta || Exponential
Beta || Gamma
Beta || Normal
Beta || Pareto
Beta || Uniform
Binomial || Binomial
Categorical || Categorical
Cauchy || Cauchy
ContinuousBernoulli || ContinuousBernoulli
ContinuousBernoulli || Exponential
ContinuousBernoulli || Normal
ContinuousBernoulli || Pareto
ContinuousBernoulli || Uniform
Dirichlet || Dirichlet
Exponential || Beta
Exponential || ContinuousBernoulli
Exponential || Exponential
Exponential || Gamma
Exponential || Gumbel
Exponential || Normal
Exponential || Pareto
Exponential || Uniform
ExponentialFamily || ExponentialFamily
Gamma || Beta
Gamma || ContinuousBernoulli
Gamma || Exponential
Gamma || Gamma
Gamma || Gumbel
Gamma || Normal
Gamma || Pareto
Gamma || Uniform
Geometric || Geometric
Gumbel || Beta
Gumbel || ContinuousBernoulli
Gumbel || Exponential
Gumbel || Gamma
Gumbel || Gumbel
Gumbel || Normal
Gumbel || Pareto
Gumbel || Uniform
HalfNormal || HalfNormal
Independent || Independent
Laplace || Beta
Laplace || ContinuousBernoulli
Laplace || Exponential
Laplace || Gamma
Laplace || Laplace
Laplace || Normal
Laplace || Pareto
Laplace || Uniform
LowRankMultivariateNormal || LowRankMultivariateNormal
LowRankMultivariateNormal || MultivariateNormal
MultivariateNormal || LowRankMultivariateNormal
MultivariateNormal || MultivariateNormal
Normal || Beta
Normal || ContinuousBernoulli
Normal || Exponential
Normal || Gamma
Normal || Gumbel
Normal || Normal
Normal || Pareto
Normal || Uniform
OneHotCategorical || OneHotCategorical
Pareto || Beta
Pareto || ContinuousBernoulli
Pareto || Exponential
Pareto || Gamma
Pareto || Normal
Pareto || Pareto
Pareto || Uniform
Poisson || Bernoulli
Poisson || Binomial
Poisson || Poisson
TransformedDistribution || TransformedDistribution
Uniform || Beta
Uniform || ContinuousBernoulli
Uniform || Exponential
Uniform || Gamma
Uniform || Gumbel
Uniform || Normal
Uniform || Pareto
Uniform || Uniform |
st49236 | This question has been asked in 2017 6, but I’m wondering now (2020) if there is any way to do tf.scan 5 or theano.scan in PyTorch.
In PyTorch, there is torch.cumsum, which can be thought of as a special case of scan. Specifically, cumsum is tied to the addition operator, whereas in TensorFlow or Theano, scan can be used with any binary operator (passed in as a function), not just addition.
From the 2017 thread (linked above), @jekbradbury said:
For equivalents of theano.scan , use Python for and while loops.
However, I would prefer not to use for and while loops, in part because I want my computation to be done in parallel on the GPU. Scans, a.k.a. prefix sums, are a common GPGPU operation, which is why CUDA libraries like Thrust contain a variety of prefix sum functions.
Has anyone (officially or unofficially) implemented a scan in PyTorch, or am I stuck with Python for and while loops? |
st49237 | Nope, I never found an answer. I ended up using a combination of torch.cumsum and torch.cumprod to implement the operation that I needed, but it would still be convenient for PyTorch to have a scan primitive that accepts an arbitrary binary operator, like in TensorFlow/Theano or even Thrust. |
st49238 | Hey everyone,
I understand that the pruning methods in Pytorch create masks of the network’s weights, and when we use prune.remove, we remove that reparametrization, leaving the same number of network weights, where the pruned weights are set to zero.
I was wondering how I might then be able to reparametrize the network to remove those zeroed weights, resulting in a smaller model for devices with limited memory. Can anyone provide some thoughts on what that would require?
Thanks! |
st49239 | Hi everyone,
I’m working on an electromagnetism project using neural network and I’m trying to create a nn.Module class for a neural network for which many layers are contained in a dictionnary. Like this:
class ComplexNet(nn.Module):
def __init__(self):
super(ComplexNet, self).__init__()
self.R = dict()
for pp in ['00', '01', '10', '11']:
for ii in ['x','y','z']:
for jj in ['x','y','z']:
for kk in ['r', 'i']:
self.R[pp+'e'+jj+'e'+ii+'_'+kk] = HadamardProduct(Nky, Nkx, pp+'e'+jj+'e'+ii+'_'+kk, bias = False)
self.R[pp+'h'+jj+'e'+ii+'_'+kk] = HadamardProduct(Nky, Nkx, pp+'h'+jj+'e'+ii+'_'+kk, bias = False)
where HadamardProduct is a layer for dot product operation:
class HadamardProduct(nn.Module):
def __init__(self, Nky, Nkx, string, bias=True):
super().__init__()
self.Nky = Nky
self.Nkx = Nkx
self.weight = nn.Parameter(torch.load(f'{path}/R{string}')).double()
def forward(self, input):
return input * self.weight
The problem arises when I want to insert model.parameters() in the optimizer. It doesn’t recognize the different layers. Do you have any clue how to fix this issue?
Otherwise, I’ll need to create layers like this:
self.R00exexr = HadamardProduct(Nky, Nkx, ‘00exex_r’, bias = False)
self.R00exeyr = HadamardProduct(Nky, Nkx, ‘00exey_r’, bias = False)
self.R00exezr = HadamardProduct(Nky, Nkx, ‘00exez_r’, bias = False)
…
But there are 4x3x6 different ones.
Any help would be greatly appreciated!
Victor |
st49240 | Ok, I think I found a trick using nn.ModuleDict
class ComplexNet(nn.Module):
def __init__(self):
super(ComplexNet, self).__init__()
self.R = nn.ModuleDict()
for pp in ['00', '01', '10', '11']:
for ii in ['x','y','z']:
for jj in ['x','y','z']:
for kk in ['r', 'i']:
self.R[pp+'e'+jj+'e'+ii+'_'+kk] = HadamardProduct(Nky, Nkx, pp+'e'+jj+'e'+ii+'_'+kk, bias = False)
self.R[pp+'h'+jj+'e'+ii+'_'+kk] = HadamardProduct(Nky, Nkx, pp+'h'+jj+'e'+ii+'_'+kk, bias = False)
Let me know if you have any other suggestion |
st49241 | I’m doing some experiments with MultiLabelClassification and I was trying to calculate the mean of the loss manually and found out, that there is a big difference to the BCEWithLogitsLoss-Mean and I don’t get why that’s the case.
Here is my code:
import math, torch, torch.nn as nn
pre = torch.tensor([0.133, 0.145, 0.692, 0.030])
des = torch.tensor([0., 0., 1., 0.])
torch.sigmoid(pre)
--> tensor([0.5332, 0.5362, 0.6664, 0.5075])
l1 = -(1*(math.log(0.5332))+(1-0)*math.log(1-0.5332))
--> 1.3907130692473197
l2 = -(1*(math.log(0.5362))+(1-0)*math.log(1-0.5362))
--> 1.391549907340984
l3 = -(1*(math.log(0.6664))+(1-1)*math.log(1-0.6664))
--> 0.4058651881295041
l4 = -(1*(math.log(0.5075))+(1-0)*math.log(1-0.5075))
--> 1.3865193864361882
1/4*(l1+l2+l3+l4)
--> 1.143661887788499
And this is the pytorch-implementation:
import math, torch, torch.nn as nn
criterion = nn.BCEWithLogitsLoss(reduction='mean')
pre = torch.tensor([0.133, 0.145, 0.692, 0.030])
des = torch.tensor([0., 0., 1., 0.])
criterion(pre, des)
--> tensor(0.6611)
If I set the reduction to ‘none’ only l3 (Loss 3) hast the same value:
tensor([0.7619, 0.7683, 0.4058, 0.7083])
Could somebody please explain to me, why that’s the case?
Thanks! |
st49242 | Solved by alexgo in post #2
you have a mistake in the labels in your manual implementation.
should be:
l1 = -(0*(math.log(0.5332))+(1-0)*math.log(1-0.5332))
l2 = -(0*(math.log(0.5362))+(1-0)*math.log(1-0.5362))
l3 = -(1*(math.log(0.6664))+(1-1)*math.log(1-0.6664))
l4 = -(0*(math.log(0.5075))+(1-0)*math.log(1-0.5075)) |
st49243 | you have a mistake in the labels in your manual implementation.
should be:
l1 = -(0*(math.log(0.5332))+(1-0)*math.log(1-0.5332))
l2 = -(0*(math.log(0.5362))+(1-0)*math.log(1-0.5362))
l3 = -(1*(math.log(0.6664))+(1-1)*math.log(1-0.6664))
l4 = -(0*(math.log(0.5075))+(1-0)*math.log(1-0.5075)) |
st49244 | I really wonder sometimes where I left my brain.
Thank you! That was the mistake I made.
And now I’m getting a loss which I understand
BCEWLL:
criterion = nn.BCEWithLogitsLoss(reduction='none', pos_weight=samples_weight)
pre = torch.tensor([-8., 0., 4., -2.])
des = torch.tensor([0., 0., 1., 0.])
criterion(pre, des)
--> tensor([3.3569e-04, 6.9315e-01, 1.8150e-02, 1.2693e-01])
torch.mean(criterion(pre,des))
--> tensor(0.2096)
Manual:
pre = torch.tensor([-8., 0., 4., -2.])
des = torch.tensor([0., 0., 1., 0.])
import math, torch, torch.nn as nn
import numpy as np
def bll(pre, des):
bitloss = 0
for p, d in zip(pre, des):
sp = torch.sigmoid(p)
loss = -(d*(math.log(sp))+(1-d)*math.log(1-sp))
bitloss += loss
print(loss)
return bitloss
ll = bll(pre, des)
BCEWLL = (1/len(pre))*ll
print(f"MEAN:{BCEWLL}")
--> tensor(0.0003)
tensor(0.6931)
tensor(0.0181)
tensor(0.1269)
MEAN:0.20964014530181885
The only thing I wonder is how -8 can have such a low loss value when it’s the farthest away?
According to log(1 - 1/(1 + e^8)) it should also be a negative value.
EDIT:
Well I answer my question myself. Lowest loss because it’s the farthest away and thus “very wrong” -> Not dangerous to interfere the true prediction. The 0 prediction is the nearest so the biggest loss there. |
st49245 | Sigmoid of -8 is a very small number so it means the prediction is correct, it is close to the label 0. So it makes sense that the loss is low.
The expression you wrote is close to log(1) which is 0. |
st49246 | Hi,
I want to get masked tensor when I batched the variable length sequences.
import torch.nn as nn
l = [torch.zeros(7, 4), torch.zeros(8, 4), torch.zeros(9, 4)]
b = nn.utils.rnn.pad_sequence(l, batch_first=True)
mask = # will be torch.BooleanTensor[3, 9] with true for valid input and false for padded input
Is there any simple implementation for this one?
mask = b[:, 0] != 0
This kind of things usually work in some case, but not all the case…
Thanks, |
st49247 | In much older library numpy method that copy ndarray is called copy. Why in torch the same method is called clone? Are there any specific reasons? |
st49248 | Solved by albanD in post #2
Hi,
I think this is mostly for historical reasons in particular copy (now copy_) was used a long time ago to copy into a tensor while clone is used to create an identical clone of a given Tensor. |
st49249 | Hi,
I think this is mostly for historical reasons in particular copy (now copy_) was used a long time ago to copy into a tensor while clone is used to create an identical clone of a given Tensor. |
st49250 | Hi, albanD.
Could you explain the difference between b = a.clone() and b.copy_(a)?
The docs said that
Unlike copy_(), clone() is recorded in the computation graph. Gradients propagating to the cloned tensor will propagate to the original tensor.
However, in the example below, the gradient was also backpropagated to the original tensor:
>>> x = torch.randn(2,2,requires_grad=True)
>>> x
tensor([[0.5113, 0.3028],
[0.7036, 1.4417]], requires_grad=True)
>>> x.grad
>>> y = x*2+3
>>> y_copy = torch.zeros_like(y)
>>> y_copy.copy_(y)
tensor([[4.0227, 3.6057],
[4.4072, 5.8835]], grad_fn=<CopyBackwards>)
>>> z = y_copy*3+3
>>> z
tensor([[15.0681, 13.8171],
[16.2216, 20.6504]], grad_fn=<AddBackward0>)
>>> loss=torch.sum(z-15)
>>> loss.backward()
>>> x.grad
tensor([[6., 6.],
[6., 6.]])
And the y_clone = y.clone() operation showed the same behavior. Could you explain the difference? |
st49251 | Hi,
I think this is most likely misleading doc here The master doc has been updated and is clearer: https://pytorch.org/docs/master/generated/torch.clone.html?highlight=clone#torch.clone 8
The difference is that if you use copy_, the original value won’t get gradients. But for clone, there is no original value so not this issue.
y = torch.rand(10, requires_grad=True)
res = y.clone().copy_(x)
res.sum().backward()
assert (y.grad == 0).all() |
st49252 | albanD:
res.sum().backward()
Hi, thank you for your reply, but, sorry, I still didn’t get it.
Please take a look at following examples:
>>> x = torch.randn(2,2,requires_grad=True)
>>> y = x.clone()
>>> res=y.sum()
>>> res.backward()
>>> y.grad
>>> x.grad
tensor([[1., 1.],
[1., 1.]])
>>> x = torch.randn(2,2,requires_grad=True)
>>> y = torch.randn(2,2)
>>> y.copy_(x)
tensor([[ 0.4119, -0.7538],
[-0.3020, -0.6225]], grad_fn=<CopyBackwards>)
>>> res = y.sum()
>>> res.backward()
>>> y.grad
>>> x.grad
tensor([[1., 1.],
[1., 1.]])
As I see it, the two operations behave the same if used separately.
In your example, there were three tensors (x, y, and res) and you used .clone().copy_(x) together. To be honest, I got more confused. Could you explain the reason why did you use them together?
And what’s the difference between >>y.grad >>nothing printed out and >>y.grad >>a tensor of zeros printed out?
Thank you for your time! |
st49253 | Hi,
You should ignore the note in the old doc as I think it is just confusing.
The two actually propagate gradients.
In my example, I use clone to avoid changing the original Tensor because the copy is done inplace.
A gradient can be None for few reasons. Either because the Tensor does not require gradients, is not a leaf Tensor or is independent of the output that you backwarded on. |
st49254 | x = torch.randn(1,1,5)
torch.cat((x,x),dim=-3)
What exactly does this mean? I could not understand |
st49255 | Solved by SAI_VARSHITTHA in post #2
My problem is resolved,thanks |
st49256 | Tough question to frame in one line but here is the context:
I have an LSTM on varying length image sequences. A CNN generates the inputs to the LSTM. I want to train the CNN on the fly, rather than use it just as an embeddings generator.
To do this I take my (batch_size, seq_length, *image_dims) and view it as one big batch of images like this (batch_size*seq_length, *image_dims). Then after it comes out of the CNN I unpack it for feeding to the LSTM.
This works just fine apart from the fact that some of the sequences are too long to fit in memory for the CNN (because I’m also storing gradients for backprop). I’d love to get some feedback on how to solve it. Here’s what I’ve been thinking about:
Break the “big batch” into sub batches. Do back-prop on the LSTM alone, then backprop on the sub-batches. Seems like a lot of work and overcomplicating things. Also, I’m not sure it would work as I still need to store gradients for everything.
Randomly select a maximum of 256 samples from the “big batch”, pick those out and run them through. All the rest runs through CNN with no grad. That way the CNN is not learning for every single image in the sequence at once, but at least I can get the inputs through to the LSTM without killing my memory.
Any ideas or guidance would be appreciated! |
st49257 | Hi all!
I would like to estimate the energy consumption of each layer in a model. Does anyone knows how to do it? |
st49258 | You would probably need to set up some model for what consumes energy.
Going after FLOPS is the most common metric, I would wonder whether memory accesses (which have a huge impact on the time something takes) also play a role.
After that, you would need to estimate the explanatory variables for each block you want to measure.
Finally you can take the overall power consumption and then allocate that to the layers using the above.
An alternative to all this could be to gradually “shorten” the model and measure the total power per 1 epoch or so. The difference between two runs could then be attributed to the part the shortened model leaves out.
Best regards
Thomas |
st49259 | Hello,
I understood the FLOPS argument but not what is EXPLANATORY variables and how to go about it.
tom:
After that, you would need to estimate the explanatory variables for each block you want to measure.
Finally you can take the overall power consumption and then allocate that to the layers using the above.
I am only interested in total energy consumption of the model and do not require layerwise diagnostic.
Is there an easy way to do this using PyTorch. Some rough estimates will also do. Even external links to GITHUB repos doing this will help |
st49260 | I can’t find the post anymore, but I read on these forums that it is better (or at least faster) to calculate loss on the CPU. I wonder whether that is true. What are the pros and cons of calculating loss on the GPU vs CPU. Particular concerns are speed and memory consumption. My assumption is also that if there is a notable difference, that this is magnified with larger batches. |
st49261 | People often measure cuda times incorrectly (in this case it is even more likely as loss.item() is often a cuda synchronization point). In practice, loss calculation times should be too insignificant to be concerned. Same with memory. |
st49262 | nn.Linaer with bias=True is initializing the bias using uniform:
init.uniform_(self.bias, -bound, bound)
I usually override it by initializing it to zeros like so:
fc = nn.Linear(in_dim, out_dim, bias=True)
nn.init.zeros_(fc.bias)
Is there any benefit to the default uniform initialization?
Thank you in advance
Roy |
st49263 | Hi everyone! I am kind of new in deep learning and pytorch. That’s why I’m having some issues and thought to address them here…
I need to create a dataset object for loading the data afterwards as a set of labeled bags (Multiple instance learning). Each bag will contain 10 images. And to label the bags (directories), I created a CSV file with two columns - one holding the directory name and the other some certain value as a label (regression task). How can I code the dataset object, such that when I provide it to the DataLoader, my data will be loaded bag-wise?
I could not find any piece of code or any link which could help me further. Any help would be much appreciated! |
st49264 | Could you explain the use case of creating the bags a bit more, please?
If I understand it correctly, you would like to sample from specific indices to create these bags?
Would you like to return a data tensor in [batch_size, 10, ...] or would 10 already be the batch size? |
st49265 | Thank you for your answer @ptrblck! Sorry for not explaining it more concisely. Actually, my batch size should be 10, meaning that it will have 10 bags per batch. And the bags will contain a specific number of images, let’s say 15. Each bag is labelled by a number, from a CSV file.
Is this according to you more reasonable? Or you think sampling from loaded images to create bags makes more sense… |
st49266 | Hi, I am doing the same project with medical data.
The images are super large with a resolution of 5000*5000, to solve this I made patches of it and saved in folders. Then created a bag for each folder images
my bag has more than 187 images which I couldn’t in the gpu memory. Is there any other way to solve it ? |
st49267 | I’m not fully understand what “bad” means in this use case.
If your data still doesn’t fit into the GPU memory, you might need to reduce the patch sizes further. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.