id
stringlengths
3
8
text
stringlengths
1
115k
st98368
I’m not completely sure, but based on the code snippet it seems samples should contain indices, as it’s passed into an nn.Embedding layer in the model. If that’s the case, samples should be of dtype=torch.long. Again, if that’s the case, samples should not be able to require gradients. At least I’m not aware of a method to get valid gradients for integer values. But I must say, I’m also not really an expert in NLP tasks, so maybe you can correct me and we can figure out, what’s going on.
st98369
Thanks for your comments! Got what you’re driving at, let me think about it and debug further.
st98370
Looking into it, I removed .requires_grad_() from samples , seems to get rid of that error. Will dig deeper to see what’s happening and post my findings here for others.
st98371
All right, I confirmed removing .requires_grad_() works. So just do this moving forward for anyone facing the same issue.
st98372
I tried to construct a resnet50 model like this: resnet50_url = 'https://download.pytorch.org/models/resnet50-19c8e357.pth' class Backbone(nn.Module): def __init__(self, *args, **kwargs): super(Backbone, self).__init__(*args, **kwargs) resnet50 = torchvision.models.resnet50() self.conv1 = resnet50.conv1 self.bn1 = resnet50.bn1 self.relu = resnet50.relu self.maxpool = resnet50.maxpool self.layer1 = resnet50.layer1 self.layer2 = resnet50.layer2 self.layer3 = resnet50.layer3 self.layer4 = resnet50.layer4 self.bn2 = nn.BatchNorm1d(2048) self.dp = nn.Dropout(0.5) self.fc = nn.Linear(in_features = 2048, out_features = 1024, bias = True) self.bn3 = nn.BatchNorm1d(1024) w1 = self.conv1.weight.detach().numpy() print(w1[1][1][1]) state = model_zoo.load_url(resnet50_url) for k, v in state.items(): if 'fc' in k: continue self.state_dict().update({k: v}) w2 = self.conv1.weight.detach().numpy() print(w2[1][1][1]) w3 = state['conv1.weight'][1][1][1].detach().numpy() print(w3) When I tried to construct this model, I have result like this: net = Backbone() [-0.011732 ...] [-0.011732 ...] [-0.07062116...] Which means that the pretrained parameters are not loaded. What is the correct way to do this then ?
st98373
I’m not sure I understand the issue. It seems you are creating a resnet50 inside your model without the pretrained weigths. If you want the pretrained model, you have to pass pretrained=True to the instantiation: resnet50 = torchvision.models.resnet50(pretrained=True)
st98374
I am actually borrowing the first few blocks of resnet50 and append a few of m own layers to their rear to create my own model. I need the resnet potion of the model to use pretrained weight, so I load the weights from some url and update the state_dict of my new created model with these url weights: state = model_zoo.load_url(resnet50_url) for k, v in state.items(): if 'fc' in k: continue self.state_dict().update({k: v}) But it turns out that the weights are not updated at all. So what is my fault doing this ? And is my best choice actually is simply assign a pretrained=True to my borrowing resnet50 ?
st98375
Thanks for clarifying the use case! There are some minor issues in the code. You should store the state_dict, update it, and reload it afterwards: def __init__(...): ... w1 = self.conv1.weight.detach().numpy() print(w1[1][1][1]) state = model_zoo.load_url(resnet50_url) state_dict = self.state_dict() for k, v in state.items(): if 'fc' in k: continue state_dict.update({k: v}) self.load_state_dict(state_dict) w2 = self.conv1.weight.detach().numpy() print(w2[1][1][1]) w3 = state['conv1.weight'][1][1][1].detach().numpy() print(w3)
st98376
The following multiprocessing code works fine with DEVICE=cpu, but seems to fail with CUDA: import torch import torch.multiprocessing as mp DEVICE = "cuda" def proc(queue): queue.put(torch.tensor([1.], device=DEVICE)) if __name__ == "__main__": ctx = mp.get_context("spawn") queue = ctx.Manager().Queue() p = ctx.Process(target=proc, args=(queue,)) p.daemon = True p.start() print("received: ", queue.get()) throws an error: Traceback (most recent call last): File "examples/ex2.py", line 17, in <module> print("received: ", queue.get()) File "<string>", line 2, in get File "/home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/multiprocessing/managers.py", line 772, in _callmethod raise convert_to_error(kind, result) multiprocessing.managers.RemoteError: --------------------------------------------------------------------------- Unserializable message: Traceback (most recent call last): File "/home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/multiprocessing/managers.py", line 283, in serve_client send(msg) File "/home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/multiprocessing/connection.py", line 206, in send self._send_bytes(_ForkingPickler.dumps(obj)) File "/home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/multiprocessing/reduction.py", line 51, in dumps cls(buf, protocol).dump(obj) File "/home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/multiprocessing/reductions.py", line 161, in reduce_tensor (device, handle, storage_size, storage_offset) = storage._share_cuda_() RuntimeError: invalid device pointer: 0x7f89d4200000 at /home/npradhan/workspace/pyro_dev/pytorch/aten/src/THC/THCCachingAllocator.cpp:262 --------------------------------------------------------------------------- I also noticed that the error thrown is different across slightly different variants of the above code. e.g. using mp.Queue instead of mp.Manager().Queue() seems to throw a cuda runtime error (30). Changing to using a FloatTensor constructor instead of a tensor constructor throws RuntimeError: legacy constructor for device type: cpu was passed device type: cuda, but device type must be: cpu. I think my mental model might be incorrect - so any help understanding what is happening here would be appreciated.
st98377
@Neeraj can you try to keep those Tensors alive on the workers until you access them on the main process, and see if that fixes it – atleast for debugging
st98378
Thanks for the suggestion, @smth. I am seeing the same exception get triggered when the main process tries to fetch via queue.get(), even though the worker can access the tensor fine.
st98379
@smth - Fun fact: if I make the worker sleep for 5 seconds, the following happens: If we use mp.Manager().Queue(), the problem still persists as I reported earlier. If we change to using mp.Queue(), then the problem is resolved (as you were expecting!). The python docs (and many other resources) seem to point out that mp.Manager().Queue() can be used wherever we are using mp.Queue(), but it does seem that torch CUDA tensors somehow do not play well with mp.Manager().Queue()? I have found using Manager().Queue() is better for handling clean up / preventing deadlock when one of the worker dies or is interrupted, and that is the reason why I was using it (it works great with CPU tensors). The other question was that even if we were to move to using mp.Queue(), I wouldn’t be able to control workers retaining access to the transferred tensors, so would be curious to know the best practices around that. I’m happy to open an issue instead if you think that’s a better channel to discuss this.
st98380
mp.Manager().Queue() is very likely not overriding these functions that will use our ForkingPickler (which shared CUDA memory etc. etc.): https://github.com/pytorch/pytorch/blob/master/torch/multiprocessing/queue.py#L34-L38 16 That explains a lot of things. The other question was that even if we were to move to using mp.Queue() , I wouldn’t be able to control workers retaining access to the transferred tensors, so would be curious to know the best practices around that. You dont actually need to hold onto those Tensors, I was just hoping that it’d give some debugging insights.
st98381
smth: mp.Manager().Queue() is very likely not overriding these functions that will use our ForkingPickler (which shared CUDA memory etc. etc.) Yes, I think that is indeed the issue - we are using multiprocessing.ForkingPickler and not the torch version. Let me see if I can try to fix this in a PR. smth: You dont actually need to hold onto those Tensors, I was just hoping that it’d give some debugging insights. Does it point to some bug, in that case?
st98382
Does it point to some bug, in that case? No, i think the bug was just that we didn’t override / support mp.Manager().Queue(), that’s all.
st98383
There are actually two issues here - one is that mp.Manager().Queue() has a different behavior than mp.Queue() in that it throws an invalid device pointer (regardless of the fix below). As I debugged a bit more, it seems that it is using the correct ForkingPickler from torch.multiprocessing, so the reason why it fails is not obvious to me. The second issue which arises when the worker finishes early, exists for mp.Queue() too, and I was able to use this suggestion 26 from @colesbury to resolve it - i.e. using an mp.Event() to keep the worker process alive until all tensors are fetched in the main process.
st98384
I’m trying to understand how the indices of MaxPool2d work. I made a simple example where I max-pool a 4x4 region with pools of size 2 and stride 2. import torch import torch.nn as nn import torch.nn.functional as fn # The two input planes for maxpooling x1 = torch.Tensor( [[1, 2, 4, 5], [4, 1, 2, 1], [0, 5, 0, 0], [1, 1, 1, 1]] ) x2 = torch.Tensor( [[2, 2, 2, 2], [4, 0, 1, 4], [5, 2, 2, 1], [0, 1, 4, 1], ] ) # Batch size: 1 # Channels: 2 input = torch.stack((x1, x2), 0).unsqueeze(0) pool = nn.MaxPool2d(2, 2, return_indices=True) o, i = pool(input) print(o) print(i) What I get is Variable containing: (0 ,0 ,.,.) = 4 5 5 1 (0 ,1 ,.,.) = 4 4 5 4 [torch.FloatTensor of size 1x2x2x2] Variable containing: (0 ,0 ,.,.) = 4 3 9 14 (0 ,1 ,.,.) = 4 7 8 14 [torch.LongTensor of size 1x2x2x2] The first output is the result of the max-pool and it’s correct. The second output are the indices of the max values. I don’t understand how these are aligned with the dimensions. If I select the elements in the input tensor with these indices, I expect to get the result from the max-pooling. However: tmp = torch.index_select(input.view(-1), 0, i.data.view(-1)) print(tmp.view(1, 2, 2, 2)) This gives me the output (0 ,0 ,.,.) = 4 5 5 1 (0 ,1 ,.,.) = 4 1 0 1 [torch.FloatTensor of size 1x2x2x2] which is not the same as the output of the max-pooling. My question is, how can I use the indices returned by MaxPool2d to “manually” select the max elements in the input tensor?
st98385
You could flatten the input tensor and use gather: x = torch.flatten(input, 2) o2 = torch.gather(x, 2, torch.flatten(i, 2)).view(o.size()) print((o==o2).all()) > tensor(1, dtype=torch.uint8)
st98386
I am doing the multiprocessing test on below code, reduce, all_reduce and all_gather are working good. but when use gather, it return the error ‘RuntimeError: Connection reset by peer’, is any one meet this problem? and how to fix. pls check below simple code. import os import torch import torch.distributed as dist from torch.multiprocessing import Process def run(rank, size): a=torch.tensor([rank]) b=a**2 #dist.reduce(b,dst=0,group=dist.new_group([0,1,2,3])) #dist.all_reduce(b,group=dist.new_group([0,1,2,3])) # tensor_list1 = [torch.zeros_like(b) for _ in range(size)] # dist.all_gather(tensor=b, tensor_list=tensor_list1, group=0) tensor_list1 = [torch.zeros_like(b) for _ in range(size)] dist.gather(tensor=b, dst=0, gather_list=tensor_list1) print('Rank ', rank, 'b: ', tensor_list1) def init_processes(rank, size, fn, backend='tcp'): """ Initialize the distributed environment. """ os.environ['MASTER_ADDR'] = '127.0.0.1' os.environ['MASTER_PORT'] = '29500' dist.init_process_group(backend, rank=rank, world_size=size) fn(rank, size) if __name__ == "__main__": size = 4 processes = [] for rank in range(size): p = Process(target=init_processes, args=(rank, size, run)) p.start() processes.append(p) for p in processes: p.join()
st98387
Documentation says gather_list is required only in the receiving process, so it makes you think that senders can take it as input as well and it will be discarded. However that’s not the case. Error ends with “RuntimeError: Connection reset by peer” but if you look middle of error output, real problem is “RuntimeError: non-empty gather_list can be given only to gather destination”. Here is working version: def run(rank, size): a=torch.tensor([rank]) b=a**2 tensor_list1 = [torch.zeros_like(b) for _ in range(size)] if rank==0: dist.gather(tensor=b,dst=0, gather_list=tensor_list1) else: dist.gather(tensor=b, dst=0) print('Rank ', rank, 'b: ', tensor_list1) def init_processes(rank, size, fn, backend='tcp'): """ Initialize the distributed environment. """ os.environ['MASTER_ADDR'] = '127.0.0.1' os.environ['MASTER_PORT'] = '29500' dist.init_process_group(backend, rank=rank, world_size=size) fn(rank, size) if __name__ == "__main__": size = 4 processes = [] for rank in range(size): p = Process(target=init_processes, args=(rank, size, run)) p.start() processes.append(p) for p in processes: p.join()
st98388
Hi all, Just discover PyTorch yesterday, the dynamic graph idea is simply amazing! I am wondering if anybody is (or plans to) developing a Bayesian Computation package in PyTorch? Something like PyMC3 (theano) or Edward (tensorflow). I think the dynamic nature of PyTorch would be perfect for dirichlet process or mixture model, and Sequential Monte Carlo etc.
st98389
from keeping tabs on the community, I’m not aware of anyone working on a PyMC3 / Edward -like package. Would love to see how far you get, let us know how it goes
st98390
I just recently started to work on this in my spare time. My plan is to: implement a selected number of variants of inference algorithms such as variational and MCMC inference (both traditional and scalable versions) separately from anything neural-network related make such framework easily applicable to the existing nn module implement basic functionalities for common statistical distributions I will post an update when I have something to show.
st98391
I would love to contribute. Did you start a repository somewhere? For the implementation of basic probability distribution, is it possible to just wrap the Scipy function: https://github.com/pytorch/tutorials/blob/master/Creating%20extensions%20using%20numpy%20and%20scipy.ipynb 210
st98392
No yet, I’ll post the link here when I do. And unfortunately that approach wouldn’t work for CUDA.
st98393
Just bumping this old thread to see if anyone’s working on variational inference using PyTorch? Been using Edward recently to do deep VI, and its great apart from having the usual TensorFlow disadvantages
st98394
the folks at Uber may be building out an Edward-like thing for PyTorch. Noah Goodman is at Uber ( he built http://webppl.org/ 411 ).
st98395
Wow, Noah Goodman sold out? Never thought that would happen? Guess every man has his price! Then again I guess Uber will give him an army of engineers at his disposal Hope they open-source it? Now that you mention Uber - yes I remember they’ve been working on Bayesian Optimization for their massive routing problems a long time. I see they signed up Zoubin Ghahramani as head scientist too. I think principled Bayesian computation, overcomes many of the deficiencies of deep learning, and vice versa. Check out Shakir’s NIPs 2016 slides http://shakirm.com/slides/NIPS2016-Bayesian%20Agents.pdf 151
st98396
Hey @smth, please post here/let me know, when Uber or anyone else make public some sort of Black-Box variational inference engine public for PyTorch. Tensorflow is driving me nuts - once you’ve used PyTorch it’s painful to go back to TF! It doesn’t look too unfriendly porting over some of the code from, Edward 34. For example, the main KL inference routines, are well written and there’s not much TF dependency, see github.com blei-lab/edward/blob/master/edward/inferences/klpq.py 85 from __future__ import absolute_import from __future__ import division from __future__ import print_function import six import tensorflow as tf from edward.inferences.variational_inference import VariationalInference from edward.models import RandomVariable from edward.util import copy, get_descendants try: from edward.models import Normal except Exception as e: raise ImportError("{0}. Your TensorFlow version is not supported.".format(e)) class KLpq(VariationalInference): """Variational inference with the KL divergence This file has been truncated. show original
st98397
Hi @yinhao, thank you very much - I haven’t seen this library before, it looks very up to date and useful. If you are working with Gaussian Processes, another very useful library is GPflow, GitHub GPflow/GPflow 65 Gaussian processes in TensorFlow. Contribute to GPflow/GPflow development by creating an account on GitHub. So it seems that there are now three variational inference libraries built upon Tensorflow by three different research groups, (Blei Lab, Tsinghua Machine Learning Group, and various contributors to GPflow)? I guess it’s now only a matter of time before something is available in PyTorch Kind regard, Ajay
st98398
I started working on different topics shortly after sending my last message so I didn’t make much progress yet. Now, however, I am back on a project which involves generative models and inference so I expect I’ll have more time to be working on this. I created scilua 28 before, so I can capitalize on that and start with statistical distributions, followed by HMC (basic and NUTS) and then variational methods. Before proceeding there are a few preliminary points I’d like to discuss: What is the plan for stochastic graphs? For unbiased gradients, pathwise-type estimators come for free. Other than that, my understanding is that the currently supported approach is via reinforce(). I also found stochastic.py 23 where the score-type estimators are implemented for some distributions. However, both of these are “local” approaches, and it doesn’t seems to me that the current framework would allow for the automatic implementation of unbiased gradient estimators for more complex cases, say example 2 in section 2.3 of stochastic computation graphs 11, without modifications. Classes for statistical distributions? Assuming that there is a plan to fully support stochastic graphs in the future it would make sense to implement distributions as classes instead of separate methods (Normal().log_pdf() vs normal_log_pdf()). Parameters would be passed to the constructor instead of passing them to every member function call. Separate gradient estimators? I would keep the logic related to gradient computations separated, via an option passed to the constructor or a wrapping class (Normal(gradient_estimator=PathwiseEstimator()) or PathwiseEstimator(Normal())) to retain flexibility as there are many different ways to produce such estimators. This can introduce some issues as tensors are not currently promoted to autograd variables 7 but I assume this will be done in the future. A cuda named argument would be passed to the constructor of statistical classes to specify that operations like random number generation are done on the GPU (which). Assumptions on data shapes? It might be beneficial to assume [batch, random_variable.size()] dimensions: the first dimension has an iid samples meaning that gets averaged over log-likelyhood computations, and it gives space to generate multiple samples. Basically I’m looking for the PyTorch’s core team comments / design suggestions to the points I mentioned above, and on the ones I failed to consider!
st98399
I am interested in contributing. I’m currently looking for a good package to test VI algorithms for big models and pytorch’s dynamic graph would make it a lot easier than working in theano or tensorflow.
st98400
I started putting something online at https://github.com/stepelu/ptstat 225, for now just some statistical distributions and a small number of related functions. I’ll implement the Gamma, Beta and Dirichlet distributions too next week, sampling aside that would need a C/CUDA implementation (and it’s not trivial to do CUDA-efficiently and in a numerically stable way). I am also working on MCMC: Metropolis-RW, Langevin-RW, HMC, NUTS. Contributions are welcome, for instance: not yet implemented statistical distributions (let me know if you plan to work on any of the above) add missing kl-divergence implementations add mean and variance methods Is there any timeline for issue #274? It would allow me to remove all these Variable() calls and facilitate the MCMC code I’m writing too.
st98401
I’m also highly interested to contribute ! I have already contributed to edward 38 and Turing 76 by implementing various MCMC methods.
st98402
Hi Bayes folks, It’s great to see people interested in this approach! We recently released 46 a probabilistic programming language built on top of PyTorch, called Pyro PPL 306. Hopefully this will be of use / interest!
st98403
For those with an inclination towards gpflow and pytorch, I did some work on a port at https://github.com/t-vi/candlegp 96 . Of course, it is much more modest in ambition than pyro. Best regards Thomas
st98404
I have a dataframe in the form where rows indicate ids and columns indicate the no of classes. Say I have 10 classes then column names would be ‘class1’, ‘class2’, . . ., ‘class10’. For each row I am predicting the probabilities of belonging to the various classes. Say for 9 classes these are the calculated probabilities stored in a tensor. tensor([1.3953e-05, 3.3629e-01, 2.9408e-01, 3.5847e-01, 1.8039e-05, 9.7759e-06, 1.1096e-02, 7.1202e-06, 1.9519e-05]) What would be the best way to add this tensor to the particular row for which I am calculating these probabilities. Given I want to add it to a dataframe. Also, how can I limit the trailing no of digits after the decimal in the tensor?
st98405
It seems more like a Pandas related question, so probably StackOverflow would be a better place to ask, as there are probably more Pandas users. However, as far as I understood the question, this should work: num_samples = 10 num_classes = 9 df = pd.DataFrame(index=range(num_samples), columns=[str(x) for x in range(num_classes)]) for i in range(num_samples): df.iloc[i] = torch.randn(1, num_classes).numpy().round(2)
st98406
In advance i apollogize to the rookienes of my question. I am bit new to pytorch. I have implemented a simple Unet model like this: class Unet(nn.Module): def __init__(self): super(Unet, self).__init__() # Down hill1 self.conv1 = nn.Conv3d(1, 2, kernel_size=3, stride=1) self.conv2 = nn.Conv3d(2, 2, kernel_size=3, stride=1) # Down hill2 self.conv3 = nn.Conv3d(2, 4, kernel_size=3, stride=1) self.conv4 = nn.Conv3d(4, 4, kernel_size=3, stride=1) #up hill1 self.upConv1 = nn.Conv3d(4, 2, kernel_size=3, stride=1) self.upConv2 = nn.Conv3d(2, 2, kernel_size=3, stride=1) #up hill2 self.upConv3 = nn.Conv3d(2, 1, kernel_size=3, stride=1) self.upConv4 = nn.Conv3d(1, 1, kernel_size=3, stride=1) self.mp = nn.MaxPool3d(kernel_size=3, stride=2, padding=1) From this i get the impression that i have 8 sets of weights. One set for each conv. conv1.weight.data conv2.weight.data .... The documentation tells me i can update these weights through optim optimizer = optim.Adam(unet.parameters(), lr=0.1) pred = unet.forward(x) loss = MyLossFunction(pred, y) loss.backward() optimizer.step() For some reason i find it hard to believe that it will update all 8 sets of weights correctly using this approach. Theoretically the weights needs to be optimized through the use of the derivative of the loss function with respect to x. I can’t seem to find any connection between the loss function and the optimizer in that code. So how on earth can the optimizer figure out the derivative? The optimizer only seem to have knowledge about the model parameters and not the loss function.
st98407
Thomas_Poulsen: The optimizer only seem to have knowledge about the model parameters and not the loss function. This is correct! The optimizer does not necessarily need to know more about the model, just which parameters should be optimized using the gradient. The gradient on the other side will be calculated during the loss.backward() call. Since the loss was calculated using your input, the model, and the target, the backward call can use all this information to calculate the gradients. Once these gradients are calculated, the optimizer just needs to update all parameters using its formula.
st98408
Let’s say I have the following model: import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.lin1 = nn.Linear(784, 128) self.lin2 = nn.Linear(128, 10) def forward(self, x): x = F.relu(self.lin1(x)) x = self.lin2(x) return x I want to be able to inspect the network somehow, and get the sequential operations performed by it. Using .children() gives the following: network = Net() print(list(network.children())) Out: "[Linear(in_features=784, out_features=128, bias=True), Linear(in_features=128, out_features=10, bias=True)]" How can I detect the torch.nn.functional calls in a Module's forward pass?
st98409
For your aim, the best bet is to have a model defined as a nn.Sequential and print that. import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.seq_model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10)) def forward(self, x): x = self.seq_model(x) return x
st98410
I’m hoping to detect calls to torch.nn.functional. I know I can use a Sequential module, but I’m hoping to detect functional operations in, say, pre-trained networks.
st98411
I am computing a vector and matrix multiplication in two different ways. Mathematically they are equivalent, however, PyTorch gives different (slightly results for them). Can someone please explain to me why it happens and hopefully the slight difference can be ignored in practice. import torch import numpy as np x = torch.from_numpy(np.array(range(12))).view(-1, 3, 4).float() ww = torch.rand(5, 12) y1 = torch.sum(x.view(-1, 12) * ww, dim=1) y2 = torch.matmul(x.view(-1, 12), ww.t()) print(y1 - y2) It’s clear that y1 shoud equal to y2, but results are non-zero tensor(1.00000e-06 * [[ 0.0000, 0.0000, 0.0000, 0.0000, 1.9073]])
st98412
Solved by ptrblck in post #2 A difference of approx 1e-6 is explainable due to the float32 precision. In practice you can ignore it. If you need a higher precision, you could use float64 instead. Note that your performance will suffer on the GPU. Here is another example. Clearly the sums should yield the same number. However…
st98413
A difference of approx 1e-6 is explainable due to the float32 precision. In practice you can ignore it. If you need a higher precision, you could use float64 instead. Note that your performance will suffer on the GPU. Here is another example. Clearly the sums should yield the same number. However, due to the order of operations, you will get a small difference between both methods: x = torch.randn(10, 10, 10) print(x.sum() - x.sum(0).sum(0).sum(0)) > tensor(-0.000005722)
st98414
Can somebody explain to me what this exception from torch/csrc/jit/interpreter.cpp:548 means? I get it on calling model->forward(inputs) for the first time from a class in the same manner that I previously used it in a simple main() function. So I’m guessing it can be caused by something being initialised wrongly or similar. I’ve confirmed that the forward() function is only getting called once before it crashes, and that inputs is defined in exactly the same way as in the tutorial. Is it relevant that it’s coming from the bool overload of ListInsert but I’m expecting floats? (I’m doing this from C++)
st98415
I use to do it like this: net(im).detach().cpu().numpy() until I got to know detach() allows two tensors have a same data which I believe means that if I change one another will be modified. What is the correct way to store the result of a model, for example, the loss or the embeds ?
st98416
Yes, detach() uses the same underlying data, but detaches the variable from the computation graph. To store tensors, you could simply use torch.save(tensor, file). If you want to save your model parameters, I would recommend to store the state_dict. Have a look at the Serialization Semantics 2 for more information.
st98417
I understand the C++ API is in beta so the documentation is sparse, but I am curious what the best way to cast from a tensor to/from a standard C type is? What I have currently is: To tensor: #define N_FEATURES 2 ... float x[N_FEATURES] = {5, 4}; std::vector<torch::jit::IValue> inputs; auto ones = torch::ones({1, N_FEATURES}); for (int i = 0; i < N_FEATURES; i++) { ones[0][i] = x[i]; } inputs.push_back(ones); Then, for output: // output is [1, 1] vector auto output = module->forward(inputs).toTensor(); float y = *(float*)(output[0][0].data_ptr()); These seem a bit ugly so I was wondering what the standard way is? I’ve looked through some of the Tensor.h template functions like .data() but couldn’t get it working. data_ptr() seems to work fine though. Cheers, Miles
st98418
I’ve started using JIT tracing with a RNN I’ve written 23. By following the seq2seq tutorial, the CPU inference speed has improved by 3x. Is this the expected speed improvement? If I were to compile the module into C++ 7, would I see further improvements?
st98419
Hello, I’m new to PyTorch! And I have seen the power of autograd.I know for Tensors in PyTorch, the deault requires_grad values is false.So if you wanna use autograd ,you have got to explicitly specify requires_grad to be True. But when I use the model built in torch.nn.Sequential or torch.nn.Modules subclasses, I find that without specifying , the optimizer can also work fine! Anyone can help me , thanks! Just like this: # _*_ coding: utf-8 _*_ import random import torch # An example to show the dynamic features of PyTorch class DynamicNet(torch.nn.Module): def __init__(self, D_in, H, D_out): super(DynamicNet, self).__init__() self.input_linear = torch.nn.Linear(D_in, H) self.middle_linear = torch.nn.Linear(H, H) self.output_linear = torch.nn.Linear(H, D_out) def forward(self, x): ''' For the forward pass of the model, we randomly choose either 0,1,2 or 3 and reuse the middle_linear Module that many times to compute hidden layer representation :param x: :return: ''' h_relu = self.input_linear(x).clamp(min=0) for _ in range(random.randint(0, 3)): h_relu = self.middle_linear(h_relu).clamp(min=0) y_pred = self.output_linear(h_relu) return y_pred if __name__ == '__main__': N, D_in, H, D_out = 64, 1000, 100, 10 x = torch.randn(N, D_in) y = torch.randn(N, D_out) model = DynamicNet(D_in, H, D_out) loss_fn = torch.nn.MSELoss(reduction='sum') # todo: why it works fine without setting requires_grad = True optimizer = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9) EPOCH = 500 for t in range(EPOCH): y_pred = model(x) loss = loss_fn(y_pred, y) print(t, loss.item()) optimizer.zero_grad() loss.backward() optimizer.step()
st98420
Hi, This is because all the parameters in the nn world are defined as nn.Parameters(). These are basically tensors that requires_grad and that work nice with nn tools. For example, for the nn.Linear layer, they are defined here 330.
st98421
I see! Thanks for your answer! It helps me a lot, and it seems that I’d better read some source code!
st98422
I want to know whether pytorch support cuda10 now ?? I can’t see it in the offical website page.
st98423
Solved by albanD in post #2 Hi, Binaries are not available for CUDA 10. It will be added for 1.0 You can use CUDA 10 if you compile from source though.
st98424
Hi, Binaries are not available for CUDA 10. It will be added for 1.0 You can use CUDA 10 if you compile from source though.
st98425
Hi everyone, I was wondering what is the best way to scale the gradient before steping the weights during backpropagation. For example, lets say I have weight w, learning rate alpha and some custom function f(x). Before updating the weight, I want to scale the gradient based on my custom function f(x) as shown below. Thank you for your time and help.
st98426
Solved by Tudor_Berariu in post #2 If f(x) is a scalar you can just scale the loss function with its value before performing backpropagation. Detach the variable if f uses any tensors that require gradients. (loss * f(x).detach()).bacward()
st98427
If f(x) is a scalar you can just scale the loss function with its value before performing backpropagation. Detach the variable if f uses any tensors that require gradients. (loss * f(x).detach()).bacward()
st98428
I perform tensor decomposition of convolution layers in serveral Models (CPM(convolutional Pose Machines) and CPN(Cascaded Pyramid Network)). the number of parameters and flops are decreased by tensor decomposition. but the test time of each model is not decreased. is there any realtionship between flops and processing time ??
st98429
There are two image tensors each containing n images having size [n,3,Width,Height] and [n,3,Width/2,Height/2] And I am trying to get convolution tensor output having size [n,3,Width,Height] by using torch.nn.functional.conv2d What kind of options and padding should I use to achieve this?
st98430
In the first case, your convolution should keep the spatial shape of your input. To achieve this, your padding should be ((kernel_size) - 1) / 2 for odd sized kernels (and default stride, dilation etc.). This code would give you the same shape: n = 5 c, h, w = 3, 12, 12 x1 = torch.randn(n, c, h, w) conv1 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=3, padding=1) output1 = conv1(x1) print(output1.shape) > torch.Size([5, 3, 12, 12]) In the second example it seems your input images are smaller so that you could use nn.ConvTranspose2d to increase the spatial size: x2 = torch.randn(n, c, h//2, w//2) conv2 = nn.ConvTranspose2d(in_channels=3, out_channels=3, kernel_size=2, stride=2) output2 = conv2(x2) print(output2.shape) > torch.Size([5, 3, 12, 12])
st98431
Thanks for the reply. However what I really wanted is convolution between two images by using torch.nn.functional.conv2d In other word, I am trying to use smaller image as convolution kernel. Having real hard time here…
st98432
Ah OK, I’ve misunderstood your question. If you are using odd shaped kernels, the padding would be straightforward, as we need to pad on both sides of the input. However, using even shaped kernels, we could use the functional pad method to add the appropriate padding to the input. Here is a small example. If you don’t need to backpropagate through the kernel (smaller image), just set requires_grad=False: batch_size = 1 c, h, w = 3, 12, 12 num_kernels = 1 kernel_size = (h//2, w//2) x = torch.randn(batch_size, c, h, w) kernel = torch.randn(num_kernels, c, *kernel_size, requires_grad=True) padding = [] for k in kernel_size: if k%2==0: pad = [(k-1)//2, (k-1)//2+1] else: pad = [(k-1)//2, (k-1)//2] padding.extend(pad) x = F.pad(x, pad=padding) output = F.conv2d(x, kernel) print(output.shape) > torch.Size([1, 1, 15, 15])
st98433
I’m looking for a method that takes an m-by-d tensor (x1) and an n-by-d tensor (x2) and computes the pairwise distance between each element of x2 with each elements of x1. I’ve seen nn.PairwiseDistance in the documentation, which requires the tensors to have the same dimensions and only computes the distance between their corresponding rows. An inefficient solution would be to use nn.PairwiseDistance and iterate over different rows of x2 to compare each row of x2 with all rows of x1.
st98434
Hi, take a look at the package torch-two-sample, and in particular the util.py 703 file. Hope this helps.
st98435
It seems it’s better to load/save the state dict of “module” instance in nn.DataParallel, not the nn.DataParallel itself. But I’m not sure if it’s valid option. Is it recommended way to do so? model = resnet101() model = torch.nn.DataParallel(model) torch.save(model.module.state_dict(), 'state') model2 = resnet101() model2 = torch.nn.DataParallel(model2) model2.module.load_state_dict(torch.load('state'))
st98436
Your code looks nice and clean and is in my opinion a good alternative to removing the .module part of the state_dict manually.
st98437
I just found that nn.DataParallel works well even if there’s no available GPU. Maybe it would better using nn.DataParallel all the time with or without GPU?
st98438
In Adam.py, I change exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad) to exp_avg_sq=exp_avg_sq.mul(beta2).addcmul(1 - beta2, grad, grad) The train loss behavior is very different(train loss increase). is there any difference except the memory efficiency?
st98439
Let’s say, I have a tensor, torch.tensor([1, 2, 3]) and a set {2, 3}. I want to check whether an element in the tensor is in the set. And return a tensor like this: torch.tensor([0, 1, 1]) because 2 and 3 are in the set. Is there a fast way to do this? Or I have to right a for loop?
st98440
Solved by smth in post #2 if you dont have a constraint of memory, then you can use a broadcasting trick: x = torch.tensor([1, 2, 3]) y = torch.tensor([2, 3]) x.view(1, -1).eq(y.view(-1, 1)).sum(0)
st98441
if you dont have a constraint of memory, then you can use a broadcasting trick: x = torch.tensor([1, 2, 3]) y = torch.tensor([2, 3]) x.view(1, -1).eq(y.view(-1, 1)).sum(0)
st98442
Hello, getting the “TypeError: can’t pickle X objects” error. As has been posted many times before this is in fact because I am running torch.save(net, PATH) and not torch.save(net.state_dict(), PATH). However, my understanding is that state_dict() just to fill in values so you have to initialize a network with the same architecture to load a state_dict() to it. My application incorporates modifying the architecture after initialization so if that is how it works I can not use state_dict for my saving. Everything was working in pytorch 0.2, I have now updated and working with 0.4. I was wondering if there was any advice on how to track down what exactly is the problem with my object that can’t be pickled. or possibly something that changed between versions that might cause this to no longer work. If it helps my object is class myObject(torch.autograd.Function). It has a forward and backward and also fills in and keeps track of a few values. Thanks!
st98443
Hi, I need to tile an 4-d tensor in an offset way. Showing the relevant dimensions in 2-d, if I have a tensor [1] [2] [3] [4] (shape [4, 1]) the desired output is: [ 1 0 0 ] [ 2 1 0 ] [ 3 2 1 ] [ 4 3 2 ] shape (4, 3). Is there a faster way to do this than a length 3 for-loop and indexing into it? Many thanks
st98444
This is a type of Hankel matrix, you can do this with scipy 4 and convert it to a torch tensor, i guess like this: torch.tensor(scipy.linalg.hankel([4,3,2,1])[:,:-1][::-1,:])
st98445
Thanks. I need it to be pytorch based though (aside from indices) as going to backprop through it
st98446
Why DataLoader has both sampler as well as batch_sampler? while there is already a sampler that is torch.utils.data.BatchSampler? does that mean I can pass BatchSampler only as batch_sampler of DataLaoder? If I want a DistributedSampler that is also in batches/BatchSampler and is random/RandomSampler I will have no option to mix them! both DistributedSampler and RandomSampler wrap a dataset/data_source and only BatchSampler can wrap one of them. Even if we could mix them, what would be difference of RandomSampler(BatchSampler(DistributedSampler(dataset))) and BatchSampler(RandomSampler(DistributedSampler(dataset))). So I think I should use sampler=DistributedSampler(dataset) and pass a batch_size to DataLoader (or use sampler=BatchSampler(DistributedSampler(dataset))). But how can I make it random? shuffle is mutually exclusive from sampler and I cannot mix RandomSampler with DistributedSampler.
st98447
Solved by dashesy in post #2 Looking at the code DistributedSampler(RandomSampler(...)) is valid, dataset does not have to be a Dataset, it can be another Sampler because only len() matters that any Sampler provides.
st98448
Looking at the code DistributedSampler(RandomSampler(...)) is valid, dataset does not have to be a Dataset, it can be another Sampler because only len() matters that any Sampler provides.
st98449
@fmassa I am reading here 10 you have added a new DistributedSampler that also has shuffle. Why not just pass sampler=DistributedSampler(RandomSampler(dataset)) to a DataLoader? I want to see if there is any particular issue with above.
st98450
Hi, I have a problem with reusing an nn.Module with a new architecture. e.g. class network(nn.Module) def __init__(self, architecture): # architecture 1 details def forward(self): # train network details net = network(architecture) # and optimizer and such if __name__ == "__main__": # train architecture 1 output = net() architecture2 = create_new_arch() # create architecture 2 del net net = network(architecture2) # train architecture 2 output = net() Normally, this will train architecture 1 perfectly fine but when it comes to the second architecture, the error doesn’t seem to budge at all. I tried testing the architecture2 independently and it seems fine. How can I reuse the net object that I have with a new architecture? Thank you.
st98451
Solved by SimonW in post #2 Your new network has a new set of parameters. You need to re-create the optimizer too because the old optimizer isn’t tracking your new parameters.
st98452
Your new network has a new set of parameters. You need to re-create the optimizer too because the old optimizer isn’t tracking your new parameters.
st98453
I used to have pytorch working for python 3 on OS X but now I can’t get it to install automatically for some reason (I don’t want to do from source). I did: conda install pytorch torchvision -c pytorch as the website suggested… then I got a mkl error so I installed it but it still complains about it: (FTIR_py3) brandomiranda~/home_simulation_research/FTIR/FTIR_proj $ conda install pytorch torchvision -c pytorch Fetching package metadata ........... Solving package specifications: PackageNotFoundError: Package not found: '' Dependencies missing in current osx-64 channels: - pytorch -> mkl >=2018 - torchvision -> pytorch >=0.3 -> mkl >=2018 You can search for packages on anaconda.org with anaconda search -t conda mkl You may need to install the anaconda-client command line client with conda install anaconda-client but I do have mkl: (FTIR_py3) brandomiranda~/home_simulation_research/FTIR/FTIR_proj $ conda install mkl Fetching package metadata ......... Solving package specifications: . # All requested packages already installed. # packages in environment at /Users/brandomiranda/miniconda3/envs/FTIR_py3: # mkl 2017.0.3 0 anyone know whats going on? it used to work a few days ago…
st98454
pytorch 0.3 requires mkl 2018. For some reason it’s not being installed. Can you try: conda install mkl=2018
st98455
smth: conda install mkl=2018 still doesn’t work: (FTIR_py3) brandomiranda~/home_simulation_research/FTIR/FTIR_proj $ conda install mkl=2018 Fetching package metadata ......... PackageNotFoundError: Package not found: '' Package missing in current osx-64 channels: - mkl 2018* You can search for packages on anaconda.org with anaconda search -t conda mkl You may need to install the anaconda-client command line client with conda install anaconda-client
st98456
it should be there. maybe try conda upgrade conda. See https://anaconda.org/anaconda/mkl 155
st98457
smth: conda upgrade conda that command gave: (FTIR_py3) brandomiranda~/home_simulation_research/FTIR/FTIR_proj $ conda upgrade conda PackageNotFoundError: Package not found: 'conda' Package 'conda' is not installed in /Users/brandomiranda/miniconda3/envs/FTIR_py3
st98458
smth: conda update conda I know this is super annoying but it didn’t work XD this is funny: (FTIR_py3) brandomiranda~/home_simulation_research/FTIR/FTIR_proj $ conda update conda PackageNotFoundError: Package not found: 'conda' Package 'conda' is not installed in /Users/brandomiranda/miniconda3/envs/FTIR_py3
st98459
well i dont know then, your anaconda installation is weird. these commands should work.
st98460
stackoverflow.com Issues installing pytorch for OS X with conda 67 python, machine-learning, neural-network, deep-learning asked by Charlie Parker on 07:43PM - 23 Dec 17
st98461
Brandon – if you do conda update conda inside of an existing environment, it will fail. Deactivate the environment then re-run the command.
st98462
@Soumith_Chintala I reproduced this issue on one of our devservers, so there might be something legitimately broken here. UPDATE: Upgrading conda fixed the problem, weirdly enough.
st98463
Trying to implement a basic neural net on the mnist dataset. train_dataset = datasets.MNIST(root = ‘./mnist_data/’,train = True,transform = transforms.ToTensor(), download = True) train_loader = torch.utils.data.DataLoader(dataset = train_dataset, batch_size = batch_size, shuffle = True) My network is class Net(nn.Module): def init(self): super(Net,self).init() self.l1 = nn.Linear(784,520) self.l2 = nn.Linear(520,320) self.l3 = nn.Linear(320,240) self.l4 = nn.Linear(240,120) self.l5 = nn.Linear(120,10) def forward(self,x): x = x.view(-1,784) x = F.relu(self.l1(x)) x = F.relu(self.l2(x)) x = F.relu(self.l3(x)) x = F.relu(self.l4(x)) return self.l5(x) After that I had model = Net() model = model.cuda() I thought this moved the network to memory, so why am i still getting the error. This is the train function: def train(epoch): model.train() for batch_idx, (data,target) in enumerate(train_loader): optimizer.zero_grad() data, target = Variable(data), Variable(target) output = model(data) loss = criterion(output, target) optimizer.step() if batch_idx%10==0: print(‘Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}’.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.data[0])) I am new to pytorch. Please help me in making the necessary changes. This is the error i get, RuntimeError Traceback (most recent call last) in () 1 for epoch in range(1,10): ----> 2 train(epoch) 3 test() in train(epoch) 4 optimizer.zero_grad() 5 data, target = Variable(data), Variable(target) ----> 6 output = model(data) 7 loss = criterion(output, target) 8 optimizer.step() ~/anaconda2/envs/fastai/lib/python3.6/site-packages/torch/nn/modules/module.py in call(self, *input, **kwargs) 355 result = self._slow_forward(*input, **kwargs) 356 else: –> 357 result = self.forward(*input, **kwargs) 358 for hook in self._forward_hooks.values(): 359 hook_result = hook(self, input, result) in forward(self, x) 9 def forward(self,x): 10 x = x.view(-1,784) —> 11 x = F.relu(self.l1(x)) 12 x = F.relu(self.l2(x)) 13 x = F.relu(self.l3(x)) ~/anaconda2/envs/fastai/lib/python3.6/site-packages/torch/nn/modules/module.py in call(self, *input, **kwargs) 355 result = self._slow_forward(*input, **kwargs) 356 else: –> 357 result = self.forward(*input, **kwargs) 358 for hook in self._forward_hooks.values(): 359 hook_result = hook(self, input, result) ~/anaconda2/envs/fastai/lib/python3.6/site-packages/torch/nn/modules/linear.py in forward(self, input) 53 54 def forward(self, input): —> 55 return F.linear(input, self.weight, self.bias) 56 57 def repr(self): ~/anaconda2/envs/fastai/lib/python3.6/site-packages/torch/nn/functional.py in linear(input, weight, bias) 833 if input.dim() == 2 and bias is not None: 834 # fused op is marginally faster –> 835 return torch.addmm(bias, input, weight.t()) 836 837 output = input.matmul(weight.t()) RuntimeError: Expected object of type Variable[torch.cuda.FloatTensor] but found type Variable[torch.FloatTensor] for argument #1 ‘mat1’ ​
st98464
Since your model is on the GPU, you need to push your data and target onto the device as well. Add this to your code: data, target = data.to('cuda'), target.to('cuda') Also as a small note: Variables are deprecated since PyTorch 0.4.0. You can just use tensors in the current releases.
st98465
Thank you. I replaced that line. Now it says ‘torch.FloatTensor’ object has no attribute ‘to’
st98466
Probably you are using an older version. You could update to the latest stable release (you’ll find the install instructions here 5) or use .cuda() instead.
st98467
I have a sequential dataset. For example, x1, x2, x3 and a corresponding label y. I want to expand data only in training session like [x1, x2, x3] -> [(x1, x2, x3), (x2, x1, x3), (x2, x3, x1)] for label y and in validate and test session. I don’t expand data just use [x1, x2, x3] How can i augment data only in training time??? and I dont use pytorch dataloader.