user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
Mina_soltan
I have a model with two branches. Both branches share the embedding layer but then they diverge and each loss is calculated against different labels. At the end, I sum the two losses up and backward only the accumulated loss. However, without retailn_graph=True it throws an error asking for retain_graph to be set to Tr...
tom
Quote likely you are doing something wrong elsewhere and store a non-leaf (like .to() before storing). As a rule of thumb retain_grad=True is only for cases when you know exactly why you need it, not for when some error message tells you (maybe we should improve the message). Best regards Thomas
mllera
I am implementing a variant of LSTMs using TorchScript by modifying the code in the fastrnn benchmark written by@tombut I am getting a weird error:RuntimeError: Return value was annotated as having type Tuple[Tensor, List[__torch__.model.subLSTM.nn.GRNState]] but is actually of type Tuple[Tensor, List[__torch__.model....
tom
I didn’t write that code, I just used it for benchmarking. So are you using PyTorch 1.3? Maybe making those a plain Tensor tuple instead of a Namedtuple helps. Best regards Thomas
21fa417e3fb06e56040c
Hi.I’m making IntermediateLayerGetter,This is torchvision Similar to the IntermediateLayerGettercpp version.Can’t use forward code in other ways?The code is below.#pragma once #include <torch/torch.h> class IntermediateLayerGetterImpl : public torch::nn::Module { public: template <typename Net> IntermediateLayerGe...
tom
Cool, will you submit it to TorchVision for its C++ interface? I think you needAnyModule, look at whatnn::Sequential does. Best regards Thomas
Wil_Helm
What is the reason behind this restriction?In the documentation for all recurrent layers is written:dropout– If non-zero, introduces a Dropout layer on the outputs of each RNN layerexcept the last layerBut why? Is it an implementation issue? Or is there research on this topic?When using only 1 LSTM layer I would not be...
tom
So the dropout in the last layer would be operating on what is the output of the RNN. This means you can do it yourself on the output if needed, an option you don’t have for the inner layers. Note that the dropout implemented by the RNN is not the dropout using one random draw for all timesteps. B…
Chame_call
Can I deploy Pytorch model under Android with Python via BeeWare?
tom
I don’t think it would be what you expect. Currently (and as far as I know), PyTorch doesn’t build the Python parts for Android. It would probably be possible to have a thin wrapper around the JIT parts (similar to what the Java offering), but it’s not been done. Best regards Thomas
xiaohan
Hi all,I met a problem withscatter_.Here is the code(it was posted here:Differentiable argmax):class ArgMax(torch.autograd.Function): @staticmethod def forward(ctx, input): idx = torch.argmax(input, 1) output = torch.zeros_like(input) output.scatter_(1, idx, 1) return output ...
tom
I think you want this to read idx = torch.argmax(input, 1, keepdim=True) Best regards Thomas
GlebBrykin
Good afternoon! I have a question why when executing the following codeimport torch a = torch.tensor([1, 2, 3], dtype = torch.float32) b = torch.tensor([1, 2, 3], dtype = torch.int) print(a + b)I get an error, but when I run other codeimport torch a = torch.tensor([1, 2, 3], dtype = torch.float32) print(a + int(1))ther...
tom
It isn’t and indeed PyTorch 1.3 introduced type promotion and make the first work, too.
Nithin_Rao
Hi,I initialized a model weight and bias parameter in init to learn while training but during training these weights are not moved to device cuda on performing .to(device) while the rest of the parameters moved. Please see sample code snippedclass myModule(nn.Module): def __init__(self,in_dim,hid_dim,out_dim): super...
tom
You need to either wrap them in nn.Parameter (for learnable) or use self.register_buffer to let the model know that they are part of its state. Best regards Thomas
Peter_Zheng
I succeed in compiling the code with cmake directly, but when I use vscode for editing, it always get error message with <torch/torch.h> not found. How can I get it?
tom
Hi, you need to add the somewhat hidden <installation dir>/include/torch/csrc/api/include to the includes. If you create the CMakeLists.txt as inthe example, the TorchConfig.cmake should set it up for you up when running find_package(Torch REQUIRED). Best regards Thomas
han.liu
I have 2 nets sharing one optimizer using different learning rate. Simple code shown as below:optim = torch.optim.Adam([ {'params': A.parameters(), 'lr': args.A}, {'params': B.parameters(), 'lr': args.B}])Is this right? I ask this because when I check parameters in optimizer (using code below), I found only 2 p...
tom
So at that point, v is the list of paramters in this group. You add the first parameter’s shape (v[0].shape). You would want to loop over ‘v’ to process all parameters. Best regards Thomas
da-bu
Hello,I’m a bit lost with understanding what PyTorch does internally in these two variations of passing a sequence through an RNN model:Version 1:out, hidden = model(sequence)Version 2:for element in sequence: out, hidden = model(element, hidden)In my understanding, version 1 and 2 should be the same - I’m just man...
tom
So the stock LSTM will use CuDNN whichhas been heavily optimizedbut is inflexible. But the JIT can make custom RNNs almost as fast: Some of this is discussed inthe LSTM with JITblogpost and wealso have optimizations for the backward. You can look atthe benchmark codeto get ideas how to use …
jwillette
The “normal” thing to call them IMO would bemuandsigmaormeanandstd, why waslocandscalechosen? Is there some background to this?I was very confused by the names the first time I had to use the distributions…
tom
Superficially, like many things in PyTorch, this is in alignment with NumPy, or herescipy.stats. Going more in depth, this is to generalize shifting (loc) and coordinate-scaling (scale) distribution from a “standard” location and scale. For example, the lognormal distribution’s scale parameter is …
Petro_Key
Hi, thank you always for your help.When I load my trained model using load_state_dict, it raises the following error:File “/root/.pyenv/versions/anaconda3-5.3.1/lib/python3.7/site-packages/torch/optim/optimizer.py”, line 114, in load_state_dictraise ValueError("loaded state dict contains a parameter group "ValueError: ...
tom
Apparently the number parameters known to the optimizer changed somehow. Note that this is from loading the optimizer’s state dict, not the model. Best regards Thomas
saruftw
I have some data of the following form,shape = (batch_size X max_seq_len X embedding_dim)np.ndarray([torch.tensor([torch.tensor(), torch.tensor(), ....]), ...])Is there a convenient way to convert it to,torch.tensor([torch.tensor([torch.tensor(), torch.tensor(), ....]), ...])Right now, I dotorch.from_numpy(devX)and get...
tom
Well, so ideally you would have shown more about how your data looks like (I must admit I don’t understand that exactly), but say it is similar to a,b,c = torch.randn(3, 2, 10) # three 2x10 tensors arr = numpy.array([a,b,c], dtype=object) # array of size 3 of 2x10 tensors then you can do t = torc…
deniz
>>> import torch >>> x = torch.arange(0, 3).view(1,3,1).expand(2,3,4) + 1 >>> permutation_indexes = torch.tensor([ >>> [[0,0,1,1], >>> [1,2,0,2], >>> [2,1,2,0]], >>> [[2,2,0,0], >>> [0,1,1,2], >>> [1,0,2,1]] >>> ]) >>> torch.all((permutation_indexes + 1) == x.gather(dim=1, index=permuta...
tom
It seems rather bold to say that it’s nearly impossible to do without for loops. For example, I can replace the line defining inverse_permutation_indexes with inverse_permutation_indexes = torch.empty_like(permutation_indexes).scatter_(dim=1, index=permutation_indexes, src=y) and get the computat…
steven47
Hi,I’m trying to convert LSTM model code from Keras to Pytorch.# input size X_train.shape = (10000, 48) # output size y_train.shape = (10000, 16)Here is the original keras model:model = Sequential() model.add(Embedding(16, 10, input_length=48)) model.add(CuDNNLSTM(50)) model.add(Dropout(0.1)) model.add(Dense(16, activa...
tom
So one thing you need to do to get it to work is to pass batch_first to the LSTM instantiation if that is what you want. While taking the last timestep (as you do with lstm_out[:, -1, :]) is certainly a common way to set up sequence-to-one problems (assuming your inputs are of the same length), I w…
flyerjia
The PackedTensorAccessor32 is faster than PackedTensorAccessor64, and is it slower than the original pointer?
tom
While 64 vs 32 matters on the GPU (because 64 bit arithmetic for indexing is much slower), I’ve not seen a visible impact of using accessors vs raw pointer arithmetic. (Let’s say at least for regular fp32 things, I don’t really know about fp16, where you want to load end bloc even more.) On CPU, us…
Arun_Sagar
I am new to pytorch . I am trying to grasp how the input and output shapes work in encoder - decoder model. while implementing attention model , i am stuck here where i need to get all hidden state outputs …My code for decoderclass DecoderLSTM(nn.Module):def __init__(self,embed_size, vocab_size, hidden_size): super...
tom
You don’t get the cell state (h_t, c_t) from the LSTM for intermediates. Thus you would want to loop over t yourself, using either LSTM with sequence length of 1 or LSTMCell. Best regards Thomas
Bruno1
Hi,I’m trying to make the result of the output of the piece of code below differentiable with respect to epsilon. I know thatwhereoperator is not differentiable wrt to its condition.Is there any way to make the output differentiable wrt. to epsilon ?eps = nn.Parameter(torch.ones(1,)) nn.init.constant_(eps,0.5) x = tor...
tom
The non-differentiability is from the discontinuity of the function. So you would have to relax (smoothen) the expression. For non-NaN/inf, where(x > eps, z, y) is (x - eps > 0) * (z - y) + y which you could change to torch.sigmoid(x - eps) * T) * (z - y) + y for some tuneable float t. Best rega…
zaki
HiI’m new to PyTorch and I want to test batch whitening (BW) as defined inhttps://github.com/roysubhankar/dwt-domain-adaptation, to train a model from scratch to do some domain adaptation and I don’t know how to define my BW layer, how I get the running_mean and running_variance?class whitening_scale_shift(nn.Module):...
tom
If you pass in None, it will instantiate the right thing: I’m not quite sure whether the authors of the code want to achieve something specific or whether the interface of optionally passing in the tensors is only accidental (the initialization seems very unidiomatic, too) – in theory that should…
mfazampour
Is it possible to calculate the pseudo inverse ofnmatrices in one tensor?Input tensor (input) has the shape of[n, rows, columns]and in the output should be a tensor (let’s call itpinv) with shape of[n, columns, rows]which for eachi,pinv[i, :,:]is the pseudo inverse ofinput[i, :, :].
tom
pinverse happily takes batches: a = torch.randn(5,6,3) b = torch.pinverse(a) c = torch.stack([torch.pinverse(a_i) for a_i in a], 0) print((b-c).abs().max()) gives 5e-8 ish discrepancy. As it goes with Linear Algebra, the invariably awesome@vishwakftwimplemented it just in time for the 1.3 relea…
ayaz-amin
Hello. I am messing around with flow-based generative models, and decided to play around with a simple implementation of Invertible Convolutions. I tried adapting one from a time-series model, only to catch this error:PS C:\Users\AyazA> & C:/Python37/python.exe c:/Users/AyazA/Desktop/RRF/modules.py Traceback (most rece...
tom
This will remove all singleton dimensions. As you have 1 channel, you delete all of them from a (1, 1, 1, 1)-shaped-Tensor. You only want to delete the last two. In general, I would recommend to furnish such code with comments or asserts on the expected shapes at each step. - The shape things are …
scarecrow21
Hi all,I’m trying to implement a text classifier using Conv1d. My dilemma is - how do we construct the linear layer to consume the output from the final CNN/MaxPool layers.I can pad all the sentences in a batch to have the same length as the longest sentence in that batch and set the input to linear layer accordingly b...
tom
CNN -> Linear: No. The batch size should never be flattened. You keep (10, 100) and feed it into a (100, 1) linear (or whatever) to get a 10, 1 - one prediction per batch item. You could concatenate the (10, 100) max with the mean (over the seq_len=5) to get a (10, 200). CNN -> RNN -> Linear H…
111158
Hi~I followed the installing steps (https://pytorch.org/cppdocs/installing.html).When I build the the project (example-app) in visual studio 2015, there was a error message “C2210 ‘T’ : pack expansions cannot be used as arguments to non-packed parameters in alias templates”.Can someone help me?
tom
I would recommend to try a newer Visual Studio. PyTorch does use pretty much all of C++11, so one would expect to need at least VS2017 or so. Best regards Thomas
Shisho_Sama
Hi everyone,I recently tried to implement the attention mechanism in Pytorch. I searched lots of github repos and also the official pytorch implementationhereplus detailed tutorials such asthis one on floydhub. However, it seems to me all of them have implemented the attention mechanism incorrectly!The problem that I s...
tom
What seems to happen is that (at least in the tutorial) the functions doing the decoding are only taking one time step (and for GRU output == new hidden) and the loop over the outputs is in the train function. One might argue that it’d be more PyTorchy to wrap this loop into a Module. Using a cell o…
Raphikowski
Hi all,I am trying to implement my first LSTM with pytorch and hence I am following some tutorials.In particular I am following:https://www.deeplearningwizard.com/deep_learning/practical_pytorch/pytorch_lstm_neuralnetwork/which looks like this:class LSTMModel(nn.Module): def __init__(self, input_dim, hidden_dim, la...
tom
Yes, zero initial hiddenstate is standard so much so that it is the default in nn.LSTM if you don’t pass in a hidden state (rather than, e.g. throwing an error). Random initialization could also be used if zeros don’t work. Two basic ideas here: If your hidden state evolution is “ergodic”, the …
vadimkantorov
If I do sth likex * (y if condition else 1), will multiplication by 1 skip copying / allocating new memory?
tom
No, you would need to do x * y if condition else x (if short circuits, so x * y will not be evaluated if the condition is false). Experiments: Multiplication is not a no-op x = torch.randn(12) y = x * 1 print(x.data_ptr(), y.data_ptr()) if short-circuits: x = [] print(x[1] if len(x) > 0 else No…
n_kotel
Hello,Initially, I faced the following issue: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.I figured out that the problem raised when I use torch.nn.Parameter in my model and do some transformatio...
tom
The problem is that you only compute self.b once - in the __init__. Then on the first backward, it’ll work. But the next time around, the edge in the computation graph connecting self.b to self.a will be gone. The most obvious way to get this to work is to move the line self.b = torch.log(self.a) …
Nikhil_Pinnaparaju
I am trying to code up a Siamese network for sentence similarity. However, I keep running into the sameRuntimeErrorproblem.class LSTMSentenceEncoder(nn.Module): def __init__(self,input_size,hidden_size,num_layers,vectors,word2idx): super(LSTMSentenceEncoder,self).__init__() self.embedding = nn.Embe...
tom
This should have gotten you UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor). Of course, you actually want to do something entirely differen, namely yo…
Shisho_Sama
Hi,Using a normal lstm with a linear layer after is trivial, you just reshape the lstm output and feed it to thenext linear layer.However, when I set the bidirection = True, the number of outputs doubles, and even if I double the input_features of my linear layer, it wont work and it will create the following error :Ru...
tom
Yeah, you have got all the ingredients there, but compare your reshaping with your rnn output and the linear in size. So you need to multiply the self.hidden_size by self.direction in the reshape.
Hovnatan_Karapetyan
When I runclass A(nn.Module): def __init__(self): super().__init__() self.c = nn.Conv2d(55, 50, 3) self.b = nn.Conv2d(50, 50, 3) self.a = nn.Conv2d(25, 25, 3) a = A() print(a)it outputs submodules in the order of addition in the class A, ...
tom
Children are kept in an collections.OderedDict, a Python dictionary to preserve order. The nn.Module class does some clever magic around __setattr__ and friends to keep the submodules (and parameters and buffers) in separate dictionaries. You can lookat the definition, it is clever yet reasonably…
zzd1992
I build a cpp extension of PyTorch and it is successfully compiled and installed.sources = ['src/my_spatialConv.cu', 'src/my_im2col.cu'] if __name__ == '__main__': assert torch.cuda.is_available(), 'Please install CUDA for GPU support.' setup( name='my_conv', ext_modules=[CUDAExtension('my_conv', sour...
tom
Hi, it would seem expected that python -c "import my_conv" does not work, as you need to load PyTorch itself and its symbols before you load the extension, so python -c "import torch, my_conv" would likely work much better. If you wanted to avoid that for some reason, you could explicitly link a…
marcin
Please help with this.Here’s the GoogleNet output of:print(list(net.named_children()))[('pre_layers', Sequential( (0): Conv2d(3, 192, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (1): BatchNorm2d(192, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (2): ReLU(inplace=True) )), ('a3', Incepti...
tom
I would recommend to modify the technique from@ptrblck’s excellentsave_activation exampleto do the appending. Then you could add the hooks in a for n, m in model.named_modules():-loop, so n can be the key to the dictionary. Best regards Thomas
Nate
Hello, I am attempting to recreate the CURE regularizer ([1811.09716] Robustness via curvature regularization, and vice versa) and have a question about how to compute the gradient of the regularization term. Specifically, the regularizer isand is used in conjunction with the standard cross entropy loss of a DNN classi...
tom
The gradient operator ∇ is in itself linear as an operator. This means that ∇a - ∇b = ∇(a-b). In fact, if you write a minus function m(x1, x2) = x1 - x2 and some loss l(m) calculated from that, then the backpropagation step for this calculation is just feeding dl/dm as grad_out into the backward o…
Bastulli
Hello, I am downloading a model via Dropbox url and saving the data as a system string. In order to load the model into Pytorch I have to convert the data from string to byte data. When I use .encode() with ‘UTF-8’ codec to convert the string data to byte data and try to load it into BytesIO I get UnpicklingError: in...
tom
There are plenty of examples and utility functions for downloading and opening models inthe utils for the torch model hub. The key likely is to download them as an octet stream into bytes. You are probably best off using the api rather than reinventing the implementation. Best regards Thomas
3210jr
Hi all,Whenever I try to move my tensors or model to the GPU using either the.cuda()or.to('cuda')method, the kernel just freezes and has to be terminated to be used again.I’ve looked through several other related issues and they are either extremely old (circa 2017) or their solutions were that they had an incompatible...
tom
There was an issue with cuda 10.1 minor versions between anaconda’s cuda and PyTorch’s cuda differing causing excessive JIT compiles. It is fixed and reinstalling PyTorch helps. Best regards Thomas
Wong
Hi everyone,We aim to measure the executive time in the GPU mode. We take Mnist as an example. The code is as follows.109 for epoch in range(1, args.epochs + 1): 110 # start time 111 torch.cuda.synchronize() 112 since = int(round(time.time()*1000)) 113 train(args, model, device, trai...
tom
I think your basic timing setup makes sense (congrats!). You’d have to figure in things such batch size, number of synchronizations during training etc. For MNIST, the main thing might not be the actual compute, but the latency of getting things to the GPU and getting results back to the CPU. If y…
hadaev8
All examples i find in google about self made attention, but i wonna use official one.
tom
Tryhttps://pytorch.org/tutorials/beginner/transformer_tutorial.htmlBest regards Thomas
lelouedec
Good evening,I needed to upgrade pytorch to use a new function implemented since 1.0. However my C++ extension for pointnet++ which was perfectly compiling and working for previous pytorch version is not working anymore and return the following error when importing :ImportError: /home/lelouedec/anaconda3/envs/test1/lib...
tom
Maybe it’s something about having the version it is compiled with and the one it is run with go out of sync? My impression is that unless you use some internal API, that is the most common source of the error. Best regards Thomas
Haolin_Jia
Hi, I have spent three days on this bug, and I can’t figure it out. desperately need your help.I wrote C++/ CUDA code to satisfy the pytorch framework and met this problem. Briefly speaking, when my code successfully goes through theforwardpart, Initializing the new tensor is many slow. ( forward part need 0.0x second,...
tom
The hardware has a limit on the total size of blocks, ie the number of threads run in parallel on a multiprocessor, of 1024. The product of the block sizes cannot exceed that. BLOCK_SIZE isn’t used in the copying, your measurement seems seems to be an artifact of not cuda.synchronize()ing. Your ke…
el_samou_samou
Hi,I am very new to the c++/cuda pytorch API and I would like to manipulate tensors containing integers (int64). I was wondering how to do so. Also the PackedTensorAccessor don’t seems to accepts int as first argument.So just two examples, first instantiate a 0-valued tensor of type int:torch::Tensor test = torch::zero...
tom
You need to match the scalar type to the tensor’s scalar_type, so: If you instantiated a torch::kLong tensor (that’s 64 bit integers), use int64_t. For kInt (32 bit) use int32_t, for nothing (aka kFloat), float. Note that you usually do not need packed_accessor for CPU tensors, they are intended f…
savior
If I use opencv to read an image (1248x384 ), convert it to tensor and move it onto cuda in python , it won’t have problems.However , when I do the same thing in c++ libtorch , it will report Segmentation fault.Furthermore , I find it’s the moving onto cuda process that causes the Segmentation fault.Is there anyone kno...
tom
It’s hard to tell with the information you give and no code. One common pitfall: if you use from_blob to get the tensor from OpenCV, you do not own the memory, i.e. you need to call the copying(! mind you) to cuda before the OpenCV memory goes out of scope / keep the memory in scope until you have …
saisai96
I know C++ implementation code is in the folder ATen. But how can i find C++ implementation of function such as torch.tensor.half().
tom
In the end, you use .to, just like you would in the “modern” PyTorch idiom. The variable function not founds in ATen can nonetheless be found using “rgrep” or somesuch on the source, in this case it is found intools/autograd/templates/python_variable_methods.cppor also, after you have built PyTor…
I-Love-U
Hello, everybody.In such two structures, is the weight update process the same? I mean, in the code beforeelse, the data is divided into two parts, which are forwarded to calculate the loss, and in the code afterelse, all the data is forwarded together to calculate the loss. Are these two methods the same whenbackwardt...
tom
Whether it is the same depends on the batchsizes of the two dataloaders and the network: The first enforces the 1/4-3/4 weighting even if the batch sizes are not in that ratio. If the criterion self.crit takes the mean over batch size, this would be identical if the batch size is 3 duts inputs to …
Ryan95
Hi, have anyone compared the GPU time spent on NMS in caffe and pytorch? I recently transfer a model from caffe to libtorch. And I found that the main time spent by libtorch is concentrated on the NMS operation. the time is 160ms, which takes 80% of all forward time. but the overall time consumption of caffe is only 15...
tom
Yeah, well, the usual way to do these things is to grab an input and try to measure the function in isolation. Benchmarking has quite a few pitfalls, in particular with CUDA asynchronous computation involved, so it’s hard to say whether you found something where PyTorch is indeed terribly slow or w…
apozas
Hi all,I have been trying to obtain the following behavior when defining an own model: In essence, what I would want is to have aParameterwhose name would beweights, so that inmodel.state_dict()I would seeweights. But, for simplicity in coding, I would want to refer to it in the code as model.W, instead of model.weight...
tom
No! This is decidedly not good style. You are trading conceptual simplicity for saving a few characters (6 instead of 12). Now, what you can do if your forward uses self.weights so often that you don’t want to spell it? I think a perfectly good solution is to do a local assignment W = self.weight…
zahra
Hi,Suppose we have a tensor with dimension of [2, 1, 2, 10] and we want to add 3 columns between columns 3,4 and columns 5,6 and columns 8,9.Is it possible to add these columns to the tensorwithout any loop?If not, according tohttps://discuss.pytorch.org/t/how-can-i-insert-a-row-into-a-floattensor/18049/2it needs 2 ca...
tom
You can use indexed assignments: a = torch.ones(2, 1, 2, 10) b = = torch.full((2, 1, 2, 3), 2.0) xa = torch.empty(2, 1, 2, 13) xa[:,:,:,[0, 1, 2, 3, 4+1, 5+1, 6+2, 7+2, 8+3, 9+3]] = a xa[:,:,:,[4, 7, 10]] = b print(xa) If your columns are a little larger (say 100 instead of 4 elements), a for lo…
kevinhaoliu
If I want to call other methods in my model(notforward), what should I do? I try to usetorch.jit.script_methodto decorate it but I can’t call it in C++.
tom
You follow thetutorial and at step 4you replace at::Tensor output = module->forward(inputs).toTensor(); with torch::Tensor output = module->run_method("weighted_kernel_sum", input).toTensor(); where input is your input tensor. Best regards Thomas
thorsten
Hi,I’m trying to use a model which I trained in Python in C++ for inference. While being in Python, the model produces reasonable outputs. However, when using it for inference in C++, the output does not make sense. My feeling is that the input/output formats are somehow wrong (type, size, etc.). In the following, I wi...
tom
Glad you solved it! If anyone is searching for a more compact and efficient solution, you might try something like std::vector<int64_t> sizes = {1, network_input.rows, network_input.cols, 3}; torch::TensorOptions options(at::kFloat); torch::Tensor input_tensor = torch::from_blob(network_input.data…
march1905
I want to implement a gated matrix multiplication. In this version of the matrix multiplication, when the gate’s value is 0 it skips the matrix multiplication. So far I try to implement it in python but it throws Cuda out of memory when the dimensions are higher than 2:import torch x = torch.rand([70, 20, 1024]) g = t...
tom
The equivalent of mm_out is torch.mm(..., out=...). So is the following correct? You have x = x.view(70, 20, 1, 1, 1024) g = g.view(70, 20, 96, 1, 1) w = w.view(1, 1, 96, 16, 1024) and want to conceptually compute (x*g*w).sum(-1) In this case, you might take a look at how F.bilinear is impleme…
John_Deterious
I’m looking @https://pytorch.org/docs/stable/_modules/torch/nn/functional.htmlto see torch.nn.kl_div but it is just a class that wraps a function called torch.kl_divI can’t find that original function. I basically made my own function and it spits out different results from what Pytorch built-in is spitting so I’m wond...
tom
kl_div and the CPU backward are inaten/src/ATen/native/Loss.cpp, the cuda backward is in aten/src/ATen/native/cuda/Loss.cu. I once tried to write this up more generally:https://lernapparat.de/selective-excursion-into-pytorch-internals/Best regards Thomas
Nikronic
Hi everyone,I want to train a GAN which has a generator and two discriminators and the discriminators have different structures but the same loss function. But I am a little confused how to deal with the second discriminator.Here is what I have done briefly:x,y = # input and ground truth details_net.train() # generato...
tom
You could dofor p in XXX.parameters(): p.requires_grad_(False) for the bits you are not training and set them to True for the bits you are training. Most GAN examples do that, it saves getting and storing unneeded gradients. You could have g_loss1 and g_loss2 for each discriminator and g_loss = alp…
HsuLinNwe
I want to know how GRU is implemented in pytorch. But I can’t find the implementation of GRU although I looked inhere. Can anyone tell me where did GRU implement in pytorch?
tom
The “native” implantations are inhttps://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/RNN.cppandhttps://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/cuda/RNN.cuThere also are CuDNN bindings…
John_Deterious
I’m tracing back the error and it points at this:def zlogit(re, im): abs_ = t.sqrt(re**2 + im**2) ang = t.atan2(im, re) mask = ~(ang > 0) abs_[mask] = -1 * abs_[mask] return abs_Where is the inplace operation that I did?
tom
No, sqrt’s backward wants abs_ to calculate d sqrt(x) = -0.5 / sqrt(x) . If you absolutely needed the memory, you use checkpointing for zlogit, but most of the time that type of memory optimization is not worth the effort. Best regards Thomas
louwers
When I calltorch::torch::cuda::is_available()from Python, it returns true.However, when I call it in C++, it returns false.Thedocsstate that it could be a driver problem.Any idea how I can find the cause? An issue with a missling library is likely because I am running everything in a Singularity container.[s2548259@pg-...
tom
Do you use the same PyTorch distribution (i.e. libtorch cmake from /usr/local/lib/python3.x/dist-packages/torch/share/cmake or somesuch)? In the end, the same libtorch should behave the same way… Best regards Thomas
Brando_Miranda
I was going over through the masking code in the chatbot tutorial and noticed that it masks with a zero on indices that are 0 but are NOT padding tokens (e.g. the first token). Is that a bug? Is the fix to use the lengths of the sequences to pad?# Returns padded target sequence tensor, padding mask, and max target leng...
tom
That’s not a bug, the token with index 0 is the padding token: PAD_token = 0 # Used for padding short sentences Best regards Thomas
lifengcai
I am trying to bulid libtorch from source bythis.I found that build/include directory only containc10d(dir)andsleef.h(file), but official pre-build release contain(ATen c10 caffe2 pybind11 TH THC THCUNN THNN torch) dirs.so, how can we get libtorch package just like official pre-build release(libtorch-win-shared-with-de...
tom
I think using an appropriate CMake + make install should work, e.g. the Android build does this. You want to disable the Python bit for this. The suggested alternative there works well, too - building Python and picking the lib and include. Libtorch 1.0 used to be built that way (actually extractin…
calincru
I have two tensors with shapes[n, d, d]and[n, 1], respectively, and I would like to add the latter to the diagonals of the matrices in the former. What’s the most straightforward way of doing it? It shouldn’t be in-place.LE: I’m curious if there’s a better way than stackingtorch.eyes.
tom
I think inplace is the best way, but I’ll throw in a .clone(), so you get to keep the input: a = torch.randn(5,4,4, requires_grad=True) b = torch.randn(5,1, requires_grad=True) c = a.clone() c.diagonal(dim1=-2, dim2=-1)[:] += b # backward works as expected: c.sum().backward() print(a.grad, b.gr…
peter_zhu
Values with the same index in a sparse tensor are accumulated when use torch.cuda.sparse.FloatTensor(i, v, torch.Size([2,3])).to_dense().How to only remain the max value when convert the sparse tensor to an dense one.Any tricks to implement this?Specifically,indices = torch.cuda.LongTensor([[0, 1, 0], [2, 0, 2]])valu...
tom
This is NOT what sparse tensors want to do! The sparse tensor represents [[ 0 0 8],[ 4 0 0]]. The operation you want is requested in#22378, which also links to a greatthird party implementation of scatter_max. Best regards Thomas
zzuczy
Suppose I define two sequential():a = nn.Sequential( ... ) b = nn.Sequential( ... )Now I want to define another Sequential() that can concat the two Sequential() a and b above. What am I supposed to do?
tom
Oh, you want the tensors concatenated? I think just running the two and then concatenating the result is the best option. Best regards Thomas
zfzhang
Hi,Suppose I have a weight tensor of shape (4,1), but I want to expand it along the second dimension so that it becomes (4,4) but the underlying storage does not change, and used as (16,1).In code:nn.parameter.Parameter(torch.Tensor(4,1).expand(4,4).view(16))Note the above code will throw exception in the view() call, ...
tom
You need to keep the Parameter of shape 4 x 1 and only do the expand in .forward. You need reshape instead of view, as it’ll need to instantiate the larger matrix. Best regards Thomas
sh0416
I have some question about normalization technique.I encounter very weird phonomena doing normalization.x = torch.rand(10, 10) print((x - x.mean(dim=1, keepdim=True)).mean(dim=1, keepdim=True))It doesn’t give zero tensor! The result is very small but it is not zero.What is going on???
tom
This is numerical precision - floating point arithmetic isn’t exact, so you will not get the exact mean. If you switch to double, you get from 5e-8ish to 5e-17ish in your example. This can be more substantial if you have larger tensors. Best regards Thomas
nullgeppetto
I want to define annn.ModuleDict()and iterate through it preserving the order of keys as defined. That is, I would like to define the dict as follows:D = nn.ModuleDict( { 'b': nn.Linear(2,4), 'a': nn.Linear(4,8) } )so asfor k, v in D.items(): print(k, v) ...
tom
If you pass in an ordered dict, the ordering will be preserved: nn.ModuleDict(OrderedDict({ 'b': nn.Linear(2,4), 'a': nn.Linear(4,8) } )) The crux is that Python 2 does not preserve order in dict (and for early Python 3.x it’s an implementation detail), so in order to have a deterministic…
Navneet_M_Kumar
I have a vector of torch tensors and wanted to know how to convert this to a torch tensor.The vector represents a batch of torch tensors.std::vector<std::tuple<torch::Tensor, torch::Tensor, torch::Tensor, torch::Tensor, torch::Tensor>> batch = buffer.sample_queue(batch_size); std::vector<torch:...
tom
Just like you would in Python, use torch::cat to concatenate along a single axis and torch::stack to create a new axis. Note that dimensions (except possible the cat dimension) must match for this to succeed. Best regards Thomas
btang
I want to fill a data tensor with a float given some index tensor. It seems very simple and almost likemasked_fill_, but my index tensor doesn’t have the same size as the data tensor. Can you please take a quick look at it? I am looking for something likex.index_fill_(index, 42)in the following example:x = torch.Tensor...
tom
The answer here is “it depends”, and it is a bit subtle. The good news is yes. We can doa = torch.randn(5,5, requires_grad=True) b = a+1 b[0] = torch.zeros(5) b.tanh().sum().backward() and it’ll work! The bad news is there are a number of caveats: You cannot do this on a leaf tensor (e.g. a abo…
wuclddwf
[ Variable[CPUType]{12,64} ]terminate called after throwing an instance of ‘c10::Error’what(): isTensor() ASSERT FAILED at /export/users/long/gits/Pytorch/libtorch-1.0.1/libtorch/include/ATen/core/ivalue.h:205, please report a bug to PyTorch. (toTensor at /export/users/ong/gits/Pytorch/libtorch-1.0.1/libtorch/include/...
tom
Comparing output, hidden = model(examples.to(“cpu”), hidden) and at::Tensor output = module->forward({indata1, tuple}).toTensor(); you would not expect the .toTensor() on the output to succeed, but you probably have a tuple that you need to unpack. This is why isTensor fails. Best regards Thom…
pablovela5620
I’m trying to figure out how to do the following in the C++ FrontendI have an (21,3) tensorxyz=torch.tensor( [[-31.986 69.746 353.42 ] [-37.302 31.703 339.31 ] [-56.901 5.73 330.64 ] [-54.698 -23.287 323.1 ] [-38.11 -42.968 316.82 ] [-18.578 -11.142 369.19 ] [ -0.725 -41.328 361.34 ] [ 12.068 -60.113 353....
tom
The C++ equivalent of [...] indexing is torch::index(self, indices) where indices is a vector of Tensors (which can be undefined). In your case: std::vector<torch::Tensor> idx_v{indexing}; auto result = torch::index(xyz, idx_v); Best regards Thomas
ilyes
Hi,I want to add a constraint (max_norm) to my 2D convolutional layer’s weights. For example we can do that easily in Keras using:keras.layers.Conv2D(8, (3, 2), activation='relu', kernel_constraint=max_norm(1.))which makes a convolutional layer with 8 kernels each one has a size of (3, 2).Is there a way to do the same ...
tom
The usual way to do this is to use the functional interface to redefine the forward class ConstrainedConv2d(nn.Conv2d): def forward(self, input): return F.conv2d(input, self.weight.clamp(min=-1.0, max=1.0), self.bias, self.stride, self.padding, self.dilation, sel…
alan_ayu
Maybe it is a stupid question but I still don’t understand, why the output of LSTMCell only consists of hx and cx? Should I add another feed-forward layer to compute o(t) based on hx(t-1) and x(t) ?Thank you.
tom
Well, h already has o applied. Keep in mind that is the output gate, not the output.
LeanderK
I’ve got a tensor where I want to make sure that all values in a certain axis are ascending. My idea was to slide a max over the dimension. Simple example:[1,2,3,4,3,6]after correction:[1,2,3,4,4,6]ideally, I would fold the max over a dimension using an accumulator (initialized with minus inf), but I wonder how to impl...
tom
Hi Leander,#20240has a race who get’s to implement cummax. Best regards Thomas
chenglu
The C++ frontend of PyTorch seems not completed to me. If we want to train a model in Python and deploy that model in C++, we have to do hard about code porting. And I think most likely is the part of data preprocessing which could be implemented by torchvision in Python, but it’s missing in C++.Thetorchvisionpackage i...
tom
Indeed, torchvision C++ support isn’t matching Python support. However,@ShahriarSSis doing some good work on it, so the gap is getting smaller. My guess is that most people use OpenCV to do transforms or do them manually. (Personally, I incorporated things like “normalizing” into the traced/scri…
chenglu
I try to optimize some manually created parameters to see how the grad system work. But the parameters never changed for the same input, here is the code:#include <string> #include <iostream> #include <torch/torch.h> torch::Tensor forward_and_optimize_parameter( torch::Tensor&& input, std::vector<torch::Tensor...
tom
You win the “exceptionally bad luck in picking a small example” award. Your parameters do change, just your loss does not. So what happens is that the gradient of (x-1)**2 is 2*(x-1) and with an SGD lr or 1, you get an oscillation between your initial value and 2-x which both happen to have the s…
huyvnphan
I have 2 losses:loss_aandloss_bloss_ais a satisficing metrics. I just need loss_a < threshold.loss_bis an optimizing metrics. I want it to be as low as possible.Right now this what I am doing:total_loss = alpha*loss_a + loss_b total_loss.backward()By adjustingalpha, I can adjustthresholdforloss_a. Is there a better way...
tom
If you use lossa.clamp(min=threshold) it will only get a gradient when it’s above the threshold. That’s cool, but in reality you may have the other losses gradient pointing towards a direction of increasing lossa. How much this matters depends on your specific situation. Best regards Thomas
Mon
I’m new about cuda programming but I need to make some pytorch cuda programming now.So I lookedthe pytorch cuda extension tutorialand had a try. First I’d like to try theaddexample, so I tried:// add_cuda.h #ifndef _ADD_CUDA #define _ADD_CUDA #include <torch/extension.h> void add(torch::Tensor a, torch::Tensor b, torc...
tom
You probably want to use const torch::OptionalDeviceGuard device_guard(a.device()); or so. This is similar towith torch.cuda.device(...) in Python. Check that a, b, c actually are on the same device. Best regards Thomas P.S.: If you take inspiration from PyTorch internals: The reason you don’…
Ravi_Gupta
A/C to me, My code is totally correct but I got an NotImplementedError. i try different to fix it by changing some layers, reviewing my times the same code.I am not expert in Pytorch but my concept is totally right about the connection. But still i don,t know how to fix it. Anyone help mecode link:-Google Colabwgan_err...
tom
Your indentation is wrong, so the def discriminator(…) is local to __init__ rather than in the discriminator class. Some of the code sources might not be quite au courant (like using Variable…). Best regards Thomas
366baae1250c24d1e035
class LSTMPricePredictor(nn.Module): def __init__(self, input_size, hidden_size, output_size, num_layers): super().__init__() self.input_dim = input_size self.hidden_dim = hidden_size self.num_layers = num_layers self.init_hidden() self.lstm = nn.LST...
tom
I think you need to detach both hiddens because the hiddens that are output from the LSTM will require grad. I would recommend doing so when you actually store them rather than before (but probably with .detach() rather than the inplace variant). Best regards Thomas
acobobby
Hello all,I am working with Pytorch 1.0.1 and I am using the CTC loss of PyTorch.The code looks like the following one (I am working on GPU):criterion = torch.nn.CTCLoss() outs, (h,c) = lstm(input) # input is padded with zeros outs = torch.nn.functional.log_softmax(outs, dim=2) loss = criterion(outs.permute(1,0,2).cont...
tom
No that is for CuDNN, you’ll be OK if you use the “native” (PyTorch) version. Two caveats If you feed “invalid” (targets to long for input length) samples, you probably want the zero_infinity option from PyTorch nightlies. This will very likely be the source of your difficulties. GPU CTC doesn’t …
Zayd
I am running PyTorch 1.0.1.post2. I was looking at the type signature fortorch.catwhich is listed as:def cat(tensors: Tuple[Tensor, ...], dim: int=0, *, out: Optional[Tensor]=None) -> Tensor: ...My understanding here is that it is expectingtensorsto a tuple ofTensorobjects. This feels overly restrictive as I often us...
tom
For 1.0.1 a version that had been generated with a preliminary toolhas been used. In masterthey are generated(for torch itself) and have been improved quite a bit since 1.0.1, so the nightlies might be a better choice if you want to make good use of the type hints (and iron out funny stuff befor…
thompa2
Hello, hoping for a little insight. I’m writing a loss function that calculates, among other things, entropy of images. I’m using torch.bincount to create a grey-level co-occurance matrix. The function is nearly 1000x slower on cuda when the input tensor contains a large number of zeros. Here’s some toy code to minim...
tom
Hi Andrew, yes, in a way they’re related. Bincount seems to eventually reduce tokernelHistogram1D in SummaryOps.cu. That uses atomicAdds, which lead to the non-determinism and are actually of poor performance when many threads want to write to the same memory location. I think one (hacky) way to…
dsp
In a simple test, using the original formula for InstanceNorm2d inhere:eps = 1e-5N = nn.InstanceNorm2d(1, eps=eps)x = torch.arange(25).view(1, 1, 5, 5).float()y1 = N(x)y2 = (x - x.mean())/torch.sqrt(x.var() + eps)The error is quite big:y2-y1tensor([[[[ 0.0336, 0.0308, 0.0280, 0.0252, 0.0224],[ 0.0196, 0.0168, 0.0...
tom
If you’re into finding out yourself: Can you spot the pattern in the deviation you see? Did you notice they both have mean 0? Look at y1/y2. It does use the same formula but the formula does not say which variance estimate to use, so you picked the one that’s not the one *Norm uses: you have unbias…
chausies
For example,numpy’s einsumhas an “order” and an “optimize” parameter, which lets you either specify exactly the order to eliminate dimensions, or whether or not/how elimination order should be specified. For example, optimize=‘greedy’ just uses a simple and fast greedy algorithm to find a good ordering.Doestorch.einsum...
tom
No. It has been on my list of things to do when I have time ever since I implemented einsum, but it never happened. You’d make a lot of friends if you implemented that.The (third party)opt_einsumpackage supports PyTorch, so you could use that, too. Best regards Thomas
henrychacon
Hi!I implemented the following class. In the forward step, it works, however, when I execute the backward step, it returns: RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operationThe output of the forward method is a sum of the elements in a vector, which is generate...
tom
You should be able to replace the for loop in j by replacing matmul with broadcasting (or einsum if you can’t help it). Then you can just write b = b + X, eliminating the inplace update. Best regards Thomas
rasbt
I know that PyTorch is primarily an auto-diff library, but I was wondering if there are also ways to integrate efficiently? Unfortunately, I couldn’t find anything when searching (probably due to the overloading of the term “integrate” in engineering contexts).For simple things, I could probably come up with something ...
tom
So there aren’t efficient ways to integrate similar to autodiff, so basically, you need (more refined) formulas like yours. I haven’t seen implementations of the advanced quadrature rules in PyTorch. It’s not quite what you want, but the Neural ODE code has ODE solvers which would give you some ad…
smonsays
I have given a batch of row vectors stored in the matrixU, a batch of column vectors stored in the matrixVand a single matrixM. For each row vectoru in Uand each column vectorv in VI want to compute the sum of the matrix productu *M*vfor each batch.How can I efficiently implement this (potentially usingbmm(),matmul()or...
tom
torch.einsum('bi,ij,bj', U, M, V) if you want the sum, 'bi,ij,bj->b' if you prefer the batch items separately.Best regards Thomas
Nikronic
Hello everyoneI am trying to initialize the layers of my network usingkaiming_normal_initializer. This method has an argument calledmodewithfan_inandfan_outoptions.I read the docs and found out it depends on the number of filters or channels. For example, I have aConv2dlayer with size of[64, 3, 4, 4]. When I calculate ...
tom
There are two parts: As Avinash points out, the default mode 'fan_in' is probably a good choice. For some intuition of why this is: Each output is a weighted sum of fan_in inputs. For linear, this is one row of the matrix multiplication, for convolutions it is number of in-channels * kernel size. …
job28
Hi team,I am using MTCNN in pytorch, and it looks like pure non-max suppression implementation in pytorch(cuda) is waaay slower than numpy implementation on cpu. I ended up running just the nms part on cpu to get decent frame rates. Could someone please correct any obvious mistakes, here is the code,def nms(boxes, _kee...
tom
NMS is one of those operations where it is common to write custom kernels because, as you note, implementing this in PyTorch directly is not so fast. In the MaskRCNN-Benchmark-Implementation there is are CPU and GPU kernels for NMS, e.g.: Best regards Thomas
ghazal_sahebzamani
I have this decoder model, which is supposed to take batches of sentence embeddings (batchsize = 50, hidden size=300) as input and output a batch of one hot representation of predicted sentences:class DecoderLSTMwithBatchSupport(nn.Module): # Your code goes here def __init__(self, embedding_size,batch_s...
tom
Don’t say batch first if you don’t mean it.Best regards Thomas P.S.: Pro tip: PyTorch supports not passing the initial state (implicitly initializing to 0). Calling like that will give you a final state where you can read off the required shape.
Nilesh_Pandey1
#include <torch/script.h> // One-stop header. #include <iostream> #include <memory> const int64_t kNoiseSize = 128; const int64_t kBatchSize = 64; using namespace torch; int main() { torch::manual_seed(1); //auto options = torch::TensorOptions().device(torch::kCUDA,0); //torch::Tensor z_save = torch::randn({kBatc...
tom
Should data be an array of int64_t? As is you seem to have a mismatch between the C++ array and the data type in from_blob. That would lead to funny values and might cause the device assert. Best regards Thomas
zippeurfou
Hi,I have been trying to implement the LSTM siamese for sentence similarity as introduced in the initialpaperon my own but I am struggling to get the last hidden layer for each iterations without using a for loop.h3 and h4 respectively on this diagram that come from the paper.01%20PM1104×668 41.8 KBAll the implementati...
tom
I’m not sure I understand your doubts? If you run a torch.nn.LSTM on seq x batch x feature - Tensors, it will have the same result as if you iterate over the seq (and keep track of the state (h,c)) as the unrolled loop in your first link does. The final state could be taken either from the output o…
pmeier
I implemented a function that performs a traditional image filtering such as gaussian smoothing inPyTorchwith depthwise convolutions and a two-dimensional kernel. To save some memory I used.expand()to get the kernel in the right shape instead ofrepeat(). In my understanding this should do the same thing, since the kern...
tom
That’s a bug in MKLDNN convolutions needing continuous kernels but not saying so. Thank you for bringing this up here!I filed an issue.Best regards Thomas
blueeagle
Hi,I am trying to do an image segmentation with PyTorch. Unfortunally I am getting an error while computing the loss:RuntimeError: Assertion cur_target &gt;= 0 &amp;&amp; cur_target &lt; n_classes' failed. at c:\programdata\miniconda3\conda-bld\pytorch_1533090623466\work\aten\src\thnn\generic/SpatialClassNLLCriterion.c...
tom
For two classes, the usual setup is to take the binary cross entropy loss. PyTorch has nn.BCELoss and nn.BCELossWithLogits for this, the latter including the sigmoid layer that you would need to add to your net for the former. The trick here is that the “probability” of the 0 class is just 1 minus t…
Red-Eyed
I just wanted to try PyTorch after several years of TensorFlow.But I wonder, why do I need to define layers ininitand use them in forward?In TensorFlow, for example, I just build graph in one place, and then use it all over the code, like so:x = Conv2D(filters=16, kernel_size=(7, 7), strides=(1, 1), padding="valid")(x)...
tom
For 1. you could use Sequential. For 2. no. And that is because PyTorch won’t ask you to specify your input size ahead of time. This does come up on the forums every now and then, but for most people it is OK to compute the (usually just one in a typical CNN) size or just put data through the lower…
kuzand
I have encountered a strange behavior. The following piece of code works as expectedmodel = models.resnet152(pretrained=True)params_to_update = [{'params': model.fc.parameters(), 'lr': 0.001}] optimizer = optim.Adam(params_to_update) print(optimizer.param_groups)However if I do something like this:params_to_update =...
tom
Try params_to_update = [{'params': list(model.fc.parameters()), 'lr': 0.001}] Best regards Thomas
Divya_B
Hi,I am trying implement different learning rate across my network .I am creating the parameter groups as follows:Simple optimizer:optimizer = optim.SGD(net.parameters(), lr=learning_rate )Optimizer with parameter groups:optimizer1 = optim.SGD([ {'params': net.top_model[0:10].parameters(), 'lr': learning_rate/10, '...
tom
The first 10 layers of vgg probably have 8 parameters (weight + bias for 4 conv layers) - those are the ones for the first param group when you split them -, the remaining part of vgg has 18 (9 more conv layers), bn1 and linear have 2 each (weight + bias). When you have a single parameter group (i.e…
Atom
Hey there,i have a model trained in Python/PyTorch and saved it via "torch.save({‘model’, model.state_dict()}). The task is to load this “.pth.tar”-file into a C++/PyTorch module and apply it to the same architecture.Is there a similar method to the Python/PyTorch mehtod "model.load_state_dict(torch.load(“model.pth.tar...
tom
So the answer here is yes. Does that also solve the need for loading the state dict? I cannot praise theexport to c++ tutorial enough. Best regards Thomas
crcrpar
Hi,I wonder if I can initialize torch::Tensor from std::vector like this#include <torch/torch.h> #include <vector> int main() { std::vector<T> initializer; ... torch::Tensor tensor = torch::from_blob(initializer); }
tom
I used torch::tensor(ArrayRef<float>) successfully. I’m not 100% certain whether that copies already. You might have to take care of ownership or clone the output while the array ref is still alive, I think you have to do that when you use form_blob, too. Best regards Thomas
isalirezag
Can someone explain what is the difference between step() and backward() and what they do?also can you explain when we should use zero_grad()? should we use it whenever we want to do backward()?
tom
Hopefully, you use them in the other order - opt.zero_grad(), loss.backward(), opt.step(). zero_grad clears old gradients from the last step (otherwise you’d just accumulate the gradients from all loss.backward() calls). loss.backward() computes the derivative of the loss w.r.t. the parameters (…
John1231983
Hello all, what is different among permute, transpose and view?If I have a feature size ofBxCxHxW, I want to reshape it toBxCxHWwhereHWis a number of channels likes (H=3, W=4 then HW=3x4=12). Which one is a good option?If I have a feature size ofBxCxHxW, I want to change it toBxCxWxH. Which one is a good option?If I ha...
tom
I think you habe it mixed up: permute changes the order of dimensions aka axes, so 2 would be a use case. Transpose is a special case of permute, use it with 2d tensors. view can combine and split axes, so 1 and 3 can use view, note that view can fail for noncontiguous layouts (e.g. crop a picture…
Zen
I want to change the size of the tensorsweightandbiasin atorch.nn.Linearlayer. Even if I setweight.grad = Noneandbias.grad = None, the backward pass returns an error. A possible way to solve the problem would be an entire re-initialization of the computational graph, but I don’t know how to do it. However, here is a mi...
tom
At the risk of being blunt:Using .data has been a bad idea for more than half a year. When you try to assign .weight and .bias, PyTorch will tell you exactly what to do, i.e. have a nn.Parameter to assign (I know, because I tried with a tensor before that): l = torch.nn.Linear(5, 4) x = torch.ra…
Keerthan_RA
Hi there,I wanted to build a neural network which accepts the number of convolutional blocks [ conv layer + relu + maxpool ] as input from the user and then build the model accordingly. I thought of using a for loop for this purpose and the following is the code i tried to implement :self.model = nn.Module for ...
tom
This self.model = nn.Module doesn’t really look like you’re supposed to do it. You could use nn.Module(). An even cleaner way might be to use a ModuleList or Sequential. Best regards Thomas