id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st48168 | I have one more question,about that:
For both noiseless data as well as noisy input of the NN, I used dataloader (I have two data loader for each) Now I am a bit of worry because the shuffle option is set to True in both data loader. Do you think this might affect my training because I should compare same pixel from the noisy data with the same pixel from the noiseless data … |
st48169 | You should use one dataloader instead of two, and get the noise and noiseless data at the same time |
st48170 | Can you please give me a clue ?
below u can see my DataLoader codes:
class CustomDataset(torch.utils.data.Dataset):
def init(self, data):
self.data = data
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return len(self.data)
x = data_ll
separation = int(x.shape[0] * 0.8)
train = x[:separation]
test = x[separation:]
train_dataset = CustomDataset(train)
test_dataset = CustomDataset(test)
train_loader_ll = torch.utils.data.DataLoader(train_dataset, batch_size=2621,shuffle = False)
test_loader_ll = torch.utils.data.DataLoader(test_dataset, batch_size=655,shuffle = False)
print ("//////////////////////////Training dataset//////////////////////////")
for train_sample in train_loader_ll:
print(train_sample.shape)
print ("//////////////////////////Test dataset//////////////////////////")
for test_sample in test_loader_ll:
print(test_sample.shape)
Basically I use this twice. One for noisy data and the other for noiseless data. |
st48171 | What it’s the format of your data? I mean x have both noise and noise less data or only one of them? |
st48172 | x here is a tensor of the size (65536,1,92) and it is just noisy data.
I made one another class one trainload for the noiseless data. |
st48173 | I wish to build a Denoising autoencoder I just use a small definition from another PyTorch thread to add noise in the MNIST dataset. While training my model gives identical loss results. please tell me what I am doing wrong.
def add_noise(inputs):
noise = torch.randn_like(inputs)*0.3
return inputs + noise
Screenshot_1201116×729 34.1 KB |
st48174 | Could you post the model definition so that we could take a look, if you are accidentally detaching the computation graph? |
st48175 | Thankyou @ptrblck for the reply. I am posting my model. and please tell me what is wrongScreenshot_124701×617 35.5 KB |
st48176 | The model looks generally alright, but I’m not sure if you really want to apply the last F.relu on the output. As a debugging step you could remove it and rerun your training.
PS: you can post code snippets by wrapping them into three backticks ```, which would allow to copy and debug your code |
st48177 | Hi, How can I update my model parameters while I am keeping the original one unchanged?
Fix_net = model()
Fix_net = Fix_net.named_parameters()
NotFix_net_par = dict(Fix_net)
net = model()
net.load_state_dict(NotFix_net_par)
…
Now the Fix_net changed as well. However, I would like to update the NotFix_net_par, but keep Fix_net unchangedged |
st48178 | Solved by ptrblck in post #2
You could use copy.deepcopy fo create NotFix_net_par. |
st48179 | I am using this code to load image and add date stamp that I want to remove.
import torchvision.transforms as transforms
transform = transforms.Compose(
[transforms.ToTensor()])
class ImageL(Dataset):
def init(self,folder,width,height,transform):
self.folder = folder
self.transform = transform
self.images = glob.glob(os.path.join(folder,‘jpg’,’’,’.jpg’))
self.toal_imgs = natsorted(self.images)
self.ts = time.time()
self.ts = datetime.datetime.fromtimestamp(self.ts).strftime('%d-%m-%Y_%H-%M-%S')
self.width = width
self.heigth_im = height
def __len__(self):
return len(self.toal_imgs)
def __getitem__(self, i):
st = self.ts
width = self.width
height = self.heigth_im
font = cv2.FONT_HERSHEY_SIMPLEX
img_loc = self.toal_imgs[i]
img = cv2.imread(img_loc)
img_noise = cv2.putText(img, st, (10, 500), font, 1, (255, 255, 255), 2)
img_noise = cv2.resize(img_noise, (width, height))
#img_noise = img_noise.astype('float32') / 255
img = cv2.resize(img, (width, height))
#img = img.astype('float32') / 255
imp = np.asarray(img)
img_noise = np.asarray(img_noise)
#img = np.moveaxis(img,2,0)
#img_noise = np.moveaxis(img_noise,2,0)
img = self.transform(img)
img_noise = self.transform(img_noise)
return (img_noise,img)
batch_size = 32
width = 48
height = 48
my_dataset = ImageL(’/Users/knutjorgenbjuland/PycharmProjects/autoencoder’,width,height,transform)
trainset = data.DataLoader(my_dataset , batch_size=batch_size, shuffle=False,
num_workers=4, drop_last=True)
I used this as source for my code, https://medium.com/@garimanishad/reconstruct-corrupted-data-using-denoising-autoencoder-python-code-aeaff4b0958e
However when I am using loss = criterion(outputs.,labels)
I get this error,
RuntimeError: only batches of spatial targets supported (3D tensors) but got targets of dimension: 4 |
st48180 | nn.CrossEntropyLoss expects model outputs with a class dimension as [batch_size, nb_classes, *additional_dims], while the target should not contain this class dimension but instead [batch_size, *additional_dims] and its values should contain the class indices in the range [0, nb_classes-1] as described in the docs.
You are not supposed to set a batch size for any layer or criterion in PyTorch and I guess your target might be one-hot encoded and has thus the additional unwanted dimension.
If that’s the case, use target = torch.argmax(target, dim=1) to create the target tensor in its expected shape.
PS: you can post code snippets by wrapping them into three backticks ```, which makes debugging easier. |
st48181 | Hello,
I’m performing a batch of matrix multiplication using torch.matmul function or torch.mm function.
but, I found that the output of matmul is not equal to batch of mm, especially when the dimensions of the matrix are large.
For reference, here is what I used:
import numpy as np
import torch
def diff(x, y):
x_expand = x.unsqueeze(0).expand(2, *x.size())
y_expand = y.unsqueeze(0).expand(2, *y.size())
# @ means `matmul`
torch_diff = x @ y - (x_expand @ y_expand)[0]
numpy_diff = x.numpy() @ y.numpy() - (x_expand.numpy() @ y_expand.numpy())[0]
torch_numpy_diff = x @ y - x.numpy() @ y.numpy()
return torch_diff, numpy_diff, torch_numpy_diff
def check(x):
print("x.mean():", x.mean(), "x.max():", x.max())
torch_diff, numpy_diff, torch_numpy_diff = diff(x, x.t())
torch_diff = torch_diff.abs()
numpy_diff = np.abs(numpy_diff)
torch_numpy_diff = torch_numpy_diff.abs()
print("torch_diff.mean():", torch_diff.mean(), "torch_diff.max():", torch_diff.max())
print("numpy_diff.mean()", numpy_diff.mean(), "numpy_diff.max():", numpy_diff.max())
print("torch_numpy_diff.mean()", torch_numpy_diff.mean(), "torch_numpy_diff.max():", torch_numpy_diff.max())
print()
if __name__ == '__main__':
torch.manual_seed(0)
check(torch.randn([81, 100]))
check(torch.randn([81, 10000]))
check(torch.randn([81, 1000000]))
check(torch.randn([81, 10000]) * 100)
check(torch.randn([81, 10000]) * 10000)
env_info = f"- PyTorch version: {torch.__version__}\n" \
f"- CUDA version: {torch.version.cuda}\n" \
f"- cuDNN version: {torch.backends.cudnn.version()}\n"
print(env_info)
and I got the output like this:
x.mean(): tensor(-0.0085) x.max(): tensor(4.1015)
torch_diff.mean(): tensor(4.8151e-08) torch_diff.max(): tensor(7.6294e-06)
numpy_diff.mean() 0.0 numpy_diff.max(): 0.0
torch_numpy_diff.mean() tensor(8.4816e-08) torch_numpy_diff.max(): tensor(9.5367e-06)
x.mean(): tensor(0.0004) x.max(): tensor(4.6582)
torch_diff.mean(): tensor(4.0393e-05) torch_diff.max(): tensor(0.0029)
numpy_diff.mean() 0.0 numpy_diff.max(): 0.0
torch_numpy_diff.mean() tensor(2.7329e-05) torch_numpy_diff.max(): tensor(0.0020)
x.mean(): tensor(2.8049e-05) x.max(): tensor(5.5180)
torch_diff.mean(): tensor(0.0091) torch_diff.max(): tensor(2.5625)
numpy_diff.mean() 0.0 numpy_diff.max(): 0.0
torch_numpy_diff.mean() tensor(0.0014) torch_numpy_diff.max(): tensor(0.4375)
x.mean(): tensor(-0.0214) x.max(): tensor(503.4597)
torch_diff.mean(): tensor(0.4008) torch_diff.max(): tensor(40.)
numpy_diff.mean() 0.0 numpy_diff.max(): 0.0
torch_numpy_diff.mean() tensor(0.2926) torch_numpy_diff.max(): tensor(24.)
x.mean(): tensor(2.8537) x.max(): tensor(44475.2266)
torch_diff.mean(): tensor(3845.2627) torch_diff.max(): tensor(327680.)
numpy_diff.mean() 0.0 numpy_diff.max(): 0.0
torch_numpy_diff.mean() tensor(2937.2839) torch_numpy_diff.max(): tensor(262144.)
- PyTorch version: 1.7.0
- CUDA version: 10.1
- cuDNN version: 7603 |
st48182 | Solved by ptrblck in post #2
If you calculate the relative difference using:
torch_diff.max()/([email protected]()).abs().max()
you’ll get differences in the range ~1e-7 to ~1e-6, which points to rounding errors due to the limited floating point precision which are created e.g. by a different order of floating point operations. |
st48183 | If you calculate the relative difference using:
torch_diff.max()/([email protected]()).abs().max()
you’ll get differences in the range ~1e-7 to ~1e-6, which points to rounding errors due to the limited floating point precision which are created e.g. by a different order of floating point operations. |
st48184 | I’m trying to use a precompiled library for custom implementations of standard routines. I’ve been looking on the internet but have not had much luck finding documentation. Does anyone know how to start/ where to look for more information? |
st48185 | Solved by ptrblck in post #4
You should be able to add your library to cmake as explained here. |
st48186 | What kind of library are you looking for and how does PyTorch come into play here?
Could you explain your use case a bit more, please? |
st48187 | I am building library to execute deep learning models with limited memory. This library has custom implementations of standard routines(forward_pass, etc) written in C++. I have attempted to extend the files as explained from this tutorial. However, I have been having issues with dependencies between the library and Pytorch. As an alternate approach, I’m trying to utilize the library precompiled. I know that Pytorch uses the cuDNN library for CUDA. Is it possible to replicate that process for a custom library? I hope that shed some light on my question.
Thank you for your help! |
st48188 | I am porting some code from Pytorch 0.4 to 1.7, and in the docs (and similarly in the code I am porting) I come across:
input = torch.empty((2,3), dtype=torch.int64)
input.new(input.size())
I’m not sure what input.new does, considering input is an empty array of shape (2,3) and dtype torch.int64. Any insights appreciated. |
st48189 | I’m using tensorboard’s
make_grid
functionality to make grid of bunch of images, and then display them as seen in the image.
I’d like to ask if it’s possible to add row and column numbers to a grid so I can refer individual images easily when discussing with others. |
st48190 | Are you sure tensorboard has a make_grid method and you are not using the one from torchvision.utils.make_grid 9?
In the latter case, you can specify the number of rows via nrow. |
st48191 | yes, you’re right. I mean torcvision’s make grid.
I know I can specify the number of rows like that but i’d rather want to add indexes by the sides of grid to
to highlight a particular image in the grid.
Like I’d like to see 1 2 … nrows at the top of the grid, and 1 2 … ncol at the left side of the grid for example. |
st48192 | There is one weird phenomenon that after I doubled my batchsize in a training process, the data loading time is almost doubled ( about 1.8 times long as original).
I measure the data loading time by measure the interval between the end of each iter and beginning of next iter. ( That is when the for loop to fetch next batch).
I simplified the logic as follows:
import ...
end = time.time()
For (input , label) in loader:
data_load_time = time.time() - end
output = model(input)
loss = crit(output, label)
...
end = time.time()
I conducted experiments on a single gpu to compare bch32 and bch64 settings:
gpu 1 batch 32
Time 2.505s (2.551s) Speed 12.8 samples/s Data 1.808s (1.849s)
gpu 1 bch 64 (cpu 5, worker 24)
Time 4.707s (4.897s) Speed 13.6 samples/s Data 3.453s (3.599s)
It shows that with larger batchsize, the dataLoading time is nearly doubled. (around 1.8).
With multiple-workers, the loading process should be conducted before hand and will be ready when it is needed.
So with enough workers, larger batch should not delay much comparing to a small batch setting as the loading is handled parallelly with multiple cpu thread.
This causes troubles. It means more gpu resource (either more gpus or larger G-mem) will not help to reduce the training time, as the data loading time is proportional to batchsize. Even you get enough GPU to handle more data at same time, the dataloading will delay everything up. |
st48193 | Sergius_Liu:
With multiple-workers, the loading process should be conducted before hand and will be ready when it is needed.
Multiple workers try to load the data in the background, while the model training is executed.
If the workers are not fast enough or bottlenecked by e.g. a local (spinning) HDD, they won’t be able to preload the next batch, which seems to be the case for your training routine.
Have a look at this post 44 for more information. |
st48194 | It makes sense that IOPS could limit the reading speed as the data are lots of images.
Here is what I think:
Let’s assume the IOPS is a fix number N.
If the data reading workload is under the drive’s capability (let’s assume the corresponding batch size is n), the data loading time cost should be similar when the batch size is lower than n.
Or we can assume that the batch/time curve is linear(proportional) when batch>n and is flattened when batch is really small batch<=n.
So I did a test with varying batch size numbers:
gpu 1 batch 32
Time 2.505s (2.551s) Speed 12.8 samples/s Data 1.808s (1.849s)
gpu 1 bch 64 (cpu 5, worker 24)
Time 4.707s (4.897s) Speed 13.6 samples/s Data 3.453s (3.599s)
bch 16
Time 1.349s (1.351s) Speed 11.9 samples/s Data 0.900s (0.917s)
proportional to batchsize??
bch 8
Time 0.814s (0.832s) Speed 9.8 samples/s Data 0.471s (0.476s)
bch 4
Time 0.542s (0.590s) Speed 7.4 samples/s Data 0.242s (0.259s)
…
It is surprising that even the batch size is as small as 4, the reading time is still almost follows the linear curve trend instead of flattened.
Does it mean the reading is very slow and even 4 batch size is already large enough to make the data loading the bottle neck.
BTW, I am working on a cluster. The shared file system could cause this issue. |
st48195 | Might be the case and you could try to profile the data reading from your storage separately to get an idea of the max. throughput.
The shared file system sound interesting. Is it a network drive? If so, this would most likely limit the loading speed. |
st48196 | I have profiled the data reading with a python loop for loop.
For cleanness, only the loop section is presented.
for i, db in enumerate(train_dataset.db):
st = time.time()
image_file = db['image']
data_numpy = cv2.imread(
image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION
)
smplRd_tm.update(time.time()- st)
if i % 100 == 0 : # print out the time
print('Time cost {tm.val:.6f}s ({tm.avg:.6f})'.format(tm=smplRd_tm))
The images are supposed to be read continuously without any processing. So it can roughly measure how fast each image is read in from the file system. What I get is:
…
Time cost 0.009754s (0.022841)
Time cost 0.015513s (0.022823)
Time cost 0.034945s (0.022812)
Time cost 0.012610s (0.022782)
Time cost 0.017248s (0.022775)
Time cost 0.030351s (0.022780)
Time cost 0.030921s (0.022800)
…
So each image reading costs roughly 0.02 s.
I found that bottleneck comes from the debug image saving in the training loop.
I reduced frequency and it is much better now.
Thanks. |
st48197 | Iused pytorch to create 3DCNN
My code works with 2 layers of conv. But does not work with 3 layers of conv.
input image size:120120120
Result: RuntimeError: mat1 dim 1 must match mat2 dim 0
I think the problem is with this line out = self.fc1(out)
can you help me please ?
thank you in advance!
class CNNModel(nn.Module):
def __init__(self):
super(CNNModel, self).__init__() # héritage
self.conv_layer1 = self._conv_layer_set(3, 32) #The first dimension of Pytorch Convolution should always be
#the the number of channels (3)
self.conv_layer2 = self._conv_layer_set(32, 64)
self.conv_layer3 = self._conv_layer_set(64, 128)
self.fc1 = nn.Linear(128*28*28*28, 2) # couche linéaire entièrement connectée,
self.fc2 = nn.Linear(2809856, num_classes) ###### couche linéaire entièrement connectée
self.relu = nn.LeakyReLU()
self.batch=nn.BatchNorm1d(2)
self.drop=nn.Dropout(p=0.15, inplace = True)
def _conv_layer_set(self, in_c, out_c):
conv_layer = nn.Sequential(
nn.Conv3d(in_c, out_c, kernel_size=(3, 3, 3), padding=0),
nn.LeakyReLU(),
nn.MaxPool3d((2, 2, 2)),
)
return conv_layer
def forward(self, x):
# Set 1
out = self.conv_layer1(x)
out = self.conv_layer2(out)
out = self.conv_layer3(out)
#out = out.view(out.size(0), -1) #regler l'output pour devenir l'input de Flly conncted layer
out = out.view(out.size(0), -1)
out = self.fc1(out)
out = self.relu(out)
out = self.batch(out) # batchnormalization pour
out = self.drop(out)
out = F.softmax(out, dim=1) # softmax dim = 1 puisque 1 sig. batch size )
return out |
st48198 | Solved by ptrblck in post #2
Could you add a print statement before the usage of fc1 and check the shape of the activation tensor?
print(out.shape)
out = self.fc1(out)
I guess that out.shape doesn’t match the expected input features as 128*28*28*28 so that you might have to adjust this value in self.fc1. |
st48199 | Could you add a print statement before the usage of fc1 and check the shape of the activation tensor?
print(out.shape)
out = self.fc1(out)
I guess that out.shape doesn’t match the expected input features as 128*28*28*28 so that you might have to adjust this value in self.fc1. |
st48200 | If I use DataParallel() in tranformer model (https://pytorch.org/tutorials/beginner/transformer_tutorial.html)
The time for each epoch increases as we increase the number of GPUs,
Example: time for one epoch
1 GPU = 42 sec - 44 sec
4 GPUs = 175 sec - 180 sec
Why performance is decreasing if we increase the number of GPUs, is it a drawback in DataParallel()? |
st48201 | nn.DataParallel creates model replicas in each forward pass and thus needs to broadcast a lot of parameters. We generally recommend to use DistributedDataParallel with a single process per device for the fastest approach(also on a single node with multiple GPUs). |
st48202 | @gnadaf were you able to actually run the model by just adding nn.DataParallel(model)?
I can run my model just fine w/o DataParallel, but w/ DataParallel the training doesn’t proceed (kind of freezes). |
st48203 | @Abhilash_Srivastava
Yes, I am able to run my code, we need to add just nn.DataParallel(model), |
st48204 | @ptrblck
Does it mean nn.DataParallel() has drawback?
Is there no advantages of using nn.DataParalllel? |
st48205 | nn.DataParallel certainly has advantages and it should speed up your training in some cases (try with a simple CNN + FC model).
However, as ptrblck mentioned the major disadvantage of nn.DataParallel is that it creates model replicas in each forward pass and thus needs to broadcast a lot of parameters.
Since most transformer models are huge (w/ millions of parameters), the advantage of increased speed (due to data parallelism) is overshadowed by the reduction in speed due to broadcasting.
Hence, DistributedDataParallel 3 is the recommended way. |
st48206 | Hi there,
I am trying to implement 1 DCNN over raw audio data (mono channel).
I have say 60ksamples in all of wav files. Now my model code goes like
…
self.conv_1 = nn.Conv1d(self.input_spec_size,self.cnn_filter_size,3,1)
self.max_pooling_1 = nn.MaxPool1d(3)
…
But it throws the error: Expected 3-dimensional input for 3-dimensional weight [64, 60000, 3], but got 2-dimensional input of size [40, 60000] instead
Here 64 is no of output filters, 3 is kernel size and 40 is my batch size. Plz someone guide how to reshape this (60000,1 ) input data.
#########################
I tried reshaping input as
data.reshape(1,60000)
then the error :
Given groups=1, weight of size [64, 60000, 3], expected input[40, 1, 60000] to have 60000 channels, but got 1 channels instead |
st48207 | For starters, it looks like your in_channels argument is taking the value 60000. I believe that needs to be 1.
Conv1d expects inputs in the shape (batch_size, n_channels, Seq Length), so your data must be reshaped as (40, 1, 60000)
CN = torch.nn.Conv1d(in_channels=1, out_channels=64, kernel_size=3)
trial = torch.randn((40, 60000))
out = CN(trial.reshape(40, 1, 60000))
# out is of shape [40, 64, 59998] , 59998 being the expected number of samples after convolution |
st48208 | Thanks a lot, I have corrected already but another problem rose. I hope you can help me with this, I am very new to understand pytorch lstm and encoderlayer.
in my model 1 D CNN is followed by lstm layers, But at this encoder layer I am getting syntax error
self.encoder_layer=nn.TransformerEncoderLayer(d_model=self.hidden_size_lstm*2,dim_feedforward=512,nhead=self.num_heads_self_attn)
I am not getting whats wrong, referred doc of pytorch too. |
st48209 | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn import functional as F
class CNN_1D(torch.nn.Module):
def init(self, num_layers_lstm, num_heads_self_attn,
hidden_size_lstm, num_emo_classes):
super(CNN_1D, self).init()
self.num_layers_lstm=num_layers_lstm
self.num_heads_self_attn=num_heads_self_attn
self.hidden_size_lstm=hidden_size_lstm
self.num_emo_classes=num_emo_classes
#self.num_gender_class=num_gender_class
self.layer1 = nn.Sequential(
nn.Conv1d(self.input_spec_size,64,3,1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2))
self.layer2 = nn.Sequential(
nn.Conv1d(64,100,5,1),
nn.BatchNorm2d(100),
nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2))
self.layer3 = nn.Sequential(
nn.Conv1d(100,100,7,1),
nn.BatchNorm2d(100),
nn.ReLU(),
###
self.lstm = nn.LSTM(input_size=100, hidden_size=self.hidden_size_lstm,num_layers=self.num_layers_lstm,bidirectional=True,dropout=0.5,batch_first=True)
## Transformer
self.encoder_layer = nn.TransformerEncoderLayer(d_model=self.hidden_size_lstm*2,dim_feedforward=512,nhead=self.num_heads_self_attn)
#self.gender_layer = nn.Linear(self.hidden_size_lstm*4,self.num_gender_class)
self.emotion_layer = nn.Linear(6664,self.num_emo_classes)
self.encoder_layer = nn.TransformerEncoderLayer(d_model=self.hidden_size_lstm*2,dim_feedforward=512,nhead=self.num_heads_self_attn)
^
SyntaxError: invalid syntax |
st48210 | In your code, some of the parameters are missing. I modified your code slightly and now it should be possible to initialize the class CNN_1D. Make changes wherever required.
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn import functional as F
class CNN_1D(torch.nn.Module):
def __init__(self, num_layers_lstm, num_heads_self_attn, hidden_size_lstm, num_emo_classes, input_spec_size):
super(CNN_1D, self).__init__()
self.num_layers_lstm = num_layers_lstm
self.num_heads_self_attn = num_heads_self_attn
self.hidden_size_lstm = hidden_size_lstm
self.num_emo_classes = num_emo_classes
self.input_spec_size = input_spec_size
# self.num_gender_class=num_gender_class
self.layer1 = nn.Sequential(
nn.Conv1d(self.input_spec_size, 64, 3, 1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2))
self.layer2 = nn.Sequential(
nn.Conv1d(64, 100, 5, 1),
nn.BatchNorm2d(100),
nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2))
self.layer3 = nn.Sequential(
nn.Conv1d(100, 100, 7, 1),
nn.BatchNorm2d(100),
nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2))
###
self.lstm = nn.LSTM(input_size=100, hidden_size=self.hidden_size_lstm, num_layers=self.num_layers_lstm,
bidirectional=True, dropout=0.5, batch_first=True)
## Transformer
self.encoder_layer = nn.TransformerEncoderLayer(d_model=self.hidden_size_lstm * 2, dim_feedforward=512,
nhead=self.num_heads_self_attn)
# self.gender_layer = nn.Linear(self.hidden_size_lstm*4,self.num_gender_class)
self.emotion_layer = nn.Linear(6664, self.num_emo_classes) |
st48211 | Still I am getting this error,
Given groups=1, weight of size [64, 7, 3], expected input[1, 1, 60000] to have 7 channels, but got 1 channels instead
this 7 channel, I am not getting. Then I am trying to calculate output at each layer
import torch
import torch.nn as nn
I=torch.randn(40,1,60000) #### 40 is batch size,60000 is sample length
layer1 = nn.Sequential(
nn.Conv1d(1,64,3,1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2))
O1=layer1(I)
It says: expected 4D input (got 3D input) |
st48212 | You’ll need to use BatchNorm1d(64).
Edit: Also seen that you are using MaxPool2d. That needs to be changed to 1D as well. Using 2D will also affect the number of filters. |
st48213 | are you able to figure out the first error here. in my previous post?
Actually let me try to clarify : I have calculated the out tensor size after three con1d layers as
[40,100,7494]
where 40 is batch size, 100 is the out features of conv layer and 7494 is the output of the sequence…right?
Now I want to move further for LSTM layer here I am doing this:
rnn = nn.LSTM(7494, 60, 2,bidirectional=True, dropout=0.5, batch_first=True)
output= rnn(O3)
I have replaced the input size as 7494 (not 100), As it was giving error.
Here the output is a tuple. Now cud you plz tell me how to check the output size further for TransformerEncoderLayer and final linear layer.
I think this shape error is arising here only.
EROOR:
Given groups=1, weight of size [64, 7, 3], expected input[1, 1, 60000] to have 7 channels, but got 1 channels instead |
st48214 | Here O3 is the output of third conv1d layer* Also my confusion is ,
there is no role of previous output features as 100.
@pchandrasekaran @Abhilash_Srivastava Sir plz help me |
st48215 | I = torch.randn(40,1,60000)
layer1 = nn.Sequential(
nn.Conv1d(1, 64, 3, 1),
nn.BatchNorm1d(64),
nn.ReLU(),
nn.MaxPool1d(kernel_size=3, stride=2))
layer2 = nn.Sequential(
nn.Conv1d(64, 100, 5, 1),
nn.BatchNorm1d(100),
nn.ReLU(),
nn.MaxPool1d(kernel_size=3, stride=2))
layer3 = nn.Sequential(
nn.Conv1d(100, 100, 7, 1),
nn.BatchNorm1d(100),
nn.ReLU(),
nn.MaxPool1d(kernel_size=3, stride=2))
op = layer1(I)
print(op.shape)
op = layer2(op)
print(op.shape)
op = layer3(op)
print(op.shape)
op is now [40, 100, 7494]
rnn = nn.LSTM(7494, 60, 2, bidirectional=True, dropout=0.5, batch_first=True)
op, not_needed = rnn(op)
In the above op is your output. Ignore the variable not_needed for now. op will be of shape (batch, seq, num_directions * hidden_size), which upon checking, it is.
op shape now = [40, 100, 120]
Here’s where I’m not too sure. I have limited experience using LSTMs and looking at my codes, I’ve only used the final sequence. Depending on what you are going to do, you can leave op as is or if you are taking the final sequence only, reshape it as, op = op[:, -1, :].reshape(40, 1, 120)
encoder_layer = nn.TransformerEncoderLayer(d_model=120, dim_feedforward=512, nhead=your_nhead)
op = encoder_layer(op)
op now will have 2 shapes, one if you used all the sequences another if you used only the last.
[40, 100, 120]
[40, 1, 120]
From here, your Linear Layers are [100x120] or [1x120].
The 100 that you mentioned is used as the sequence length for your LSTM. |
st48216 | @pchandrasekaran Thanks
This 100 is not mentioned there in LSTM layer, so is it automatically taken ?
and how to choose between this option of 1 and 100.Yes in this way I am getting this shape [40,100,120]
and in last linear layer
############
self.emotion_layer = nn.Linear(120, self.num_emo_classes)
############
I have read a blog where its wriiten that ’ The input of our fully connected nn.Linear() layer requires an input size corresponding to the number of hidden nodes in the preceding LSTM layer. Therefore we must reshape our data into the form’
So I wrote 120 here.
and finally defined the forward function as
def forward(self,inputs):
out = self.layer1(inputs)
out = self.layer2(out)
out = self.layer3(out)
out = self.lstm(out)
out = self.encoder_layer(out)
pred = self.emotion_layer(out)
return pred
Error: Given groups=1, weight of size [64, 7, 3], expected input[1, 1, 60000] to have 7 channels, but got 1 channels instead
I hope I am clear now sir? |
st48217 | I have read a blog where its wriiten that ’ The input of our fully connected nn.Linear() layer requires an input size corresponding to the number of hidden nodes in the preceding LSTM layer.
That explains why my codes only have the last sequence. Ty for that. So use only the last sequence of the LSTM. For the error, could you copy your entire code snippet so I can try and reproduce the error. That looks like an error in the convolution layers. |
st48218 | This code is in 4 parts , I dnt know how to post here?
Can I mail You the entire code? |
st48219 | Last night I put my model on training. A transformer model for Lyft5 Kaggle competition. Lo and behold, the next morning my SSD (Biostar m500 1TB) is dead (I mean dead as a brick and sent back to use warranty). The dataloader had memory leak despite my efforts to tune workers and batch size. I don’t know what happened. Whether it was swap memory overload or checkpoint model saving that lead to this event, I have no idea.
I was wondering if any of you guys had such an experience. Thank you.
PC spec:
core i9 10980xe
64gb of RAM
RTX 2080TI |
st48220 | I’m trying to train multi gpu DistributedDataParallel.
for epoch in range(args.start_epoch, args.num_epoch):
train(train_loader, model, scheduler, optimizer, epoch, args)
if (epoch + 1) % 1 == 0:
print('test args...',args)
validation(valid_dataset, model, epoch, args)
state = {
'epoch': epoch,
'parser': args,
'state_dict': get_state_dict(model)
}
torch.save(
state,
os.path.join(
args.save_folder,
args.dataset,
args.network,
"checkpoint_{}.pth".format(epoch)))
this code give some error
-- Process 0 terminated with the following error:
Traceback (most recent call last):
File "/home/jake/venv/lib/python3.6/site-packages/torch/multiprocessing/spawn.py", line 20, in _wrap
fn(i, *args)
File "/home/jake/Gits/EfficientDet.Pytorch/train.py", line 341, in main_worker
test(valid_dataset, model, epoch, args)
File "/home/jake/Gits/EfficientDet.Pytorch/train.py", line 164, in test
evaluate(dataset, model)
File "/home/jake/Gits/EfficientDet.Pytorch/eval.py", line 190, in evaluate
generator, retinanet, score_threshold=score_threshold, max_detections=max_detections, save_path=save_path)
File "/home/jake/Gits/EfficientDet.Pytorch/eval.py", line 103, in _get_detections
2, 0, 1).cuda().float().unsqueeze(dim=0))
File "/home/jake/venv/lib/python3.6/site-packages/torch/nn/modules/module.py", line 722, in _call_impl
result = self.forward(*input, **kwargs)
File "/home/jake/venv/lib/python3.6/site-packages/torch/nn/parallel/distributed.py", line 511, in forward
output = self.module(*inputs[0], **kwargs[0])
File "/home/jake/venv/lib/python3.6/site-packages/torch/nn/modules/module.py", line 722, in _call_impl
result = self.forward(*input, **kwargs)
File "/home/jake/Gits/EfficientDet.Pytorch/models/efficientdet.py", line 61, in forward
inputs, annotations = inputs
ValueError: not enough values to unpack (expected 2, got 1)
seems like it run gpu0 and gpu1 and try to validation one by one.
but some how second one does not recognized as validation then gives this error |
st48221 | I’m trying to one-hot encode a feature in my network, but I’m not sure how to properly update the weights or if this is a good approach at all. Any feedback is appreciated.
My current approach:
A helper class for the encoded feature:
class Encoder(torch.nn.Module):
def __init__(self, num_classes):
super().__init__()
self.fc = torch.nn.Linear(in_features=num_classes, out_features=1)
def forward(self, x):
return self.fc(x.float())
My actual network’s forward method assumes the first feature is to be encoded (pclass is the name of the feature & self.pclass_encoder is an instance of the above helper class):
def forward(self, x):
real_features = x[:, 1:]
encoded_features = torch.nn.functional.one_hot(x[:, 0].long() - 1)
sig = torch.nn.Sigmoid()
pclass_out = self.pclass_encoder.forward(encoded_features)
x = torch.cat((pclass_out, real_features), 1)
x = self.fc1(x)
x = sig(self.out(x))
return x
In my training loop, I hoped that the gradient would propagate by just adding an extra optimizer for the helper class and stepping it like I do for the main network.
optimzer = torch.optim.Adam(model.parameters(), lr=0.01)
encoder_optimizer = torch.optim.Adam(pclass_encoder.parameters(), lr=.01)
EPOCHS = 4000
for i in range(EPOCHS):
predictions = model.forward(features)
loss = loss_fn(predictions, labels)
optimzer.zero_grad()
encoder_optimizer.zero_grad()
loss.backward()
optimzer.step()
encoder_optimizer.step()
The weight attribute of the encoded layer does appear to be updating. |
st48222 | To me, the entire thing seems to be end-to-end trainable. Have you tried using only the model optimizer and checking if the weights of Encoder fully connected layer are updated or not? |
st48223 | Good call! Originally I only used the one optimizer, but I got sidetracked by my troubleshooting and forgot to revisit that.
The weights of Encoder do in fact get updated with just the model optimizer. This is what I was hoping for and had assumed that the model graph would include anything through which my input tensors were passed. |
st48224 | I’m trying to improve the performance of my PyTorch code by using a preallocated page locked tensor to copy all my results from the GPU into. The results from the GPU will vary in size in the first dimension so I created a pinned buffer large enough to handle the max sized result.
What is the most performant way to copy the undersized results in the pinned memory and then to numpy arrays of their original size?
import torch
channels = 8
maxsize = 10
# create a page locked buffer on the cpu of masize in first dimension
buf = torch.zeros([maxsize, channels], pin_memory=True)
# create smaller tensors on the gpu
data = [
torch.empty((i, channels), device="cuda").fill_(i)
for i in range(1, 6)
]
model = lambda x: x
results = []
for res in data:
# run dummy model
res = model(res)
# best way to async copy the smaller res tensor from the gpu?
buf[:res.shape[0], :] = res
# check buffer looks correct
print(buf[:, 0], buf.data_ptr())
# do something with the correct sized results
results.append(buf[:res.shape[0], :].clone().numpy())
# check results look correct
for res in results:
print(res[:, 0])
tensor([1., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) 140124862021632
tensor([2., 2., 0., 0., 0., 0., 0., 0., 0., 0.]) 140124862021632
tensor([3., 3., 3., 0., 0., 0., 0., 0., 0., 0.]) 140124862021632
tensor([4., 4., 4., 4., 0., 0., 0., 0., 0., 0.]) 140124862021632
tensor([5., 5., 5., 5., 5., 0., 0., 0., 0., 0.]) 140124862021632
[1.]
[2. 2.]
[3. 3. 3.]
[4. 4. 4. 4.]
[5. 5. 5. 5. 5.] |
st48225 | How do I compute geometric mean of the weights and biases in a federated learning settings?
I’m able to compute the arithmetic mean, only. |
st48226 | Hi en!
en_tetteh:
How do I compute geometric mean?
You can calculate the geometric mean directly. Suppose that you
have the weights and/or biases whose geometric mean you want
in a single tensor, w. Then:
geom_mean = w.prod()**(1 / w.numel())
Note, it might be preferable to perform the calculation in log-space:
geom_mean = w.log().mean().exp()
(The geometric mean only makes sense – for some definition of
“makes sense” – if the values are all strictly positive. As you can
see, both the fractional power in the direct-space calculation and
the log() in the log-space calculation will fail for negative values.)
Best.
K. Frank |
st48227 | Thanks for your response Frank. I tried your approach, but it didn’t work for my case.
Instead of the mean computation below, I want the geom.
model_dict[k] = th.stack([h_models[i].state_dict()[k].float()*(n*h_lens[i]/total) for i in range(len(h_models))], 0).mean(0)```
code source: (https://towardsdatascience.com/preserving-data-privacy-in-deep-learning-part-3-ae2103c40c22) |
st48228 | def validation_epoch_end(self, outputs):
val_loss = torch.stack([x['val_loss'] for x in outputs]).mean()
log = {'avg_val_loss': val_loss}
return {'log': log, 'val_loss': log}
When i am using the above method in pytorh lightning it throws me an error TypeError: cannot unpack non-iterable NoneType object
This is happening before the last step of validation data. I can see that the return {'log': log, 'val_loss': log} is where the error is but couldnt actually find out whats wrong |
st48229 | nivesh_gadipudi:
[x['val_loss'] for x in outputs]
Check if this part is returning the results as expected. |
st48230 | def validation_epoch_end(self, outputs):
val_loss = torch.stack([x['val_loss'] for x in outputs]).mean()
log = {'avg_val_loss': val_loss}
return {'val_loss': val_loss, 'log': log}
I used it instead like this and now its working, thanks @Abhilash_Srivastava |
st48231 | class LSTMModel(nn.Module):
def __init__(self, lstm_size=50, linear_size=50, vocab_size=20000):
super(LSTMModel, self).__init__()
self.linear_size = linear_size
self.lstm_size = lstm_size
self.embeds = nn.Embedding(vocab_size, 128)
self.lstm = nn.LSTM(128, lstm_size)
self.dropout = nn.Dropout(.1)
self.fc1 = nn.Linear(lstm_size, linear_size) # * 2 for bidirection
self.fc2 = nn.Linear(linear_size, 6)
def forward(self, x):
h0 = Variable(torch.zeros(1, x.size(1), self.lstm_size)) # 2 for bidirection
c0 = Variable(torch.zeros(1, x.size(1), self.lstm_size))
out = self.embeds(x)
out = out.view(len(x), x.size(1), -1)
out, _ = self.lstm(out, (h0, c0))
out = self.dropout(out[-1])
out = self.fc1(out)
out = torch.nn.functional.relu(out)
out = self.dropout(out)
out = self.fc2(out)
out = torch.nn.functional.sigmoid(out)
return out
If I forward pass with a batch size bigger than 1 I get this error:
RuntimeError Traceback (most recent call last)
<ipython-input-219-ce43ac67861e> in <module>()
1 t = dataset[:10][0]
----> 2 model(t.t())
~/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
323 for hook in self._forward_pre_hooks.values():
324 hook(self, input)
--> 325 result = self.forward(*input, **kwargs)
326 for hook in self._forward_hooks.values():
327 hook_result = hook(self, input, result)
<ipython-input-217-478ca91c0a21> in forward(self, x)
20 h0 = Variable(torch.zeros(1, x.size(1), self.lstm_size)) # 2 for bidirection
21 c0 = Variable(torch.zeros(1, x.size(1), self.lstm_size))
---> 22 out = self.embeds(x)
23 out = out.view(len(x), x.size(1), -1)
~/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
323 for hook in self._forward_pre_hooks.values():
324 hook(self, input)
--> 325 result = self.forward(*input, **kwargs)
326 for hook in self._forward_hooks.values():
327 hook_result = hook(self, input, result)
~/anaconda3/lib/python3.6/site-packages/torch/nn/modules/sparse.py in forward(self, input)
101 input, self.weight,
102 padding_idx, self.max_norm, self.norm_type,
--> 103 self.scale_grad_by_freq, self.sparse
104 )
105
~/anaconda3/lib/python3.6/site-packages/torch/nn/_functions/thnn/sparse.py in forward(cls, ctx, indices, weight, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse)
57 output = torch.index_select(weight, 0, indices)
58 else:
---> 59 output = torch.index_select(weight, 0, indices.view(-1))
60 output = output.view(indices.size(0), indices.size(1), weight.size(1))
61
RuntimeError: index out of range at /Users/soumith/minicondabuild3/conda-bld/pytorch_1512381214802/work/torch/lib/TH/generic/THTensorMath.c:277 |
st48232 | The traceback indicates that (in sparse.py 106) you’re trying to index_select weight with something that’s out of range. What is the shape of your input to forward? |
st48233 | For anyone else getting this error: check that you’re not passing in any lookup indices larger than the size of your embedding matrix. This might happen if you’re encoding your input with an additional UNK index but didn’t include in when specifying the size of your embedding layer. |
st48234 | That’s what I was doing wrong – thanks! AveryLiu’s response to this stackoverflow post 2.2k has a good example of how to use nn.Embedding properly, to make sure you’re initializing it with the right arguments. |
st48235 | I have the same problem. When I pass batch size of more than 1, I get an error index out of range. Did any one found a solution? |
st48236 | @Sohaib_Mian This shouldn’t have anything to do with your batch size, but the values that your input tensor contains. How are you representing your input to the embedding lookup? |
st48237 | What if my index is very large, e.g. [10000]? Does the Embedding layer generates a matrix like (10001, embedding_size)? If so, how to improve the efficiency? |
st48238 | This kind of error is happening to me help!!!
It runs good in my size of this
vocab_size: 20
embedding_dim: 15
hidden_dim: 10
n_layers: 2
output_size: 10
but gives wrong output and error like
RuntimeError: index out of range at /opt/conda/conda-bld/pytorch_1524584710464/work/aten/src/TH/generic/THTensorMath.c:343
in this sizes
vocab_size: 72
embedding_dim: 256
hidden_dim: 256
n_layers: 3
output_size: 72
My code is below
import torch.nn as nn
class RNN(nn.Module):
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.5):
"""
:param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary)
:param output_size: The number of output dimensions of the neural network
:param embedding_dim: The size of embeddings, should you choose to use them
:param hidden_dim: The size of the hidden layer outputs
:param dropout: dropout to add in between LSTM/GRU layers
"""
super(RNN, self).__init__()
# TODO: Implement function
# set class variables
self.output_size = output_size
self.n_layers = n_layers
self.hidden_dim = hidden_dim
self.embedding_dim = embedding_dim
self.vocab_size = vocab_size
print('vocab_size:', self.vocab_size,
'embedding_dim:', self.embedding_dim,
'hidden_dim:',self.hidden_dim,
'n_layers:',self.n_layers,
'output_size:',self.output_size,
sep='\t'
)
# define model layers
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=dropout, batch_first=True)
#linear layer
self.dropout = nn.Dropout(0.3)
self.fc = nn.Linear(hidden_dim,output_size)
self.sig = nn.Sigmoid()
def forward(self, nn_input, hidden):
"""
Forward propagation of the neural network
:param nn_input: The input to the neural network
:param hidden: The hidden state
:return: Two Tensors, the output of the neural network and the latest hidden state
"""
# TODO: Implement function
#get the batch size
batch_size = nn_input.size(0)
#change to long tensor
nn_input = nn_input.long()
#embedding and lstm_out
embeds = self.embedding(nn_input)
lstm_out, hidden = self.lstm(embeds,hidden)
#stack up lstm outputs
lstm_out = lstm_out.contiguous().view(-1, self.hidden_dim)
#dropout and fully-connected layer
out = self.dropout(lstm_out)
out = self.fc(out)
out = out.view(batch_size, -1, self.output_size)
out = out[:, -1] # last batch of labels
# return one batch of output word scores and the hidden state
return out, hidden
def init_hidden(self, batch_size):
'''
Initialize the hidden state of an LSTM/GRU
:param batch_size: The batch_size of the hidden state
:return: hidden state of dims (n_layers, batch_size, hidden_dim)
'''
# Implement function
weight = next(self.parameters()).data
# initialize hidden state with zero weights, and move to GPU if available
if(train_on_gpu):
hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda(),
weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda())
else:
hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_(),
weight.new(self.n_layers, batch_size, self.hidden_dim).zero_())
return hidden
I tried to debug it it specifically started giving error in
self.embedding = nn.Embedding(vocab_size, embedding_dim)
Any help will be appretiated and Thank your for response. |
st48239 | Same problem for me ‘nn.Embedding’ not working
no_layers = 3
vocab_size = padded_rev.shape[0] + 1 #extra 1 for padding
embedding_dim = 400
output_dim = 1
hidden_dim = 256
train_on_gpu = False
model = SentimentRNN(no_layers,seq_length,embedding_dim,hidden_dim,drop_prob=0.5,
train_on_gpu=train_on_gpu)
print(model)
SentimentRNN(
(embedding): Embedding(49975, 400)
(lstm): LSTM(400, 256, num_layers=3, batch_first=True, dropout=0.5)
(dropout): Dropout(p=0.3, inplace=False)
(fc): Linear(in_features=256, out_features=1, bias=True)
(sig): Sigmoid()
)
Unable to train model.It is giving index error. |
st48240 | Could you check the min and max values of the input tensors you are passing to the embedding layer and make sure their values are in the valid range [0, num_embeddings-1]?
CC @mathematics |
st48241 | @ptrblck tx for the response.I figured out my mistake.The value i had given for embedding layer was wrong.Now I made it correct. |
st48242 | Hi @ptrblck,
I’ve found error was on my batch_size function and its internal logic. I was making batches of words given text as
batch_data(words, sequence_length, batch_size)
I was given a problem to Implement the batch_data function to batch words data into chunks of size batch_size using the TensorDataset and DataLoader classes
My illogical code was
def batch_data(words, sequence_length, batch_size):
batch_size_total = batch_size * sequence_length
n_batches = len(words) // batch_size_total
words = words[:n_batches*batch_size_total]
x = np.arange(len(words)).reshape(batch_size,sequence_length)
y = x.T[-1] + 1
feature_tensors = torch.from_numpy(x)
target_tensors = torch.from_numpy(y)
data = TensorDataset(feature_tensors, target_tensors)
data_loader = torch.utils.data.DataLoader(data, batch_size=batch_size, shuffle=True)
return data_loader
I’m trying to solving the problem. Thanks and appretitate for you support .
edit:
I think i have solved it . I had to change the x values. |
st48243 | @ptrblck
Hi, i have the same problem, but i tried your suggestion and the error released again, can you help me please?
Thanks
max_len=250
min_count=50
batch_size=11
LSTM parameters
embed_size =251
hidden_size = 256
num_layers = 1
training parameters
lr = 0.001
num_epochs = 10
model = LSTMClassifier(embed_size=embed_size,
hidden_size=hidden_size,
vocab_size=vocab_size, # my vocab_size is 67
num_layers=num_layers,
num_classes=train_ds.num_classes,
batch_size=batch_size)
if use_gpu:
model = model.cuda()
criterion = nn.CrossEntropyLoss()
if use_gpu:
criterion = criterion.cuda()
optimizer = optim.Adam(model.parameters(), lr=lr, betas=(0.7, 0.99))
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.975)
`hist = train(model, train_dl, valid_dl, criterion, optimizer, scheduler, num_epochs)`
IndexError Traceback (most recent call last)
<ipython-input-192-7e0f888e140e> in <module>
----> 1 hist = train(model, train_dl, valid_dl, criterion, optimizer, scheduler, num_epochs)
~\train_utils.py in train(model, train_dl, valid_dl, criterion, optimizer, scheduler, num_epochs)
85
86 ## perform one epoch of training and validation
---> 87 trn_loss, trn_acc = train_step(model, train_dl, criterion, optimizer, scheduler)
88 val_loss, val_acc = validate_step(model, valid_dl, criterion)
89
~\train_utils.py in train_step(model, train_dl, criterion, optimizer, scheduler)
29 model.zero_grad()
30
---> 31 output = model(train_inputs.t())
32
33 loss = criterion(output, train_labels)
C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\module.py in _call_impl(self, *input, **kwargs)
720 result = self._slow_forward(*input, **kwargs)
721 else:
--> 722 result = self.forward(*input, **kwargs)
723 for hook in itertools.chain(
724 _global_forward_hooks.values(),
<ipython-input-181-360ed93de0e5> in forward(self, x)
24
25 def forward(self, x):
---> 26 x = self.embedding(x)
27 x, self.hidden = self.lstm(x, self.hidden)
28 x = self.fc(x[-1]) # select the last output
C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\module.py in _call_impl(self, *input, **kwargs)
720 result = self._slow_forward(*input, **kwargs)
721 else:
--> 722 result = self.forward(*input, **kwargs)
723 for hook in itertools.chain(
724 _global_forward_hooks.values(),
C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\sparse.py in forward(self, input)
122
123 def forward(self, input: Tensor) -> Tensor:
--> 124 return F.embedding(
125 input, self.weight, self.padding_idx, self.max_norm,
126 self.norm_type, self.scale_grad_by_freq, self.sparse)
C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\functional.py in embedding(input, weight, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse)
1812 # remove once script supports set_grad_enabled
1813 _no_grad_embedding_renorm_(weight, input, max_norm, norm_type)
-> 1814 return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)
1815
1816
IndexError: index out of range in self |
st48244 | Could you print the min and max values for all inputs as well as the embedding size?
Based on the error message you are passing word indices to an embedding layer, which are not in the expected range. |
st48245 | print(len(train_ds))
44
print(len(valid_ds))
22
vocab_size = 2 + len([w for (w, c) in train_ds.vocab.word2count.items() if c >= min_count])
print(vocab_size)
67
i don’t have any other input…
@ptrblck |
st48246 | These values would be interesting to see:
print(train_inputs.min())
print(train_inputs.max())
before using model(train_inputs.t()). |
st48247 | Thanks for your reply, My inputs are as shown below:
@ptrblck
print(train_inputs.size())
print(train_inputs.min())
print(train_inputs.max())
print(train_inputs)
torch.Size([11, 250])
tensor(0)
tensor(8427)
tensor([[ 243, 97, 1999, …, 3, 19, 166],
[ 0, 0, 0, …, 8083, 2, 8084],
[8293, 1146, 2027, …, 2, 8225, 2],
…,
[ 0, 0, 0, …, 2, 597, 598],
[ 4, 4, 4, …, 34, 2019, 5802],
[5735, 6, 5878, …, 26, 10, 228]]) |
st48248 | Thanks for the update.
In a previous post you’ve posted: # my vocab_size is 67. If that value is used as num_embeddings in an nn.Embedding module, the error is expected, as your inputs have to stay in the expected range [0, num_embeddings-1], so [0, 66] in your case, while the max. value is 8427. |
st48249 | @ptrblck
Thanks for your attention,
Sorry for my questions, i am new in python and deep learning.
can you help me that this code related to earn vocab_size, is wrong?
vocab_size = 2 + len([w for (w, c) in train_ds.vocab.word2count.items() if c >= min_count])
I should mention that my project is text classification, and i am using persian language. |
st48250 | Hello everyone,
I’m trying to build pytorch from source following the official documentation 8. I’m on a universities cluster and thus use conda to have control over my environment. I installed magma-cuda101 and cudatoolkit=10.1. The whole install-command within a so far empty environment is
conda install -c conda-forge -c pytorch -c nvidia magma-cuda101 mkl-include mkl gcc_linux-64 cxx-compiler numpy pyyaml setuptools cmake cffi python cudatoolkit=10.1
But if i try python setup.py install the following happens:
-- Found CUDA: /usr/local/cuda (found version "8.0")
-- Caffe2: CUDA detected: 8.0
-- Caffe2: CUDA nvcc is: /usr/local/cuda/bin/nvcc
-- Caffe2: CUDA toolkit directory: /usr/local/cuda
CMake Error at cmake/public/cuda.cmake:42 (message):
PyTorch requires CUDA 9.0 and above.
So it does not find the proper cuda version. nvidia-smi tells me cuda 10.1 is available. However I cannot find a corresponding folder in /usr/. Right now I’m wondering how to find the origin of the cuda 10.1 reported by nvidia-smi and how to build pytorch against it.
Best Regards
Scipio |
st48251 | Hi,
Did you setup the proper CMAKE_PREFIX_PATH before running the install command? Is the nvcc that you get when you do which nvcc the one from conda? |
st48252 | The CMAKE_PREFIX_PATH is set properly. When I try to run nvcc from the installation described above no nvcc is found. If I add nvcc_linux-64 to the environment the last output of the installation is
Cannot determine CUDA_HOME: cuda-gdb not in PATH
Subsequently, which nvcc yields the one in /conda_env/bin/ but running it returns
/conda_env/bin/nvcc: line 2: /bin/nvcc: No such file or directory
This is no surprise as the nvcc in the env itself is nothing but a shell script pointing to the system-wide nvcc. I could set CUDA_HOME manually if I knew where to look for the proper version. |
st48253 | It looks like the cuda in your env is not properly installed. It should contain a full install that is independent to the system wide one. Especially if your system-wide cuda is not the same version as the one in conda. |
st48254 | Also if you can try cuda samples (if that exist on conda) or other very simple cuda package, that will make sure the cuda install is done properly. |
st48255 | So reinstalling brought no change. A short search looks like cuda samples are neither shipped with the cuda toolkit nor available as a package in conda. I’m wondering, is the cuda version reported by nvidia-smi just the highest one supported by the driver itself or does it reside somewhere on the system? Or should CUDA_HOME somehow point to my environment? |
st48256 | Does nvidia-smi reports a cuda version? It only reports the driver version from what I remember. Cuda is independent of that.
You can set CUDA_HOME before running the pytorch install to point to the conda install. But you should not need to do that… |
st48257 | According to https://stackoverflow.com/questions/53422407/different-cuda-versions-shown-by-nvcc-and-nvidia-smi 26 Nvidia-smi reports which is the highest CUDA version that can be used with the installed driver. So the output of nvidia-smi actually has little to do with my problem. However, I’m going to go on working on this tomorrow. I hope I can provide an answer for anyone stumbling upon this thread within the next few days. |
st48258 | By adding cudatoolkit-dev to the list of installed packages I got a proper nvcc in my environment. Now I moved on to the next problem:
File /path_to_conda/miniconda3/envs/pytorch_build/lib64/stubs/libcuda.so doesn't exist
So now I’m trying to figure out how to get this file. It looks like there’s still something wrong/missing with my cuda-installation. Is magma-cuda101 the relevant package or what am I looking for? |
st48259 | I found /usr/lib/x86_64-linux-gnu/libcuda.so and created a symlink in /path_to_conda/miniconda3/envs/pytorch_build/lib64/stubs/ but as was to be expected this just led to another message
grep: /path_to_conda/miniconda3/envs/pytorch_build/version.txt: No such file or directory
And if I try to build pytorch I’m back at the original error, although which nvcc now yields the one within the conda environment. |
st48260 | You should not need to do that… There is definitely something not right here.
Have you tried to set the CUDA_HOME to the cuda version in conda, and the PATH to make sure that the nvcc is the one from conda. (the real one that was installed! not a symlink to the system one that is cuda 8.0). |
st48261 | Hello again,
Sorry for taking so long but construction workers damaged the clusters power supply and I couldn’t access the system for the past nine days. Now I am trying again and still encounter the problem from the first post. I am wondering what the proper value for CUDA_HOME would be. I tried /miniconda3/envs/pytorch_build/pkgs/cuda-toolkit/include/thrust/system/cuda/ and /miniconda3/envs/pytorch_build/bin/ but neither did the trick. |
st48262 | Your CUDA_HOME should be such that CUDA_HOME/bin/nvcc can be found and CUDA_HOME/lib64/* contains all the cuda shared libraries. |
st48263 | This worked for me, posting for future reference.
export CUDA_HOME=/usr/local/cuda
Found here 69 |
st48264 | method1
mu_x = nn.functional.avg_pool2d(x, window_size, 1, padding=1)
sigma_x = nn.functional.avg_pool2d((x - mu_x)**2, window_size, 1, padding=1)
print(“sigma_x1=”,torch.max(sigma_x))
print(“sigma_x1=”,torch.min(sigma_x))
method2
mu_x = nn.functional.avg_pool2d(x, window_size, 1, padding=1)
sigma_x = nn.functional.avg_pool2d(x2, window_size, 1, padding=1)-mu_x2
print(“sigma_x2=”,torch.max(sigma_x))
print(“sigma_x2=”,torch.min(sigma_x))
I input same gray scaled image. but result seems diferrent
output
(‘sigma_x1=’, tensor(5441.0488, device=‘cuda:0’))
(‘sigma_x1=’, tensor(0., device=‘cuda:0’))
(‘sigma_x2=’, tensor(16055.5547, device=‘cuda:0’))
(‘sigma_x2=’, tensor(-0.0078, device=‘cuda:0’))
Do you have any idea what’s wrong?
and standard deviation cannot be minus. so I guess something wrong with method 2 |
st48265 | The data in my train.csv likes this:
[
[0, 0,……, 0],
[0, 1,……, 0],
[0, 2,……, 0],
[0, 3,……, 0],
[1, 0,……, 0],
[2, 0,……, 0],
[3, 0,……, 0],
[1, 1,……, 1],
[2, 1,……, 1],
[1, 2,……, 1],
[3, 1,……, 1],
]
The training set has 800,000 rows data and the test set has 20,000 rows data.
The value of y_train is only 0 and 1, and there are more than 150 columns of data in csv.
I want to use pytorch to predict the probability of 0 and 1 with x_test, how to do it?
Here is my code:
import pandas as pd
train = pd.read_csv(r'train.csv')
x_test = pd.read_csv(r'test.csv')
x_train = train[:, :-1]
y_train = train[:, -1]
I want 2 columns of probability, the first column is the probability of 0 , and the second column is the probability of 1 , such as this:
[[0.23334,0.76267]
……
[0.84984,0.15685]
[0.16663,0.83291]]
When I use keras,I can do it like this:
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from sklearn.preprocessing import LabelEncoder
from keras.utils import np_utils
data_train = np.array([
[0, 0, 0],
[0, 1, 0],
[0, 2, 0],
[0, 3, 0],
[1, 0, 0],
[2, 0, 0],
[3, 0, 0],
[1, 1, 1],
[2, 1, 1],
[1, 2, 1],
[3, 1, 1],
])
data_test = np.array([
[1, 3],
[0, 4],
[5, 0]
])
x_train = data_train[:, :-1]
y_train = data_train[:, -1]
x_test = data_test
encoder = LabelEncoder()
encoder.fit(y_train)
encoded_y = encoder.transform(y_train)
y_train = np_utils.to_categorical(encoded_y)
model = Sequential()
model.add(Dense(512, activation='relu', input_dim=2))
model.add(Dense(200, activation='relu'))
model.add(Dense(200, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(2, activation='softmax'))
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['binary_accuracy'])
model.fit(x_train, y_train, epochs=5, batch_size=1, verbose=1)
predict = model.predict_proba(x_test, batch_size=1)
print(predict)
result:
[[0.46373594 0.53626406]
[0.99079037 0.00920963]
[0.72976 0.27024 ]]
But how to do it with pytorch? |
st48266 | Solved by ptrblck in post #8
800,000 would then be the batch size (or the total number of samples) while 153 would be the feature dimension.
In that case use
self.fc1 = nn.Linear(153, any_value)
self.fc2 = nn.Linear(any_value, 2)
The batch size is not part of the layer definition, as all PyTorch layers accept a variable bat… |
st48267 | You could create a model with two output neurons (e.g. via nn.Linear) and setup a multi-label classification use case using nn.BCEWithLogitsLoss.
Since the model output would be logits, you could apply torch.sigmoid on them to get the probabilities for each class.
Here is a very simple example:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc1 = nn.Linear(128, 64)
self.fc2 = nn.Linear(64, 40)
def forward(self, x):
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
model = MyModel()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
criterion = nn.BCEWithLogitsLoss()
data = torch.randn(64, 128)
target = torch.randint(0, 2, (64, 40)).float()
for epoch in range(100):
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
print('epoch {}, loss {}'.format(epoch, loss.item()))
# check predictions
output = model(data)
probs = torch.sigmoid(output)
print(probs)
print(target) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.