id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st32768
|
If I have a matrix M of size (d1, d2) and a vector V of size d2, doing M*V gives me an output OUT of size (d1, d2), where each row of M has been multiplied by V.
I need to do the same thing batch-wise, where the matrix M is fixed and I have a batch of dB vectors.
In practice, given a tensor M of size (d1, d2) and a tensor V of size (dB, d2), I need to get as output OUT a tensor of size (dB, d1, d2), so that OUT[i] = M*V[i].
How can I efficiently get it?
|
st32769
|
Solved by eqy in post #2
I think you can get the desired behavior by explicitly inserting the dimension that was implicitly inserted for the single vector case via unqueeze(1) on your “batched” vector.
Example:
import torch
d1 = 16
d2 = 32
dB = 64
m = torch.randn(d1, d2)
v = torch.randn(dB, d2)
out = torch.empty(dB, d1,…
|
st32770
|
I think you can get the desired behavior by explicitly inserting the dimension that was implicitly inserted for the single vector case via unqueeze(1) on your “batched” vector.
Example:
import torch
d1 = 16
d2 = 32
dB = 64
m = torch.randn(d1, d2)
v = torch.randn(dB, d2)
out = torch.empty(dB, d1, d2)
for i in range(dB):
out[i, :, :] = m*v[i]
print(out.shape)
v2 = v.unsqueeze(1)
out2 = m*v2
print(out2.shape)
print(torch.allclose(out, out2))
|
st32771
|
I think torch.einsum can simply do that. But I’m not sure whether it’s efficient or not.
>>> A = torch.randn((3,4))
>>> B = torch.randn((16,4))
>>> C = torch.einsum("ij,bj->bij", (A, B))
>>> C.size()
torch.Size([16, 3, 4])
>>> C[0]-A*B[0] # for testing the correctness
tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
>>> C[5]-A*B[5]
tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
|
st32772
|
Usually in a convolution we just multiply the kernel with the input and return the scalar, and then move the kernel and repeat the process. The problem I have is that instead of returning a scalar I have an “internal” 2d plane to convolve over, at each 3d point. So the 3d convolution has to return, instead of a scalar, a 2d convolution result.
I am not sure how to implement something like this. A good starting step for me would be if I could efficiently extract 3x3x3 chunks of the input in the same way that pytorch does for regular 3d convolutions. I have tried looking at conv3d in torch/nn/quantized/functional.py but cant seem to find the part the actual convolutions are being taken.
|
st32773
|
To create these “patches” you could use nn.Unfold 3, which also shows the manual conv operation in its example.
|
st32774
|
I’m trying to simulate federated learning with a simple approach: I have a “local model” and some “workers” that have their own models (at the beginning just a copy from local model) and data. The data should be private so only the models can have access through ‘worker.model’
Every epoch after all workers are done with the training on own data a federated_aggregation function is called which calculates the average of all worker model parameters and save it to the specific local model parameter:
def federated_aggregation(local_model, workers):
with torch.no_grad():
for name, local_parameter in local_model.named_parameters():
parameter_stack = torch.zeros_like(local_parameter)
for worker in workers:
parameter_stack += worker.model.state_dict()[name].clone().detach()
parameter_stack /= len(workers)
local_parameter.set_(parameter_stack)
The thing is, when evaluating the local model, this doesn’t reflect the performance it should get after the training of the workers. A simple test to visualize this was to run a test with just one worker:
Performance of just one worker (training recall, validation recall) left, right the validation recall of local model:
summary1180×326 40.5 KB
Any ideas what is the cause for this mismatch, I’ve tried different ways to update de local model parameter but I’m stuck in this behavior
|
st32775
|
I’m working with graph neural networks and it’s important for my work to perform some padding. Here is the problem -
I have 3 graphs [g1, g2, g3] and each with 1,2,3 nodes respectively. I want to aggregate these nodes such that they are padded with a fixed size. Here is the example
all_nodes_feature = torch.tensor[
[1, 1],
[2, 2],
[2, 2],
[3, 3],
[3, 3],
[3, 3] ]
number_of_nodes_in_each_graph = torch.tensor([1, 2, 3])
fixed_length = 3
resulting_output = [
[ [1,1], [0, 0], [0,0] ],
[ [2,2], [2, 2], [0,0] ],
[ [3,3], [3, 3], [3,3] ]
]
|
st32776
|
Hi,
you could firstly split the all_nodes_feature tensor to then pad them as sequences. Be aware however that in this case number_of_nodes_in_each_graph should be a normal list of integers.
So you would have:
all_nodes_feature = torch.tensor([[1, 1],
[2, 2],
[2, 2],
[3, 3],
[3, 3],
[3, 3]])
number_of_nodes_in_each_graph = [1, 2, 3]
all_nodes_feature_tensor_list = torch.split(
tensor=all_nodes_feature,
split_size_or_sections=number_of_nodes_in_each_graph
)
all_nodes_feature_padded = torch.nn.utils.rnn.pad_sequence(
sequences=all_nodes_feature_tensor_list,
batch_first=True,
padding_value=0
)
I hope I could help you with that.
Regards,
Unity05
|
st32777
|
Hi everyone second post here!
I got this error
TypeError: linear(): argument 'input' (position 1) must be Tensor, not int
This is my code - it runs pretty slow
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import numpy as np
from PIL import Image
import time
start = time.time()
transform = transforms.Compose([transforms.Resize(255), transforms.CenterCrop(224), transforms.ToTensor(),])
# This gives us some transforms to apply later on
training = torchvision.datasets.ImageFolder(root = "training_set", transform = transform)
print(training)
train_dataloader = DataLoader(dataset = training, shuffle = True, batch_size = 32)
print(train_dataloader)
print("Before NN creation",start-time.time())
# Creating the model
class NeuralNetwork (nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.Linear_Stack = nn.Sequential(
nn.Linear(224*224, 40000),
nn.ReLU(),
nn.Linear(40000, 10000),
nn.ReLU(),
nn.Linear(10000, 75),
nn.ReLU(),
nn.Linear(75, 5),
nn.ReLU(),
nn.Linear(5, 1),
nn.LogSoftmax(dim=1)
)
def forward (self, x):
logits = self.Linear_Stack(x)
return logits
model = NeuralNetwork()
print(model)
epochs = 2
lr = 0.001
loss = nn.CrossEntropyLoss()
optim = torch.optim.SGD(model.parameters(), lr = lr)
print(loss, optim)
#creating the main loop
def main(loader, model, loss, optim):
size = len(loader.dataset)
for (images, labels) in enumerate(loader):
# Prediction
pred = model.forward(images)
loss = loss(pred, target)
#backprop
optim.zero_grad()
loss.backward()
optim.step()
print(loss)
for x in range(epochs):
main(train_dataloader, model, loss, optim)
print(start-time.time())
I guess main question is: Am I using Image Folder correctly? (I know it works because I get the correct amount of datapoints when I print it) Is my code even succinct and I couldn’t find anything on what the variable names for the outputs are (like X, y or Sample, Target). I think that answering these questions will help me solve my question, reply if you have anything else that you think will be helpful and I will take it onboard.
|
st32778
|
Solved by ptrmcl in post #12
General advice, look at the docs! This will answer most of your questions. For example, here, it says that if you pass in a single parameter, it will resize the shortest side of the image to that (and maintain the aspect ratio).
First thing I would do though is to make sure you understand the basic…
|
st32779
|
enumerate(loader) will give you something like batch_idx, (data, target) back so it is likely you are passing the batch_idx in place of the image. examples/main.py at 01539f9eada34aef67ae7b3d674f30634c35f468 · pytorch/examples · GitHub
|
st32780
|
enumerate will give you an index for whatever you are iterating over so it is simply the batch number out of the total number of batches in an epoch
|
st32781
|
Thank you. How can I go about implementing these into my code. Could you edit it for me to review? I am a little confused about batch_idx.
|
st32782
|
Here is an example of enumerate. You need to add another variable to your loop which is batch index in this case.
Screenshot_20210511-040141_Dcoder720×640 125 KB
|
st32783
|
Thank you everyone (@eqy, @m3tobom_M ). At the moment, my i5 hangs (it is only just a laptop) with this code. I have ironed out the errors but it just hangs and my computer stops. I ran the FashionMNIST in a reasonable time but this is super slow. Can anyone help me out?
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import numpy as np
from PIL import Image
import time
start = time.time()
transform = transforms.Compose([transforms.Resize(200*200), transforms.CenterCrop(224), transforms.ToTensor(),])
# This gives us some transforms to apply later on
training = torchvision.datasets.ImageFolder(root = "training_set", transform = transform)
print(training)
train_dataloader = DataLoader(dataset = training, shuffle = True, batch_size = 32)
print(train_dataloader)
print("Before NN creation",start-time.time())
# Creating the model
class NeuralNetwork (nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.Linear_Stack = nn.Sequential(
nn.Linear(200*200, 40000),
nn.ReLU(),
nn.Linear(40000, 10000),
nn.ReLU(),
nn.Linear(10000, 75),
nn.ReLU(),
nn.Linear(75, 5),
nn.ReLU(),
nn.Linear(5, 1),
nn.LogSoftmax(dim=1)
)
def forward (self, x):
logits = self.Linear_Stack(x)
return logits
model = NeuralNetwork()
print(model)
epochs = 1
check = 0
lr = 0.001
loss = nn.CrossEntropyLoss()
optim = torch.optim.SGD(model.parameters(), lr = lr)
print(loss, optim)
#creating the main loop
def main(loader, model, loss, optim):
size = len(loader.dataset)
print(size)
for batch_idx, (data, target) in enumerate(loader):
# Prediction
check = check + 1
print(check)
pred = model.forward(data)
loss = loss(pred, target)
#backprop
optim.zero_grad()
loss.backward()
optim.step()
print(loss)
for x in range(epochs):
main(train_dataloader, model, loss, optim)
print(start-time.time())
Upon adding some print commands, I get stuck after print(check) and before creating the model. The main one is after the print(check) though. That’s where everything just hangs.
|
st32784
|
Number of layers is reasonable, maybe try 2-3. The number of units in the first 2 layers is way too much. It should be in the tens to hundreds at max. You have to try out different values. This is called hyperparameter tuning, which, in essence, is tuning the parameters not learned by the model from the data. Other examples include learning rate, number of layers, etc.
I also suggest maybe going for a smaller dataset so you can train faster
After that, I suggest looking at an architecture called convolutional neural networks. These have been the goto for computer vision for quite a while, although recent research suggests that may change soon…
Lastly, I suggest using a platform called Google Colab. This is resource that gives you a free GPU to play around with, which will substantially speed up your experiments. It’s in a notebook format, where you can type and run your code piece-by-piece.
|
st32785
|
Okie. I have tried Colab, its a pain to upload all my data though but I will try it again. Secondly, with this code:
start = time.time()
transform = transforms.Compose([transforms.Resize(200*200), transforms.CenterCrop(224), transforms.ToTensor(),])
# This gives us some transforms to apply later on
training = torchvision.datasets.ImageFolder(root = "training_set", transform = transform)
print(training)
train_dataloader = DataLoader(dataset = training, shuffle = True, batch_size = 32)
print(train_dataloader)
print("Before NN creation",start-time.time())
# Creating the model
class NeuralNetwork (nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.Linear_Stack = nn.Sequential(
nn.Linear(200*200, 40000),
nn.ReLU(),
nn.Linear(40000, 5),
nn.ReLU(),
nn.Linear(5, 1),
nn.LogSoftmax(dim=1)
)
def forward (self, x):
logits = self.Linear_Stack(x)
return logits
model = NeuralNetwork()
print(model)
epochs = 1
check = 0
lr = 0.001
loss = nn.CrossEntropyLoss()
optim = torch.optim.SGD(model.parameters(), lr = lr)
print(loss, optim)
#creating the main loop
def main(loader, model, loss, optim):
size = len(loader.dataset)
print(size)
for batch_idx, (data, target) in enumerate(loader):
# Prediction
check = check + 1
print(check)
pred = model.forward(data)
loss = loss(pred, target)
#backprop
optim.zero_grad()
loss.backward()
optim.step()
print(loss)
How would I go about changing the values. Am I right in changing the transforms.Resize() value to exactly what I put into the Model, in this case 200*200. Admittedly, I blindly put that transform in thinking it did what I think it would do.
|
st32786
|
General advice, look at the docs! This will answer most of your questions. For example, here 1, it says that if you pass in a single parameter, it will resize the shortest side of the image to that (and maintain the aspect ratio).
First thing I would do though is to make sure you understand the basics of what you’re trying to do. Do you know what a fully connected neural net is? I see that your bio says you’re in high school and you’re just starting. That’s when I started! A common starting point for many (including myself) is Andrew Ng’s free machine learning course.
|
st32787
|
Yes I am. Yeet. Haha, 69. I’m in high school. Really childish and foolish.
Thanks @ptrmcl . How do I change the parameters of the full image to be 224 by 224?
BTW, does Andrew Ng’s course require Calulus??
|
st32788
|
Also, after doing some work after school,
This is m new code:
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import numpy as np
from PIL import Image
import time
start = time.time()
transform = transforms.Compose([transforms.resize((225,225)),transforms.CenterCrop(224),transforms.ToTensor()])
# This gives us some transforms to apply later on
# transforms.Resize(225),
training = torchvision.datasets.ImageFolder(root = "training_set", transform = transform)
print(training)
train_dataloader = DataLoader(dataset = training, shuffle = True, batch_size = 32)
print(train_dataloader)
print("Before NN creation",start-time.time())
# Creating the model
class NeuralNetwork (nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.Linear_Stack = nn.Sequential(
nn.Linear(50176, 1000),
nn.ReLU(),
nn.Linear(1000, 5),
nn.ReLU(),
nn.Linear(5, 1),
nn.LogSoftmax(dim=1)
)
def forward (self, x):
logits = self.Linear_Stack(x)
return logits
model = NeuralNetwork()
print(model)
epochs = 1
lr = 0.001
loss = nn.CrossEntropyLoss()
optim = torch.optim.SGD(model.parameters(), lr = lr)
print(loss, optim)
#creating the main loop
def main(loader, model, loss, optim):
size = len(loader.dataset)
print(size)
for batch_idx, (data, target) in enumerate(loader):
# Prediction
pred = model.forward(data)
loss = loss(pred, target)
#backprop
optim.zero_grad()
loss.backward()
optim.step()
print(loss)
for x in range(epochs):
main(train_dataloader, model, loss, optim)
print(start-time.time())
I get this error
RuntimeError: mat1 and mat2 shapes cannot be multiplied (21504x224 and 50176x1000)
Can anyone point me out on what I’m doing wrong?
|
st32789
|
Resize((224,224))
Yeah you need some basic calculus + linear algebra. I think he gives a refresher?? If not there are lots of resources to learn that.
I just remembered this series which introduces the neural nets you’re using on images from a famous youtuber called 3 blue 1 brown. He has very nice visualizations.
|
st32790
|
I get this
RuntimeError: mat1 and mat2 shapes cannot be multiplied (21504x224 and 50176x1000)
What does this message mean and can you help me fix it?
|
st32791
|
First, you need to resize all your inputs to a fixed size, then flatten your inputs. Flatten input size and first linear layer’s input sizes must match. Here is a sample code. Also as I recommend you to read docs as @ptrmcl suggested.
Also here is a sample for you. You can read what view do from docs. It is a simple function
>>> import torch
>>> input_tensor = torch.rand((1, 3, 224, 224)) # Input images resized to 224x224 in transform
>>> _, c, h, w = input_tensor.shape
>>> input_size_of_first_linear_layer = c * h * w
>>> flat_input_tensor = input_tensor.view(-1, input_size_of_first_linear_layer)
>>> input_tensor.shape
torch.Size([1, 3, 224, 224])
>>> flat_input_tensor.shape
torch.Size([1, 150528])
>>> layers = torch.nn.Sequential(
... torch.nn.Linear(input_size_of_first_linear_layer, 1000),
... torch.nn.Linear(1000, 2))
>>>
>>> layers
Sequential(
(0): Linear(in_features=150528, out_features=1000, bias=True)
(1): Linear(in_features=1000, out_features=2, bias=True)
)
>>> layers(flat_input_tensor)
tensor([[-0.0779, 0.3057]], grad_fn=<AddmmBac
|
st32792
|
Thank you @m3tobom_M . After flattening, I get this tensor size - torch.Size([64, 19200])
Is that ok? Can I change it to be 1, 19200?
Secondly, I also get this weird error
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
For reference, this is my current code:
import torch
from torch import tensor
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import numpy as np
from PIL import Image
import time
start = time.time()
transform = transforms.Compose([transforms.Resize((200,200)),transforms.CenterCrop(80),transforms.ToTensor()])
training = torchvision.datasets.ImageFolder(root = "training_set", transform = transform)
print(training)
train_dataloader = DataLoader(dataset = training, shuffle = True, batch_size = 64)
print(train_dataloader)
print("Before NN creation",start-time.time())
# Creating the model
class NeuralNetwork (nn.Module):
def __init__(self,input_dims):
super(NeuralNetwork, self).__init__()
self.Linear_Stack = nn.Sequential(
nn.Linear(input_dims, 1000),
nn.ReLU(),
nn.Linear(1000, 5),
nn.ReLU(),
nn.Linear(5, 1),
nn.LogSoftmax(dim=1)
)
def forward (self, x):
logits = self.Linear_Stack(x)
return logits
model = NeuralNetwork(19200)
print(model)
epochs = 1
lr = 0.001
loss = nn.CrossEntropyLoss()
optim = torch.optim.SGD(model.parameters(), lr = lr)
print(loss, optim)
out = 0
def process(tensorin):
global out
_, c,h,w = tensorin.shape
first_layer = c * h * w
out = tensorin.view(-1, first_layer)
return out
#creating the main loop
def main(loader, model, loss, optim):
size = len(loader.dataset)
print(size)
for batch_idx, (data, target) in enumerate(loader):
print(data.shape)
process(data)
print(target)
print(out.shape)
pred = model(out)
loss = loss(out, target)
#backprop
optim.zero_grad()
loss.backward()
optim.step()
print(loss)
for x in range(epochs):
main(train_dataloader, model, loss, optim)
print(start-time.time())
Thank you for any help (and help given - @m3tobom_M , @eqy, @ptrblck and @ptrmcl)
|
st32793
|
It seems you are defining out = 0 in the global scope, pass this integer then to the model in:
print(out.shape)
pred = model(out)
which I would assume should yield errors, since neither out.shape is defined nor would the model accept an int as the input, and later calculate the loss using out.
Besides that you are also overriding loss (the criterion) with the loss value, so wou might also want to fix this.
|
st32794
|
I am wondering How we could construct a graph from neural network where layer are nodes.
I have some vague idea of how to do this. For example, we can use hooks to record the layer and their connection, but this method seems to only work for sequential model, when we have skip connections, this does not work well.
I have also seen people using onnx and traces to construct a trace graph, but in that case, the node are onnx operation instead of pytorch module.
|
st32795
|
I’m working on a stochastic method acting row wise on a tensor. I’ve realized some strange behavior on CPU vs GPU.
Suppose I use an MSE loss:
sqloss = torch.nn.MSELoss()
Then, I get the following time results. Z requires a gradient, M does not. For now, I’m sampling idx at each iteration. I’ve also tried to put Z and M into a torch.utils.data.TensorDataset(Z, M), to no avail.
Z = torch.rand(1000,1000)
Z.requires_grad_(True)
M = torch.rand(1000, 1000)
idx = torch.randint(Z.size(0), size=(10,))
Replacing sqloss from above by the MSELoss:
sqloss = MSEloss()
GPU
In [6]: %timeit sqloss(Z, M)
49 µs ± 7.4 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [7]: %timeit sqloss(Z[idx], M[idx])
222 µs ± 32.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
CPU:
In [10]: %timeit sqloss(Z, M)
612 µs ± 167 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [11]: %timeit sqloss(Z[idx], M[idx])
52.9 µs ± 2.25 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
This is due to the indexing:
GPU:
In [21]: %timeit Z[idx]
96.3 µs ± 15.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
CPU:
In [25]: %timeit Z[idx]
13 µs ± 2.63 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Is this behavior expected? Why is the subsampled loss much faster than the full loss on CPU but not on GPU ? Is there anyway to speed this up?
|
st32796
|
Hello, long time listener first time caller!
I’m trying to create custom a dataset from a set of time series .csv’s with accompanying ground truth .csv’s. Let’s say my folder structure looks like:
root/
- action1/
-sync/
-data1.csv
-data2.csv
-truth1.csv
-truth2.csv
- ...
- action2/
-sync/
-data1.csv
-data2.csv
-truth1.csv
-truth2.csv
- ...
I would like to take windows from each .csv (e.g. data1 and truth1) as my x and y to feed into my NN. I can write a function that stores the path to each .csv and stores the accompanying length. My issue is how to write the custom dataset class - if it is possible?
All the .csv’s are of unique length so I would like to interate over each .csv at a time and take len(data[i]) - windowlength sequences from each.
When defining the len, is this the TOTAL number of windows from all the data?
Any help would be greatly GREATLY appreciated. Thankyou:)
|
st32797
|
Hello, I have two tensors. Tensor A is of size (n,d), and tensor B is of size (n, k, d). I want to calculate the cosine similarity for the first row of tensor A to each row of the first layer in Tensor B. Then to calculate the cosine similarity for the second row of tensor A to each row of the second layer in Tensor B. So on so forth as illustrated below:
cos_simi921×739 11 KB
I cannot think of a good way of doing it rather than using a for-loop. Can someone help me?
|
st32798
|
never mind. I solved this by expanding tensor A to be of the same size of tensor B.
|
st32799
|
Hello All,
I am getting an above error when I am calling
fit(siamese_train_loader, siamese_test_loader, model, loss_fn, optimizer, scheduler, n_epochs, cuda, log_interval)
for
for batch_idx, (data, target) in enumerate(train_loader):
target = target if len(target) > 0 else None
if not type(data) in (tuple, list):
data = (data,)
if cuda:
data = tuple(d.cuda() for d in data)
if target is not None:
print(target)
target = target.cuda()
output of print list is as follows:
[tensor([[[[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.1943, -0.4279],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2509, 0.0435],
...,
[ 0.2697, 0.2697, 0.2697, ..., -0.2016, -0.2016, -0.0885],
[ 0.2697, 0.2697, 0.2697, ..., 0.2320, 0.2132, 0.2320],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697]],
[[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.1943, -0.4279],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2509, 0.0435],
...,
[ 0.2697, 0.2697, 0.2697, ..., -0.2016, -0.2016, -0.0885],
[ 0.2697, 0.2697, 0.2697, ..., 0.2320, 0.2132, 0.2320],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697]],
[[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.1943, -0.4279],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2509, 0.0435],
...,
[ 0.2697, 0.2697, 0.2697, ..., -0.2016, -0.2016, -0.0885],
[ 0.2697, 0.2697, 0.2697, ..., 0.2320, 0.2132, 0.2320],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697]]],
[[[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
...,
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697]],
[[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
...,
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697]],
[[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
...,
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697]]],
[[[ 0.2697, 0.2697, 0.2697, ..., -0.2393, -0.3148, -0.2959],
[ 0.2697, 0.2697, 0.2697, ..., 0.1754, 0.1377, 0.1566],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
...,
[ 0.2697, 0.2697, 0.2697, ..., -0.2582, -0.3713, -0.3336],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697]],
[[ 0.2697, 0.2697, 0.2697, ..., -0.2393, -0.3148, -0.2959],
[ 0.2697, 0.2697, 0.2697, ..., 0.1754, 0.1377, 0.1566],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
...,
[ 0.2697, 0.2697, 0.2697, ..., -0.2582, -0.3713, -0.3336],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697]],
[[ 0.2697, 0.2697, 0.2697, ..., -0.2393, -0.3148, -0.2959],
[ 0.2697, 0.2697, 0.2697, ..., 0.1754, 0.1377, 0.1566],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
...,
[ 0.2697, 0.2697, 0.2697, ..., -0.2582, -0.3713, -0.3336],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697]]],
...,
[[[ 0.0058, -0.0885, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[-0.3148, -0.5410, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
...,
[ 0.2697, 0.2697, 0.2697, ..., -0.1639, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., -0.3148, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., -0.8615, 0.2132, 0.2697]],
[[ 0.0058, -0.0885, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[-0.3148, -0.5410, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
...,
[ 0.2697, 0.2697, 0.2697, ..., -0.1639, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., -0.3148, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., -0.8615, 0.2132, 0.2697]],
[[ 0.0058, -0.0885, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[-0.3148, -0.5410, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
...,
[ 0.2697, 0.2697, 0.2697, ..., -0.1639, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., -0.3148, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., -0.8615, 0.2132, 0.2697]]],
[[[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
...,
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697]],
[[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
...,
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697]],
[[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
...,
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697]]],
[[[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
...,
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697]],
[[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
...,
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697]],
[[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
...,
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697],
[ 0.2697, 0.2697, 0.2697, ..., 0.2697, 0.2697, 0.2697]]]]),
tensor([24, 23, 12, 21, 7, 3, 24, 3, 14, 4, 10, 3, 11, 9, 15, 20, 14, 11,
1, 11, 16, 2, 16, 26, 22, 10, 0, 17, 25, 0, 11, 11, 0, 5, 8, 13,
20, 2, 26, 22, 19, 5, 6, 6, 10, 26, 2, 2, 1, 10, 11, 3, 17, 5,
21, 6, 5, 19, 26, 1, 4, 5, 19, 12, 2, 25, 21, 18, 17, 4, 15, 20,
24, 20, 5, 2, 23, 26, 11, 18, 14, 14, 0, 26, 20, 6, 19, 19, 12, 6,
25, 21, 23, 18, 1, 17, 22, 18, 5, 1, 16, 15, 10, 5, 15, 2, 4, 19,
8, 14, 19, 13, 1, 3, 19, 9, 11, 26, 10, 18, 21, 8, 13, 24, 15, 2,
24, 2])]
I tried to convert this list into NumPy array but it gives me another error that
"ValueError: only one element tensors can be converted to Python scalars"
What is the solution for the above? Any suggestions are welcome.
21241×177 56.3 KB
Thanks in advance.
|
st32800
|
It looks like there is a custom dataloader implementation being used that doesn’t return target tensors but rather a list of tensors.
Do you want to convert the targets to a single tensor? You can likely just use stack or cat depending on whether you want a dimension to be added.
Otherwise, you can do something similar to what is already done for data (target = [t.cuda() for t in target]).
|
st32801
|
eqy:
target = [t.cuda() for t in target]).
Thanks for the reply, after applying the solution and putting``(target = [t.cuda() for t in target] )`
it gives me another following error, what would be the reason for this?
shall I use cat/stack?
RuntimeError: Expected 4-dimensional input for 4-dimensional weight [32, 3, 5, 5], but got 1-dimensional input of size [128] instead
|
st32802
|
It looks like you may be passing your target where you intend to pass the data (maybe double check the target and data are the shapes you expect).
|
st32803
|
I am using this neural network architecture.
File "/home/sharad/miniconda3/lib/python3.8/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "/home/sharad/Few-shot-classification-siamese/siamese-triplet-master/networks.py", line 68, in forward
output2 = self.embedding_net(x2)
File "/home/sharad/miniconda3/lib/python3.8/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "/home/sharad/Few-shot-classification-siamese/siamese-triplet-master/networks.py", line 21, in forward
output = self.convnet(x)
File "/home/sharad/miniconda3/lib/python3.8/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "/home/sharad/miniconda3/lib/python3.8/site-packages/torch/nn/modules/container.py", line 119, in forward
input = module(input)
File "/home/sharad/miniconda3/lib/python3.8/site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
File "/home/sharad/miniconda3/lib/python3.8/site-packages/torch/nn/modules/conv.py", line 399, in forward
return self._conv_forward(input, self.weight, self.bias)
File "/home/sharad/miniconda3/lib/python3.8/site-packages/torch/nn/modules/conv.py", line 395, in _conv_forward
return F.conv2d(input, weight, bias, self.stride,
RuntimeError: Expected 4-dimensional input for 4-dimensional weight [32, 3, 5, 5], but got 1-dimensional input of size [128] instead
according to errrorlog its causing problem in Siamesenet as I mentioned above.
import torch.nn as nn
import torch.nn.functional as F
class EmbeddingNet(nn.Module):
def __init__(self):
super(EmbeddingNet, self).__init__()
self.convnet = nn.Sequential(nn.Conv2d(3, 32, 5), nn.PReLU(),
nn.MaxPool2d(2, stride=2),
nn.Conv2d(32, 64, 5), nn.PReLU(),
nn.MaxPool2d(2, stride=2))
self.fc = nn.Sequential(nn.Linear(64 * 61 * 61, 256),
nn.PReLU(),
nn.Linear(256, 256),
nn.PReLU(),
nn.Linear(256, 2)
)
def forward(self, x):
output = self.convnet(x)
output = output.view(output.size()[0], -1)
output = self.fc(output)
return output
def get_embedding(self, x):
return self.forward(x)
class EmbeddingNetL2(EmbeddingNet):
def __init__(self):
super(EmbeddingNetL2, self).__init__()
def forward(self, x):
output = super(EmbeddingNetL2, self).forward(x)
output /= output.pow(2).sum(1, keepdim=True).sqrt()
return output
def get_embedding(self, x):
return self.forward(x)
class ClassificationNet(nn.Module):
def __init__(self, embedding_net, n_classes):
super(ClassificationNet, self).__init__()
self.embedding_net = embedding_net
self.n_classes = n_classes
self.nonlinear = nn.PReLU()
self.fc1 = nn.Linear(2, n_classes)
def forward(self, x):
output = self.embedding_net(x)
output = self.nonlinear(output)
scores = F.log_softmax(self.fc1(output), dim=-1)
return scores
def get_embedding(self, x):
return self.nonlinear(self.embedding_net(x))
class SiameseNet(nn.Module):
def __init__(self, embedding_net):
super(SiameseNet, self).__init__()
self.embedding_net = embedding_net
def forward(self, x1, x2):
output1 = self.embedding_net(x1)
print(output1.shape)
output2 = self.embedding_net(x2)
print(output2.shape)
return output1, output2
def get_embedding(self, x):
return self.embedding_net(x)
class TripletNet(nn.Module):
def __init__(self, embedding_net):
super(TripletNet, self).__init__()
self.embedding_net = embedding_net
def forward(self, x1, x2, x3):
output1 = self.embedding_net(x1)
output2 = self.embedding_net(x2)
output3 = self.embedding_net(x3)
return output1, output2, output3
def get_embedding(self, x):
return self.embedding_net(x)
I have tried to change the input size but still its giving me an error.
|
st32804
|
Hi,
I’m new using PyTorch. I am implementing and testing a new paper called Sound of Pixels 21.
In short it’s a net which works with a 2-tower stream. One tower is fed with a stack of images and the other one is fed with audio spectrograms.
I’m using a private dataset, in which each sample is a numpy binary file which contains a python dictionary with both, audio and images.
I’ve created my own dataset subclass in which I’m enlisting all the files inside a folder and using this list to call
__getitem__ function.
The matter is I have to combine features of N samples (since the net is trained by summing audio samples). As far as I understand, I have to combine these N samples inside the __getitem__ function. However, this function is designed to deal with one sample and pass the info to the dataloader.
I considered the option of doing a post-processing of the batch doing what I need or making my own dataloader using one of the implemented samplers. Before doing that I would like to know if there is a more efficient way of dealing with this in pytorch because I have to compute fourier transforms of audio and I don’t want to bottleneck the training with a bad data preprocessing.
Thank you very much
Dataset class designed for just one sample
class BinaryData(torch.utils.data.Dataset):
def __init__(self, root_dir,transform):
self.input_list = []
self.transform = transform
for path, subdirs, files in os.walk(root_dir):
for name in files:
self.input_list.append(os.path.join(path, name))
def __len__(self):
return len(self.input_list)
def __getitem__(self, idx):
dic = data2dic(np.load(self.input_list[idx]))
audio = dic['audio']
audio = Sound_standarize(audio)
frames = dic['frames']
size = np.shape(frames)
images = []
for i in range(size[3]):
images.append(self.transform(Image.fromarray(frames[:,:,:,i])))
frames = torch.stack(images)
return audio,frames
|
st32805
|
Hi, this was not a pytorch framework problem.
If I understood correctly how to speed up your post-processing during the download?
I suggest you use a multi-thread approach.
http://chriskiehl.com/article/parallelism-in-one-line/ 79
|
st32806
|
Well, It’s not a matter of post-processing or speed up. In sample words:
I have ie 1000 files (dataset).
I want that my dataloader opens (ie) 2 of these files (randomly) and sum them. This sum is what i will feed the net with, so in the end my net will percive there are 1000/2 = 500 samples. A batch have to be done of sums (but not raw files)
The matter is I don’t know what is the proper way to do this in pytorch. I can roughly emulate this behavior but I would like to know if pytorch framework is prepared to do this is a easy way.
|
st32807
|
I’m not sure, if this covers your whole use case, but you could just get the desired number of samples from your dataset and process them in __getitem__.
Here is a small example:
class MyDataset(Dataset):
def __init__(self, nb_samples):
self.images = torch.randn(100, 3, 24, 24)
self.audio = torch.randn(100, 1024, 12)
self.nb_samples = nb_samples
def __getitem__(self, index):
# Load all nb_samples
images = self.images[index*self.nb_samples:index*self.nb_samples+self.nb_samples]
audio_specs = self.audio[index*self.nb_samples:index*self.nb_samples+self.nb_samples]
# Transform
# Sum samples
x1 = torch.sum(images)
x2 = torch.sum(audio_specs)
return x1, x2
def __len__(self):
return len(self.images) / self.nb_samples - self.nb_samples
dataset = MyDataset(2)
img_sum, audio_sum = dataset[0]
Currently adjacent samples are used. Let me know, if you need another strategy.
|
st32808
|
@ptrblck, thank you for an example. My dataset is “endless” and stored externally, thus, unfeasible to store in the class instance. So currently __getitem__() retrieves just one sample from the external database.
I’m concerned with the high overhead for this sample-by-sample querying; for batch size of e.g. 64, __getitem__() gets called 64 times consequently, doesn’t it?
I thought I could build a cache in MyDataset, fetching and storing bunches of samples in the class instance before returning them individually via __getitem__(). Is there a better way / better place to implement it?
|
st32809
|
Yes, you are right.
If you are concerned about the overhead of the (DB) query, you could create the whole batch directly in __getitem__ (with a single query) and set batch_size=1 in your DataLoader.
Would this work for you?
|
st32810
|
Sure. Thanks! I just didn’t dare to, wondering instead why I need to torch.unsqueeze() single samples into tensors with singleton outer dimension prior to returning them from __getitem__().
Without unsqueeze(), I was getting the famous RuntimeError: Expected 4-dimensional input for 4-dimensional weight [4, 1, 3, 3], but got 3-dimensional input of size [64, 32, 32] instead from the very first layer, conv2d (3x3 to four features). The input is a 32x32 gray-scale image, batch_size is 64.
|
st32811
|
This should usually not be necessary since the DataLoader should take care of this.
Did you get an error if you didn’t unsqueeze the data sample?
|
st32812
|
Thank you for this nice answer! Is there a way to do the same when you do not have self.images, but instead loading random seq of images from the folder. Before that, I used Image.open() from PIL to open an image in getitem. Now I want to do the same but for the seq of images (let’s say 5 images) each time. So the shape of the batch would be (8, 5). It seems like a not optimal solution to load images in a loop with Image.open()
|
st32813
|
I’m not aware of a “batched” open method for multiple image files, so I think you would need to use the loop. However, note that you could speed up the image loading by replacing PIL with PIL-SIMD. You would still need to execute the loading in a loop, but might lower the duration.
|
st32814
|
I will check the performance of PIL-SIMD. For now, I solved the problem by using imread_collection from skimage.io 1. In principle, everything works properly but I face the problem of slow DataLoader. I use such a code:
def __getitem__(self, idx):
idx_q = int(torch.randint(0 + self.boundary, self.length - self.boundary, (1,)))
idx_n = int(torch.randint(0 + self.boundary, self.length - self.boundary, (1,)))
q = imread_collection([self.image_paths[idx_q-1], self.image_paths[idx_q], self.image_paths[idx_q+1]], conserve_memory=True)
p = imread_collection([self.image_paths_winter[idx_q-1], self.image_paths_winter[idx_q], self.image_paths_winter[idx_q+1]], conserve_memory=True)
n = imread_collection([self.image_paths_winter[idx_n-1], self.image_paths_winter[idx_n], self.image_paths_winter[idx_n+1]], conserve_memory=True)
if self.transform:
q = torch.stack([self.transform(img) for img in q])
p = torch.stack([self.transform(img) for img in p])
n = torch.stack([self.transform(img) for img in n])
return q, p, n
So, for batch_size=4 I load 4x3x3 images which are 36 images. When I try to run all this code from getitem out of torch’s DataLoader it takes around 0.3 sec to run. But with DataLoader it takes 13 seconds which is a huge difference. Of course, num_workers help here when there are more iterations. But I don’t know where is the bottleneck. If you have any thoughts, that could be very helpful.
|
st32815
|
How large is your batch size when you are using the DataLoader?
Each worker of the DataLoader will create a full batch before the DataLoader loop is executed, so in particular the first iteration might be slow, since all workers would start collecting all samples. Once the workers are done, the ready batches will be added to a queue and the workers will start creating the next batch while the training loop is executed, which might reduce the data loading time assuming that the actual model training is not tiny compared to the data loading.
|
st32816
|
I checked for batch size = 4. If I run such a code:
batch_size = 4
trainloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, num_workers=4)
dataiter = iter(trainloader)
for i in range(8):
start = time.time()
q, p, n = dataiter.next()
q, p, n = q.to(device), p.to(device), n.to(device)
end = time.time()
print(end - start)
I will get such time results:
10.58901309967041
1.8810162544250488
0.009713411331176758
0.7070198059082031
10.15380048751831
2.085867404937744
0.009247779846191406
0.009662628173828125
I mean this is ok compared to one worker, but still, I don’t know what is happening inside the loader so that it needs 10 seconds instead of 0.3. Maybe it is because workers collecting all samples as you explained, but for one worker problem stays
|
st32817
|
Btw for batch size 8:
23.229380130767822
0.024968624114990234
0.023113250732421875
1.4580109119415283
24.699864387512207
0.018816709518432617
0.01724529266357422
0.017206192016601562
So it grows linearly
|
st32818
|
The periodical slowdown every num_workers iterations points towards the aforementioned loading of a full batch in each worker.
In your current script you don’t have any workload, so it’s expected that you would see slower iterations once the queue is empty.
The timings would refer to:
10.58901309967041 # no batches ready in the queue, all 4 workers are preloading
1.8810162544250488 # Grab next batch from queue. Since this is slower than the next step the queue might not have been filled yet.
0.009713411331176758 # grab next batch from queue
0.7070198059082031 # grab next batch from queue
10.15380048751831 # Queue is empty, as no worker was able to load a full batch yet
If your model training is sufficiently large, the DataLoader might be able to preload the next batch(es) while your model is training.
|
st32819
|
Hi all,
I’m wondering how should I write a tree-lstm in pytorch? Is there any particular functionalities I should look more into? Is there any similar examples I should look at? What is the roughly outline of the implementation?
Thanks!
Best,
Demi
|
st32820
|
You can have a look at this implementation - https://gist.github.com/wolet/1b49c03968b2c83897a4a15c78980b18 691
|
st32821
|
Or this one, if you want a partially-batched approach like the SPINN paper: https://github.com/jekbradbury/examples/blob/spinn/snli/spinn.py 401
|
st32822
|
I already implement the pytorch version here https://github.com/ttpro1995/TreeLSTMSentiment 419
Which I convert from torch code https://github.com/stanfordnlp/treelstm 118
|
st32823
|
In your implementation of the BinaryTreeLSTM,
Can you explain the leaf / base condition - self.ox just passes through a linear layer, that is understandable since there is no hidden state for leafs, but why is there no weight params for input, update or forget gating, and why is cell state just passed through a linear layer?
And also for non-leaf nodes, you are completely ignoring passing the input through a linear layer, for all the gating units. Is there an explanation for that? In ChildSum, you have weight parameters for x_j, why not in n-ary lstm ?
self.ix = nn.Linear(self.in_dim,self.mem_dim)
|
st32824
|
A implementation with easy-first parsing, with explanations 4
Tree LSTMs are conceptually straightforward extension of RNN-LSTMs. Here’s what we need:
A parser (takes in a sentence and outputs the parse tree structure).
Stanford Core NLP/your own parser
Given the parse tree structure which implicitly contains how the word units should be progressively combined, convert this into a series of instructions which explicitly describes how the nodes should be combined.
Write a RNN that takes in a series of instructions on how to combine a list of inputs.
|
st32825
|
perhaps using a well tested library for graphs is the way to go: Tutorial: Tree-LSTM in DGL — DGL 0.4.3post2 documentation 10
|
st32826
|
In vision we usually process multiple images at once. I believe this is possible because most images are the same size or we can easily pad them with zeros if they are not (and thus process many at once).
However, I don’t see a simple way to do this for structure data like data (e.g. programs, code, not NLP) in the form of Trees (e.g. while using a TreeLSTM). It seems that the processing of the data and the forward pass of the TreeLSTM are tightly coupled. e.g. if our TreeLSTM is processing the Abstract Syntax Tree (AST) top-down or bottom-up my guess is that the batching has to be different and custom for each of these. What I am imagining very vaguely and abstracting is that we get each node from the AST, generate the tensor for that node and then do the 1 step forward pass. If we were to do this for many ASTs I’d assume to do this style of batching we’d need to collect ASTs of the same topology (not only size, since I assume even if two trees are the same size their branches everywhere have to match somehow…unless we padd them with zeros?). That way I’d imagine the code to be something like this:
def forward(asts):
""" asts have already been collated according to their matching topology. """
# order trees according to how the TreeNN will process it e.g. post order for bottom up
order_asts_according_to_traversal = oder_asts(asts) ## e.g. order in a post order
# do the forward pass
current_node_embeddings = torch.zeros(batch_size, D_embedding)
for batch_node in order_asts_according_to_traversal:
current_node_embeddings = node_step_forward(batch_node, current_node_embeddings)
return current_node_embeddings
in addition, we’d have to collate the asts (pseudo-code that I didn’t write since I’m not sure how to do this). For me, my data is usually already parsed (e.g. in json or s-expressions, but I prefer and plan to use json for each data point).
The problem that I have above does not feel new. TreeNNs (e.g. TreeLSTMs) have been implemented before so I’d rather use a tested method - the standard way to process and do forward passes on tree data for pytorch. Is there such a tutorial or library for pytorch one could easily use?
Research I’ve done
I’ve found the following options:
using CoqGym’s example (How to efficiently process a batch of terms in one go for Tree Neural Networks? · Discussion #48 · princeton-vl/CoqGym · GitHub 3 and How to efficiently process a batch of terms in one go for Tree Neural Networks · Issue #16 · princeton-vl/CoqGym · GitHub 1) though that general repo feels very hacky and their way of doing things seem very very custom, which worries me.
this option: PyTorch — Dynamic Batching. If you have been reading my blog, you… | by Illia Polosukhin | NEAR AI | Medium 2
a pytorch implementation of tree lstms: GitHub - unbounce/pytorch-tree-lstm: Pytorch implementation of the child-sum Tree-LSTM model 5
yet another link: Recursive Neural Networks with PyTorch | NVIDIA Developer Blog 2
what worries me is that none of these seemed to be part of the standard pytorch ecosystem (Ecosystem | PyTorch), which raises doubt to me which one to use (if any of them). Should I be using any of these above? My guess is that perhaps the 4th one is the one I should be using? Ideally, I’d like to be able to implement a custom data set object that returns ASTs (from my Json file or s-expressions) and create a batch that takes advantage of GPU acceleration.
Another Solution: using Graph Neural Network libraries
I also realized that tree are really just a special case of graphs (perhaps not in the way we do the forward pass since GNNs seem to have a more complex set of “cycles” to produce embeddings). So with that I found these links:
question from the pytorch forum: What is an efficient way to do a forward pass of a batch of data for an Graph Neural Network (GNN)? - #2 by Brando_Miranda
deep graph library: https://www.dgl.ai/ 1
geometric library: GitHub - rusty1s/pytorch_geometric: Geometric Deep Learning Extension Library for PyTorch 2
with the last two being part of the pytorch ecosystem. Though these are built for GNNs, so I am unsure if they are really worth the effort to check out to decide what to use.
Overall: What is the standard/recommended way to generate batches and process batches of tree data in pytorch to leverage the power of GPUs?
cross posted:
python - What is the standard way to batch and do a forward pass through tree structured data (ASTs) in pytorch so to leverage the power of GPUs? - Stack Overflow 6
What is the standard way to batch and do a forward pass through tree structured data (ASTs) in pytorch so to leverage the power of GPUs?
|
st32827
|
A possible solution is to use a graph NN library to do the heavy work:
The challenge in training Tree-LSTMs is batching — a standard technique in machine learning to accelerate optimization. However, since trees generally have different shapes by nature, parallization is non-trivial. DGL offers an alternative. Pool all the trees into one single graph then induce the message passing over them, guided by the structure of eac
e.g. from dgl: Tutorial: Tree-LSTM in DGL — DGL 0.4.3post2 documentation 6
|
st32828
|
Hello All;
Here is my issue. I’m running PyTorch model on AWS Studio from Sagemaker.
I manage to sent my tensord and my model and my criterion to cuda(). But GPU seems not to be used., and I don’t know why. I’m running the model in an instance with GPU Tesla 4, which isn’t used as seen in the following snapshot:
image1198×614 28.2 KB
But when I run this code, and I add manually tensors to cuda, with ponctual operations, I can see GPU being consumed:
import torch
a = torch.rand(20000,20000).cuda()
while True:
a += 1
a -= 1
print("Allocated:", round(torch.cuda.memory_allocated(0)/1024**3,1), "GB")
Which is appearing also in nvidia-smi command:
image1206×600 28.5 KB
here’s my model:
class Clf(nn.Module):
def __init__(self, params):
super(Clf, self).__init__()
# Input: N x channels_img x 256 x 256
self.pretrained = params['Pretrained']
C_in, C_out, H_in, W_in = params['Input']
self.conv1 = nn.Conv2d(C_in, C_out, kernel_size=3)
self.relu = nn.LeakyReLU(0.2)
self.pool = nn.MaxPool2d(2,2)
h,w,_ = findConv2dOutShape(H_in,W_in,self.conv1,pool=2)
self.conv2 = nn.Conv2d(C_out, C_out * 2, 3)
h,w,_ = findConv2dOutShape(h,w,self.conv2,pool=2)
self.conv3 = nn.Conv2d(C_out * 2, C_out * 4, 3)
h,w,c = findConv2dOutShape(h,w,self.conv3,pool=2)
#self.conv4 = nn.Conv2d(C_out * 4, C_out * 8, 3)
#h,w = findConv2dOutShape(h,w,self.conv4,pool=2)
#self.reshape = Reshape() # => (64, -1)
self.num_flatten = h*w*c
self.fc1 = nn.Linear(self.num_flatten, 512)
self.fc2 = nn.Linear(512, 1)
def forward(self, x):
if self.pretrained is None:
x = self.relu(self.conv1(x))
x = self.pool(x)
x = self.relu(self.conv2(x))
x = self.pool(x)
x = self.relu(self.conv3(x))
x = self.pool(x)
#x = self.relu(self.conv4(x))
#x = self.pool(x)
x = x.view(-1, self.num_flatten)
x = self.fc1(x)
x = self.fc2(x)
return torch.sigmoid(x)
And here’s my training loop
def train_model(model, criterion, optimizer, loader, test_loader, num_epoch):
for epoch in range(num_epoch):
print(f'Epoch -- {epoch}')
train_one_epoch(model, loader, optimizer, criterion)
def train_one_epoch(model, loader, optimizer, criterion):
losses = []
longueur_data = 0
for batch_idx, (x, y) in enumerate(loader):
print(f'Batch num -- {batch_idx}')
x = x.cuda()
y = y.to(torch.float32).unsqueeze(1).cuda()
optimizer.zero_grad()
scores= model(x)
loss = criterion(scores, y)
loss.backward()
optimizer.step()
print("Allocated:", round(torch.cuda.memory_allocated(0)/1024**3,1), "GB")
losses.append(loss.item())
longueur_data += x.size(0)
Loss = sum(losses) / longueur_data
print(f'Loss Epoch : {Loss}')
Please help, this is driving crazy since two weeks.
Thank you very much
Habib
|
st32829
|
Solved by twister9458 in post #7
Thank you @ptrblck.
As I’m working on aws services, I found that when I moved all my dataset to my EC2 instance, where I have my PyTorch/Cuda optimized notebooks, the GPU started to be used, which speeded it up.
Though, the usage of the GPU is still low, and doesn’t reach 80% unless I input big lo…
|
st32830
|
If the code isn’t raising an error and you’ve pushed the data as well as the model to the GPU, it’ll be used.
You might face another bottleneck, so that the GPU utilization is low and you would mostly see a 0% util. in nvidia-smi.
To check for a data loading bottleneck, you could remove the data loading and use random tensors created on the GPU, which should show a higher GPU util.
|
st32831
|
Thank you very much for your reply.
Yes that’s the case, I’m sending everything to cuda(), but nvidia-smi gives almost 0% GPU utilisation.
I’m struggling with this since two weeks, I can’t figure out what’s wrong.
Here is my DataLoader Class: (I’m loading data from S3 Bucket into memory via this Class)
class myDataset(Dataset):
def __init__(self, csv_file, root_dir, target, length, transform=None):
self.annotations = pd.read_csv(fs.open(csv_file)).iloc[:length,:]
self.root_dir = root_dir
self.transform = transform
self.target = target
self.length = length
def __len__(self):
return len(self.annotations)
def __getitem__(self, index):
img_path = fs.open(os.path.join(self.root_dir, self.annotations.loc[index, 'image_id']))
image = Image.open(img_path)
image = np.array(image)
if self.transform:
image = self.transform(image=image)["image"]
image = np.transpose(image, (2, 0, 1)).astype(np.float32)
image = torch.Tensor(image)
y_label = torch.tensor(int(self.annotations.loc[index, str(self.target)]))
return image, y_label
And my training loop:
def train_model(model, criterion, optimizer, loader, test_loader, num_epoch):
for epoch in tqdm(range(num_epoch)):
#print(f'Epoch -- {epoch}')
train_one_epoch(model, loader, optimizer, criterion)
def train_one_epoch(model, loader, optimizer, criterion):
losses = []
longueur_data = 0
for batch_idx, (x, y) in enumerate(tqdm(loader)):
x = x.to('cuda')
y = y.to(torch.float32).unsqueeze(1).to('cuda')
optimizer.zero_grad()
scores= model(x)
loss = criterion(scores, y)
loss.backward()
optimizer.step()
losses.append(loss.item())
longueur_data += x.size(0)
Loss = sum(losses) / longueur_data
print(f'Loss Epoch : {Loss}')
Here is the call to my Dataset Class, and my data loading (I’m using albumentations for data augmentation):
aug = al.Compose([
al.RandomResizedCrop(H, W, p=0.2),
al.Resize(H, W),
al.Transpose(p=0.2),
al.HorizontalFlip(p=0.5),
al.VerticalFlip(p=0.2),
al.augmentations.transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225],
max_pixel_value=255.0,
always_apply=True,
p=1.0)
])
dataset = myDataset(csv_file=LABEL_PATH,
root_dir=IMAGE_PATH,
target='gender',
length=LENGTH,
transform=aug)
train_set, test_set = torch.utils.data.random_split(dataset,[int(LENGTH*0.8), LENGTH - int(LENGTH*0.8)])
train_loader = DataLoader(dataset=train_set, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(dataset=test_set, batch_size=batch_size, shuffle=True)
I cannot figure out where is the issue.
Thank you very much,
|
st32832
|
Did you try to remove the data loading and check the GPU utilization using random tensors created on the GPU as described before? This could narrow down the bottleneck of your code and make it easier to isolate it.
Also, you could profile your code as described in this post 1 using Nsight Systems or the PyTorch profiler.
|
st32833
|
Thank you @ptrblck for your response, yes I did as shown in the first post.
When I run this code, and I add manually tensors to cuda, with ponctual operations, I can see GPU being consumed:
import torch
a = torch.rand(20000,20000).cuda()
while True:
a += 1
a -= 1
print("Allocated:", round(torch.cuda.memory_allocated(0)/1024**3,1), "GB")
It raises the % of utilisation of GPU from 1.7GB to 3.2GB, as shown in the nvidia-smi command results, please see the nvidia-smi screenshots of my first post.
I’ll try with the packages you listed, thank you.
What might be the solutions to solve this GPU Bottleneck ? I can try them all.
Thank you very much
|
st32834
|
You would first have to isolate the bottleneck before a solution can be found.
E.g. if the data loading is the bottleneck, you would need to speed it up by e.g. using multiple workers, speeding up the transformations etc.
twister9458:
It raises the % of utilisation of GPU from 1.7GB to 3.2GB
The utilization shows a percentage of the time the GPU was busy in a specific last time frame, not the memory usage.
|
st32835
|
Thank you @ptrblck.
As I’m working on aws services, I found that when I moved all my dataset to my EC2 instance, where I have my PyTorch/Cuda optimized notebooks, the GPU started to be used, which speeded it up.
Though, the usage of the GPU is still low, and doesn’t reach 80% unless I input big load of images, and big batch_size.
Hence, I presume the data loading being the origin of my issues.
I’ll test pinning memory, using multiple workers, and let you know.
Thank you very much
Habib
|
st32836
|
Just to confirm this solution. For training Deeplearning in AWS, must have your data locally, either locally in EC2 instance, either locally in EC2 of Notebook of Sagemaker.
And last information, pin_memory and num_worker, make the training faster ! much faster !
Thank you
Habib
|
st32837
|
Hello, I’m trying to understand the CosineSimilarity for tensors with different dimensions. I don’t quite understand the reason why the output is >1. Shouldn’t cosine similarity always be between -1 to 1?
from torch.nn import CosineSimilarity as cs
f = torch.tensor([[3,2]], dtype = torch.float)
g = torch.tensor([[3,2],[1,2]], dtype = torch.float)
cos = cs(dim =0,eps = 0.3)
z = cos(d,e)
print(z)
output: tensor([1.2649, 1.4142])
|
st32838
|
Hey @Yunchao_Liu
I think here you would need to keep the dims of both the matrices the same. With reference to the docs 2 we need to have same shape matrices and do the cosine similarity on a said dim.
With that in mind, we will have a value from the range of -1 to 1.
|
st32839
|
Hi @ariG23498 Thanks!
Now I have another question since I need to implement calculating cosine similarity between tensors of different dimensions. This is the problem description 1
|
st32840
|
I have a batch of sequences that have a variable length. To save computation I used pack_padded_sequence 1 as following:
input = torch.nn.utils.rnn.pad_sequence(input, batch_first=True)
input = torch.nn.utils.rnn.pack_padded_sequence(input,
batch_first=True,
lengths=lengths)
Because sequences are long, I use gradient checkpointing to save memory
output, hiddens = cp.checkpoint(self.gru, *(input, hiddens, self.dummy_tensor))
As a result I have such error:
File ".../src/sequence_models/gru.py", line 86, in forward
output, hiddens = cp.checkpoint(self.gru, *(input, hiddens, self.dummy_tensor))
File ".../torch/utils/checkpoint.py", line 177, in checkpoint
return CheckpointFunction.apply(function, preserve, *args)
TypeError: CheckpointFunctionBackward.forward: expected Tensor or tuple of Tensor (got PackedSequence) for return value 0
How can I handle it?
|
st32841
|
I want to train a network on the Imagewoof dataset. I would like to know if I correctly use transforms.Compose() for testing my network.
Currently I use the following approach:
avg = (0.4914, 0.4822, 0.4465)
std = (0.2023, 0.1994, 0.2010)
stats = (avg, std)
train_transform = transforms.Compose([
transforms.RandomResizedCrop(size=(128, 128)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(*stats, inplace=True)])
test_transform = transforms.Compose([
transforms.RandomResizedCrop(size=(128, 128)),
transforms.ToTensor(),
transforms.Normalize(*stats)])
However, I think it is not right to use transforms.RandomResizedCrop(size=(128, 128)) for testing my network, because it randomly crops the image. If I want to compare my results to those from the official leaderboard, how do I have to configure test_transform?
|
st32842
|
Solved by eqy in post #2
I believe the standard approach is to use a Center Crop although different datasets may use different “rules” sometimes. Note that you may want to resize the images first (e.g., examples/main.py at 01539f9eada34aef67ae7b3d674f30634c35f468 · pytorch/examples · GitHub) before taking a center crop due …
|
st32843
|
I believe the standard approach is to use a Center Crop although different datasets may use different “rules” sometimes. Note that you may want to resize the images first (e.g., examples/main.py at 01539f9eada34aef67ae7b3d674f30634c35f468 · pytorch/examples · GitHub 1) before taking a center crop due to the variation in resolution of images.
|
st32844
|
Using Center Crop seems like the most logical approach, thanks!
Do I need to resize the images, if I know, that their height and width is larger than 128 pixels?
|
st32845
|
For example, if a test image is 10000x10000 pixels, taking the 128x128 center crop before resizing to say (160x160 or 192x192) might result in a huge mismatch between the size of objects your model is used to seeing at training time and what it is now being tested on. Resizing to a known size before taking the center crop is a way to help alleviate this problem.
Overall, this issue is somewhat tricky to deal with even with resizing (see Touvron et. al 1 for more details).
|
st32846
|
I have a very strange task that requires pairs of inputs be passed through a neural network, where the pairs create many-to-many relationship, and each “many” is really “very many”. This means that for each input tensor from set 1, there will be lots of redundant calculations made for each comparison made with each tensor from set 2. I believe one could do operation fusion to speed this up - fusion of a repetitive input and a similar layer seems conceptually similar to fusion of a conv and BN layer, however i cannot seem to find a good way to do this. Most of the ideas I came up with are stupid, and do not actually do fusion.
Does anyone know of a good way to do this - or - if it is even possible natively in pytorch?
Additionally, do people believe my hypothesis is correct, and this would boost performance measurably?
|
st32847
|
Hi everyone,
I’m trying to code a custom LSTM layer with an attention gate, as explained in “https://arxiv.org/pdf/1807.04445.pdf 1”, for a classification problem. But I’m struggling with this error when it comes to multiplying the result obtained from the attention gate and the input x. By removing the AtGate lines the code works just fine. Can anyone give me some help? Thanks in advance!
The custom LSTM Layer code is below:
import math
class AttCustomLSTM(nn.Module):
def __init__(self, input_sz: int, hidden_sz: int):
super().__init__()
self.input_size = input_sz
self.hidden_size = hidden_sz
#i_t
self.W_i = nn.Parameter(torch.Tensor(input_sz, hidden_sz))
self.U_i = nn.Parameter(torch.Tensor(hidden_sz, hidden_sz))
self.b_i = nn.Parameter(torch.Tensor(hidden_sz))
#f_t
self.W_f = nn.Parameter(torch.Tensor(input_sz, hidden_sz))
self.U_f = nn.Parameter(torch.Tensor(hidden_sz, hidden_sz))
self.b_f = nn.Parameter(torch.Tensor(hidden_sz))
#c_t
self.W_c = nn.Parameter(torch.Tensor(input_sz, hidden_sz))
self.U_c = nn.Parameter(torch.Tensor(hidden_sz, hidden_sz))
self.b_c = nn.Parameter(torch.Tensor(hidden_sz))
#o_t
self.W_o = nn.Parameter(torch.Tensor(input_sz, hidden_sz))
self.U_o = nn.Parameter(torch.Tensor(hidden_sz, hidden_sz))
self.b_o = nn.Parameter(torch.Tensor(hidden_sz))
#att_t
self.W_a = nn.Parameter(torch.Tensor(input_sz, hidden_sz))
self.U_a = nn.Parameter(torch.Tensor(hidden_sz, hidden_sz))
self.b_a = nn.Parameter(torch.Tensor(hidden_sz))
self.init_weights()
def init_weights(self):
stdv = 1.0 / math.sqrt(self.hidden_size)
for weight in self.parameters():
weight.data.uniform_(-stdv, stdv)
def forward(self,
x,
init_states=None):
bs, seq_sz, _ = x.size()
hidden_seq = []
if init_states is None:
h_t, c_t = (
torch.zeros(bs, self.hidden_size).to(x.device),
torch.zeros(bs, self.hidden_size).to(x.device),
)
else:
h_t, c_t = init_states
for t in range(seq_sz):
x_t = x[:, t, :]
# Attention gate
a_t = torch.sigmoid(x_t @ self.W_a + h_t @ self.U_a + self.b_a)
x_t = a_t @ x_t
i_t = torch.sigmoid(x_t @ self.W_i + h_t @ self.U_i + self.b_i)
f_t = torch.sigmoid(x_t @ self.W_f + h_t @ self.U_f + self.b_f)
g_t = torch.tanh(x_t @ self.W_c + h_t @ self.U_c + self.b_c)
o_t = torch.sigmoid(x_t @ self.W_o + h_t @ self.U_o + self.b_o)
c_t = f_t * c_t + i_t * g_t
h_t = o_t * torch.tanh(c_t)
hidden_seq.append(h_t.unsqueeze(0))
#reshape hidden_seq p/ retornar
hidden_seq = torch.cat(hidden_seq, dim=0)
hidden_seq = hidden_seq.transpose(0, 1).contiguous()
return hidden_seq, (h_t, c_t)
class Net(nn.Module):
def __init__(self):
super().__init__()
self.embedding = nn.Embedding(len(encoder.vocab)+1, 32)
self.lstm = NaiveCustomLSTM(32,32)#nn.LSTM(32, 32, batch_first=True)
self.fc1 = nn.Linear(32, 2)
def forward(self, x):
x_ = self.embedding(x)
x_, (h_n, c_n) = self.lstm(x_)
x_ = (x_[:, -1, :])
x_ = self.fc1(x_)
return x_
|
st32848
|
Solved by a_d in post #4
Hello
According to your code, you are not passing the vanilla input but rather an attentive input into your input gate which is of shape batch, hidden_size. The W_i which maps from input to hidden is of input, hidden, and therein lies the problem.
Also, based on a cursory reading of the paper, t…
|
st32849
|
Hi, Based on your error, you would have to transpose one matrix for them to be multiple, as the second dimension of the first matrix and the first dimension of the second matrix should be the same.
Therefore you should multiply matrices of shape 128 x 32 and 32 x 128 to get a resultant shape of 128 x 128
x_t = a_t @ x_t
because a_t would be of shape batch x hidden_size and x_t is of shape batch x input_size
Please check your input shapes once. I believe the error comes from the line
On a side note, instead of using the @ operator, I believe using torch.bmm would be much faster.
|
st32850
|
Hi, thanks for the help. I transposed the matrix to get a 128 x 128 as result, but got into another problem that it can’t be multiplied in the input gate by the weight because the weight is shape 32 x 32.
PyTorch856×583 32.6 KB
Note: I’ve tried with a 32x32 result, and it can do the multiplication, but the input and hidden state sum in the input gate doesn’t work because of the shape as well.
PyTorch21037×42 2.4 KB
|
st32851
|
Hello
According to your code, you are not passing the vanilla input but rather an attentive input into your input gate which is of shape batch, hidden_size. The W_i which maps from input to hidden is of input, hidden, and therein lies the problem.
Also, based on a cursory reading of the paper, the dimension of the input vector and the attention vector should be the same, therefore, your W_a should be of size input, input and the U_a should be hidden, input. The line from the paper which suggests this is as follows -
The response of
an EleAttG is a vector at with the same dimension as the input xt of the RNNs,
Also I believe the author calculates the hardmat product instead of matrix multiplication to get the final xt which therefore would change to xt = at * xt
|
st32852
|
Hello
I tried the change you suggested in the W_a and U_a size, and it worked perfectly. I even tried to change the size before posting this issue, but it wasn’t working, mostly because I did it wrong. I’m kinda new to DL especially with PyTorch, so I’m still struggling with some implementations and logic regarding matrix operations.
Thanks a lot for the help
|
st32853
|
I use RTX2080 to run my code on pytorch0.4.1
But I found that RTX2080 just support cuda 10.0,while pytorch 0.4.1 can’t support cuda 10.0.
Do you know how to fix it up?
|
st32854
|
You could install CUDA10.0 locally and build PyTorch from source as described here 151. If I’m not mistaken, CUDA10 wasn’t released yet when PyTorch 0.4 came out.
What’s the reason you are using such an old PyTorch version?
|
st32855
|
Thanks! I will have a try. I use 0.4.1 to run some paper’s codes which are based on torch 0.4.1.
When I use the higher version to run codes,there are so many errors
|
st32856
|
Hello! Do you fix you problem?
I use 0.4.1 to run some paper’s codes which are based on torch 0.4.1
But I only have RTX2070
|
st32857
|
I didn’t solve this problem. Finally I used pytorch1.0 to run the code based on pytorch 0.4.1.
|
st32858
|
Hello I am trying to build a custom loss function which include using tanh.
if forward pass is y=tanhx
than how should be the backward pass?
In other word what should be the relationship between gradOutput and gradInput?
|
st32859
|
I guess you’re implementing the backward by hand? Otherwise it will work with the autograd.
The derivative for tanh is quite common and can be found here 147 for example. The C implementation of the backward pass by pytorch is here 88.
|
st32860
|
@albanD Thanks for the reply. I’m a bit confused by the autograd process. The document says it computes the vector-Jacobian result, which usually returns a vector.
However, the tanh function is element-wise, that is, Y_{ij} = nn.tanh(X_{ij}), where X and Y are both matrices.
In this case, we have a matrix-valued function and the gradient of Y wrt X would be a 4-D Jacobian matrix.
The C-souce code is like this:
*gradInput_data = *gradOutput_data * (1. - z*z);
It seems so perform an elementwise multiplication: Y_ij * (1-X_ij^2)
Could you please explain how the auto-grad actually handle this?
P.S.: Sorry if it’s inappropriate to reply such an old post.
|
st32861
|
As you mentioned, autograd just does the vector jacobian product.
In this case, you multiply the 2d matrix of gradients wrt the output (grad_output) again a 4D Jacobian matrix for that op.
The nice thing is that the op is element-wise and so the 4D Jacibian is actually diagonal and what this vector jacobian product boils down to is multiply each element of the input 2D matrix with each element in the diagonal of the Jacobian.
Here, (1. - z*z) is actually the “diagonal” of the jacobian and the result is computed by doing an element-wise product with the gradient flowing back to get the gradient wrt the input.
|
st32862
|
I’m currently training a faster-rcnn model. Normal training consumes ~1900MiB of gpu memory. When I try to resume training from a checkpoint with torch.load, the model takes over 3000MiB. With identical settings specified in a config file.
I believe these are the relevant bits of code:
voc_dataset = PascalVOC(DATA_PATH, transform, LIMIT)
voc_loader = DataLoader(voc_dataset, shuffle=SHUFFLE, pin_memory=True)
basecnn = BaseCNN(ARCHITECTURE, REQUIRES_GRAD)
rpn = RegionProposalNetwork(batch_size=RPN_BATCH_SIZE)
detector = Detector(batch_size=CLF_BATCH_SIZE)
frcnn = FasterRCNN(basecnn, rpn, detector)
optimizer = Adam(filter(lambda p: p.requires_grad, frcnn.parameters()), lr=LEARNING_RATE)
if RESUME_PATH:
experiment = torch.load(RESUME_PATH)
frcnn.load_state_dict(experiment['model_state'])
optimizer.load_state_dict(experiment['optimizer_state'])
frcnn.basecnn.finetune()
frcnn.cuda()
Full training code is here: https://github.com/A-Jacobson/faster_rcnn/blob/master/train.py 7
|
st32863
|
Yes, I have experienced the same situation before. This is quiet annoying ! I will bump on OOM if I would like to resume training from a checkpoint.
|
st32864
|
Have you tried to save and load the state_dict? I’ve seen some issues where e.g. the training resumed when using the second approach explained here 149.
|
st32865
|
Yes. I always follow the best practice to save and load the state_dict.
I found a related issue here 67
It says torch.cuda.empty_cache()might help, but in my case I still have OOM.
By the way, I’m using pytorch 0.3.1
|
st32866
|
Good news ! I seems able to avoid OOM by the following loading strategy:
checkpoint = torch.load(ckpt_file, map_location=lambda storage, loc: storage)
net.load_state_dict(checkpoint['model'])
optimizer.load_state_dict(checkpoint['optimizer']) # pytorch 0.3.1 has a bug on this, it's fix in master
del checkpoint # dereference seems crucial
torch.cuda.empty_cache()
|
st32867
|
That’s good!
Btw, shouldn’t the checkpoint be in CPU memory when loading with the map_location parameter?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.