id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st104600 | It should be deleted when output goes out of scope.
Are you storing output or your loss somehow? |
st104601 | Thanks for the quick reply. No, it is not being stored, infact I have also tried doing del loss, logits, inputs explicitely. Is there any recommended way of looking memory usage/allocated on gpu by tensors? |
st104602 | I get 3.97 GB as output from the code snippet(I have modified it slightly, please check) and if I use del on loss, outputs and other parameters used/created in the training step then it reduces to 2.35 GB. Main problem is that nvidia-smi is showing consumption of complete 16GB.
Here is the modified code snippet -
total = 0
for obj in gc.get_objects():
try:
if torch.is_tensor(obj) or (hasattr(obj, 'data') and torch.is_tensor(obj.data)):
if len(obj.size()) > 0:
if obj.type() == 'torch.cuda.FloatTensor':
total += reduce(lambda x, y: x*y, obj.size()) * 32
elif obj.type() == 'torch.cuda.LongTensor':
total += reduce(lambda x, y: x*y, obj.size()) * 64
elif obj.type() == 'torch.cuda.IntTensor':
total += reduce(lambda x, y: x*y, obj.size()) * 32
#else:
# Few non-cuda tensors in my case from dataloader
except Exception as e:
pass
print("{} GB".format(total/((1024**3) * 8)))
Some more updates on the issue:
If I disable backprop part of the model then the snippet gives 0.78GB as output but the program crashes very fastly when I don’t use del logits in this case as it doesn’t use existing memory(maybe loss.backward() has some flag which allows to reclaim unused part of GPU |
st104603 | I wonder if gc.get_objects() actually gives all the objects declared(specially the ones on GPU), maybe there is some C level API which is creating object and the reference is dangling somewhere out of the scope and gc is not able to access those objects. I am not sure about this but let me know your thoughts |
st104604 | nvidia-smi might show a higher usage, since PyTorch uses a caching memory allocator.
Have a look at the memory management 386 for more information.
Your current problem is that your GPU runs out of memory, if you don’t delete logits?
Could you post your code then please? It might be due to unwanted storing of logits, thus keeping the computation graph alive. |
st104605 | After some more debugging, it turned out that my model was close to the point of going OOM since the beginning but only when input with large number of batch size arrived it actually crashed. I was able to delay this event of crash by doing del logits in the end which apparently gave more room for the larger batch size but nevertheless it crashed after many epochs. The reason why model is not able to fit in the gpu seems a bit bizarre and I have opened separate discussion thread 260 regarding that.
Many many thanks for support |
st104606 | Fresh install of ubuntu 16, I downloaded cuda fine, created a python3.5 virtual environment. Once there, I wrote pip install http://download.pytorch.org/whl/cu90/torch-0.4.0-cp35-cp35m-linux_x86_64.whl, which gave me a response of
Collecting torch==0.4.0 from https://download.pytorch.org/whl/cu90/torch-0.4.0-cp35-cp35m-linux_x86_64.whl 6
Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by ‘NewConnectionError(’<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f7c3f80a128>: Failed to establish a new connection: [Errno -2] Name or service not known’,)’: /whl/cu90/torch-0.4.0-cp35-cp35m-linux_x86_64.whl
Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by ‘NewConnectionError(’<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f7c3f80a9e8>: Failed to establish a new connection: [Errno -2] Name or service not known’,)’: /whl/cu90/torch-0.4.0-cp35-cp35m-linux_x86_64.whl
Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by ‘NewConnectionError(’<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f7c3f80a7f0>: Failed to establish a new connection: [Errno -2] Name or service not known’,)’: /whl/cu90/torch-0.4.0-cp35-cp35m-linux_x86_64.whl
Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by ‘NewConnectionError(’<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f7c3f80a278>: Failed to establish a new connection: [Errno -2] Name or service not known’,)’: /whl/cu90/torch-0.4.0-cp35-cp35m-linux_x86_64.whl
Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by ‘NewConnectionError(’<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f7c3f80af28>: Failed to establish a new connection: [Errno -2] Name or service not known’,)’: /whl/cu90/torch-0.4.0-cp35-cp35m-linux_x86_64.whl
Could not install packages due to an EnvironmentError: HTTPSConnectionPool(host=‘download.pytorch.org 2’, port=443): Max retries exceeded with url: /whl/cu90/torch-0.4.0-cp35-cp35m-linux_x86_64.whl (Caused by NewConnectionError(’<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f7c3f80ada0>: Failed to establish a new connection: [Errno -2] Name or service not known’,))
download.pytorch .org gives me a flat 404 error when I try to manually open it, and if I try to download a previous version of pytorch I again get a 404 error. I had the same problem a few months ago, on a fully different setup. How can I fix it? Is pytorch not compatible with cuda9.0 or something? |
st104607 | That’s strange, because it’s a valid link in Firefox on my system.
I’ve searched this error and just came across one post stating it was the proxy’s fault. |
st104608 | Don’t think that’s it, I should have the same IP in both firefox and chromium. Plus, a few months ago I had the same issue on a different network. The only thing I can guess, is that they filter requests in some way by user-agent AND location, so firefox-bulgaria is filtered, while chrome-bulgaria and firefox-russia are not. |
st104609 | I built a C3D network.
self.conv1 = nn.Conv3d(3, 64, kernel_size=(3, 3, 3), padding=(1, 1, 1))
self.pool1 = nn.MaxPool3d(kernel_size=(1, 2, 2), stride=(1, 2, 2))
self.conv2 = nn.Conv3d(64, 128, kernel_size=(3, 3, 3), padding=(1, 1, 1))
self.pool2 = nn.MaxPool3d(kernel_size=(2, 2, 2), stride=(2, 2, 2))
…
When I enter the color picture sequence can be normal stitching.
clip = np.array([resize(io.imread(frame), output_shape=(112, 200), preserve_range=True) for frame in clip])
clip = clip[:, :, 44:44+112, :]
But when I enter a grayscale image sequence£¬can cause
IndexError: too many indices for array
so I change it
clip = clip[:, :, 44:44+112]
so that can stitching.
Meanwhile I change network
self.conv1 = nn.Conv3d(1, 64, kernel_size=(3, 3, 3), padding=(1, 1, 1))
But still making mistakes
expected stride to be a single integer value or a list of 2 values to match the convolution dimensions, but got stride=[1, 1, 1]
Should I expand the channel and if so, how do I do it? |
st104610 | Solved by ptrblck in post #2
Your last error message might be a misleading error due to a missing batch dimension in your input.
It has been fixed in master.
Could you unsqueeze at dim0 and try it again? |
st104611 | Your last error message might be a misleading error due to a missing batch dimension in your input.
It has been fixed in master 5.
Could you unsqueeze at dim0 and try it again? |
st104612 | yes,l print input shape and find you’re right
unsqueeze can add dim.(1,…)
thanks |
st104613 | and l have a problem.
l want to build network with siamese and c3d.can you give me some advice about the loss for 2 outputs |
st104614 | Here 2 you can find an implementation of a Siemese-Network.
I’m not sure, what c3d means. |
st104615 | it’s conv3d.
the demo is conv2d.
I would like to know if the loss function can be used in the same way |
st104616 | The model in the repo flattens the output and applies to criterion on it, so it should work if you do the same using Conv3d. |
st104617 | Hi,
I am trying out below network. But, I am facing the problem that training and validation loss both goes to zero after some batches. This happens even when the margin in triplet loss is a high value (like 10000).
It would be very helpful if someone can suggest what could possibly be wrong in the process that I have chosen.
import torch
from torch.autograd import Variable
import torch.nn as nn
import torchvision.models as models
import os
# Setting GPU
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "3"
num_inputs = 2
resnet = models.resnet50(pretrained=True)
mod_resnet = list(resnet.children())
mod_resnet.pop()
resnet_model = nn.Sequential(*mod_resnet)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# Resnet model
self.resnet = resnet_model
self.fc1 = nn.Linear(2048, 512, bias=True)
self.bn = nn.BatchNorm1d(512)
# self.relu = nn.PReLU()
# self.bn_merge1 = nn.BatchNorm1d(num_inputs)
self.conv1 = nn.Conv1d(in_channels=num_inputs, out_channels=1, kernel_size=1, stride=1)
self.bn1 = nn.BatchNorm1d(512)
# self.bn_merge2 = nn.BatchNorm1d(num_inputs)
self.conv2 = nn.Conv1d(in_channels=num_inputs, out_channels=1, kernel_size=1, stride=1)
self.bn2 = nn.BatchNorm1d(512)
self.triplet = TripletDist()
def forward_once(self, x):
output = self.resnet(x)
N, C, H, W = output.size()
output = output.view(N, C * H * W)
output = self.fc1(output)
# output = self.relu(output)
output = self.bn(output)
return output
def forward(self, in_1, in_n_2, in_n_3):
'''
:param in_1: First input of size batch_size x 3 x 224 x 224
:param in_n_2: A list of inputs similar to in_1 ; each of size batch_size x 3 x 224 x 224
:param in_n_3: A list of inputs very different from in_1; each of size batch_size x 3 x 224 x 224
:return:
'''
output_2_list = []
output_3_list = []
output_1 = self.forward_once(in_1)
for j in range(0, num_inputs):
output_2_list.append(self.forward_once(in_n_2[j]))
for j in range(0, num_inputs):
output_3_list.append(self.forward_once(in_n_3[j]))
# output_bn_n_2 = self.bn_merge1(torch.stack(output_2_list, 1))
output_bn_n_2 = torch.stack(output_2_list, 1)
output_n_2 = self.conv1(output_bn_n_2).squeeze()
output_n_2 = self.bn1(output_n_2)
# output_bn_n_3 = self.bn_merge2(torch.stack(output_3_list, 1))
output_bn_n_3 = torch.stack(output_3_list, 1)
output_n_3 = self.conv2(output_bn_n_3).squeeze()
output_n_3 = self.bn1(output_n_3)
model_output = self.triplet(output_1, output_n_2, output_n_3)
return model_output, output_1, output_n_2, output_n_3
class TripletDist(nn.Module):
# finds pairwise 2-norm distances, concatenates and returns a vector
def __init__(self):
super(TripletDist, self).__init__()
self.dist = nn.PairwiseDistance()
def forward(self, *x):
pair1_2norm_dist = self.dist(x[0], x[1])
pair2_2norm_dist = self.dist(x[0], x[2])
output = torch.cat((pair1_2norm_dist, pair2_2norm_dist), 0)
N, C = output.size()
return output.view(N * C)
model = Net()
val_1 = Variable(torch.randn(4, 3, 224, 224).cuda(async=True), volatile=True)
val_n_2 = []
val_n_3 = []
for j in range(num_inputs):
val_n_2.append(Variable(torch.randn(4, 3, 224, 224).cuda(async=True), volatile=True))
val_n_3.append(Variable(torch.randn(4, 3, 224, 224).cuda(async=True), volatile=True))
criterion = nn.TripletMarginLoss(margin=3000, p=2)
optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=0.1)
for i in range(1000):
model.train()
model.cuda()
# wrap inputs in Variables
input_1 = Variable(((torch.randn(4, 3, 224, 224)).cuda(async=True)))
input_n_2 = []
input_n_3 = []
for j in range(num_inputs):
input_n_2.append(Variable(((torch.randn(4, 3, 224, 224)).cuda(async=True))))
input_n_3.append(Variable(((torch.randn(4, 3, 224, 224)).cuda(async=True))))
# Training
# zero the parameter gradients
optimizer.zero_grad()
dist, out_1, out_n_2, out_n_3 = model(input_1, input_n_2, input_n_3)
loss = criterion(out_1, out_n_2, out_n_3)
loss.backward()
train_loss = loss.data[0]
# Take one optimization step
optimizer.step()
if i % 10 == 0:
model.eval()
val_dist, val_anc_out, val_pos_out, val_neg_out = model(val_1, val_n_2, val_n_3)
triplet_margin_val = criterion(val_anc_out, val_pos_out, val_neg_out)
val_loss = triplet_margin_val.data[0]
print(i, "Train_loss: ", train_loss, ", VAL_LOSS: ", val_loss) |
st104618 | Hello world, hope all is well,
Today I am trying to use my ConvNet skills and apply them to doing a regression problem. Unfortunately, there is little documentation compared to classification. Here (https://arxiv.org/pdf/1803.08450.pdf 8) I found the basic advice, “Besides classification,
ConvNets are also used to solve regression problems. In this
case, the softmax layer is commonly replaced with a fully
connected regression layer with linear or sigmoid activations.”
In my problem I have classes 0 through 4 and I want the algorithm to return a regression. After following the above advice all scores were between 1.8 and 4.1 - almost completely ignoring the 0 and 1 class. The results for classes 2,3,and 4 also look nonsensical. I am using MSELoss.
Any advice on how to start a problem like this correctly would be appreciated!
Thanks,
jjosh |
st104619 | Hello everyone,
First of all, a bit of a presentation: I am new to the world of Artificial Neural Networks, but I am an HPC specialist (from OpenMP and MPI to CUDA and OpenCL. Yes, I speak Fortran).
I am currently trying to understand the needs of the data analysts/Machine Learning community in terms of a computer science-centric approach.
Basically, at the moment, I do see that a lot of the codes are using 2d-convolution networks, which rely heavily on dense matrix-matrix operations (GEMM). Obviously, these work extremely well for cache-based processors, and even better on GPU’s.
So my question could be summarized as a chicken and egg conundrum: do data scientists use 2D-convolutions at the core of the networks because the hardware we have is very fast for that, or are there no other ways to solve these problems?
Formulated differently: as a data scientist, are there cases that you cannot efficiently resolve with the current “gemm-heavy” approach, for instance with sparse tensors, or very large problems that are just incredibly slow even with the latest shiny GPU, etc…
Thank you by advance for your help! I find this domain truly fascinating.
Geraud |
st104620 | geraudk:
Formulated differently: as a data scientist, are there cases that you cannot efficiently resolve with the current “gemm-heavy” approach, for instance with sparse tensors, or very large problems that are just incredibly slow even with the latest shiny GPU, etc…
Group convolutions with a large number of groups, dilated convolutions, strided convolutions – all these are not used as much as they should be because they bring sparsity and cache-unfriendly memory accesses into play.
See https://github.com/vdumoulin/conv_arithmetic 9 for reference of dilated, strided. |
st104621 | In numpy, when i have a 3D tensor X with shape [A, B, C] and a 2D tensor Y with shape [C, D], then np.dot(X, Y) gives a 3D tensor with shape [A, B, D].
In PyTorch, i can do this as below. However, it seems that 2nd method is numerically unstable. How can i fix this?
X = Variable(torch.randn(2, 30, 400))
Y = Variable(torch.randn(400, 400))
# 1st method
outs = []
for i in range(X.size(0)):
out = torch.mm(X[i], Y)
outs.append(out)
result1 = torch.stack(outs) # shape of (2, 3, 4)
# 2nd method
result2 = X.resize(2*30, 400).mm(Y)
result2 = result2.resize(2, 30, 400)
# 3rd method
result3 = torch.bmm(X, Y.unsqueeze(0).expand(X.size(0), *Y.size()))
assert np.allclose(result1.data.numpy(), result2.data.numpy()) # this causes an error
assert np.allclose(result1.data.numpy(), result3.data.numpy())
assert np.allclose(result2.data.numpy(), result3.data.numpy()) # this causes an error
assert np.allclose(result2.data.numpy(), result3.data.numpy(), 1e-2) # this doesn't cause an error |
st104622 | I couldn’t reproduce the error with your script.
But note that the resize function might change the underlying data if the size doesn’t match with the size of the original tensor. In those situations, it’s better to simply use .view, which is guaranteed not to modify your tensor and to error out if the number of elements don’t match |
st104623 | Hi all,
I am facing a similar issue: I have to implement a layer from a Theano implementation and reproducing it with the PyTorch framework leads to small numerical instability.
As an example I want to multiply two tensors: a and b.
A permutation is applied because the representation of those tensors are not the same between the two implementations.
Here is the code:
import torch
import numpy as np
import theano
import theano.tensor as T
torch.manual_seed(7)
def func_pytorch(a, b):
a = a.permute(0,2,1).contiguous().view(-1,400)
b = b.view(400,-1)
return torch.matmul(a, b).view(100,5,400,10).permute(0,2,3,1)
def func_theano(a, b):
return T.tensordot(a, b, [[2], [2]])
def func_numpy(a, b):
return np.tensordot(a, b, [[2], [2]])
a = torch.randn(100,400,5)
b = torch.randn(400,400,10)
a_p = a.permute(0,2,1)
b_p = b.permute(2,1,0)
out_pytorch = func_pytorch(a, b)
out_numpy = np.transpose(func_numpy(a_p,b_p), (0,3,2,1))
out_true = np.transpose(func_theano(a_p, b_p).eval(), (0,3,2,1))
np.testing.assert_allclose(actual=out_numpy, desired=out_true, rtol=1e-7) # OK
np.testing.assert_allclose(actual=out_pytorch, desired=out_true, rtol=1e-7) # 76% mismatch
We see that between Theano and Numpy there is no problem when comparing both results. However, we can’t say the same about PyTorch. Does anyone know something about it ? Will we have a function similar to tensordot in PyTorch in the next release ?
Thanks in advance! |
st104624 | According to the autograd tutorial code in pytorch with example 5.
with torch.no_grad():
w1 -= learning_rate * w1.grad
w2 -= learning_rate * w2.grad
# Manually zero the gradients after updating weights
w1.grad.zero_()
w2.grad.zero_()
It returns in console with following error:
<ipython-input-67-ca9abcaafd03> in <module>()
1 # update the weight
----> 2 w1 -= lr * w1.grad
3 w2 -= lr * w2.grad
RuntimeError: a leaf Variable that requires grad has been used in an in-place operation.
Should it change to the latest version with in-place tensor operation?
such as:
learning_rate = 0.01
for f in net.parameters():
f.data.sub_(f.grad.data * learning_rate) |
st104625 | To be clear:
the following code
with torch.no_grad():
w1 -= learning_rate * w1.grad
w2 -= learning_rate * w2.grad
# Manually zero the gradients after updating weights
w1.grad.zero_()
w2.grad.zero_()
does run properly with
with torch.no_grad():
it is just the piece got error without the with condition.
w1 -= learning_rate * w1.grad
w2 -= learning_rate * w2.grad
it is just bit confusing when I am trying the autograd features but with this condition of require_grad=False maner.
Thanks Tom |
st104626 | Hello all! I’ve recently started learning Pytorch and as a learning exercise I am trying to create a RNN + fully connected module. Unfortunately when I try to use the module I find that my network is not learning. In fact when I do a trace I find that my parameter gradients are all remaining None. I’d appreciate any debugging tips or critiques of the module.
class Sequence(nn.Module):
def __init__(self, input_size, hidden_units, output_size):
super(Sequence, self).__init__()
self.hidden_units = hidden_units
self.l1 = nn.Linear(input_size + hidden_units, hidden_units)
self.swish = Swish()
self.do = nn.Dropout(0.2)
self.l2 = nn.Linear(hidden_units, output_size)
self.tanh = nn.Tanh()
self.reset_mem()
def forward(self, input_seq):
'''
Start off treating entire training set as one sequence
input_seq - (very large, 1)
'''
if self.a1 is None:
self.a1 = torch.zeros(self.hidden_units, dtype=torch.float)
outputs = []
for i, input_t in enumerate(input_seq):
input_t = torch.tensor(input_t) # (4)
combined = torch.cat((input_t, self.a1)) # (132)
h1 = self.l1(combined) # (128)
self.a1 = self.swish(h1) # (128)
do1 = self.do(self.a1) # (128)
h2 = self.l2(do1) # (1)
output = self.tanh(h2) # (1)
outputs.append(output)
# Outputs is now 12533 long (using default data)
outputs = torch.tensor(outputs, requires_grad=True)
outputs = outputs.reshape((len(outputs), 1)) # (12533, 1)
return outputs
def reset_mem(self):
self.a1 = None
Training code looks like this
X = np.array([i[0] for i in training_data])
X = torch.Tensor(X) # This is (12533, 4)
y = [i[1] for i in training_data]
y = torch.Tensor(y) # This is (12533, 1)
model = Sequence(4, 128, 1)
loss_fn = torch.nn.MSELoss(size_average=False)
# Use optimizer from the sequence prediction tutorial
optimizer = torch.optim.LBFGS(model.parameters(), lr=0.8)
for i in range(training_epochs):
def closure():
optimizer.zero_grad()
y_pred = model(X)
loss = loss_fn(y_pred, y)
loss.backward()
return loss
optimizer.step(closure)
The optimizer reports that for each Parameter the .grad is None and immediately exits. (In _gather_flat_grad() from the LBFGS code 1) |
st104627 | Solved by smth in post #2
so, i think i know the problem. let’s see.
you are doing this, to signal that your model requires gradients:
outputs = torch.tensor(outputs, requires_grad=True)
A tensor constructor torch.tensor(outputs, requires_grad=True) has taken outputs here which are lists of Tensors. The constructor doesn’… |
st104628 | so, i think i know the problem. let’s see.
you are doing this, to signal that your model requires gradients:
outputs = torch.tensor(outputs, requires_grad=True)
A tensor constructor torch.tensor(outputs, requires_grad=True) has taken outputs here which are lists of Tensors. The constructor doesn’t know how to backprop through a list [of Tensors or numbers].
What you probably want to do here is:
outputs = torch.cat(outputs) # unlike a constructor which treats inputs as opaque entities, torch.cat knows exactly how to backprop through the list of Tensors |
st104629 | You sir are fantastic! This worked and makes perfect sense.
Not surprisingly I immediately ran into another question (which there is probably good documentation for somewhere).
Initially I got
RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.
Which I then followed and restarted training. For each LBFGS internal iteration it takes a longer and longer time.
Is the graph growing and growing with each iteration? More generally what would you suggest I read / search for to better understand what is happening here.
Thanks again for your solution to my problem and the great library! |
st104630 | from the surface of your code snippet, it looks fine, so I’m not sure where the memory growth / holding onto the graph is coming from.
A common pattern that is dangerously growing the graph across iterations is:
total_loss += loss # for reporting / logging purposes
here, loss is a torch zero-dimensional Tensor, so it records gradient (and hence holds onto the graph).
The right thing to do would be:
total_loss += loss.item() # loss.item() converts it into a python number |
st104631 | Hi everyone,
I get the broken pipe error while running the data_loading_tutorial code on my Windows10 machine but fine on my Linux machine.
the code is from the pytorch website:
https://pytorch.org/tutorials/beginner/data_loading_tutorial.html 57
I googled and find relevant problem for cifar10_tutorial code on Windows10. someone recommended wrapping the code with
if name == ‘main’:
But this solution does not work with this code. when set the num_workers = 0 then it works fine.
data_loader = DataLoader(face_dataset, batch_size=4,
shuffle=True, num_workers=1)
Does anyone have a similar problem? |
st104632 | From the error description it still looks like the Windows fork/spawn issue.
Did you make sure to wrap your complete code into a function and call it in the guard:
def main():
# your complete code
if __name__=='__main__':
main() |
st104633 | Thanks for your suggestion. I tried but now I have a new error:
Can’t pickle local object ‘main..FaceLandmarksDataset’
Still when I set num_workers=0, this error will be gone? Any solutions? I use Spyder. and Python 3.6
My code is as follows:
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import os
import torch
import pandas as pd
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
# Ignore warnings
import warnings
warnings.filterwarnings("ignore")
def main():
plt.ion() # interactive mode
class FaceLandmarksDataset(Dataset):
"""Face Landmarks dataset."""
def __init__(self, csv_file, root_dir, transform=None):
"""
Args:
csv_file (string): Path to the csv file with annotations.
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on a sample.
"""
self.landmarks_frame = pd.read_csv(csv_file)
self.root_dir = root_dir
self.transform = transform
def __len__(self):
return len(self.landmarks_frame)
def __getitem__(self, idx):
img_name = os.path.join(self.root_dir,
self.landmarks_frame.iloc[idx, 0])
image = io.imread(img_name)
landmarks = self.landmarks_frame.iloc[idx, 1:].as_matrix()
landmarks = landmarks.astype('float').reshape(-1, 2)
sample = {'image': image, 'landmarks': landmarks}
if self.transform:
sample = self.transform(sample)
return sample
transformed_dataset = FaceLandmarksDataset(csv_file='faces/face_landmarks.csv',
root_dir='faces/')
dataloader = DataLoader(transformed_dataset, batch_size=4,
shuffle=True, num_workers=4)
enumerate(dataloader)
if __name__=='__main__':
main() |
st104634 | Could you put the class definition outside of main.
Sorry for being unclear about it, but the functions and classes can be defined at the “global” level.
Just put your training code etc. into main. |
st104635 | It worked ! Thank you very much. I really appreciate your help. I am new to python. I used to play with C and matlab. |
st104636 | When could Pytorch give a windows version?
I find one one github, but I’m not sure whether it’s stable or not.
Since I’m taking a deep learning course this semester, I don’t want to use Tensorflow anymore but I need to make sure Pytorch works no problem on Windows…
best
Many thanks! |
st104637 | See https://github.com/pytorch/pytorch/issues/494#issuecomment-304439658 26 and https://github.com/pytorch/pytorch/issues/3649#issuecomment-344280941 45 for more details. Windows support is planned for 0.4.0.
I’m not sure how stable it is right now, so if you’re using it for something critical for a class and don’t want it to crash I’d recommend just dual-booting into Linux or grabbing a Linux box somewhere. |
st104638 | Hi Richard,
I just notice that I failed to publish my reply to it when you replied to me.
Now pytorch 0.4 is released and I’m learning it to implement my model.
Thank you very much!
Best,
Peter |
st104639 | I want to have a model with shared memory (same model parameter, no training) across all processes, so it is necessary to use torch.multiprocessing.Process. And in addition, I want to have duplex communicator between master and all workers, can I combine PyTorch Process and python Pipe together ?
i.e. sending pipe connection heads as argument to PyTorch Process
from torch.multiprocessing import Process
from multiprocessing import Pipe
def worker(master_connection, worker_connection):
do something
def master():
master_connection, worker_connection = Pipe()
process = Process(target=worker, args=[master_connection, worker_connection])
process.start()
process.join() |
st104640 | Hi
I am trying to implement the fcn paper which performs unpooling in the deconvolution part, I am not exactly sure how to go about this, I know that when performing max_pooling we can save the indices using the return_index =True ,but i’m not sure what to do from there,
Any suggestions would be really helpful,Thanks in advance, |
st104641 | You can just pass the returned indices to the unpooling operation as shown in this 739 thread.
Note there was an error regarding the output size, which was solved using the output_size argument in MaxUnpool2d. |
st104642 | I’m getting the following error when I try to backpropagate an error:
RuntimeError: The expanded size of the tensor (36) must match the existing size (3) at non-singleton dimension 0
(The 3 above is because I have it running in parallel on 3 GPUs. On a single GPU that becomes a 1.)
I suspect this has something to do with reductions, but I don’t quite understand why…
The above error only occurs when I add a new component to my error. That component is defined in a function that takes as input a batch of 36 variables, mutates them a bit (preserving their variable state), computes their distance from some ground truth, and returns a scalar: the average of the distances in the batch. It’s just an additional loss term.
The error occurs when I try to backpropagate as
one = torch.ones(num_gpus).cuda().double()
# ...compute err...
err = network(input)
# err.backward(one) <-- no problems here!
err = err + my_function(other_input, gt)
err.backward(one) # <--problems!
Note that everything is scalar by the time the backward computation is done:
print err.shape
>> ()
How do the loss functions that accept batches of variables address this? There doesn’t seem to be anything particularly obvious in the source code (here 1 or here). What is being “expanded” here and why is it causing this error?
I suspect this is because I am applying the function to a tensor of BATCH_SIZE x SAMPLE_ERROR rather than using a reduction that applies the function to each sample independently within the batch (a la reduce=True in the built-in losses). How can I resolve this? |
st104643 | Did you define a custom backward() function? (Note that defining your own backward function is not required in most cases because autograd takes care of it). If you didn’t then this is most likely a pytorch bug. |
st104644 | @richard I did not. It shouldn’t be required in this case, though, as the series of operations are all primitives (+,-, etc.) or built-in Pytorch functions. I am doing a NN search using PyFLANN (offline), then using those indices to sample my dataset, and subsequently finding the Euclidean distance between data points. Ultimately I take the average over all.
The operations I use are torch.index_select(), torch.sqrt(), torch.mean() and torch.sum(), along with +, -, and ** (power).
If absolutely necessary I can share the function here if that helps (although I’m avoiding posting it here as it’s research related). |
st104645 | Given that err is a scalar, you simply can’t pass three values to err.backward(). Passing in a single value should be enough. PyTorch should backpropagate it properly.
That said, if I understand you correctly, you are running one model in parallel on 3 GPUs, in which case you will need to somehow synchronise the updates between the three of them, otherwise you will have three models that diverge from each other. |
st104646 | @jpeg729 When you run one model in parallel on 3 GPUs the error is duplicated I think. The reason for 3 values is due to an error telling me it was necessary ;-).
But you’re right about synchronizing the updates. I take the mean (torch.mean()) of the 3 outputs. |
st104647 | Did you mean that you take the mean of the 3 sets of gradients before applying the update?
If you meant to say that you take the mean of the 3 model outputs, then I am fairly certain that won’t work because PyTorch is smart enough to know where the 3 parts came from and backpropagate accordingly. In other words, if model1 produces a large loss on sample1, and model2 produces a small loss on sample2, then model1 will get larger gradients even if you average the losses before backpropagating. |
st104648 | I take the mean of the model outputs. It hasn’t caused any issues so far–the network converges and training seems to be working. It’s only when I add a custom term to the loss that things get wonky. |
st104649 | This type of setup is a little too far outside what I am used to, I’d better shut up before I say something stupid.
Hopefully someone else can help. |
st104650 | @jpeg729 No worries. I get your point: the three parallel networks ought to have the same same gradients to train identically, but I think PyTorch’s DataParallel module automatically sums the gradients before backprop. I will check that out.
All of this being said, this is exchange has tangential to my original question.
Anyone know why torch.mean(A) over when A is a BATCH_SIZE x 1 variable with requires_grad=True doesn’t seem to stay reduced on backward()? |
st104651 | Hi, Marc,
I got the same error during loss.backward().
RuntimeError: The size of tensor a (501) must match the size of tensor b (434) at non-singleton dimension 0
Have you solved this error? Any hint?
Thanks |
st104652 | The code that Imports/Exports a model into ONNX is a separate package for Caffe2 and is part of the ONNX project - https://github.com/onnx/onnx-caffe2 6.
Whereas for PyTorch the import/export functionality ships as part of the PyTorch package itself.
Any reason for this difference? Were there any design decisions or tradeoff involved while making this call? |
st104653 | As for import/export issue, I understand current support functionality for PyTorch and Caffe2.
https://github.com/onnx/tutorials/blob/master/README.md 3
https://github.com/caffe2/caffe2/blob/master/caffe2/python/onnx/ONNXOpCoverage.md 8
Is there any issue related to “import ONNX model to PyTorch” in PyTorch issue? |
st104654 | I wrote a model for doing latent space representation of graphs in PyTorch utilizing the autograd to minimize a cost function, this should according to my understanding be possible to run it on the GPU, but when I run my script i get 0% GPU utliziation.
import numpy as np
import torch
import torch.autograd as autograd
import pickle
import networkx as nx
'''
Pairwise euclidean distance
'''
def distMatrix(m):
n = m.size(0)
d = m.size(1)
x = m.unsqueeze(1).expand(n, n, d)
y = m.unsqueeze(0).expand(n, n, d)
return torch.sqrt(torch.pow(x - y, 2).sum(2) + 1e-4)
def lossIdx(tY):
d = -distMatrix(tZ)+B
sigmoidD = torch.sigmoid(d)
#calculating cost
reduce = torch.add(torch.mul(tY, torch.log(sigmoidD)), torch.mul((1-tY), torch.log(1-sigmoidD)))
#remove diagonal
reduce[torch.eye(n).byte().cuda()] = 0
return -reduce.sum()
def createBAnetwork(n, m, clusters):
a = nx.barabasi_albert_graph(n,m)
b = nx.barabasi_albert_graph(n,m)
c = nx.union(a,b,rename=('a-', 'b-'))
c.add_edge('a-0', 'b-0')
for i in range(clusters-2):
c = nx.convert_node_labels_to_integers(c)
c = nx.union(a,c,rename=('a-', 'b-'))
c.add_edge('a-0', 'b-0')
return(c)
c = createBAnetwork(1000,3,3)
Y = np.asarray(nx.adj_matrix(c).todense())
#loading adjacency matrix from pickle file
#Y = pickle.load(open( "data.p", "rb" ))
n = np.shape(Y)[0]
k = 2
Z = np.random.rand(n,k)
tZ = autograd.Variable(torch.cuda.FloatTensor(Z), requires_grad=True)
B = autograd.Variable(torch.cuda.FloatTensor([0]), requires_grad=True)
tY = autograd.Variable(torch.cuda.FloatTensor(Y.astype("uint8")), requires_grad=False)
optimizer = torch.optim.Adam([tZ, B], lr = 1e-3)
steps = 50000
for i in range(steps):
optimizer.zero_grad()
l = lossIdx(tY).cuda()
l.backward(retain_graph=True)
optimizer.step()
del l
It works, and it is solving the problem, just not on the GPU, but on the CPU.
Any help on whats going wrong or how to get this working on the GPU would be highly appreciated.
The file can be found here: https://drive.google.com/open?id=1j6kkD9-YNW11iFfVYBzjYrvssFNcqSXf 5 |
st104655 | How do you know, it’s not working on the GPU?
Since you initialized your data on the GPU, it would throw an error, if that’s not possible. |
st104656 | The windows task manager shows 0% gpu utilization while running the script, it loads the data onto the GPU memory. The GPU itself is not being utilized though. When running other scripts particularly for neural networks I get up to 80-90% GPU utilization. Here it just stays on 0% |
st104657 | OK, I see. Maybe your actual workload is just small compared to data moving (idx = torch.randperm(n)[:1000].cuda()) and expanding (x = m.unsqueeze(1).expand(n, n, d)).
Have you tried to run it on the CPU? If the workload is really small (I cannot estimate it without shapes), probably the data transfer overhead is bigger than the performance advantage on the GPU. |
st104658 | Updated the code without the slicing, it was originally done because matrices around a size of 8000x8000 uses up all my GPU memory (11gb). This problem is however small enough to be entirely in memory (4039x4039).
Without the indexing it still dosen’t run on the gpu
When I run this script it executes fine, but it only uses the CPU and GPU memory
image.png937×587 20.1 KB
This is from running the script, note that the 5% is from using the snipping tool to take the screenshot… |
st104659 | I assume the window in the top left is showing the utilization?
For other scripts it’s showing a high usage?
Could you try to profile your code with e.g. utils.bottleneck 105.
Also, could you create random inputs with your shapes, so that I could try it on my machine? |
st104660 | You can use the file from the google drive link with dimensions 4039x4039, or the function I just added in the original question, it generates a network with an adjacency matrix of size 3000x3000
ran the bottleneck on the script with data.p file and 100 steps, got these results. Not sure how to interpret them, seems like barely any CUDA time
image.png961×562 15.1 KB
image.png912×845 38.6 KB |
st104661 | Could you change
tY = autograd.Variable(torch.cuda.FloatTensor(Y.astype("uint8")), requires_grad=False)
to
tY = autograd.Variable(torch.cuda.FloatTensor(Y.astype(np.float32)), requires_grad=False)
and run it again? |
st104662 | image.png984×533 15 KB
image.png870×839 15.9 KB
not much of a difference, I think it might be in the
reduce[torch.eye(n).byte().cuda()] = 0
line |
st104663 | Might be. That’s what I suspected. Some copy or transfer ops are taking more time than the actual computation.
Since the slicing seems to be constant, could you somehow pre-compute it?
Or is it just as an example? |
st104664 | I need to set the diagonal to 0 before taking the sum
reduce[torch.eye(n).byte().cuda()] = 0
Is what I am doing right now, is there another, more efficient way of doing it?
edit:
am currently creating an array with the indexes, so I dont have to call .eye every time, then using that list as an index to overwrite the diagonal
diagArray = np.array([np.array(range(0,n)),np.array(range(0,n))]) |
st104665 | You could pre-compute it somewhere outside of the function like you are already doing it with tZ and B:
reduce[idx] = 0
...
idx = torch.eye(n).byte().cuda()
Alternatively you could multiply reduce with a mask.
As a side note, I’m not sure, if it’s a good idea to use a Python keyword as a variable name.
I’ve changed a bit and get a peak GPU utilization (GTX 1070) of approx. 62%.
def distMatrix(m):
n = m.size(0)
d = m.size(1)
x = m.unsqueeze(1).expand(n, n, d)
y = m.unsqueeze(0).expand(n, n, d)
return torch.sqrt(torch.pow(x - y, 2).sum(2) + 1e-4)
def lossIdx(tY):
d = -distMatrix(tZ)+B
sigmoidD = torch.sigmoid(d)
#calculating cost
r = torch.add(torch.mul(tY, torch.log(sigmoidD)), torch.mul((1-tY), torch.log(1-sigmoidD)))
#remove diagonal
r = r * idx
return -r.sum()
device = 'cuda:0'
Y = np.asarray(np.random.randn(3000, 3000))
n = np.shape(Y)[0]
k = 2
idx = 1 - torch.eye(n).to(device)
Z = np.random.rand(n,k)
tZ = torch.tensor(Z, dtype=torch.float, requires_grad=True, device=device)
B = torch.tensor([0.], requires_grad=True, device=device)
tY = torch.from_numpy(Y.astype(np.float32))
tY.requires_grad_(True)
tY = tY.to(device)
optimizer = torch.optim.Adam([tZ, B], lr = 1e-3)
steps = 100
torch.cuda.synchronize()
t0 = time.time()
for i in range(steps):
optimizer.zero_grad()
l = lossIdx(tY)#.cuda()
l.backward(retain_graph=False)
optimizer.step()
torch.cuda.synchronize()
print(time.time() - t0) |
st104666 | seems to work, still not much utilization:
image.png796×838 17.3 KB
but atleast there is some CUDA action now. the bottle neck is now the sum function, I cant really do anything about that one can I? |
st104667 | I’m not sure, what your code is doing to be honest, but I think it’s a good sign to see a necessary operation now takes the time. |
st104668 | Creates a k dimensional latent space representation tZ given a graph Y in adjacency matrix format.
Thank you so much for your time, and especially for showing me that super cool and powerful bottleneck tool |
st104669 | I’ve been reading up on pytorch and had my mind blown by the shared memory stuff via queues with torch.Tensor and torch.multiprocessing.
In general, I’ve done a lot of numpy array processing using Python’s multiprocessing module, but the pickling of the arrays is not ideal. I’d assume that the same tricks that pytorch is using for Tensors could be carried over to pure numpy arrays? It not, what is it that stands in the way?
Thanks! |
st104670 | This comment 51 indicates, that the default pickler is the reason and I’m not sure, if it’s that easy to change the pickling in numpy. |
st104671 | Thanks for finding that! I guess it wouldn’t be too hard to use a torch.Tensor as a container and share the array that way between processes. |
st104672 | What kind of numpy operations are you using? Maybe you could implement them in PyTorch?
EDIT: Also, this should be quite cheap, as numpy arrays and torch.tensors share the same underlying data. |
st104673 | Its image processing with really large (10’s of GBs) images. The pattern is usually to have one reader throwing chunks of the image onto a queue, a bunch of workers cranking through them and placing the result on a writer queue, and then a writer writing the result.
The workers are often times calling libraries that don’t release the GIL so you’re stuck with multiprocessing. |
st104674 | You want to use a sharedctypes Array. This will make your variables global variables and get around lock. You can choose to use locks in place or not. Here is documentation: https://github.com/kwlzn/python-sources/blob/master/Python-3.1.2/Lib/multiprocessing/sharedctypes.py 64 |
st104675 | Np
You might find this link very helpful: https://code.i-harness.com/en/q/787707 88 |
st104676 | I have read the documentation but as a newbie I am having difficulties comprehending it. What is the purpose of transforms? Thank you! |
st104677 | You can use the transformations to e.g. preprocess your data or augment it.
Preprocessing is often necessary, if you would like to resize your images to fit your model definition (a lot of pre-trained models require an image size of 224x224, although you can use adaptive layers to skip this condition).
Data augmentation helps while training your model. You can randomly transform your image data, e.g. by randomly flipping the images or changing their color, saturation etc., to artificially create more data.
The current transformations in torchvision use PIL.Images, so make sure to pass the loaded images and not tensors. |
st104678 | I was wondering if there was any sort of issue with torch.optim.lr_scheduler.ReduceLROnPlateau in version 0.3.1b0+2b47480!!!
Since as soon as I switch to using scheduler my loss stays almost constant!
Here is the code I am using:
optimizer = torch.optim.Adam(model.parameters(), lr=0.00003)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=300, verbose=True, min_lr=0.00000001)
And I use the following in my training loop:
#optimizer.step()
scheduler.step(loss.data[0])
Thanks |
st104679 | Solved by ptrblck in post #2
You still have to call optimizer.step().
The scheduler will just adjust the learning rate. It won’t perform the weight updates. |
st104680 | You still have to call optimizer.step().
The scheduler will just adjust the learning rate. It won’t perform the weight updates. |
st104681 | I am working on training a Variational Autoencoder(VAE) for disentangling features of variation from a dataset. In order to do that, encode and decode layers of VAE are used separately while defining the loss function; since common factor of two images with same label in the dataset are replaced. Using such method, only one GPU is being used while using DataParallel on my model. I have trained other models on my current setup which successfully use both GPUs. How can I correct this? I also found a somewhat relevant question on discussion page of pytorch but without any answers here. |
st104682 | I’m unsure what exactly you’re trying to do, are you trying to run different parts of your model on different GPU? If so, @ailzhang’s answer here might be relevant.
How to implement distributed model parallel autograd
Hi @Ryobot, for distributed model parallel across different machines, it requires inter-node communication, right now we don’t have good support for it like DistributedDataParallel wrapper.
For the single node multiple GPU model parallel( like DataParallel wrapper), yes parallel_apply should work in your case.
If not, can you describe what you’re trying to do in more detail? |
st104683 | Hi @daemonslayer, please make sure you merge your encoder model & decoder model to a single model and then apply DP on model. If this doesn’t solve your problem, feel free to paste a minimal repro of your script so that we can help. |
st104684 | Hi @ailzhang, thanks for the reply. Here is my model code :
#!/usr/bin/env python
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class VAE(nn.Module):
def __init__(self, nc, ngf, ndf, latent_variable_size):
super(VAE, self).__init__()
self.nc = nc
self.ngf = ngf
self.ndf = ndf
self.latent_variable_size = latent_variable_size
# encoder
self.e1 = nn.Conv2d(nc, ndf, 4, 2, 1)
self.bn1 = nn.BatchNorm2d(ndf)
self.e2 = nn.Conv2d(ndf, ndf*2, 4, 2, 1)
self.bn2 = nn.BatchNorm2d(ndf*2)
self.e3 = nn.Conv2d(ndf*2, ndf*4, 4, 2, 1)
self.bn3 = nn.BatchNorm2d(ndf*4)
self.e4 = nn.Conv2d(ndf*4, ndf*8, 4, 2, 1)
self.bn4 = nn.BatchNorm2d(ndf*8)
self.e5 = nn.Conv2d(ndf*8, ndf*8, 4, 2, 1)
self.bn5 = nn.BatchNorm2d(ndf*8)
self.fc1 = nn.Linear(ndf*8*4*4, latent_variable_size)
self.fc2 = nn.Linear(ndf*8*4*4, latent_variable_size)
self.fc3 = nn.Linear(ndf*8*4*4, latent_variable_size)
# decoder
self.d1 = nn.Linear(latent_variable_size, ngf*8*2*4*4)
self.up1 = nn.UpsamplingNearest2d(scale_factor=2)
self.pd1 = nn.ReplicationPad2d(1)
self.d2 = nn.Conv2d(ngf*8*2, ngf*8, 3, 1)
self.bn6 = nn.BatchNorm2d(ngf*8, 1.e-3)
self.up2 = nn.UpsamplingNearest2d(scale_factor=2)
self.pd2 = nn.ReplicationPad2d(1)
self.d3 = nn.Conv2d(ngf*8, ngf*4, 3, 1)
self.bn7 = nn.BatchNorm2d(ngf*4, 1.e-3)
self.up3 = nn.UpsamplingNearest2d(scale_factor=2)
self.pd3 = nn.ReplicationPad2d(1)
self.d4 = nn.Conv2d(ngf*4, ngf*2, 3, 1)
self.bn8 = nn.BatchNorm2d(ngf*2, 1.e-3)
self.up4 = nn.UpsamplingNearest2d(scale_factor=2)
self.pd4 = nn.ReplicationPad2d(1)
self.d5 = nn.Conv2d(ngf*2, ngf, 3, 1)
self.bn9 = nn.BatchNorm2d(ngf, 1.e-3)
self.up5 = nn.UpsamplingNearest2d(scale_factor=2)
self.pd5 = nn.ReplicationPad2d(1)
self.d6 = nn.Conv2d(ngf, nc, 3, 1)
self.leakyrelu = nn.LeakyReLU(0.2)
self.relu = nn.ReLU()
self.sigmoid = nn.Sigmoid()
def encode(self, x):
h1 = self.leakyrelu(self.bn1(self.e1(x)))
h2 = self.leakyrelu(self.bn2(self.e2(h1)))
h3 = self.leakyrelu(self.bn3(self.e3(h2)))
h4 = self.leakyrelu(self.bn4(self.e4(h3)))
h5 = self.leakyrelu(self.bn5(self.e5(h4)))
h5 = h5.view(-1, self.ndf*8*4*4)
return self.fc1(h5), self.fc2(h5), self.fc3(h5)
def reparameterize(self, mu, logvar):
# std = logvar.mul(0.5).exp_()
# eps = torch.cuda.FloatTensor(std.size()).normal_()
# eps = Variable(eps).cuda()
# return eps.mul(std).add_(mu)
if self.training:
std = torch.exp(0.5*logvar)
eps = torch.randn_like(std)
return eps.mul(std).add_(mu)
else:
return mu
def decode(self, common_factor, varying_factor):
h1_c = self.relu(self.d1(common_factor))
h1_v = self.relu(self.d1(varying_factor))
# h1 = torch.cat([h1_c, h1_v], dim=0)
h1 = h1_c + h1_v
h1 = h1.view(-1, self.ngf*8*2, 4, 4)
h2 = self.leakyrelu(self.bn6(self.d2(self.pd1(self.up1(h1)))))
h3 = self.leakyrelu(self.bn7(self.d3(self.pd2(self.up2(h2)))))
h4 = self.leakyrelu(self.bn8(self.d4(self.pd3(self.up3(h3)))))
h5 = self.leakyrelu(self.bn9(self.d5(self.pd4(self.up4(h4)))))
return self.sigmoid(self.d6(self.pd5(self.up5(h5))))
def get_latent_var(self, x):
common_factor, mu, logvar = self.encode(x.view(-1, self.nc, self.ndf, self.ngf))
z = self.reparametrize(mu, logvar)
return z
def forward(self, x):
common_factor, mu, logvar = self.encode(x.view(-1, self.nc, self.ndf, self.ngf))
z = self.reparametrize(mu, logvar)
res = self.decode(z)
return res, mu, logvar
model = VAE(nc=3, ngf=128, ndf=128, latent_variable_size=500)
model = nn.DataParallel(model).to(device)
model.train()
train_data_1 = np.random.randn(10, 20, 3, 128, 128)
train_data_2 = np.random.randn(10, 20, 3, 128, 128)
train_data_1 = torch.from_numpy(train_data_1).float()
train_data_2 = torch.from_numpy(train_data_2).float()
# train_data_1 = torch.unsqueeze(train_data_1, 0)
# train_data_2 = torch.unsqueeze(train_data_2, 0)
def vae_loss_function(image1, decoded_1, image2, decoded_2, mu_1, logvar_1):
MSE = nn.MSELoss()
mse_loss_1 = MSE(image1, decoded_1.detach())
mse_loss_2 = MSE(image2, decoded_2.detach())
# print("Shape of image is {} and decoded tensor is {}".format(image1.shape, decoded_1.shape))
# mse_loss_1 = torch.sum((image1 - decoded_1)**2) / image1.data.nelement()
# mse_loss_2 = torch.sum((image2 - decoded_2)**2) / image2.data.nelement()
kl_div = torch.sum(-0.5 * torch.sum(1 + 2 * logvar_1 - mu_1**2 - torch.exp(2*logvar_1),1))
total_loss = mse_loss_1 + mse_loss_2 + kl_div
return total_loss
num_epochs = 100
lr = 0.001
optimizer = torch.optim.Adam(model.parameters(), lr)
train_data_1 = train_data_1.to(device)
train_data_2 = train_data_2.to(device)
for epoch in range(num_epochs):
for batch_idx, image in enumerate(train_data_1):
# print('hello batch {}'.format(batch_idx))
common_factor_1, mu_1, logvar_1 = model.module.encode(image)
reparam_out_1 = model.module.reparameterize(mu_1, logvar_1)
common_factor_2, mu_2, logvar_2 = model.module.encode(train_data_2[batch_idx])
reparam_out_2 = model.module.reparameterize(mu_2, logvar_2)
decoded_1 = model.module.decode(common_factor_2, reparam_out_1)
decoded_2 = model.module.decode(common_factor_1, reparam_out_2)
loss = vae_loss_function(image, decoded_1, train_data_2[batch_idx], decoded_2, mu_1, logvar_1)
optimizer.zero_grad()
loss.backward()
train_loss = loss.item()
optimizer.step()
if batch_idx % 10 == 0:
print(
'Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}\tlr: {:.6f}'.format(
epoch+1, batch_idx * len(train_data_1), len(train_data_1),
100. * batch_idx / len(train_data_1),
loss.item() / len(train_data_1), lr)
)
This code is not able to use more than one gpu available to it. What is wrong in here? |
st104685 | Hi @daemonslayer, the problem is that you are using model.module to train which is limited to the default device. In DP, you should specify all forward behavior in forward() function and just call model(input) instead of calling model.encode/decode separately. |
st104686 | Hi there,
We have a tensor A of size [ batch_size, beam_size, model_dim * n_steps ] and a tensor positions of size [ batch_size, beam_size ], and we want to build a tensor B like this:
B[i][j] = A[i][positions[i][j]].
This is kind of like the index_copy_ function but which would handle several dimensions instead of only a vector of indices.
Is there a way to optimize this to run it as a tensor operation?
To give a bit of context, we’re trying to optimize this code 3, which is called within a for loop. Would such an operation as described above be faster?
Thanks in advance!
François |
st104687 | I’m using log_sum_exp, and I’ve noticed it seems to break when you use keepdim=False.
torch.distributions.utils.log_sum_exp(torch.ones([10, 100]), keepdim=True).shape
torch.Size([10, 1])
torch.distributions.utils.log_sum_exp(torch.ones([10, 100]), keepdim=False).shape
torch.Size([10, 10])
Shouldn’t it give torch.Size([10])? I’m working on larger dimensions and getting 5000x5000 tensors as output.
Or is there an alternative log-sum-exp I should be using? |
st104688 | I think that’s a bug, but I can’t find documentation for torch.distributions.utils.log_sum_exp so I can’t confirm – do you know where the docs for that are? |
st104689 | I couldn’t find any docs – I just happened to find it after looking through github to see if there was a native log-sum-exp function somewhere! |
st104690 | On master there is torch.logsumexp https://github.com/pytorch/pytorch/pull/7254 51, but it hasn’t been documented yet. I’ll make a note that torch.distributions.utils.log_sum_exp appears to be strange. |
st104691 | torch.utils.data.DataLoader(
train_dataset,
batch_size=args.batch_size,
shuffle=(train_sampler is None),
num_workers=args.workers,
pin_memory=True,
sampler=train_sampler)
What are ‘pin_memory’ and ‘sampler’ here?
I could not understand this explanation.
“sampler (Sampler, optional): defines the strategy to draw samples from the dataset. If specified, shuffle must be False.”
And, Is it true that using ‘pin_memory=True’ will speed up the GPU operation, but will it run out of memory soon? |
st104692 | The sampler implements a strategy to sample observations from the indices.
Have a look at the docs 19 for the provided samplers.
There is also an explanation regarding pin_memory 22.
Host to GPU copies are much faster when they originate from pinned (page-locked) memory.
This will not speed up the GPU operation, but the copies between the host and the GPU.
Also, it shouldn’t run out of memory. |
st104693 | So I read Link 10 to understand how to extract the features from a pretrained network.
In the following I use VGG16. VGG has two Sequentials (features and classifier), so I used the following way to just keep the feature part and get rid of the classifier part. (well I still dont know clearly how to do it for resnet, but that is something that we can discuss later).
vgg16 = models.vgg16(pretrained=True)
New_VGG_Without_Classifier = nn.Sequential(*list(vgg16.features))
print New_VGG_Without_Classifier
and the output for printing is:
Sequential(
(0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU(inplace)
(2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(3): ReLU(inplace)
(4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(6): ReLU(inplace)
(7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(8): ReLU(inplace)
(9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(11): ReLU(inplace)
(12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(13): ReLU(inplace)
(14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(15): ReLU(inplace)
(16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(18): ReLU(inplace)
(19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(20): ReLU(inplace)
(21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(22): ReLU(inplace)
(23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(25): ReLU(inplace)
(26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(27): ReLU(inplace)
(28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(29): ReLU(inplace)
(30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
I test this method by just giving an example to this new network, and it seems that it works:
OutPut = New_VGG_Without_Classifier(InputVar)
print OutPut.shape
torch.Size([1, 512, 7, 7])
Here are my questions and I appreciate if anyone can explain how i can solve them:
1) This is my main question. I designed a network (lets call in SecondNet) as follows, I want to attach it to the end of my New_VGG_Without_Classifier, How I should do that??
Here is my SecondNet network, I put the input of the SecondNet in way that is compatible with the output of New_VGG_Without_Classifier (hopefully it is right and i didint do any mistake)
class SecondNet(nn.Module):
def __init__(self):
super(SecondNet, self).__init__()
self.conv1 = nn.Conv2d(512, 100, 3)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(100, 16, 3)
self.fc1 = nn.Linear(16 * 3 * 3, 12)
self.fc2 = nn.Linear(12, 8)
self.fc3 = nn.Linear(8, 15)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 3 * 3)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
2) If I want to have the output of last 3 Conv2d layers and save them and work with them, how should i do that? |
st104694 | Regarding your 1st question, you can do this in a single nn.Module class.
class SecondNet(nn.Module):
def __init__(self):
super(SecondNet, self).__init__()
vgg16 = models.vgg16(pretrained=True)
child = vgg16.children()
New_VGG_Without_Classifier = nn.Sequential(*list(child)) # you can control the children layers by slicing
self.conv1 = nn.Conv2d(512, 100, 3)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(100, 16, 3)
self.fc1 = nn.Linear(16 * 3 * 3, 12)
self.fc2 = nn.Linear(12, 8)
self.fc3 = nn.Linear(8, 15)
def forward(self,x):
x = self.New_VGG_Without_Classifier(x)
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 3 * 3)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x |
st104695 | Regarding your 2nd question, if I understand it correctly, you want to extract the weights/outputs from an intermediate conv layer.
This can be done by
Jk749:
nn.Sequential(*list(child))
each element in the above list will give an individual layer in the network with weights and bias from the original network, hence once you get those, you can save them as you do for a regular network.
torch.save(<model_state_dict>) |
st104696 | Thanks for the explaining.
Does it matter if instead of:
New_VGG_Without_Classifier = nn.Sequential(*list(child))
I use:
New_VGG_Without_Classifier = nn.Sequential(*list(vgg16.features)) |
st104697 | I guess, both should give the same output; as both will give the list of layers in the network.
But, I’m not able to try your approach which I think might be because of version mismatch.
I currently have 0.4.0 pytorch version. |
st104698 | My understanding is that SGD conceptually means running gradient descent on mini-batches that you sample randomly from the dataset (hence, the “stochastic” in the name). In all examples I’ve seen, the task of sampling data and shuffling the dataset is done independently of the optimizer used. If I always use my entire dataset and never shuffle it, calling optimizer.step() for SGD would essentially do regular gradient descent, right? Is there some parameter in SGD that actually makes it deserve the name “stochastic” that I’m missing? |
st104699 | Hi, everyone, is there any tools like tensorboard for tensorflow that can plot the training loss, and weights etc. , to help people debugging the neuron network? Thanks. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.