user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
AlphaBetaGamma96
Hi All,I was wondering what’s the most efficient way to grab the off-diagonal elements of a batch of matrices?Let’s assume I have some Tensor of shape[B,N,N]and wish to grab all off-diagonal elements (set all diagonal elements to 0) I’m currently using this,def get_off_diagonal_elements(M): dim=len(M.shape)-2 if(M....
tom
You need the clone if you want to keep M unchanged. def get_off_diagonal_elements(M): res = M.clone() res.diagonal(dim1=-1, dim2=-2).zero_() return res
ayrts
Hello, I am trying to implement this loss function taken from Section 2.1 ofRight for the Right Reasons: Training Differentiable Models by Constraining their Explanations (Ross, et al., 2017)The first and third term are the Cross-entropy loss and L2 regularization, respectively and are already implemented in Pytorch. ...
tom
You hardly ever need one hot labels, I don’t think you need them here. Also, I would use torch.nn.functional.cross_entropy_loss instead of re-instantiating the module over and over. You do need predictions, but these are per-class encoded anyways. You would want to use log_softmax rather than soft…
BruceDai003
As I’m tracking down the source code in aten/src/ATen/native/cuda/PowKernel.cu file, as you see there is a lot of host and device functions that would call somestd::pow()and also global ‘::pow()’ functions. But I’m not sure where are those functions defined? I mean in<cmath>there is std::pow on the host side, if I reme...
tom
On Linux this is in include/crt/math_functions.hpp, but there the code snippet actually uses ::pow, which comes fromthe CUDA Math API. As far as I understand, much of the trickery is needed to support half datatypes on Windows due to templating limitations (as the comment suggests) in the compiler…
jhp
Hi, I have a quick question about parameters passed into the optimizer.I knew that only the parameters assigned in the optimizer were updated by gradients, but after the optimizer was defined and start training, I make the parameters that were not assigned to the optimizer to compute gradient(requires_grad=True), which...
tom
The training step parts of “run backward” and “optimizer step” are independent in PyTorch, so the first computes gradients for everything that has requires_grad=True and is ignorant of whether you use them in the optimizer step. So you would keep allocating gradients for the unused parameters but ne…
schaefertim
During my backward hook, I’d like to know the values ofretain_graphandcreate_graph.Forcreate_graph, the value can be determined withtorch.is_grad_enabled().Is there a similar function forretain_graph?If no, is there a workaround?Here is a code illustration at which point in the code I’d like to determine the value.from...
tom
The easiest probably is to just ask grad / backward for the parameter it got (after fixing the retain_grad vs. retain_graph typo): from torch import nn, is_grad_enabled, rand, randint def _hook(module, grad_input, grad_output): fr = ([f[0] for f in inspect.stack() if '/torch/autog…
Cedric_Baron
When enumerating over my dataset I get this error:mask_path = self.mask_files[idx]IndexError: list index out of rangefrom this line:for index, (tiles, labels) in enumerate(loader):I tried with other datasets it is working well. The problem seem to come from a subsetting I am doing when loading the dataset to gain time....
tom
You could just print the idx in your getitem and also compare to len(ds) and len(ds.mask_files).
lcxywfe
I’m writing a custom op for TorchScript, and the c++ function is likeat::Tensor myforward(const at::Tensor& input0, // input const at::Tensor& input1, // weight const optional<Tensor>& input2, // biasbecause the bias may be None in python, and how to convert the ...
tom
You can dereference it (*input2) if it .has_value() is true). As far as I can tell, these type of utility interfaces usually designed to be compatible with the usual (herestd::optional, interfaces) but is duplicated to avoid implementation quirks with older (?) c++ compilers. Best regards Thom…
BruceDai003
I’m using pytorch 1.8.1. As I’m running a testcase in test_autograd.py, e.g.addcmul. I see there is a gradgradcheck to check the second order derivatives. I just want to know how the backward is done.So I usedtorchvizto generate the backward graph below:addcmul1106×791 44.6 KB(This graph is generated in an pytorch 1.9 ...
tom
It’s generated during the build in torch/csrc/autograd/generated. In Functions.cpp: variable_list MulBackward1::apply(variable_list&& grads) { IndexRangeGenerator gen; auto self_ix = gen.range(1); variable_list grad_inputs(gen.size()); auto& grad = grads[0]; bool any_grad_defined = any_v…
Syzygianinfern0
How can I implement something like PRelu by inheriting autograd.Function?
tom
You likely want nn.Module for holding the parameters, in fact see the PyTorch implementation of nn.PReLU and also theWhat is torch.nn tutorial. Best regards Thomas
Samuel_Bachorik
Hi I bought new GPU - RTX 3060 12GB. While training on 480x640 RGB images (1200 images) with batch 32. I have very low GPU utilization.As you can see on this image,CPU Intel I5 10 th gen 6 core 3.8 ghz - Ulitization 98-100%I have 16 GB RAM 3200 Mhz - 14GB of 16 filledGPU - 11 of 12 GB memory filled and Ulitization onl...
tom
I would try to replace the PIL augmentation by one on GPU using torchvision or eg kornia. Also, you would probably do yourself a favour by using Dataset and Dataloader from PyTorch.
gorjanradevski
I have a model that outputs a sequence of vectors for each element in the batch, e.g.,[Batch size, Sequence Length, Hidden size]. Then, I want to select a variable number of vectors for each element in the batch, and copy these vectors to a tensor whererequires_grad = True. A sample code is bellow:from torch import nn ...
tom
That is from a time long gone and anwering a different question. No. Between creating a new tensor requiring grad and using .data, which you never should these days, you created a new leaf which will accumulate .grad. Because you requested it. no_grad signals that you do not need the grad, it does…
VERSPD0
For a tensorain shape of 1 x n, andbin batch x m x n, is there any elegant way to concatenateato the second dimension ofbso that the result should in shape of batch x (m + 1) x n. Meanwhile, the gradient in different batch can effect the same originabyloss.backward().
tom
You can decompose cat into allocating an empty tensor and assigning slices (which broadcasts) res = torch.empty((b, m + 1, n), device=a.device, dtype=a.dtype) res[:, :1] = a[None] res[:, 1:] = b[:, :, None] Best regards Thomas
Gabriella_m
Hi friends, want to ask you, when I want output from model image, for example 500x500 pixels. What layers should I use ? Can you give me example ?I want to put image in model , and also output from model should be also image.
tom
A typical/highly successful architecture for image to image networks in U-Nets. Best regards Thomas
Lovely-Qianyun
Hi! I’m a newbie in pytorch and i’m learning linear regression with pytorch.Below is my jupyter notebook when building model.In In[11] (tle last block shown below),I encountered problems as below:The .grad attribute of a Tensor that is not a leaf Tensor is being accessed…TypeError: unsupported operand type(s) for *: ‘f...
tom
.to is computation if it changes the device, so your parameter tensors will not be leaves. Replacing .to(device) with a device=device keyword argument in the factory functions (torch.normal and torch.zeros) should solve make it work on GPU as well. Best regards Thomas
chinmay5
I have a model wherein I need to compute the cross-entropy loss for only a certain index. Thenode_maskallows for the selection of those indices. There is alsoignore_indexfield in the Cross-Entropy loss class. Since I have the gt for only these masked labels, I thought maybe it would make sense in terms of the overall s...
tom
I think this is a very cool question! CrossEntropyLoss consists of two things, a LogSoftmax followed by a NLLLoss (Negative Log Likelihood). Accordingly, there are two parts: If you select the the rows (you could also use x[:, class_mask] btw if you have fixed classes), the implicit (log) softm…
slapeeh
Hi,I have been browsing the forum and could not find answer to my question.I have a model that has two outputs. At first, I combined the two losses and used one optimizer to calculate the gradients.Now, I want to try using two separate optimizers. However, the two branches of the model (that result in two outputs) have...
tom
So what do you want to do for the parameters that appears in both? If you want to update them twice, you don’t really need to do anything except keeping the zero_grad-backward-step bits of each model disentangled. For the first, you probabably want retain_graph or so. An alternative could be to up…
Samuel_Bachorik
Hi, thanks for help with rotation matrix, now when i got it, iam trying to rotate matrix and then find angle with Pytorch. This is my code - iam not sure if loss function is good but my angle_pred and loss does not change after 100 loops.Do you have idea where problem is ?import torch x = torch.rand((256,2)) angle = t...
tom
There used to be a warning about this, but torch.tensor is bad here as it’ll treat the inputs as numbers rather than connecting them through autograd (and maybe needing the requires_grad=True should have given you a hint). Edit: Let me emphasize, that it’s a common enough thing to get this wrong, …
Samuel_Bachorik
Hi, lets think matrix x = Torch.rand((256,2)). How can I rotate this matrix in PyTorch ? For example by 5 degrees. How to create rotation matrix for this ?Thank you
tom
So you have 256 points in 2d? import math x = torch.rand(256, 2) phi = torch.tensor(5 * math.pi / 180) s = torch.sin(phi) c = torch.cos(phi) rot = torch.stack([torch.stack([c, -s]), torch.stack([s, c])]) x_rot = x @ rot.t() # same as x_rot = (rot @ x.t()).t() due to rot in O(n…
WuSht
When we deal with imbalanced training data (there are more negative samples and less positive samples), usuallypos_weightparameter will be used.The expectation ofpos_weightis that the model will get higher loss when thepositive samplegets the wrong label than thenegative sample.When I use thebinary_cross_entropy_with_l...
tom
Glad you solved it! If you allow me a comment: I think balancing the data by oversampling the minority class / undersampling the majority class is even more common and - at least in my experience - can be more effective. Best regards Thomas
One4ever
Hi,I have a 3D tensor of an image in YCbCr color space instead of RGB.I want to save the image usingtorchvision.utils.save_image, how can I set the mode to YCbCr? Are there any other ways to do this?Thanks
tom
So under the hood, save_image does is lines of code: First it uses make_grid which will arrange a batch of tensors in a grid, giving you a c x h x w tensor even if you passed in b x c x h x w. You may or may not need this. Then it maps from 0…1 to 0…255, clamps, permutes to h x w x c and conver…
kennethdirker
I am trying to get the pretrained faster rcnn model to work, but I keep running into this error./opt/conda/conda-bld/pytorch_1616554793803/work/aten/src/ATen/native/cuda/IndexKernel.cu:142: operator(): block: [0,0,0], thread: [0,0,0] Assertionindex >= -sizes[i] && index < sizes[i] && "index out of bounds"failed./opt/co...
tom
Right, as per@ptrblck's advice, you could try upgrading:
A_Ray
I’m trying to share tensors from pytorch with a cuda kernel that I have compiled separately, and I’m seeing illegal memory access errors when passing the data pointer for the torch tensor into the kernel.As far as I can tell, from the perspective of the kernel, the pointer I get fromtensor.data_ptr()isn’t actually a re...
tom
.data_ptr() is fine, just passing it to ctypes as an int is not a good idea. Wrap in ctypes.c_void_p, and fix the dtype to float. I might add that it’s always a good idea to print the stuff you’re passing across the Python-C interface, discovering the mismatch between the Python pointer and the (on…
mamadpierre
I have a tensor of size(n1, n2, n3)and alstof sizen2with integer values in[0, 1, ..., n2-1]as partition (or cluster) assignments. What I want is an output of size(n1, len(set(lst)), n3)where the second elements are the mean of those belong to the same partition (cluster). For instance, imagine we have tensoraof size(50...
tom
I’d look at the third-party packagePyTorch scatter. It has a reduction=mean mode. You need to convert lst to a tensor and possibly use broadcasting. Now, the scatter implementation uses atomics, which is problematic e.g. in terms of performance. If the partitions are ordered (as your example sugg…
KouWeiBin
Hello,I used pytorch to train a faster-rcnn model and then convert it into TorchScript model in order to deploy in c++ platform. After I deployed it in c++ platfrom, there is about 10s delay in predicting the second frame. so can anyone help me to solve it or give some valualbe comments? Thanks
tom
This is when the JIT does its optimizations. Typically, the first pass is an unoptimized profiling pass where the JIT collects tensor shape and layout information (and profiling means that, not something with timing). Then before the second pass, the JIT specializes the graph for the observed shape…
kjans123
Hello, I have set of 30 xyz Cartesian coordinate points (30x3). There are 759 of these sets stacked on top of each other (759x30x3). I need to dot multiply them by another set of points so that the output is 759x30. I’ve tried torch.bmm, torch.matmul and torch.tensordot. So far, I’ve had no luck getting the correct out...
tom
Either use einsum with bij,bij->bi or use unsqueeze(-2) and unsqueeze(-1) on the inputs of matmul and squeeze the result. (matmul reduces the second to last and last axes of the first and second input, respectively) or you could multiply with * and then sum at the expense of some time and memory.
Mriganka_Nath
So I have to train two models simultaneously, where the input of the 2nd model is the output of the 1st model.And the output of my 2nd model is the grad of 1st model’s output wrt its inputPreviously I was training these 2 models independentlygetting the outputs from the 1st model, then calculating its grad wrt input,th...
tom
Then I would try something along the lines that you suggested. Usually I advise against using .backward for anything except model parameters (and use torch.autograd.grad instead, but this seems to be the exception to the rule because we don’t want to duplicate the work of doing grad and backward. S…
Ali_Boushehri
HiI have a pretty big dataset of images. I would like to calculate the 5% and 95% of pixel ranges for the whole dataset.I am wondering if there is any method for that? Also, how can I do that in pytorch?Please let me know if you have any quetions
tom
Hi Ali, if your values are 8 or 16 bit integers (which is quite common), I’d probably just compute a histogram. If they are not, you could do this iteratively: Quantize to 8 bits by rounding down and up (keeping statistics for both rounded-down and rounded-up). Then you know the 5% percentile is b…
AfonsoSalgadoSousa
Hi. I have an adversarial training process with a few models and two optimizers. The two optimizers update different parameters, and yet I get this error:RuntimeError: Trying to backward through the graph a second time, but the saved intermediate results have already been freed. Specify retain_graph=True when calling ....
tom
Use generated.detach() when feeding generator output inro the discrimibator when you want backward to not go into the generator.
savvas17
I have experimented with some example tensors of reasonably large size, and fetching theminandmaxvalues from these tensors seems suspiciously fast. Are these operations O(n) or does Pytorch perhaps keep track of them behind the scenes for quick retrieval? Of course the time taken will be system dependent, as well as GP...
tom
Yes. No. You want warmup, probably. You don’t want to use time.time for timing. Use time.perf_counter. Or use Jupyter/IPython and %timeit One thing to keep in mind with GPU benchmarking is to do the syncing before looking at the wall clock (before start and before end). Best regards Thomas
yichong96
Given a 1-d array in python labelledarray, I can convert the array into a tensor using the following codetensor = torch.FloatTensor(array) # array with normalised pixel values tensor = torch.reshape(tensor, (3, 320, 320)) model([tensor]) # run model inferenceHow would I convert the 1-d array into a tensor in c++ with (...
tom
This is what I meant with using from_blob requires you to keep the pointer array alive for the lifetime of the returned tensor. So you pass in a pointer to from_blob but PyTorch “not taking ownership” means that PyTorch doesn’t know where it comes from or tries to do anything with it. This mean…
avitase
We have a strange problem with a (JIT) compiled model. We have twopytestunit tests of our model. In both tests the model is initialized with the same parameters, compiled viatorch.script.jit(model)and fed with toy data, but only the second test uses the output to calculate a loss and eventually callsbackwardon it. If b...
tom
What happens is that in the second run you get the JIT autodiffed abs and that has been broken when complex support was added to the derivative of backward. Sadly, it seems that while the autograd that you get on the first run had been updated 10 months ago, the JIT has not been getting as much love…
ItalianSC
I create a cuda tensor use code like below:auto my_tensor = torch::ones({1,3,512,512},torch::device(torch::kCUDA,0));so how can I copy the data in a cuda memory to a cuda tensor ,or copy from cuda tensor to cuda memory directly? What I want is to be able to complete the copy inside GPU without having to do GPU->CPU->G...
tom
I’m not sure what you want to do here, but there are several ways to do things: use from_blob with a pointer to cuda memory, create the cuda tensor and use the tensor.data_ptr() as a destination, create a cuda tensor and use tensor.copy_(src)
Arsham_mor
I tried to train CTC model based on LibriSpeech dataset,but CTCLoss always return inf or 0 if I use zero_infinity=True.here is my decoder:class ConvDecoder(nn.Module): def __init__(self, in_channels, vocab_size): super().__init__() self.decoder = nn.Conv1d( in_channels=in_channels, out_c...
tom
You almost certainly want permute here and not view. A loss of inf means your input sequence is too short to be aligned to your target sequence (ie the data has likelihood 0 given the model - CTC loss is a negative log likelihood after all). Best regards Thomas
dancedpipi
I need do something on libtorch, then return Tensor to pytorch, implement by pybind11code snip:#include <torch/torch.h> #include <pybind11/pybind11.h> #include <iostream> torch::Tensor create() { return torch::rand({2, 3}); } PYBIND11_MODULE(example, m) { m.doc() = "libtorch tensor test"; m.def("create",...
tom
Yes, PyTorch can do it, but you need to import the right header, I think #include <torch/extension.h> will do the trick. The background is that the Python bits are the thing you would not want to include when you are using libtorch purely in C++, so you want more than just torch/torch.h if you us…
Michael_Lellouch
Hey everyoneI’m trying to train a network to do an image processing operation. Since I was having some trouble with that, I moved to just trying to train a network to do nothing, and it still doesn’t converge to anything good.Does anything looks off in my code? Any idea/remark will be gladly appreciatedThanks!class Net...
tom
What is your input range? I’m asking because usually people leave out the final relu.
YannLe
It seems like a bug to me, so I am not sure if this is correct place for this question but here it is.I have declared a custom dataset something like:from torch.utils.data import Dataset class FaceLandmarksDataset(Dataset): """Face Landmarks dataset.""" def __init__(self, csv_file, root_dir, transform=None): ...
tom
So random_split returns to Subset instances that themselves refer to the (single!) DataSet instance. The modern workflow for this is to override the collate function in the dataloader (calling default collate and then optionally augmenting the dataset). Or you could make full instances of your da…
morphism
Hello, everyoneI called RoIAlignFunction from RoIAlignAvgbut there is an error‘RoIAlignFunctionBackward’ object has no attribute ‘aligned_height’How can I solve this problem???Thank you in advance and have a nice day##############class RoIAlignAvg(Module):definit(self, aligned_height, aligned_width, spatial_scale):supe...
tom
Well, the rename to ctx is a good idea, but really, you would need to find a source for your shape. For example TorchVision’s roi align-function takes some more parameters (vision/roi_align_kernel.cpp at 0013d9314cf1bd83eaf38c3ac6e0e9342fa99683 · pytorch/vision · GitHub), maybe the forward should, …
udemirezen
HiI have been trying to undertand autograd operation given in different forms from several repos while i investigate a specific topic:u = net(x,t) u_t = torch.autograd.grad(u.sum(), t, create_graph=True)[0]and,u = net(x,t) u_t = torch.autograd.grad(u, t, grad_outputs=torch.ones_like(u), create_graph=True)[0]and,u = ...
tom
The backward of .sum() is “.expand()”. The first variant (btw. I tend to write it u_t, = torch.autograd.grad(...), i.e. use tuple unpacking instead of indexing) is implicitly furnishing a scalar 1 as the grad_outputs. Thus the difference is that 1. has a first step does an expand of the 1 as the b…
Arthur_Zakirov
Hello everyone,after studying codes from different authors, I’ve seen different approaches to encode an image into a latent variable.1 ) [N, 1, 28, 28] → Conv → [N, 32, 14, 14] → Conv → [N, 64, 7, 7] → Conv [N, 128, 1, 1]→ fc → [N, latent_dim]2 ) [N, 1, 100, 100] → Conv → [N, 10, 48, 48] → Conv → [N, 20, 22, ...
tom
(I think you might need a flatten in 1, too.) We have a short discussion of the more general number of channels and width in our book (Stevens/Antiga/Viehmann: Deep Learning with PyTorch, Section “8.3.1 Our network as an nn.Module”). So the idea behind “channels should increase while width should …
smani
I need to aggregate the outputs from different networks and then do some calculations based on this aggregated outputs, and finally update individual networks. I am unclear about how to keep the outputs which are obtained in the first for loop (from individual networks) and use it in the second for loop to calculate th...
tom
I would probably just add the losses like this: loss = 0 for i in range(noOfModels): loss = loss + criterion(outputs[:,:,i], x) loss.backward() for i in range(noOfModels): optimizer[i].step() This should work if you didn’t break the computational graph somewhere.
Andre_Chang
is there are new way to create a custom transformation pass in torchscript with torch1.8.0 ?just like here:pytorch_compiler_tutorial/register.cpp at master · bwasti/pytorch_compiler_tutorial · GitHubtorch.jit.trace() doesnt call: RegisterPass pass anymore
tom
RegisterPass still is the right thing to do (or use registerPostPass if you want to call something - RegisterPass is just a trick to call registerPostPass at initialization, there also is a registerPrePass to get an earlier graph). Note that custom passes are not called during the tracing/scripting …
smani
I have a loop, and I am getting a 10x10 tensor for each iteration of that loop. Lets assume that I am running that loop five times, and the output after the loop completes should be the concatenation of these tensors, i.e., a size of 10x10x5. How to concatenate this?outx = [] for i in range(5): tmp = net(x) # this ...
tom
Building the list and then using stack at the end is reasonable: outx = [] for i in range(5): tmp = net(x) # this will return a 10x10 tensor outx.append(tmp) outx = torch.stack(outx, 2) Best regards Thomas
Arthur_Zakirov
Hello everyone,why do these two implementations of the KL divergence give me different results, can anybody find the error? The difference is about 5%note: I’ve commented out the ’ .sum() ’ because if I don’t, the code colours in the forum text editor change, can anybody suggest the reason?Version 1:def q_z_dist(self, ...
tom
So you have prior = p = N(0,1) and q = N(mu, diag(var)) It seems that you compute D_KL(p || q) in the first and the more common D_KL(q || p) in the second. KL Divergence is not symmetric, so these will differ. Best regards Thomas
Maggie_Mae
Hi All,I am very new to PyTorch and I’m seeing something weird when my code runs that I can’t figure out.In short this I am applying a gaussian to many images and then a regression with brain data.The code batches the gaussian/image process. The center location and width of the gaussian changes, each combination is con...
tom
I’m not sure anything in your code immediately jumps into the eye that is bad. So there a couple of things to keep in mind here: PyTorch has a caching GPU memory allocator, this means that it will not return memory to the system when freeing tensors but instead keep it and re-use it for the next…
andreys42
I’m wonder why we don’t use model.eval() command in training_step method of the “LightningModule”def training_step(self, batch, batch_idx):x, y = batchpred = self(x) ### but our model is in training mode now …
tom
There is two parts to this. training_step is about training, so it seems natural that the model is in training mode, Lightning automatically sets the model to training for training_step and to eval for validation. Best regards Thomas
valiantljk
Hi, I’m using allennlp to do distributed bert training.In their code, model has some customized functions, e.g.,get_metrics, andget_regularization_penalty. After wrapping it with ddp, there is a comment says# Using `DistributedDataParallel`(ddp) brings in a quirk wrt AllenNLP's `Model` interface and its # usage...
tom
You have one object for each of the three classes m = ThePyTorchModel (without DDP) ddp_m = DistributedDataParallel(ThePyTorchModel) anlp_m = Model(ThePyTorchModel) (AllenNLP’s model class) ddp_m and anlp_m wrap (i.e. contain a reference to) the (same) instance m as .module and .model usually. …
Golden_Caviar
Hi, I’m working on a CRNN project forked fromthis repo. I felt like it was a bit messy so I decided to clean it. Here is the original code:class CRNN0(nn.Module): def __init__(self, img_channel, img_height, img_width, num_class, map_to_seq_hidden=64, rnn_hidden=256, leaky_relu=False): super...
tom
First thing, good job to simplify the stuff you find on the internet. I often do this, too, when I need to look at code from others. You are not using the same weights with this. The random init for the second will be different than the one for the first because you not re-seeding after instiatiati…
yichong96
Reading the pytorch documentation about faster RCNNfrom this page, It says that the input to the model during training is a list of dictionaries with the keys as ‘boxes’, ‘labels’.However, when reading thefine tuning tutorial for faster r-cnn, there are additional arguments defined such as the ‘image_id’, ‘area’ and ‘i...
tom
The training only uses boxes and labels and ignores any other keys. As the tutorial says, the image_id, area and iscrowd are used in evaluation (but not during training). Best regards Thomas
lhc
I have tried to integrate ffmpeg with libtorch, but found that libtorch can not compiled by C. Did someone do this work sucessfully?
tom
I don’t think PyTorch supports that. You would likely need to define a wrapper library with extern “C” functions and compile that in C++. The wrapper can then be called from C. Best regards Thomas
Charles-Xie
I’m trying to build a custom C++ extension using the aten api.Does aten library provide a simple way to manually delete/free a tensor? Please take a look at the example below:// create a tensor torch::Tensor tensor = torch::randn({3,4,5}); // manually delete this tensor delete tensor; // something like thisThe targe...
tom
Yeah well, I usually just introduce a local scope for that. void myfunc() { some code here { torch::Tensor a = ... } here a is gone } But if you must: Assigning the default-constructed undefined Tensor would likely work, too. Best regards Thomas
lightbooster
Hey, i would like to know how i can concatenate two tensors like this:t1 = torch.rand(2, 10, 512) t2 = torch.rand(2, 768)and get tensor like this:>>> torch.Size([2, 10, 1280])Let’s assume that shapes are:t1_shape = (batch_size, sequence_len, embedding_dim) t2_shape = (batch_size, embedding_dim)I want to concatenate the...
tom
You could use t2.unsqueeze(1).expand(-1, 10, -1). This will take no extra memory (before the cat, that is) as it is a view (print stride() and shape to see what is going on) and the 10-dimension is just stride 0 (i.e. all copies in the same location). Best regards Thomas
ProGamerGov
So, I am trying to modify some of my code so that it supports the batch dimension. One of the lines usestorch.diagflat, and I was wondering what would be the batched version of it?I see there are thetorch.diagandtorch.diagonalfunctions, but it’s not clear if they replicatetorch.diagflat?import torch x = torch.randn(2, ...
tom
You can usetorch.diag_embedwith torch.view(batch_size, -1) as the input. If your tensor is not necessarily contiguous, you can use torch.resize instead of torch.view. Diagonals seems to be one of the bits of the numpy api that isn’t thought out terribly well w.r.t. being flexible/intuitive for us…
Ajinkya_Ambatwar
Hi I have a custom map-style dataLoader function for my application. Please excuse the indentation below.class data(object): def __init__(self, train): self.train = train <some other init> def __len__(self): if self.train: return 640 else: ...
tom
I think this is the total number of batches (training + validation). Best regards Thomas
melike
Hi all, I have an input tensor of shape12x3x3which corresponds to 12 patches of size3x3, can be explained as {Patch1, Patch2, …, Patch12}. I want to convert it to1x12x9, keeping the patches as described below,Patch1 Patch2 Patch3Patch4 Patch5 Patch6Patch7 Patch8 Patch9Patch10 Patch11 Patch12I triedtorch.unfold()with di...
tom
How about inp.view(4, 3, 3, 3).permute(0, 2, 1, 3).reshape(1, 12, 9)? (If anything, unfold would be used when getting into the other direction with overlapping patches.)
Alexander_Soare
I’m new to quantization so I couldn’t figure out a way to easily reproduce this without going through the whole flow.Frompdbduring a forward pass of a quantized model:print(x.dtype) # >> torch.quint8 print(x.shape) # >> torch.Size([1, 40, 64, 384]) print(x.mean((2,3), keepdim=True).shape) # >> torch.Size([1, 40])This h...
tom
Hello Alexander, I can confirm this and took the liberty to fileQNNPACK mean with keepdim doesn't work · Issue #58668 · pytorch/pytorch · GitHub. Thank you so much for reporting this with very precise repro information! This makes things much easier. For reference: This illustrates the problem: …
sevagh
Hello. I have a deeply nested list of tensors. It’s returned by an external library which was previously numpy based, which I modified to convert numpy to torch:a = list(self.nsgt.forward((x,))) print(type(a)) print(len(a)) print(type(a[0])) print(len(a[0])) print(type(a[0][0])) print(len(a[0][0])) print(type(a[0][0][...
tom
For PyTorch you would need to use nested stacks or a for loop t = torch.stack([torch.stack([torch.stack(l2, dim=0) for l2 in l1], dim=0) for l1 in a], dim=0) or somesuch (I might have gotten the brackets wrong). But this will copy the tensors several times, so an alternative is just allocate and c…
tree5680
i want to fix weights which have a value of ‘zero’ in model.parameters() (model is a neural network) it means i have to freeze it in element-wise so i made a code below.in the code, model.parameters() will be input of ‘Lparam’ and when i ran the code, i got an error like 'nonetype has no attribute ‘zero_()’and when i t...
tom
The conceptually clean way to fix some part of weights is to have buffers (with self.register_buffer('weight_update_mask', the_mask) in the module initialization for the mask of what should be updated and the fixed weights and then in the forward use weight = torch.where(self.weight_update_mask, sel…
Joseph_Kao
I’m working on a delayed online learning scheme where I want to do the optimization step after certain delay, and I’m encountering the in-place operation when doing slicing. Here is a rough pseudo code of what I’m doing.Let E be the number of episodes, T be the time horizon of each episode, and D be the delay.input=tor...
tom
This is a decidedly difficult pattern. Would it be possible to move taking the gradient (but not the optimizer step) to where the output is generated? That would make it much easier because you only need to keep the gradients around, not the computational graph. The problem here is that you can only…
ysig
Hi,I have created the following wrapper around CTC in order to make it an x, y criterion:import torch.nn class CTC(object): def __init__(self, pred_len, target_len, reduction='sum', blank=0): self.pred_len = pred_len self.target_len = target_len self.criterion = torch.nn.CTCLoss(blank=blank...
tom
That is not how you’re supposed to use CTC loss. Do feed in the proper target lengths. What happens is that the loss as you call it would require the model to output PAD BLANK PAD BLANK PAD … for as many pads as you have at the end (for repetitions, CTC needs two x elements to represent one y eleme…
dm23
Hi, I am a beginner in PyTorch, and recently faced an issue. Tried thinking a lot but couldn’t figure it out.Consider we have two matrices#takec = 500x = torch.randn(c,c)y = torch.randn(c,c)And we do this :r1 = torch.sum(x*y,axis=1)Alternatively, if we instead take transpose of second matrix, and then perform a matrix ...
tom
The mistake is to compare floating point variables with == instead of torch.allclose. What you are seeing is that floating point numbers are not as nice as actual real numbers. For example, addition (of multiple values) does not commute due to numerical precision effects: Try print(1e20 + 1 - 1e20).…
ekremcet
Hi,I have updated the PytorchMobile for my Android application from 1.7.1 to 1.8.0 but doing so caused an error in the inference phase. Somehow the tensor dimensions became not valid anymore for PixelShuffle layer. Here is the error:Process: com.example.pytorchtutorial, PID: 14078 java.lang.RuntimeException: The fo...
tom
So I’m happy to report that in 1.8.1 this is fixed thanks to your report. Thank you!
seankala
Hi. I’m trying to solve a device-side assert error. Within my dataset, only a few samples seem to be the culprits of the program crashing, and so I think it’d be convenient if there were a way to target them.So far I’ve tried adding in try-except blocks as such:try: some_variable = some_embedding_function(x) except...
tom
Device asserts are asynchronous, so you will typically see the backtrace in a later operation. Byforcing synchronous operations, you can pin down the exact function. As device asserts invalidate the GPU context, you need to move the data you want to inspect after them to CPU before calling the fai…
AbishekBashyal
In many blogpost and discussion section it is said that by defaultF.backward()isequivalentasF.backward(gradient=torch.Tensor([1.])).But looking at the implementation oftensor.pyandautograd.backward()implementation the default value for external gradient isnonei.e#tensor.py def backward(self, gradient=None, retain_graph...
tom
These blogposts should really use torch.ones_like(loss) (but only for scalar-valued loss) even when ignoring the memory layout to keep things simple. torch.autograd.backward will call an auxiliary function_make_gradsthat creates those if they are not passed in. Having a None formal default argum…
sc21
I thought torch.nn.functional.kl_div should compute KL divergence inKullback–Leibler divergence - Wikipedia(the same as scipy.stats.entropy and tf.keras.losses.KLDivergence), but I cannot get the same results from a simple example. Does anyone know why?from scipy.stats import entropy entropy([0.5,0.5],[0.7,0.3]) 0.0871...
tom
So if we look at thedocumentation for kl_divwe are instructed to SeeKLDivLossfor details. There it says: the input given is expected to contain log-probabilities and is not restricted to a 2D Tensor. The targets are interpreted as probabilities by default, but could be considered as log-proba…
ronnie
i have two tensors, lets say, x=torch.rand([64,8,1,33325]) and x1= torch.rand([64,1,1,33325]) and i want to get an output of my torch.cat to be output.size([64,8,1,66650]) [batch_size, channels, height, width]. i am trying to do things but cannot get it done. anybody can help?
tom
So you want the tensor x1 to be expanded to 64 x 8 x 1 x 33325, right? This is a case where broadcasting isn’t automatic, but if you do x1 = x1.expand(-1, 8, -1, -1, -1), the torch.cat([x, x1], dim=-1) should work. Best regards Thomas
Andreea-Codrina
Hi everyone! I am getting this error when I am trying to train a BERT model. It takes in 60 or something examples and then this error pops up. I made sure my labels are fine. There are no negative labels.RuntimeError Traceback (most recent call last) <ipython-input-34-87f0e3931c4a> in <modu...
tom
This is usually a label problem. Can you do the following: save logits.shape and labels.cpu() in temporary variables, after the device assert is triggered, print these. If you have a label that is >= num_lables or < 0, you have the problem.
hendryx
For multiple reasons including that my model contains control flow and forbetter device portability, I need to use scripting instead of tracing to TorchScript compile at least parts and ideally all of my model. Unfortunately, my model contains type conversion as predicted floats need to be converted to int be used as i...
tom
.to is a great way to cast the type. type is one of these odd legacy functions that haven’t been properly deprecated - I would probably not use it in any of my projects.
Omroth
Hi all.I’m often doing this:torch::Tensor c = torch::matmul(a, b);And I’m aware of a lot of unnecessary allocating, when I would really like to have the result of the matmul stored in b (or a).Is there an easy way to achieve this?
tom
On the GPU it has its own cache, I think on mobile, too. On the CPU it uses posix_memalign which relies on libc to do caching (I think they do in contemporary systems), so I would not worry about it. You can also reserve the memory once and use matmul_out if you love manual, but very likely it will…
hidefromkgb
While exploring atorch.jit.trace()of the standard ResNet50 fromtorchvision.modelsI stumbled upon a peculiar structure at the very end of the network:<...> | ________v_________ ________ _________ | | | | | | | aten::avg_pool2d | | Int(0) | ...
tom
I think with more recent PyTorch/TorchVision you’d get aten::flatten instead – this a traced version of torch.view(x, [x.size(0), -1]) to move from n,c,h,w to n,features. Keras does this flattening implicitly when you use “GlobalAveragePooling” because it actually removes the spatial dimensions whi…
MrPositron
I have a classifier, and I want to compute outputs from the model in the training and validation modes. I am also checking their respective accuracies. However, I found one interestingly strange behaviour.I have already pre-trained the model (ResNet-18) on Cifar-10 and saved the best model on the validation set with ac...
tom
@ptrblckactually already mentioned what’s going on there: The BatchNorm statistics are updated when you run in train mode, so you have a different network. Note that you need to check the state dict or the buffers, not just the parameters. To abstract the situation: You have something where you g…
kevs
Hi, I am trying to figure how the tensor gradient is calculated when using the einsum operator. Can someone point me towards documentation for this or alteast the internal implementation in source code?
tom
Good question, actually one of the exercises in my advanced autograd class. The answer lies in the autograd graph: x = torch.randn(5,5, requires_grad=True) y = torch.randn(5,5, requires_grad=True) a = torch.einsum('ik,kj->ij', x, y) a will show you that the grad_fn of a it is some view backward. …
michalsustr
Suppose I have a training set ofset of sequences of variable size, i.e.D = { (x^i, y^i) | i \in (1...N)} where x^i = { x^{i,j} | j \in (1...N_i)} and y^i \in \R^N_i where x^{i,j} \in \R^N_{i,j}with some sizesN_i, N_{i,j}.What is the best way to save them in memory? Doestorch::Tensorallow to save block of heterogeneo...
tom
What you describe is calledNestedTensorsin PyTorch parlance and it isn’t there yet. Until that materializes, the options are mostly padding (to regular shape) orpacking. Either might be good to combine with “stratifying” your batches to have similar sizes, e.g.torchtext does this, I have done t…
javierlorenzod
Hi everyone!I am fine tuningthe following modelusingthe script provided. However, even if I follow thereproducibility guidelines, I obtain different losses across experiments with the same seed. I used PyTorch Lightningseed_everythingfunctionand also tried doing it manually for each random source, as follows:import tor...
tom
To expand a bit on Alex answer: In general, what you compute by atomicAdd is an “index add”, a sequential version would look like for i in range(...): foo[key[i]] += value[i] The non-determinism comes from the fact that the order in which the additions are computed in the atomicAdd is non-…
Samue1
I’m still trying to wrap my head around PyTorch’s Autograd engine. I wanted to implement a toy network architecture but keep getting the same error:RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operationLooking at my code, I can’t figure out, what exactly causes the ...
tom
The error you had before the present one, namely RuntimeError: Trying to backward through the graph a second time, but the saved intermediate results have already been freed. Specify retain_graph=True when calling .backward() or autograd.grad() the first time. is a bit incomplete. Between the tw…
fs4ss1
Hi!Does multiprocessing works in CPU?I need to predict 200 images (200x200) with CPU, but when I use multiprocessing to create some process the execution time don’t change (or the execution time increase).Thanks!
tom
PyTorch uses multiple threads in the default configuration, if you want PyTorch to only use one thread per process, you would want to disable that:https://pytorch.org/docs/stable/torch.html#parallelism
jleobernard
Hello,I’m struggling while trying to implementthis paper. After some epochs the loss stops going down but my network only produces blanks. I’ve seen a lot of posts on the forum concerning this issue and most of the time the problem resulted from a wrong understanding of the way CTCLoss works. So I tried to make a mini...
tom
The inputs of log_softmax are in log-space, so you’d need to take the log (-inf and 0 instead of 0 and 1 respectively).
liqi17thu
Hi there!I have two matricesproj_matandcam_coordswhich shape as (B, 4, 4) and (B, 4, N). The matrixcam_coordsis just copies of matrix shape as (4, N), i.e., cam_coords[0] == cam_coords[1] == … == cam_coords[B-1]. So according to the broadcast rules I think we should haveproj_mat @ cam_coords == proj_mat @ cam_coords[0]...
tom
Yes, you typically have approximately fixed relative error (given tensor shapes). If you have 1e-5ish relative error with 1e0ish and now have operands are 1e5ish then the error can get 1e0ish. You could compare to the same computation with .double() to see which is closer, but in the end there isn’…
Abhigyan_Raman
I have noticed a disturbing pattern with pytorch (and other libraries too) but can’t get to the bottom of it!Any operation which involves bias term gives different (wrong results!) I will illustrate with Conv2d module here!WithoutBiasterm!import torch import numpy as np torch.set_printoptions(precision=32) np.random.se...
tom
If you print the difference: print(output2-output1 - torch.as_tensor(bias)) you see that it is 1e-8ish, so this is an effect of numerical precision. With floating points, you cannot expect two “algebraically equivalent” (i.e. the maths say it should be the same but calculated differently) to give…
Napam
Hi, during some sanity checking I discovered that torchvision.models.resnet50 (probably other models as well) gives different results when passing in a batch of data versus passing one input at the time. I have ensured that I have set the model to evaluation mode bymodel.eval().My question isWhy batch feed forward vs “...
tom
Changing the batch size may change how computation is organized and deviations within numerical accuracy are expected. For things like convolutions you might even have specialized “inference” kernels for batch size one, but you can even see this with much simpler operations: If you want CPU comp…
Muhammad4hmed
Hi, I am trying to run this repo on my custom dataset:GitHub - Lotayou/everybody_dance_now_pytorch: A PyTorch Implementation of "Everybody Dance Now" from Berkeley AI lab.the repo requires pytorch’s 0.4.1.post2 version but I’m running on latest pytorch version 1.7+ on google colabIn models/spynet.py file they have used...
tom
Yeah, torch.load will do the right thing (or torch.jit.load if it’s a scripted model).
Prateek_Malhotra
I don’t understand why this code snippet gives the output it gives. Can you explain the math behind this or post a link to someplace explaining higher dimensional matrix multiplication? Thanks!A = torch.randn(1, 64, 1152, 1, 8) B = torch.randn(10, 1, 1152, 8, 16) C = A @ B print(C.size())output: torch.Size([10, 64, 11...
tom
The matrix multiplication(s) are done between the last two dimensions (1×8 @ 8×16 --> 1×16). The remaining first three dimensions are broadcast and are ‘batch’, so you get 10×64×1152 matrix multiplications. Best regards Thomas
enterthevoidf22
working on a large UNET3D that worked fine with input samples of shape (batch_n,1,64,64,32).now i switch to a new dataset with different sample shape - (batch_n,1,79,95,68)getting an error during concatenation of skip connection caused by dimension mismatch.i’m pretty sure the root of the error is in the fact there’s ...
tom
At the risk of saying the obvious, you can pass an output size instead of scale_factor to nn.Upsample.
Omroth
Hi all.I have a function f(X) which takes a 1d tensor and returns a float. I would like to attempt to find an X which minimizes f(X) using the pytorch c++ api.I’ve seen a couple of mentions here of modelling the function with pytorch modules, but I’m having difficulty getting my head around the concept - can anyone he...
tom
Neither do the Python optimizers take a single tensor. You can take pass in avector of tensors, tough ({dynamic_parameters} might do the trick). Best regards Thomas
vdantu
I am facing a weird issue. I am doing the followingFreezeatorchvision modelonCPUhost, which internalizes parameters/weight tensors as constants.Save this frozen module.Try to load and run the model onGPUhost.I see that the weight tensor constants are not getting loaded ontoGPUdespite me invokingmodel.to(cuda:0)on the l...
tom
torch.jit.load(...., map_location="cuda") will work on master. scripted_module = torch.jit.script(torch.nn.Linear(2, 3).eval()) frozen_module = torch.jit.freeze(scripted_module) assert len(list(frozen_module.named_parameters())) == 0 print(frozen_module.code) frozen_module.save('/tmp/x.pt') and th…
haorannlp
I wrote a seq2seq model which requires sampling during training.I guess this error might be related to the sampling procedure but I’m not sure what this error message suggests about the multinomial distribution./opt/conda/conda-bld/pytorch_1565272271120/work/aten/src/THC/THCTensorRandom.cuh:179: void sampleMultinomialO...
tom
This means that the categories you sample from all have probability mass 0. Best regards Thomas
CombustibleLemonade
I’m trying to get pytorch to use my AMD RX vega 56 on Ubuntu 20.04, and to do that I have to compile it with ROCm. My actions are as follows:git clone https://github.com/ROCmSoftwarePlatform/pytorch.git cd pytorch/ git submodule init git submodule update git submodule sync git submodule update --init --recursive tools/...
tom
So I use the AMD-provided deb repository from the AMD. Obviously, I am prone to usingthis recipe for building. From the error message, you probably don’t have a full rocm installation. For me, the clang is in the llvm-amdgpu package: $ dpkg -S /opt/rocm-4.0.0/llvm/bin/clang++ llvm-amdgpu: /opt/…
Sining_Sun
Hi all,Recently, I am deploying my model to Android. I found that my quantized model has very high cpu usage, even much higher than fp32 float model. So I tried to run a model with only one Linear layer like:Class Linear(torch.nn.Module):def _init_(self, idim, odim):self.quant= torch.quantization.QuantStub()self.dequan...
tom
I think you have (from torch/include/ATen/Parallel.h) void set_num_threads(int); void set_num_interop_threads(int); Best regards Thomas
Karan_Chhabra
Hi,I am using differential learning rates for different layers. But at the same time I am also using LR decay (I might change to OneCycle policy). But I wanted to know for which layers is the LR decay applied, below is the sample code:optimizer = optim.SGD([ {'params': model.base.parameters()}, {'params': model.classif...
tom
Yes, stick the parameters in two optimizers. That should not make much of a difference w.r.t. performance, you just need to zero_grad and step twice.
iiSeymour
I’m writing a shim to use a C++ function with PyTorch and would like to know how to converttorch::Tensorto astd:vector<int32_t>?float f_cpp(std::vector<int32_t>& result); float f(torch::Tensor results_t) { // std:vector<int32_t> <-- torch::Tensor? std::vector<int32_t> result = result_t.data_ptr<std::vector<int3...
tom
The problem here is that a std::vector can’t use “foreign” memory. Some avenues that might work: Use a pointer (int32_t* ) as an array or a ArrayRef<int32_t> (available in c10). In this case you need to keep the tensor allocated while you are using them. Also note that you need to be a bit carefu…
Zheng_Wen
Hi,I’m currently rewrite a CUDA kernel about rendering, the goal I want to achieve is that rendering the depth map and normal vector map at the same time when I’m rendering the RGBA image. Previously, the code only offers the output from the forward function where the RGBA image is returned, so I need to add two more r...
tom
I think you wantctx.mark_non_differentiable. It does not, however, spare you from taking a second grad_out argument in the backward even if it will be all zero (and indeed fully materialized at the moment): class MyFunction(torch.autograd.Function): @staticmethod def forward(ctx, inp): …
m75
How do you construct a tensor from data in C++ API?Python:x = torch.Tensor([[1,2],[2,3],[3,4],[4,-1],[5,-5]])C++:std::vector<torch::jit::IValue> inputs; auto input = torch::zeros({5,5}); input[0][0] = 1; // manually copy values one by one input[0][1] = 2; inputs.push_back(input);
tom
The problem is in the Python. Thetorch.Tensor constructor has been deprecated in PyTorch 0.4or so. The new way is using torch.tensor instead, and that has an equivalent in C++.
tlsshh
In my network, there are two models A and B. It runs like:a = A(input) b = B(a)I want to freeze model A, only train model B. I want to know, are these enough to fix model A which has batchnorm layers and dropout layers:for param in A.parameters(): param.requires_grad = False optimizer = torch.optim.Adam(B.parameter...
tom
There are three things to batchnorm (Optional) Parameters (weight and bias aka scale and location aka gamma and beta) that behave like those of a linear layer except they are per-channel. Those are trained using gradient descent and by disabling gradients you inhibit that they are updated. There a…
TinfoilHat0
I’m working with the MNIST dataset where the memory of my GPU can accommodate the entire dataset.Naturally, I’d like to push everything to GPU before starting to train my model to make things faster. However, even though I want everything in GPU, I’d like to take small batches of data to ensure good generalization. Wha...
tom
For MNIST, the dataset already stores everything in Tensors, so you can grab the ds.data and ds.targets Tensors from the torchvision MNIST dataset directly and stick them into your TensorDataset. Best regards Thomas
Chame_call
Hi.I’m performing object detection class with only one class.Trained network show good results by detection the class objects but sometimes it identifies false areas as objects with a fairly high percentage of confidence.Is there are any methods by suppressing such detections?Thanks.
tom
No, you should label all things correctly, but you can show the network images where nothing of interest is to be seen (and where it mistakenly detects something) more often.
DanielC
hi there,I have a question about the mechanism of the Pytorch autograd.For the usual loss functions, we have two inputs which are yhat(real output) and y(expected output), as shown in the following two codes.def mse_loss (yhat, y): loss = torch.mean((y - yhat) ** 2) return lossdef cross_entropy_loss(yhat,y): ...
tom
Yes. To the autograd machinery, any scalar function will do as a loss and it will just go over the computational graph regardless of how you arrived there (within the restrictions of needing differentiable things and only following nodes that have requires_grad, which e.g. the true labels usually do…
YuvalA
Hi,I am trying to work with some pictures of mine, loading withImageFolderand making some transforms, when usingtransforms.ToTensor(), I receive multi-image picture.If I’m removingToTensor(), it’s working as expected, however, need to be converted to Tensor.What is the problem? (Pictures Attached)1734×688 108 KB2775×61...
tom
PyTorch uses CHW format (channels first), Matplotlib expects HWC, so you need to permute the image instead of using reshape. .permute(1, 2, 0) should do the trick. reshape does not rearrange your data in memory, it just changes where PyTorch thinks after how many items in memory it should start the…
qiminchen
Hi,Suppose after feeding a 224x224x3 image into a backbone network, the output of last conv layer is 7x7x1280, and I have a well-trained two layersMLPClassifierwhich has1280x100weights and100x6weights, how can I convert these two weights to do fully convolution on7x7x1280feature so I can get7x7x100and then7x7x6. I know...
tom
Linear layer weights are of shape out_feat x in_feat, conv weights are out_chan x in_chan x kernel_height x kernel_width, so all you need is to use channels as features and then add two dimensions to the weight: with torch.no_grad(): conv_layer.weight.copy_(lin_layer[:, :, None, None]) Indexing …
Shisho_Sama
I wonder is it possible to instantiate a model from its repr output in Pytprch?
tom
No. It might work if its only classes from the standard library (they (roughly?) advertise the parameters you could instantiate them with), but the moment you have anything custom, the lack of code for the forward would seem to hit you. You would need the state dict, too. Currently the main way to …
sisaman
I was wondering if there is any more efficient alternative for the below code, without using the “for” loop in the 4th line?import torch n, d = 37700, 7842 k = 4 sample = torch.cat([torch.randperm(d)[:k] for _ in range(n)]).view(n, k) mask = torch.zeros(n, d, dtype=torch.bool) mask.scatter_(dim=1, index=sample, value=T...
tom
The obvious thing would be to use torch.multinomial(torch.ones(n, d), 4), which would take out ~1/3 of the time for me but is somewhat slow. I can half the time (relative to your code, on my machine, on CPU etc.) by using rand + topk. sample = torch.rand(n, d).topk(4, dim=1).indices mask =…
WowPy
Hi All,I am relatively new to PyTorch, and I am trying to find the second derivative. However, it is always zero for some reason. Below is the code:import torch from torch.autograd import grad dev = torch.device('cpu') if torch.cuda.is_available(): dev = torch.device('cuda') torch.set_default_tensor_type('torch...
tom
Now you tricked yourself with too much linearity. While relu is nonlinear globally (else we would famously not have the universal representation property) it is linear in a neighborhood of almost every input (if you pardon the mathematics lingo), rendering your network linear in a neighborhood of y…