id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st183100 | Could You post a simple example on how to properly initialize weights?
Do I have to re-initialize LSTM weights after each epoch or sample? |
st183101 | Ok, I initialized all my Linear weights based on this comment 6, but pytorch is still not learning:
def weight_init(m):
if isinstance(m, nn.Linear):
size = m.weight.size()
fan_out = size[0] # number of rows
fan_in = size[1] # number of columns
variance = np.sqrt(2.0/(fan_in + fan_out))
m.weight.data.normal_(0.0, variance)
baseline_model = FCBaseline(SEGMENT_WIDTH, SEGMENT_HEIGHT, SEGMENT_CHANNELS, num_classes)
baseline_model.apply(weight_init) |
st183102 | Could be that I missed it but it seems like a possible reason is that you forgot to zero the gradients before/after running a batch. You only seem to do it at the start. Try adding the following INSIDE your training loop:
optimizer.zero_grad()
Does this solve your issue?
See here 1 for an example or here for the reason why this is needed. 6 |
st183103 | Thank You, this solved my issue. I forgot to zero out gradients after each minbach. Now works fine.
# Optimizer needs the gradients of this minibatch only, so zero out prev grads.
optimizer.zero_grad()
loss.backward() # Calculates derivatives with autograd
optimizer.step() # Update weights |
st183104 | Hello!
I’m currently working on language recognition and I wanted to implement a Gaussian mixture model which can run parallelly on multiple GPUs(I have 2 GPU’s of 11 Gb each) . As of now, I have implemented a naive GMM comprising normal def functions which does everything on CPU without any parallelization and optimization(Like I don’t need to store the grads of tensors as well) .I wanted to get an idea or some suggestions about how I should go ahead with Parallelization implementation of GMM!
Thanks! |
st183105 | Would you like to apply some data parallelism (cloning the model on each GPU and splitting the data) or would you like to shard the model somehow (different GPUs compute different parts of your model)? |
st183106 | I was thinking of the first way similar to nn.Dataparallel approach! This seems possible to me…
I’m not sure how I can go about if I want to implement it in the second way though. |
st183107 | Hi, I want to train librispeech which contains variable length of samples.
How to use Dataloader for this ( should I Cut it into framewise and then train) or is their any methods for loading different sample size.
If I follow to cut it into frames wise, its a huge number files which it able to handle properly by the GPU.
Is their any method to write a customized way to train the neural network. |
st183108 | What is the best way to train a network with large database contain billions of samples ??
When the same network is trained with a small dataset in GPU, its taking less time.
But when the datsamples are increased its taking too much time irrespective of same number of batch size, no_worker and same dataloader also.
I am not able to figure out, why the total batch size execution time is not matching with epoch time.
I am just following this link https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html.
MY network is simple DNN. |
st183109 | Hello,
I am curious about the fft built-in function.
Is this function calculate the DFT coefficient directly?
What is the time complexity of fft function if we do not use GPU?
Is this function use divide-and-conquer algorithm for calculating fft?
Thanks, |
st183110 | Solved by KFrank in post #4
Hello 성현!
It looks like the gradient is supported. Try:
>>> import torch
>>> t = torch.randn (1, 8, 2)
>>> t.requires_grad = True
>>> torch.fft (t, 1)
tensor([[[-2.7232, 3.8741],
[-2.9743, -2.1404],
[ 1.1234, 4.4275],
[ 1.7661, 1.6113],
[-3.6401, 3.6872],
… |
st183111 | Hi 성현!
sh0416:
…
What is the time complexity of fft function if we do not use GPU?
Is this function use divide-and-conquer algorithm for calculating fft?
I haven’t actually looked at the code, but the time complexity
should be n log n.
After all, the function in question is torch.fft, where “fft”
stands for “fast Fourier transform,” which uses what you call
the “divide-and-conquer” algorithm and runs in n log n.
It would be false advertising if torch.fft instead used the
sft* algorithm.
*) “Slow Fourier transform”
Best regards.
K. Frank |
st183112 | So much thanks for reply
I have one more question.
Can we get the gradient of fft function with respect to input?
I think it is possible, but I want to make sure things. |
st183113 | Hello 성현!
sh0416:
…
Can we get the gradient of fft function with respect to input?
I think it is possible, but I want to make sure things.
It looks like the gradient is supported. Try:
>>> import torch
>>> t = torch.randn (1, 8, 2)
>>> t.requires_grad = True
>>> torch.fft (t, 1)
tensor([[[-2.7232, 3.8741],
[-2.9743, -2.1404],
[ 1.1234, 4.4275],
[ 1.7661, 1.6113],
[-3.6401, 3.6872],
[ 0.0582, -3.4854],
[-1.6034, 0.3976],
[ 0.3413, 0.8839]]], grad_fn=<FftWithSizeBackward>)
(I haven’t actually tried this, but I would imagine that
FftWithSizeBackward works correctly.)
Best.
K. Frank |
st183114 | About the speed, on CUDA, the cufft package is used, on CPU, MKL is used. They are both highly-optimized libraries, so it should be very fast. |
st183115 | I’m trying to install warp-CTC for deepSpeech2.
I’m using python 3.7.2, pytorch 1.1.0, cuda 9.0.
I get the following error:
src/binding.cpp:10:33: fatal error: c10/cuda/CUDAGuard.h: No such file or directory
I’d appreciate any direction for solving this, thanks. |
st183116 | Quoting from the documentation:
Replicate padding is implemented for padding the last 3 dimensions of 5D input tensor, or the last 2 dimensions of 4D input tensor, or the last dimension of 3D input tensor. Reflect padding is only implemented for padding the last 2 dimensions of 4D input tensor, or the last dimension of 3D input tensor.
Is this by choice? |
st183117 | Hi everyone
We released our audtorch package yesterday and would like to invite everyone to take a look and use it.
You can find its repository here: https://github.com/audeering/audtorch 38. We welcome all new issues and contributions
We will also synchronize with the rest of the audio community that’s working on torchaudio-contrib 7 and try to promote usage of PyTorch in the audio community in general.
Cheers |
st183118 | Dear all,
Currently, I have training the GRU network for speech recognition using pytorch. The training is successfully finished. However, the evaluation time, the Cuda out of memory runtime error occurs.
The actual error is RuntimeError: CUDA out of memory. Tried to allocate 1.72 GiB (GPU 0; 11.92 GiB total capacity; 5.72 GiB already allocated; 1.65 GiB free; 4.04 GiB cached)
My Cuda has around (4.04GB + 1.65GB ) unused memory but Cuda is unable to allocate 1.72GB memory, which is unreasonable.
Please suggest possible solutions to overcome this error.
With best regards, |
st183119 | Hello there,
There are a few things that you can do to lower your memory footprint. First is to run your validation code with torch.no_grad() so to not save any gradients. Are you by any chance running your validation code inside your training loop? If so, there might be a few tensors that you could delete from the training loop, perhaps del training_input, del training_output, del .... Lastly, I found that putting this once before training lowers my memory footprint but I don’t know it’s inner workings.
torch.backends.cudnn.benchmark = True # Optimizes cudnn
I don’t know about the cache though, good luck |
st183120 | Thank you very much Oli.
I already done the first two memory footprint methods, but i did not used the third one i will try and just come up with the result. |
st183121 | Hi all,
I just published a Pytorch implementation of Google’s new data augmentation technique 70 in SpecAugment with torch audio 310. Thought it might be of interest to some people working on audio in the forum.
freqmask.jpg2296×642 621 KB
To implement one of the transforms we ported a Tensorflow function sparse_image_warp to Pytorch. FWIW this was my deep dive into Pytorch and I found the experience really enjoyable with good docs and APIs that were easy to match with their TF counterparts |
st183122 | Hi,
I would like to know how to implement a phase unwrapping like “numpy.unwrap” with the backward functionality? Could it be possible to support “torch.stft” with magnitude and phase instead of real and imaginary components to make life easier?
Regards |
st183123 | Traceback (most recent call last):
File "main.py", line 49, in <module>
solver.exec()
File "/project/src/solver.py", line 195, in exec
self.valid()
File "/project/src/solver.py", line 234, in valid
ctc_pred, state_len, att_pred, att_maps = self.asr_model(x, ans_len+VAL_STEP,state_len=state_len)
File "/home/anaconda2/envs/dlp/lib/python3.6/site-packages/torch/nn/modules/module.py", line 489, in __call__
result = self.forward(*input, **kwargs)
File "/project/src/asr.py", line 61, in forward
encode_feature,encode_len = self.encoder(audio_feature,state_len)
File "/home/anaconda2/envs/dlp/lib/python3.6/site-packages/torch/nn/modules/module.py", line 489, in __call__
result = self.forward(*input, **kwargs)
File "/project/home/src/asr.py", line 314, in forward
input_x,enc_len = self.vgg_extractor(input_x,enc_len)
File "/home/anaconda2/envs/dlp/lib/python3.6/site-packages/torch/nn/modules/module.py", line 489, in __call__
result = self.forward(*input, **kwargs)
File "/project/src/asr.py", line 554, in forward
feature = self.pool2(feature) # BSx128xT/4xD/4
File "/home/anaconda2/envs/dlp/lib/python3.6/site-packages/torch/nn/modules/module.py", line 489, in __call__
result = self.forward(*input, **kwargs)
File "/home/anaconda2/envs/dlp/lib/python3.6/site-packages/torch/nn/modules/pooling.py", line 148, in forward
self.return_indices)
File "/home/anaconda2/envs/dlp/lib/python3.6/site-packages/torch/_jit_internal.py", line 132, in fn
return if_false(*args, **kwargs)
File "/home/anaconda2/envs/dlp/lib/python3.6/site-packages/torch/nn/functional.py", line 425, in _max_pool2d
input, kernel_size, stride, padding, dilation, ceil_mode)[0]
File "/home/anaconda2/envs/dlp/lib/python3.6/site-packages/torch/nn/functional.py", line 417, in max_pool2d_with_indices
return torch._C._nn.max_pool2d_with_indices(input, kernel_size, _stride, padding, dilation, ceil_mode)
RuntimeError: CUDA out of memory. Tried to allocate 24.12 MiB (GPU 0; 10.91 GiB total capacity; 9.25 GiB already allocated; 17.44 MiB free; 41.97 MiB cached)
I keep increasing the GPU size, using 2 gpus but i still get this error even when batch size is 1.
How could I resolve it? |
st183124 | This also means it is not using the 2 GPUs.
How could I use 2 GPUs ( using nn.DataParallel?), and any way to remove this error? |
st183125 | I’m implementing an LSTM on audio clips of different sizes. After going through padding/packing, the output of the lstm is:
a.shape = torch.Size([16, 1580, 201])
with (batch, padded sequence, feature). I also have a list of the actual lengths of the sequences:
lengths = [1580, 959, 896, 881, 881, 881, 881, 881, 881, 881, 881, 881, 881, 335, 254, 219].
What I would like to do is for every element in the batch select the output of the last element in the sequence, and end up with a tensor of shape:
torch.Size([16, 201])
(independent of the variable sequence length the examples have). So far I’ve been using:
torch.cat([a[i:i+1][:,ind-1] for i,ind in enumerate(lengths)], dim=0)
but I was wondering if there’s a proper PyTorch function for such use case?
Thanks. |
st183126 | Solved by ptrblck in post #2
The following indexing should work:
x = torch.randn(16, 1580, 201)
idx = torch.tensor(
[1580, 959, 896, 881, 881, 881, 881, 881, 881, 881, 881, 881, 881, 335, 254, 219]
)
idx = idx - 1 # 0-based index
y = x[torch.arange(x.size(0)), idx] |
st183127 | The following indexing should work:
x = torch.randn(16, 1580, 201)
idx = torch.tensor(
[1580, 959, 896, 881, 881, 881, 881, 881, 881, 881, 881, 881, 881, 335, 254, 219]
)
idx = idx - 1 # 0-based index
y = x[torch.arange(x.size(0)), idx] |
st183128 | LSTM is expecting (seq_len, batch, input_size) but when I do that PyTorch throws an error:
ValueError: Expected input batch_size (20) to match target batch_size (27).
20 is seq_len and 27 is batch_size.
Input shape:
torch.Size([20, 27, 87])
(seq_len, batch, input_size) accordingly.
My model:
class RNN(nn.Module):
def __init__(self):
super(RNN, self).__init__()
self.lstm1 = nn.LSTM(input_size=87, hidden_size=256)
self.lstm2 = nn.LSTM(input_size=256, hidden_size=128)
self.lstm3 = nn.LSTM(input_size=128, hidden_size=64)
self.lstm4 = nn.LSTM(input_size=64, hidden_size=32)
self.fc1 = nn.Linear(in_features=32, out_features=128)
self.fc2 = nn.Linear(in_features=128, out_features=64)
self.fc3 = nn.Linear(in_features=64, out_features=32)
self.fc4 = nn.Linear(in_features=32, out_features=3)
def forward(self, x):
x = torch.tanh(self.lstm1(x)[0])
x = torch.tanh(self.lstm2(x)[0])
x = torch.tanh(self.lstm3(x)[0])
x = torch.tanh(self.lstm4(x)[0])
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = self.fc4(x)
return x
There are two questions:
What’s wrong with seq_len in my case?
Is it ok to swapaxes to meet requirments or it mixes important things:
X_train = X_train.swapaxes(1,0) |
st183129 | I think it depends on your use case.
Currently you are feeding a tensor with the shape [seq_len, batch_size, hidden_size] into your linear layer.
Usually the input to a linear layer should be [batch_size, *, in_features]. The * means any number of additional dimensions, where the same linear operation will be performed on.
In this case, your output won’t differ, but will be shaped [seq_len, batch_size, out_features].
Since your target is most likely in the shape [batch_size, *], you’ll get an error trying to calculate the loss.
You could permute the output or the activation in your model to set the batch dimension as dim0.
In case your target is only a single class for the whole sequence, probably you would like to get the activation of the last step from your LSTM. |
st183130 | Changed to dim0 labels, got error:
ValueError: Expected target size (27, 3), got torch.Size([27])
Manual:
Target: (N)(N) where each value is 0≤targets[i]≤C−10≤targets[i]≤C−1, or
(N,d1,d2,...,dK)(N,d1,d2,...,dK) with K≥2K≥2 in the case of K-dimensional loss.
So, manual allow [batch_size, * ] for target.
The question is how it should be encoded. I used the following data to encode labels and nn works:
y_train_torch.shape
torch.Size([27, 3])
tensor([[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1]])
Feeding into nn any other shape causes an error.
I strongly believe in PyTorch and on my first task where I analyzed financial reports of Russian companies to define target capitalization it performed really well. Slightly better than TensorFlow. Keras caused an overfit.
I also strongly believe that I am monkey playing with collider and I want to learn.
Considering our case with seq_len it seems that it doesn’t really matter whether batch come first or seq_len.
But it’s nn and it should fit the data it should learn and give me accuracy at least on training data. Of course my dataset is really small but… I said: "One, two and three’ to mic and trying to classify it into three categories. Made it 30 times. Keras is fine and I reached 100% val acc and 100% test acc for 6 epochs but I want to use flexible instrument such as PyTorch for my tasks.
model(input) in PyTorch gives me that(see below) after 3000 epochs my doubt that I incorrectly encoded labels:
tensor([[[ -7.7228, 3.0183, 11.2289],
[ 0.1328, -3.4348, 4.6932],
[-10.8275, -10.2396, 0.1168],
...,
[-10.7704, -10.0659, 0.1782],
[-10.8403, -10.1490, 0.1689],
[-10.7978, -10.1629, 0.1400]],
[[-11.1168, 4.3190, 15.7578],
[ 0.3338, -5.1119, 6.4511],
[-15.0107, -15.3557, -0.3449],
...,
[-14.9699, -15.3302, -0.3514],
[-14.9923, -15.2761, -0.3178],
[-14.9932, -15.3604, -0.3547]],
[[-11.9856, 4.5941, 16.8911],
[ 0.4712, -5.5082, 6.8625],
[-16.2449, -17.0981, -0.5629],
...,
[-16.2539, -17.0999, -0.5594],
[-16.2275, -17.0364, -0.5457],
[-16.2737, -17.1193, -0.5595]],
...,
[[ 0.2076, -5.2667, 17.3286],
[ -7.1703, -13.7633, 25.5701],
[-17.3713, -18.6646, -0.7112],
...,
[-17.3655, -18.6440, -0.7082],
[-17.3683, -18.6579, -0.7098],
[-17.3624, -18.6468, -0.7087]],
[[ 0.2093, -5.2638, 17.3253],
[ -7.1709, -13.7636, 25.5766],
[-17.3682, -18.6617, -0.7112],
...,
[-17.3644, -18.6427, -0.7081],
[-17.3678, -18.6579, -0.7099],
[-17.3617, -18.6466, -0.7088]],
[[ 0.2100, -5.2618, 17.3232],
[ -7.1747, -13.7550, 25.5766],
[-17.3694, -18.6632, -0.7113],
...,
[-17.3630, -18.6415, -0.7081],
[-17.3680, -18.6584, -0.7100],
[-17.3609, -18.6461, -0.7089]]], grad_fn=<ThAddBackward>)
Visual inspection and calculation gives my acc 0% on training set and 33 percent acc on test set.
And big thank you for answer ptrblck.
Hope to find the truth in my problem.
Ready to post any data for the task at my disposal.
Full code:
import librosa
from os import listdir
import numpy as np
from sklearn.model_selection import train_test_split
import torch
import torch.nn as nn
import torch.nn.functional as F
def loadSound(path):
soundList = listdir(path)
loadedSound = []
for sound in soundList:
Y, sr = librosa.load(path + sound)
loadedSound.append(librosa.feature.mfcc(Y, sr=sr))
return np.array(loadedSound)
one = loadSound('./voice_123/one/')
one = loadSound('./voice_123/one/')
two = loadSound('./voice_123/two/')
three = loadSound('./voice_123/three/')
X = np.concatenate((one, two, three), axis=0)
one_label = np.concatenate((np.ones(10), np.zeros(10), np.zeros(10)))
two_label = np.concatenate((np.zeros(10), np.ones(10), np.zeros(10)))
three_label = np.concatenate((np.zeros(10), np.zeros(10), np.ones(10)))
y = np.concatenate((one_label[:, None], two_label[:, None], three_label[:, None]), axis=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42, shuffle=False)
# X_train = X_train.swapaxes(1,0)
# X_test = X_test.swapaxes(1,0)
X_train_torch = torch.from_numpy(X_train).float()
X_test_torch = torch.from_numpy(X_test).float()
y_train_torch = torch.from_numpy(y_train).long()
y_test_torch = torch.from_numpy(y_test).long()
class RNN(nn.Module):
def __init__(self):
super(RNN, self).__init__()
self.lstm1 = nn.LSTM(input_size=87, hidden_size=256)
self.lstm2 = nn.LSTM(input_size=256, hidden_size=128)
self.lstm3 = nn.LSTM(input_size=128, hidden_size=64)
self.lstm4 = nn.LSTM(input_size=64, hidden_size=32)
self.fc1 = nn.Linear(in_features=32, out_features=128)
self.fc2 = nn.Linear(in_features=128, out_features=64)
self.fc3 = nn.Linear(in_features=64, out_features=32)
self.fc4 = nn.Linear(in_features=32, out_features=3)
def forward(self, x):
x = torch.tanh(self.lstm1(x)[0])
x = torch.tanh(self.lstm2(x)[0])
x = torch.tanh(self.lstm3(x)[0])
x = torch.tanh(self.lstm4(x)[0])
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = self.fc4(x)
return x
model = RNN()
model(X_train_torch)
loss_fn = torch.nn.CrossEntropyLoss()
learning_rate = 0.00001
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
for t in range(3000):
y_pred = model(X_train_torch)
loss = loss_fn(y_pred, y_train_torch)
print(t, loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
for t in range(3000):
y_pred = model(X_train_torch)
loss = loss_fn(y_pred, y_train_torch)
print(t, loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
learning_rate = 0.0001
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
for t in range(3000):
y_pred = model(X_train_torch)
loss = loss_fn(y_pred, y_train_torch)
print(t, loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
And I can provide my: “One, two and three”. |
st183131 | Based on your description, it seems you are trying to classify your dataset into one of three classes.
You are right about the docs of nn.CrossEntropyLoss, i.e. the target might be multi-dimensional.
However, if you compare the shapes of the input (model output) and the target, you see that the channel dimension is missing (C in the docs).
In your case, your target should have the shape [batch_size] and contain the class indices, i.e. values in the range [0, 2].
Just call y_train_torch = torch.argmax(y_train_torch) and you should be fine.
The multi-dimensional use case is useful for e.g. segmentation tasks, where each pixel belongs to one particular class. |
st183132 | What you mean is that:
tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2,
2, 2, 2])
I did it around 10 times and couldn’t believe my eyes till I read docs.
Actually [batch_size, *] is possible, I believe.
torch.argmax(y_train_torch) gives on my y_train_torch:
tensor(20)
Okay. I am closer to truth. I checked the shape of input and output tensors they are fine.
But:
model_for = model(X_train_torch)
for number in range(27):
print(model_for[number].argmax())
Gives:
tensor(1)
tensor(1)
tensor(1)
tensor(1)
tensor(1)
tensor(1)
tensor(1)
tensor(1)
tensor(1)
tensor(2)
tensor(2)
tensor(2)
tensor(2)
tensor(2)
tensor(2)
tensor(2)
tensor(2)
tensor(10)
tensor(0)
tensor(0)
tensor(11)
tensor(5)
tensor(11)
tensor(11)
tensor(5)
tensor(5)
tensor(5)
Why is 5,10 and 11? I didn’t say that
Labels are fine. Not sure but without it. It’s not working and asking me to give exact dimensions of the labels.
What if the problem is in seq_len and batch?
But PyTorch is giving me the error in the case when I correctly did a model that batch should be second.
So, even in the case of messing up with seq_len I have a bunch of Linear layers that should play the game and make everything perfect. Even if there is a mistake. Correct me if I am wrong.
Therefore, the problem might be in: seq_len.
Therefore, I have to change slicing of lstm to something else for model to be happy.
How? |
st183133 | Sorry, my bad. It should be torch.argmax(y_train_torch, dim=1).
This will give you the right class indices. |
st183134 | model(X_train_torch)[0] gives:
tensor([[-355.4695, -424.0195, -681.5226],
[-339.5056, -432.3004, -696.3847],
[-359.5927, -438.7826, -705.6765],
[-346.2557, -439.3127, -707.5528],
[-359.3715, -437.6559, -703.8282],
[-356.7079, -443.8343, -714.3834],
[-357.2831, -442.1734, -711.5266],
[-355.7645, -442.3993, -712.0264],
[-359.3816, -440.9185, -709.2794],
[-357.2108, -443.9724, -714.5976],
[-355.9514, -443.8340, -714.3595],
[-359.4459, -440.7137, -708.9507],
[-359.6165, -440.2903, -708.2195],
[-357.3955, -443.4591, -713.6996],
[-359.5545, -442.3593, -711.6683],
[-356.2823, -443.2863, -713.4790],
[-359.6244, -439.4549, -706.8243],
[-358.2084, -445.1720, -716.4835],
[-359.5984, -437.4826, -703.5777],
[-356.8849, -442.9969, -712.9752]], grad_fn=<SelectBackward>)
which is shape:
torch.Size([20, 3])
Made a change as ptrblck suggested and I have become closer to truth data of output. At least it looks better. Going deeper in what ptrblck said.
tensor([[0.0890, 0.0380, 0.0673],
[0.0890, 0.0379, 0.0674],
[0.0891, 0.0380, 0.0674],
[0.0891, 0.0379, 0.0674],
[0.0891, 0.0379, 0.0674],
[0.0892, 0.0380, 0.0675],
[0.0891, 0.0380, 0.0675],
[0.0891, 0.0378, 0.0673],
[0.0891, 0.0378, 0.0673],
[0.0891, 0.0379, 0.0676],
[0.0890, 0.0379, 0.0674],
[0.0890, 0.0379, 0.0675],
[0.0891, 0.0379, 0.0674],
[0.0892, 0.0379, 0.0675],
[0.0891, 0.0379, 0.0674],
[0.0892, 0.0380, 0.0675],
[0.0891, 0.0380, 0.0675],
[0.0891, 0.0379, 0.0675],
[0.0891, 0.0379, 0.0674],
[0.0892, 0.0379, 0.0675]], grad_fn=<SelectBackward>)
Obviously problem with seq_len because 20 is seq_len not a batch_size:
torch.Size([20, 3])
Trying to change input data to match manual [seq_len, batch_size, *]. Got an error:
ValueError: Expected input batch_size (20) to match target batch_size (27).
Will try to debug.
Shape of output from model(input) is still:
torch.Size([20, 27, 3])
Strange we did self.lstm1(x)[0]) that should destroy dimension 20.
Obviously, I should change the code in lstm part of my model to match dimension, it seems that tanh make it fit for the next lstm which is not right because I want to feed it to Linear. As was suggested to me earlier. Will try to debug the model.
According to the manual tanh doesn’t change output:
input (Tensor) – the input tensor
out (Tensor, optional) – the output tensor
Will try to look manual for lstm.
Changing model to:
x = torch.tanh(self.lstm1(x))
x = torch.tanh(self.lstm2(x))
x = torch.tanh(self.lstm3(x))
x = torch.tanh(self.lstm4(x)[0])
Didn’t help. Got error:
TypeError: tanh(): argument 'input' (position 1) must be Tensor, not tuple
What if I try:
class RNN(nn.Module):
def __init__(self):
super(RNN, self).__init__()
self.lstm1 = nn.LSTM(input_size=87, hidden_size=256)
self.lstm2 = nn.LSTM(input_size=256, hidden_size=128)
self.lstm3 = nn.LSTM(input_size=128, hidden_size=64)
self.lstm4 = nn.LSTM(input_size=64, hidden_size=32)
self.fc1 = nn.Linear(in_features=32, out_features=128)
self.fc2 = nn.Linear(in_features=128, out_features=64)
self.fc3 = nn.Linear(in_features=64, out_features=32)
self.fc4 = nn.Linear(in_features=32, out_features=3)
def forward(self, x):
x = torch.tanh(self.lstm1(x)[0])
x = torch.tanh(self.lstm2(x)[0])
x = torch.tanh(self.lstm3(x)[0])
x = torch.tanh(self.lstm4(x)[0][0])
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = self.fc4(x)
return x
Oh my God, it finally worked
And acc:
Training accuracy: 100.0%
Testing accuracy: 100.0%
Thank you very much ptrblck,all is good! |
st183135 | Awesome @andreiliphd!
It was a pleasure to see how you managed to get rid of all the bugs! |
st183136 | I have a question regarding sequence-wise batch-normalization for RNNs, as described in the paper: https://arxiv.org/abs/1510.01378 13
[Note: I swapped the indices in the formula to be consistent with sequence-first format]
Assuming variable length sequences, what would be the best way to implement this as a layer in PyTorch?
My first idea was to manually compute the inner sum (i.e. along the time axis for each sequence independently), create a new vector of size (N, H) where N is the mini-batch size and H the number of features, with this vector containing the sum of all outputs for each sequence, and then call BatchNorm1d on that.
However, this will not work properly for the standard deviation (and probably for other things as well).
Has anyone implemented this already in PyTorch? What is the best way to do this? |
st183137 | I worked on speech enhancement with VCTK database.
I want to load data and apply the pre-processing method simultaneously and efficiently. pre-processing is performed in just one python function.
My problem is, when I use the dataloader, it load just one wave file per loading. And it return the different amount of training data after pre-processing because the wave files which have different time length are chopped into input size in pre-processing. It means for every iteration, network will be trained with small and different batch size, and it is time consuming.
So I want to loading and pre-processing simultaneously for training with same batch size ( It should be stacked for several wav file). Now, I saved all preprocessed data as npy file. Is there more efficient way for loading data. |
st183138 | You can create a custom collate_fn in your dataloader that pads or trims the output from the Dataset properly and then stacks the padded/trimmed tensors into a batch. Or if you are using an rnn then you can put it into a PackedSequence 21. |
st183139 | thank you for reply.
could you give me some simple example code or link for stacking tensor into a batch… |
st183140 | You can search the forum for padding packed sequences. But the gist of it is that the collate function takes a list of outputs from the Dataset, then you unpack that, get the lengths, then pad based on the maximum length in the batch.
def collate_spectrograms_fn(batch):
# assuming sig has size (c, l, n_ftt)
sigs, targets = zip(*batch)
lengths = torch.tensor([sig.size(1) for sig in sigs], dtype=torch.long)
max_len = lengths.max()
sigs = [pad(sig, (0, 0, 0, ma_len - sig.size(1)) for sig in sigs]
return torch.stack(sigs), torch.cat(targets), lengths
I haven’t tested that but that’s the general idea. |
st183141 | Hi,
I’m trying to implement a modified version of LAS model. Everything works fine the loss and wer is decreasing but after the second epochs the attention seems to be wrong because it’s attending not only the right part of the listener features but also the end of the sequence.
Here is an attention plot: https://i.imgur.com/iCp404F.jpg 3
I think in one point it should attend one part of the sequence not two, its also hard for softmax.
Does anyone have any idea what can cause this? common structural problems or anything? |
st183142 | Hello,
I would love to convert Sean Naren’s DeepSpeech to Hogwild on Cuda (2 or more GPUs).
I did not find a working implementation of Hogwild on GPUs. Is this possible, and if yes, is there a reference implementation I can use as an example?
Thanks & kind regards
Ernst |
st183143 | At the moment my model gives me an error:
TypeError: tanh(): argument 'input' (position 1) must be Tensor, not tuple
If there is a solution?
How to implement this model in PyTorch?
The model is following:
class RNN(nn.Module):
def __init__(self):
super(RNN, self).__init__()
self.lstm1 = nn.LSTM(input_size=87, hidden_size=256)
self.lstm2 = nn.LSTM(input_size=256, hidden_size=128)
self.lstm3 = nn.LSTM(input_size=128, hidden_size=64)
self.lstm4 = nn.LSTM(input_size=64, hidden_size=32)
self.fc1 = nn.Linear(in_features=32, out_features=128)
self.fc2 = nn.Linear(in_features=128, out_features=64)
self.fc3 = nn.Linear(in_features=64, out_features=32)
self.fc4 = nn.Linear(in_features=32, out_features=3)
def forward(self, x):
x = torch.tanh(self.lstm1(x))
x = torch.tanh(self.lstm2(x))
x = torch.tanh(self.lstm3(x))
x = torch.tanh(self.lstm4(x))
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = self.fc4(x)
return x |
st183144 | Solved by lelouedec in post #2
Good morning @andreiliphd,
I believe LSTM outputs siomething like this : output, (h_n, c_n)
Maybe you only want to apply your tanh on the “output” ? So you should do :
torch.tanh(self.lstm1(x)[0]) |
st183145 | Good morning @andreiliphd,
I believe LSTM outputs siomething like this : output, (h_n, c_n)
Maybe you only want to apply your tanh on the “output” ? So you should do :
torch.tanh(self.lstm1(x)[0]) |
st183146 | Hi all,
I’m developing a neural vocoder. My loss is based on STFT. However, when I switch to pytorch 0.4.1, the loss became NaN after my first batch. I tried to reduce learning rate, however, the error still happens.
I created a simple code to test it:
import numpy as np
import torch
def cal_spec(signal, n_fft=2048, hop_length=256, win_length=1024):
window = torch.hann_window(win_length).cuda()
complex_spectrogram = torch.stft(
signal, n_fft=n_fft, hop_length=hop_length, win_length=win_length, window=window, center=False)
power_spectrogram = complex_spectrogram[:, :, :, 0] ** 2 + complex_spectrogram[:, :, :, 1] ** 2
return torch.sqrt(power_spectrogram)
grads = {}
def add_grad(name, x):
grads[name] = x
def reg(name):
return lambda x: add_grad(name, x)
# file can be downloaded from:
# https://drive.google.com/file/d/1qxTIKLcSShBcfX3kIgtf5scJSlQKtrPa/view?usp=sharing
d = np.load('a.npy.npz')
x = torch.tensor(d['pred'], requires_grad=True)
y = torch.tensor(d['target'], requires_grad=False)
pred_spec = cal_spec(x)
target_spec = cal_spec(y)
x.register_hook(reg('x'))
pred_spec.register_hook(reg('pred_spec'))
loss = torch.mean(torch.abs(pred_spec - target_spec))
loss.backward()
After inspecting, I see that the gradient of pred_spec is fine. However, the gradient of x is NaN.
Thanks. |
st183147 | Maybe the non-differentiability of sqrt at 0 causes you trouble? If it does you could add a small constant (but beware, the square root of a small constant isn’t nearly as small) or just drop the square root and operate with the squares.
Best regards
Thomas |
st183148 | Hi @tom,
Thanks for your reply. And yes, the non-differentiability of sqrt at 0 causes the problem. In pytorch 0.4.0, I didn’t see the problem. Maybe there’s some changes in STFT calculation in torch from 0.4.0 to 0.4.1 |
st183149 | I‘m a beginner of Pytorch ,and I try to build a lstm acoustic model, I used merlin’s frontend to prepare data,but my result is not as good as keras or tensorflow,here is my code,Did I make any mistakes in building the model and training?
class LSTM(nn.Module):
def __init__(self, embedding_dim, hidden_dim, output_size):
super(LSTM, self).__init__()
self.fc1=nn.Linear(embedding_dim,hidden_dim)
self.fc2=nn.Linear(hidden_dim,hidden_dim)
self.hidden_dim = hidden_dim
self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers=2,batch_first=True)
self.hidden2out = nn.Linear(hidden_dim, output_size)
self.dropout_layer = nn.Dropout(p=0.1)
def init_hidden(self, batch_size):
return (autograd.Variable(torch.randn(2, batch_size, self.hidden_dim)).cuda(),
autograd.Variable(torch.randn(2, batch_size, self.hidden_dim)).cuda())
def forward(self,input, lengths):
self.hidden = self.init_hidden(batch_size)
input1=torch.tanh(self.fc1(input))
input2=torch.tanh(self.fc2(input1))
packed_input = pack_padded_sequence(input2, lengths,batch_first=True)
outputs, (ht, ct) = self.lstm(packed_input, self.hidden)
opt,_=pad_packed_sequence(outputs,batch_first=True)
outputs=self.hidden2out(opt)
return outputs
model =LSTM(ins,ins,outs).to(device)
optimizer = optim.Adam(model.parameters(), lr=0.002)
for epoch in range(25): # again, normally you would NOT do 300 epochs, it is toy data
L = 1
overall_loss = 0
for iteration in range(int(len(train_x.keys()) / batch_size) + 1):
x_batch, y_batch, utt_length_batch = get_batch(train_x, train_y,keys_list,iteration,batch_size)
if utt_length_batch == []:
continue
else:
L += 1
max_length_batch = max(utt_length_batch)
x_batch = data_utils.transform_data_to_3d_matrix(x_batch, max_length=max_length_batch, shuffle_data=False)
y_batch = data_utils.transform_data_to_3d_matrix(y_batch, max_length=max_length_batch, shuffle_data=False)
# for i in range(len(x_batch)):
# for s in range(len(x_batch[i])):
# temp_x_batch[s][i][:]=x_batch[i][s][:]
# temp_y_batch[s][i][:]=y_batch[i][s][:]
inputs = torch.from_numpy(x_batch).float().to(device)
tags = torch.from_numpy(y_batch).float().to(device)
# Also, we need to clear out the hidden state of the LSTM,
# detaching it from its history on the last instance.
model.zero_grad()
# Step 2. Get our inputs ready for the network, that is, turn them into
# Tensors of word indices.
# Step 3. Run our forward pass.
#output,hidden = model(inputs,utt_length_batch)
pred = model(torch.autograd.Variable(inputs), utt_length_batch)
loss=criterion(pred,tags)
loss.backward()
optimizer.step()
overall_loss += loss
print(overall_loss/L) |
st183150 | Maybe there are some minor differences between your PyTorch and Keras/TF code.
Could you post the Keras code and also some dummy input and target tensors, i.e. data = torch.randn(...) so that we could compare the results and debug the code? |
st183151 | it shows :::
Your compiler (c++) may be ABI-incompatible with PyTorch! Please use a compiler that is ABI-compatible with GCC 4.9 and above.
however, I have updated my GCC version ,and it’s already satisfied .
image.png1814×254 62.6 KB |
st183152 | Hi,
How did you installed pytorch?
This test is designed to find if the compiler used to build the binaries is compatible with the compiler you use for your extensions.
Compiling pytorch from source will solve the problem for sure. Otherwise @smth should be able to tell you which compiler was used to build the package (depending on how you installed pytorch). |
st183153 | Usually we use DTW(Dynamic Time warpping) to measure the similarity between two variabel voice sequences. However DTW is time-cunsuming and not easy to run in the GPU since too much control in it. I wish to find a deep learning algorithm to measure the similarty. Anybody has ideas? Thanks:) |
st183154 | Solved by ptrblck in post #2
What kind of input are you using for DTW?
Some kind of mel frequency cepstral coefficient?
If the DTW works sufficiently well and you have the data, you could try to train a model to predict the DTW score for two voice sequences.
If your DTW results aren’t really good, you would have to get someh… |
st183155 | What kind of input are you using for DTW?
Some kind of mel frequency cepstral coefficient?
If the DTW works sufficiently well and you have the data, you could try to train a model to predict the DTW score for two voice sequences.
If your DTW results aren’t really good, you would have to get somehow the “ground truth” for your data. |
st183156 | I have a CNN network that designed for speech emotion recognition task and I am trying to learn the network from the scratch in an end-to-end manner. I used concordance correlation coefficient (CCC) as objective function ( I am trying to maximize CCC or minimize 1-CCC). But, It seems my network does not learn. My input is audio sample extracted from video clip. There are totally 23 video clip with 5 minute duration that the audio frames of 14 person considered as training data. The audio sample extracted each 40 ms that results 7500 audio frame for each video clip. At 16 kHz sampling rate, this correspond to 640 sample in each frame. Each frame labeled with arousal and valence. The structure of my training network is as follow:
for i_batch, sample_batched in enumerate(train_loader):
data_time.update(time.time() - since)
ground_truth, audio = sample_batched['landmark'], sample_batched['audio']
ground_truth = Variable (ground_truth, requires_grad = False)
audio = Variable (audio, requires_grad = True)
# Define model.
optimizer.zero_grad()
prediction = model(audio)
mse_mean = 0
ccc_mean = 0
for i, name in enumerate(['arousal', 'valence']):
gt_single = ground_truth[:,i]
gt_single = gt_single.float()
pred_single = prediction[:, i]
ccc_loss = criterion1(pred_single , gt_single)
if i==0:
ccc_arousal = ccc_loss.item()
else:
ccc_valence = ccc_loss.item()
ccc_mean += ccc_loss
CCC_arousal.update(ccc_arousal, audio.size(0))
CCC_valence.update(ccc_valence, audio.size(0))
losses.update((ccc_mean/2).item(), audio.size(0))
(ccc_mean/2).backward(retain_graph=True)
optimizer.step()
the loss value (1-CCC) is around 1 from the beginning and does not change considerably after even 50 epoch. Can anyone help me about this issue? |
st183157 | One way to debug it is to try to overfit your network by training with only 1 mini batch repeatedly. If your network is designed properly, your network should converge very quickly and get a loss of nearly 0. Otherwise, there might be serious design issues in your network. |
st183158 | Thank you for reply. As your suggestion I used 1 mini batch with 500 sample and trained my network. Unfortunately, the loss did not change considerably. My prediction model is as follow:
class RecurrentModel(nn.Module):
def init(self, input_size = args.input_size, hidden_units=256, number_of_outputs=2):
super(RecurrentModel, self).init()
self.hidden = hidden_units
self. input_size = input_size
self. n_outputs = number_of_outputs
self.lstm = nn.LSTM(input_size = self.input_size, hidden_size = self.hidden, num_layers = 2, batch_first=True)
self.linear = nn.Linear (hidden_units, number_of_outputs)
def forward(self, net):
batch_size, seq_length, num_features = list (net.size())
outputs, _ = self.lstm (net)
prediction = self.linear(outputs[0])
return torch.reshape(prediction, (batch_size*seq_length, self.n_outputs))
class AudioModel(nn.Module):
def init(self):
super(AudioModel, self).init()
self.drop = nn.Dropout()
self.conv1 = nn.Conv2d(1, 40, (1,20), padding=(0,9))
self.relu1 = nn.ReLU()
self.pool1 = nn.MaxPool2d((1, 2), (1, 2))
self.conv2 = nn.Conv2d(20, 40, (1,160), padding=(0,80) ) #padding = (0,38)
self.relu2 = nn.ReLU()
self.pool2 = nn.MaxPool2d((1, 10), (1, 10))
def forward(self, audio_frames, conv_filters = 40):
batch_seq_length, num_features = list (audio_frames.size())
seq_length = args.seq_length
batch_size = args.batch_size
rnn = RecurrentModel ()
audio_input = torch.reshape(audio_frames, [1, 1, batch_size * seq_length, num_features])
net = self.drop(audio_input)
net = self.conv1(net)
net = self.relu1(net)
# Subsampling of the signal to 8KhZ.
net = self.pool1(net)
net = self.conv2(net)
net = self.relu2(net)
net = torch.reshape(net, (1,batch_size * seq_length,
num_features // 2, conv_filters)) #(num_features // 3)+37
net = self.pool2(net)
net = torch.reshape(net, (batch_size, seq_length, num_features // 2 * 4))
net = rnn (net)
return net
batch_size and seq_length are equal to 25 and 1, respectively. |
st183159 | This suggests your network is not designed properly. I would suggest you simplify your model to a couple of layers to start with and train it with 1 mini batch. Once confirmed the network can reliably converge, you can start adding more layers. |
st183160 | Hi all,
Firstly I followed tutorial for multi-gpu. https://pytorch.org/tutorials/beginner/blitz/data_parallel_tutorial.html 9
It works for me. Unfortunately I tried to implement my own dataset and my own network architecture for multi-gpu training
Single GPU - works fine (i think)
Multi gpu for pytorch 0.4.0 I had an error:
RuntimeError: Expected tensor for argument #1 ‘input’ to have the same device as tensor for argument #2 ‘weight’; but device 1 does not equal 0 (while checking arguments for cudnn_convolution)
For pytorch 0.4.1 I have now an error
TypeError: ‘float’ object cannot be interpreted as an integer
My nn module subclass forward method. Simple dilated convolution, batchnorm and relu.
def forward(self, x):
out = self.dil_conv(x)
out = self.bn1(out)
out = self.relu(out)
Error in this function. I use torch.nn.DataParallel(net)
def forward(self, input):
return F.conv1d(input, self.weight, self.bias, self.stride,
self.padding, self.dilation, self.groups)
Error for conv1d
TypeError: ‘float’ object cannot be interpreted as an integer |
st183161 | Ok I think that previously by mistake I add padding as floating number, but it was casted to int so that’s why everything looked fine and now it has changed after upgrade. Probably during conv1d init there should be type validators or am I wrong?
Now i have the same error. Shold I use inputs.cuda() or rather inputs.to(device) for Multi-gpu? In the example I can see inputs.to(device), but this approach gives me error below. I tried to find this kind of error, but solutions were not clear or didn’t work for me.
RuntimeError: Expected tensor for argument #1 ‘input’ to have the same device as tensor for argument #2 ‘weight’; but device 1 does not equal 0 (while checking arguments for cudnn_convolution) |
st183162 | Hey all, having some trouble with the pytorch audio installation.
$ python setup.py install
running install
running bdist_egg
running egg_info
writing torchaudio.egg-info/PKG-INFO
writing dependency_links to torchaudio.egg-info/dependency_links.txt
writing top-level names to torchaudio.egg-info/top_level.txt
reading manifest file ‘torchaudio.egg-info/SOURCES.txt’
writing manifest file ‘torchaudio.egg-info/SOURCES.txt’
installing library code to build/bdist.macosx-10.7-x86_64/egg
running install_lib
running build_py
running build_ext
building ‘_torch_sox’ extension
gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/anaconda3/include -arch x86_64 -I/anaconda3/include -arch x86_64 -I/anaconda3/lib/python3.6/site-packages/torch/lib/include -I/anaconda3/lib/python3.6/site-packages/torch/lib/include/TH -I/anaconda3/lib/python3.6/site-packages/torch/lib/include/THC -I/anaconda3/include/python3.6m -c torchaudio/torch_sox.cpp -o build/temp.macosx-10.7-x86_64-3.6/torchaudio/torch_sox.o -DTORCH_EXTENSION_NAME=_torch_sox -std=c++11
In file included from torchaudio/torch_sox.cpp:1:
In file included from /anaconda3/lib/python3.6/site-packages/torch/lib/include/torch/torch.h:5:
In file included from /anaconda3/lib/python3.6/site-packages/torch/lib/include/ATen/ATen.h:5:
In file included from /anaconda3/lib/python3.6/site-packages/torch/lib/include/ATen/Allocator.h:6:
/anaconda3/lib/python3.6/site-packages/torch/lib/include/ATen/Retainable.h:3:10: fatal error: ‘atomic’ file not found
#include
^~~~~~~~
1 error generated.
error: command ‘gcc’ failed with exit status 1
This is after installing sox and cloning the repo. Is there something I am missing?
I also tried upgrading my g++ to g+±8, but with no luck.
The corresponding issue is here: https://github.com/pytorch/audio/issues/52 3. Just thought I could also ask the community.
Any help appreciated! |
st183163 | A solution from @soumith :
Try
MACOSX_DEPLOYMENT_TARGET=10.10 CC=clang CXX=clang++ python setup.py install
Worked for me. Thanks. |
st183164 | When using the PyTorch, if you want to use the GPU only need to add ‘.cuda()’ in the corresponding place, or do you need other instructions in addition to this operation?
Why, when I only use ‘.cuda()’, I can be sure that he is running on the GPU, but I can’t feel the speed increase. |
st183165 | You should make sure to call .cuda() or .to(device='cuda') on your data and your model.
Depending on the model architecture, pushing it to the GPU won’t give you any speedups.
This is usually the case for small models.
Could you post your model architecture? |
st183166 | U can also check the bottleneck of your code. Sometimes, the data loading or other preprocessing will occupy some time. |
st183167 | Hello!
It is easy to convert audio (wav) to tensor using .load() command. But I am interested in reverse operation. Can someone help me?
Thanks! |
st183168 | Isn’t it torchaudio.save('amazing_sound.wav', sound, sample_rate) ?
By the way, you can find the doc here: http://pytorch.org/audio/ 261 |
st183169 | I am trying to create a data loader for audio dataset. I have a bunch of audio files and those are listed in a csv file. To create a data loader, I need to inherit Dataset class and implement getitem and len methods. I want to load and process audio data on the fly and additionally my DNN model is not sequence wise. I need to load a set of audio files pre-process it and divide it into frames of constant size. At the time of input(to DNN) I need to take a minibatch of audio frames(not whole audio sequence).
getitem method takes an index and return the data frame corresponding to the index. All my audio file paths are in a CSV file and I want the Dataset loader to input it and load, pre-process and divide it into frames on the fly.
What do i do to make ‘index’ variable of getitem correspond to audio data frames ?
Please help. |
st183170 | You can check yesno dataset implementation 124 for a general idea about how to build a custom dataset.
Regarding paths in csv, you can maybe create a preprocessed file which contains the audio files as tensors similar to how they have done it in here 40.
Well a simple trick is to do you own calculations and set your own length in the __init__ of you dataset class, and return that length in the __len__ method. And not worry about the index argument. So the dataloader will call your __getitem__ length-1 times and you can randomly pick the frames you want from your data, irrespective of the index value.
As for trimming the audio, normalizing, stft calculation, etc, you can use any of the available transforms 21, or write your own transforms which you can pass to your custom dataset. |
st183171 | I have installed torchaudio on top of pytorch 0.3.1 for python3.5.
But When I try to import torchaudioI get the following error:
AttributeError: module ‘torch’ has no attribute ‘hann_window’
Please help. |
st183172 | Pytorch 0.3.1 does not have the audio related functions. You should install 0.4, that has those required functions |
st183173 | This category is for topics related to either pytorch/opacus or general differential privacy related topics. |
st183174 | Hello,
I’m using Opacus for computing the per-sample gradient w.r.t the parameter. However, I also need to compute per-sample gradient of each logit w.r.t the input. Therefore I need to do back-propagation several times. A minimal example is as follows
import torch
from opacus.grad_sample import GradSampleModule
from torch.autograd import grad
class Model(torch.nn.Module):
def __init__(self, inputSize, outputSize):
super(Model, self).__init__()
self.linear = torch.nn.Linear(inputSize, outputSize)
def forward(self, x):
out = self.linear(x)
return out
num_classes = 2
bs = 16
model = Model(10,num_classes)
op_model = GradSampleModule(model)
op_model.zero_grad()
X = torch.rand(bs,10)
X.requires_grad = True
grad_x = torch.zeros(bs,num_classes,10)
output = op_model(X) # bs * num_classes
for c in range(num_classes):
grad_x[:,c,:] = grad(outputs=output[:,c], inputs=X,\
grad_outputs=torch.ones_like(output[:,c]),retain_graph=True)[0]
The error shows
IndexError: pop from empty list
It seems that Opacus won’t work if the number of backprop is greater than the number of forward pass, according to this post 4. However, in my use case (adversarial training) at some point I need to do backprop several times to compute input gradient (not parameter’s gradient). I wonder if it is possible to disable the grad_sample functionality temporarily, and enable it afterwards. I appreciate any suggestions on this.
Thanks! |
st183175 | Hi @Yuancheng_Xu!
The hook for computing grad_sample doesn’t work correctly with more than one backward pass.
I’m not sure I completely understand your use case, but I think you can do the following:
# initialize the vanilla model
model = Model(10,num_classes)
model.zero_grad()
X = torch.rand(bs,10)
X.requires_grad = True
grad_x = torch.zeros(bs,num_classes,10)
# compute the output and doutput/dinput
output = model(X) # bs * num_classes
for c in range(num_classes):
grad_x[:,c,:] = grad(
outputs=output[:,c],
inputs=X,
grad_outputs=torch.ones_like(output[:,c]),
retain_graph=True
)[0]
# add the hook & evaluate the model one more time to get the grad_sample
dp_model = GradSampleModule(model)
output = dp_model(X)
# ... apply gradient step with grad_sample
# remove hooks before the next iteration
# if you don't remove hooks, model(data) will be computed with grad_samples leading to the exception
# also you won't be able to recreate GradSampleModule(model) before removing hooks
dp_model.remove_hooks()
Note that using grads without properly added noise like in this case could break DP guarantees if you expected any. |
st183176 | Thanks for the reply!
My use case is that I need to compute a) grad_sample b) multiple backdrop for gradient of inputs alternatively. I have figured out the way to do it: ddp_model.module.enable_hooks() before a) and ddp_model.module.disable_hooks() before b). It works fine for me. |
st183177 | Hello,
I am using PyTorch 1.10.0+cu102 and Opacus 1.0.0 and would like to use differential privacy for the training of an image classifier. When using optimizer.step() during training, I get the following ValueError: Unexpected grad_sample type: <class ‘NoneType’>
Specifically, this is my Traceback:
Traceback (most recent call last):
File "run.py", line 102, in <module>
sc.run_learning()
File "/gpfs/home/user/diffp_project/run2.py", line 82, in run_learning
le.run_learning_and_testing_process()
File "/gpfs/home/user/diffp_project/LearningEnvironment.py", line 165, in run_learning_and_testing_process
client.federated_round_local_train(model=self.global_model)
File "/gpfs/home/user/diffp_project/Client.py", line 208, in federated_round_local_train
epoch_loss_train = self.local_train(model=self.model)
File "/gpfs/home/user/diffp_project/Client.py", line 176, in local_train
running_loss = BatchIterator(model=model, phase=phase, Data_loader=train_loader, criterion=criterion, optimizer=optimizer, device=self.device)
File "/gpfs/home/user/diffp_project/batchiterator.py", line 58, in BatchIterator
optimizer.step()
File "/home/user/miniconda3/envs/env5/lib/python3.7/site-packages/opacus/optimizers/optimizer.py", line 478, in step
if self.pre_step():
File "/home/user/miniconda3/envs/env5/lib/python3.7/site-packages/opacus/optimizers/optimizer.py", line 459, in pre_step
self.clip_and_accumulate()
File "/home/user/miniconda3/envs/env5/lib/python3.7/site-packages/opacus/optimizers/optimizer.py", line 366, in clip_and_accumulate
g.view(len(g), -1).norm(2, dim=-1) for g in self.grad_samples
File "/home/user/miniconda3/envs/env5/lib/python3.7/site-packages/opacus/optimizers/optimizer.py", line 313, in grad_samples
ret.append(_get_flat_grad_sample(p))
File "/home/user/miniconda3/envs/env5/lib/python3.7/site-packages/opacus/optimizers/optimizer.py", line 186, in _get_flat_grad_sample
raise ValueError(f"Unexpected grad_sample type: {type(p.grad_sample)}")
ValueError: Unexpected grad_sample type: <class 'NoneType'>
Does anybody know how to fix it?
Here is some more information about my code:
The model is a torchvision.models.densenet121(pretrained=True), the optimizer is a torch.optim.SGD(self.model.parameters(), lr=0.1, momentum=0), the loss criterion is nn.BCELoss().to(self.device).
I also run model = ModuleValidator.fix(model), and of course model, optimizer, train_loader = self.privacy_engine.make_private(…) before the training.
Thanks in advance! |
st183178 | Hi @general,
Would you be able to share with us a reproducible code so we can debug it? I believe another user has reported this here:
github.com/pytorch/opacus
Getting "ValueError: Unexpected grad_sample type: <class 'NoneType'>" for self-supervised training. 4
opened
Dec 12, 2021
vangorade
Congratulations on the new opacus version release!
I am trying to train a con…trastive learning model on time-series data with opacus version 1.0 by following the official [tutorial ](https://github.com/pytorch/opacus/blob/main/tutorials/building_image_classifier.ipynb).
Error:
"ValueError: Unexpected grad_sample type: <class 'NoneType'>"
Full error:
model_optimizer.step() -> error starts from this line in my code.
File "/mnt/f/AI_research/TS-TCC-main/opacus/opacus/optimizers/optimizer.py", line 478, in step
if self.pre_step():
File "/mnt/f/AI_research/TS-TCC-main/opacus/opacus/optimizers/optimizer.py", line 459, in pre_step
self.clip_and_accumulate()
File "/mnt/f/AI_research/TS-TCC-main/opacus/opacus/optimizers/optimizer.py", line 366, in clip_and_accumulate
g.view(len(g), -1).norm(2, dim=-1) for g in self.grad_samples
File "/mnt/f/AI_research/TS-TCC-main/opacus/opacus/optimizers/optimizer.py", line 313, in grad_samples
ret.append(_get_flat_grad_sample(p))
File "/mnt/f/AI_research/TS-TCC-main/opacus/opacus/optimizers/optimizer.py", line 186, in _get_flat_grad_sample
raise ValueError(f"Unexpected grad_sample type: {type(p.grad_sample)}")
ValueError: Unexpected grad_sample type: <class 'NoneType'>
Thank you. |
st183179 | Answered on Github
github.com/pytorch/opacus
Getting "ValueError: Unexpected grad_sample type: <class 'NoneType'>" for self-supervised training. 7
opened
Dec 12, 2021
closed
Jan 20, 2022
vangorade
Congratulations on the new opacus version release!
I am trying to train a con…trastive learning model on time-series data with opacus version 1.0 by following the official [tutorial ](https://github.com/pytorch/opacus/blob/main/tutorials/building_image_classifier.ipynb).
Error:
"ValueError: Unexpected grad_sample type: <class 'NoneType'>"
Full error:
model_optimizer.step() -> error starts from this line in my code.
File "/mnt/f/AI_research/TS-TCC-main/opacus/opacus/optimizers/optimizer.py", line 478, in step
if self.pre_step():
File "/mnt/f/AI_research/TS-TCC-main/opacus/opacus/optimizers/optimizer.py", line 459, in pre_step
self.clip_and_accumulate()
File "/mnt/f/AI_research/TS-TCC-main/opacus/opacus/optimizers/optimizer.py", line 366, in clip_and_accumulate
g.view(len(g), -1).norm(2, dim=-1) for g in self.grad_samples
File "/mnt/f/AI_research/TS-TCC-main/opacus/opacus/optimizers/optimizer.py", line 313, in grad_samples
ret.append(_get_flat_grad_sample(p))
File "/mnt/f/AI_research/TS-TCC-main/opacus/opacus/optimizers/optimizer.py", line 186, in _get_flat_grad_sample
raise ValueError(f"Unexpected grad_sample type: {type(p.grad_sample)}")
ValueError: Unexpected grad_sample type: <class 'NoneType'>
Thank you. |
st183180 | Hi, I compared two tests:
resnet20 on cifar10 with privacy-engine, the clipping norm is set to 10M. This should be equivalent to not doing clipping at all.
resnet20 on cifar10 without privacy-engine (noise-multiplier is set as 0), with exactly the same parameters as example 1.
Test 2 soon reached 92% accuracy while test 1 struggled to reach 85%. I then wrote another test where we created two models for the two above tests and made them train on the same data (with the same trainloader) simultaneously. Model 1 has optimizer 1 which is attached to a privacy-engine, while model 2 has optimizer 2 which is just a normal SGD optimizer.
The code looks something like this:
loss1.backward()
loss2.backward()
optimizer1.step()
optimizer2.step()
Before we call the step() functions, the param.grad are exactly the same between the two models. However, after we called the step() functions, there are approximately a 3% difference between the param.grad of the two models.
Is this because pytorch’s default way of computing gradient is different from opacus even when the clipping value is 10 million? Or is it because of accuracy loss during opacus computations? |
st183181 | Are you sure you use the same exact network in both cases? The “canonical” Resnet20 includes batch normalization, which is incompatible with DP-SGD. |
st183182 | Yes. We called the opacus’ convert_batchnorm_modules() function for both models. All the batchnorm layers are converted to groupnorm layers.
We also use model2.load_state_dict(copy.deepcopy(model1.state_dict())) at the beginning to make sure they start with the same network parameters. |
st183183 | Hi @Jun_Wan, is it possible your noise multiplier was non-zero in your first case? If yes, do you mind sharing a notebook with the above issue? This will help us debug further. |
st183184 | Hi @Jun_Wan. Has your issue been resolved? If not, do you mind sharing a notebook so we can look into this? |
st183185 | Hi, sorry. For some reasons, the previous notification emails went to the trash folder. I just noticed them today.
I posted our test code on GitHub - junwan0224/test-code 2. We used the compare.py file compare the gradients. One model has privacy engine while the other does not. We feed them the exact same data, but the resulted gradients are different.
For a previous question: yes, our noise multiplier is set as zero. Please let me know if there is any other question. Thank you for helping! |
st183186 | Hi @Jun_Wan
Thanks for sharing your code and thanks again for using Opacus!
I looked at your code and I suspect the issue might be because of the learning rate. It seems that the learning rate for the 2 optimizers are different:
on line 155 you define a LR scheduler for optimizer1 but not for optimizer2. So technically the two learnings are going through different training surfaces. You wrote
Jun_Wan:
Before we call the step() functions, the param.grad are exactly the same between the two models. However, after we called the step() functions, there are approximately a 3% difference between the param.grad of the two models.
and this kind of shows that, I think.
I know the test is for resnet20, but in case you use other resnets, make sure to also include optimizer2 on line 169.
lines 224-228 seem to only be for optimizer1
Last but not least, we have released Opacus 1.0 recently. So, when you have time, please migrate to Opacus 1.0 for more features: Release Opacus v1.0.0 · pytorch/opacus · GitHub
Please let us know if that didn’t solve the issue and we can investigate further. |
st183187 | I’m trying to utilise opacus with the PyTorch Lightning framework which we use as a wrapper around a lot of our models. I can see that there was an effort to integrate this partially into PyTorch Lightning late last year 5 but this seems to have stalled due to lack of bandwidth.
I’ve created a simple MVP 9 but there seems to be a compatibility problem with even this simple model; it throws AttributeError: 'Parameter' object has no attribute 'grad_sample' as soon as it hits the optimization step.
What’s the likely underlying cause of this? I can see on the opacus GitHub that similar errors have been encountered before where it’s been caused by unsupported layers but as the gist shows, this model is incredibly simple so I don’t think it’s any of the layers.
This is with:
opacus==0.11.0
pytorch-lightning==1.2.1
torch==1.7.1
torchaudio==0.7.2
torchvision==0.8.2 |
st183188 | Hi James! Would you have time to file a bug and share a colab so I can take a look? Integrating with Lightning is indeed on our plate |
st183189 | Hi @Darktex @James_M,
was there some progress made with the interaction with PyTorch Lightning?
I wrote a single integration myself also using the LightningCLI. I’m initializing the PrivacyEngine in the before_fit hook of a custom LightningCLI and attaching it to the configure_optimizer function of a typical LightningModule.
It seems to work, but I would be curious if there’s a best practice way of integration.
Regards |
st183190 | Hello @NiWaRe @James_M e have not worked yet on integrating PyTorch Lightning with Opacus. As mentioned, it is on our roadmap. Meanwhile, if you could share your changes either in Google Colab or send out a pull request in Github we would consider your changes when we are ready to start work on this. |
st183191 | Thanks for describing your solution @NiWaRe, do you have a code snippet you could share? |
st183192 | @sayanghosh @amin-nejad sorry was busy last weeks. I can gladly share the snippets, concerning PR should I rather commit to a tutorial in a Jupyter Notebook or think about how to integrate it directly into the framework without the need to overwrite different hooks?
What I have for now (prototyping code, the hparams are the defined params in my PL Model):
class LightningCLI_Custom(LightningCLI):
[...]
def before_fit(self):
"""Hook to run some code before fit is started"""
# possible because self.datamodule and self.model are instantiated beforehand
# in LightningCLI.instantiate_trainer(self) -- see docs
# TODO: why do I have to call them explictly here
# -- in docs not mentioned (not found in .trainerfit())
self.datamodule.prepare_data()
self.datamodule.setup()
if self.model.hparams.dp:
if self.model.hparams.dp_tool == "opacus":
# NOTE: for now the adding to the optimizers is in model.configure_optimizers()
# because at this point model.configure_optimizers() wasn't called yet.
# That's also why we save n_accumulation_steps as a model parameter.
sample_rate = self.datamodule.batch_size/len(self.datamodule.dataset_train)
if self.model.hparams.virtual_batch_size >= self.model.hparams.batch_size:
self.model.n_accumulation_steps = int(
self.model.hparams.virtual_batch_size/self.model.hparams.batch_size
)
else:
self.model.n_accumulation_steps = 1 # neutral
print("Virtual batch size has to be bigger than real batch size!")
# NOTE: For multiple GPU support: see PL code.
# For now we only consider shifting to cuda, if there's at least one GPU ('gpus' > 0)
self.model.privacy_engine = PrivacyEngine(
self.model.model,
sample_rate=sample_rate * self.model.n_accumulation_steps,
target_delta = self.model.hparams.target_delta,
target_epsilon=self.model.hparams.target_epsilon,
epochs=self.trainer.max_epochs,
max_grad_norm=self.model.hparams.L2_clip,
).to("cuda:0" if self.trainer.gpus else "cpu")
# necessary if noise_multiplier is dynamically calculated by opacus
# in order to ensure that the param is tracked
self.model.hparams.noise_multiplier = self.model.privacy_engine.noise_multiplier
print(f"Noise Multiplier: {self.model.privacy_engine.noise_multiplier}")
else:
print("Use either 'opacus' or 'deepee' as DP tool.")
# self.fit_kwargs is passed to self.trainer.fit() in LightningCLI.fit(self)
self.fit_kwargs.update({
'model': self.model
})
# in addition to the params saved through the model, save some others from trainer
important_keys_trainer = ['gpus', 'max_epochs', 'deterministic']
self.trainer.logger.experiment.config.update(
{
important_key:self.config['trainer'][important_key]
for important_key in important_keys_trainer
}
)
# the rest is stored as part of the SaveConfigCallbackWandB
# (too big to store every metric as part of the above config)
# track gradients, etc.
self.trainer.logger.experiment.watch(self.model)
Then in my model:
class LitModelDP(LightningModule):
def __init__(...):
[...]
# disable auto. backward to be able to add noise and track
# the global grad norm (also in the non-dp case, lightning
# only does per param grad tracking)
self.automatic_optimization = False
# manual training step, eval, etc.
def configure_optimizers(self):
optims = {}
# DeePee: we want params from wrapped mdoel
# self.paramters() -> self.model.wrapped_model.parameters()
if self.hparams.optimizer=='sgd':
optimizer = torch.optim.SGD(
self.model.parameters(),
**self.hparams.opt_kwargs,
)
elif self.hparams.optimizer=='adam':
optimizer = torch.optim.Adam(
self.model.parameters(),
**self.hparams.opt_kwargs,
)
if self.hparams.dp_tool=='opacus' and self.hparams.dp:
self.privacy_engine.attach(optimizer)
optims.update({'optimizer': optimizer})
[...]
return optims
Calling the LightningCLI at the end
cli = LightningCLI_Custom(model_class=LitModelDP, datamodule_class=[...])
I’m very open to feedback and would also gladly help to integrate that into PL. |
st183193 | Hello @NiWaRe,
Apologies for the delay in response. Adding Lightning support to Opacus will certainly electrify it. Thank you so much for working on it.
What took us so long to respond you ask? Well, we have been working on a major refactor to Opacus (v1.0), and this would mean breaking API changes and code movement. Would you mind sending a PR on top of GitHub - pytorch/opacus at experimental_v1.0 3 branch? |
st183194 | Hi @karthikprasad,
great yes, I’ll take a look at the new version on the weekend!
Best,
Nicolas |
st183195 | Hi everyone!
The problem reported by @James_M is fixed in this pull request 4. You can now add PrivacyEngine to LightningModel (see the demo in examples/mnist_lightning.py).
As we are working on the new API in experimental_v1.0 branch, I’m exploring ways to implement tighter (ideally seamless) integration between PyTorch Lightning and Opacus. In this RFC 1 I’ve shared some thoughts on how this integration can be implemented. Feedback and comments are much appreciated. Actually, I need help there.
@NiWaRe Many thanks for your prototype!
In LitModelDP we now can use automatic_optimization=True.
In my demos I simply put all the DP parameters in LightningModule.init so that we can enable DP and configure it via --model.xxx cmdline args. Extending LightningCLI is indeed a good next step. |
st183196 | Hi @Peter_Romov and @karthikprasad,
I’m sorry I didn’t respond, I was extremely busy with my thesis, which is due in three weeks.
Thanks for implementing this! I’ll take a look latest in three weeks when I’m done with my project |
st183197 | I was trying to use opacus with DCGAN,while i am training Discriminator with fake images,
In the line of “opt_D.step()”,such value error happened,i can’t figure out what’s going wrong?PLEASE HELP
162604723×297 21.8 KB |
st183198 | May I ask which version of Opacus you are using? Also, if you can provide a minimal reproducing code it would be easier for us to help you.
I just tried the dcgan example (opacus/dcgan.py at main · pytorch/opacus · GitHub 4) on my end and it seems to work well with Opacus 1.0 |
st183199 | I am training on MNIST images using resnet-18 architecture on a 16 GB GPU memory machine. Everything works perfectly if I do not attach the privacy engine to my optimizer, each batch takes about 1-2 GB GPU memory, which is flushed out after processing each batch, and hence the total GPU memory consumption stays around 2 GB throughout the process of training.
However, when I attach the privacy engine to my optimizer, the used GPU memory keeps accumulating with each batch. Hence, with the processing of each batch, the used GPU memory increases, and soon I receive CUDA out of memory error.
I am not able to understand why GPU memory is not being freed at the end of every batch upon the inclusion of the privacy engine. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.