user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
woutr | I am having a weird issue with PyTorch’s autograd functionality when implementing a custom loss calculation on a second order differential equation. In the code below, predictions of the neural network are checked if they satisfy a second order differential equation. This works fine. However, when I want to calculate t... | KFrank | Hi woutr!
You could also say that the prior derivatives originate from X, rather than from u.
Consider y = x**2. In “ordinary calculus” you would typically say that
dy / dx = 2 * x, so that dy / dx depends on x. You would not typically say
that dy / dx = 2 * sqrt (y), although this is in a se… |
glenguo06 | It appears that for CrossEntropyLoss,.to()doesn’t copy theweightto the same device. Would be great to know is this by-design or a bug that is fixed on newer releases?Minimum example from the usage doc:>>> loss = nn.CrossEntropyLoss(weight=torch.FloatTensor([1, 2, 3])).cuda()
>>> input = torch.randn(3, 5, requires_grad=... | KFrank | Hi Glen!
It works for me on version 2.6.0:
>>> import torch
>>> print (torch.__version__)
2.6.0+cu126
>>>
>>> ce = torch.nn.CrossEntropyLoss (weight = torch.ones (3))
>>>
>>> ce.weight
tensor([1., 1., 1.])
>>> list (ce.buffers())
[tensor([1., 1., 1.])]
>>> _ = ce.cuda()
>>> ce.weight
tensor([1.… |
Geremia | PyTorch have a built-in 0-1 loss function?Goodfellow et al. p. 102:The 0-1 loss on a particular example is 0 if it is correctly classified and 1 if it is not.A custom 0-1 loss function could easily be implemented:class ZeroOneLoss(torch.nn.Module):
def __init__(self):
super(ZeroOneLoss, self).__init__()
... | KFrank | Hi Geremia!
No.
A 0-1 loss function would not be (usefully) differentiable. That is, after backpropagation,
the gradients computed for a model’s parameters would all be zero (hence giving the
optimizer no information about how to modify those parameters to reduce the loss).
This if-else con… |
Aakira | I’m following the tutorialhereand use the code:class MyCube(torch.autograd.Function):
@staticmethod
def forward(x):
# We wish to save dx for backward. In order to do so, it must
# be returned as an output.
dx = 3 * x ** 2
result = x ** 3
return result, dx
@staticmeth... | KFrank | Hi Aakira!
This error makes it seem that MyCube.forward() is being treated as a non-static
class method (where when you call .forward (x) with a single explicit argument,
it actually gets called with an additional self argument: .forward (self, x)).
Quite some time ago, the .forward() method of… |
ziv_chen | I’m implementing a neural network to solve ODEs. I want to encode several points at once and get several results of the ODE (one result per corresponding input) at the same run.Currently I’m running a toy model where I try to getu(x)=sin(x)according to the loss function:du_dx - cos(x).The network structure is:network s... | KFrank | Hi Ziv!
If I understand correctly what you are asking, when in_out_size is
greater than one, the various values along the n_nodes dimension
are mixed together – multiple time with non-linearities – so the
dependence of the, say, first output value on the the first input value
is not the same a… |
MoRoBe | I am aware variations of this have been asked multiple times, but even after working through many of those, I’m still stuck. I’m trying to get pytorch with CUDA support running on my Laptop. However, torch.cuda.is_available() returns False. Selected system information and diagnostic outputs are as follows:Lenovo ThinkP... | KFrank | Hi Mo!
I have a laptop with a gpu similar to yours – ThinkPad P16v Gen 2, with
the NVIDIA RTX 3000 Ada Generation Laptop GPU running Ubuntu (not
Manjaro) LTS with kernel 22.04.1-49.
Note that the gpu driver – at least as used by cuda / pytorch – has some
issues with ubuntu’s (and maybe linux’s… |
jumdc | Hi everyone,I am training a neural network with a loss function denoted as L. I aim to constrain the network’s outputs (z) such that they lie on a hypersphere of dimension d.To maintain a valid training framework, I need the backpropagated gradients to respect this constraint, meaning they should be tangent to the hype... | KFrank | Hi jumdc!
I’m not sure I follow what you are asking, but if I understand your use case, it should
suffice to project your z onto the hypersphere and then compute your loss function
using the values of the projected z. The gradients with respect to the unprojected z
will then naturally be tange… |
Siddhanth_Ramani | Hi, I am curious as to how Pytorch’s backward function handles multiple inputs.Specifically, are the losses averaged across inputs in the final layer itself (cross entropy loss, etc.), or are the input specific loss matrixes passed on to previous layers and each layer averages/sums across these losses?For ex. For a Inp... | KFrank | Hi Siddhanth!
Logically, it is not necessary to have a batch dimension. There are, however, a
number of built-in pytorch layers that do require a batch dimension (but such batch
dimensions can always have size 1). For example, Linear does not require a
batch dimension, but Conv2d does.
I’m … |
JimW | According to some constraint within our project, I need to rewrite KL divergence computation with basic PyTorch operations. Here is my implementation of KL divergence.torch.mean(q*torch.log(q/p)I compared the output values of this implement with the output values from the following:nn.KLDivLoss()(p.log(), q)And they ge... | KFrank | Hi Jim!
Depending on your use case, computing log (q) - log (p) can be more stable
numerically than computing log (q / p). (They are the same mathematically,
but can differ numerically.)
Try using torch.mean (q * (q.log() - p.loq()))as your KL divergence
implementation.
As an aside, p would … |
kmaeng | Dear experts,I am seeing that uint64 datatype in torch does not have a wraparound behavior on overflow/underflow (which is the expected behavior in C/C++ from my understanding). Below is my code:import torch
A = torch.tensor([2 ** 40], dtype=torch.uint64)
B = torch.tensor([2 ** 40], dtype=torch.uint64)
C = A * B
print... | KFrank | Hi kmaeng!
You are seeing the correct behavior (as do I on pytorch version 2.5.1).
I think you are being fooled by the fact that 2**40 * 2**40 = 2**80 and
2**80 = 0 mod 2**64. So 0 is the correct “wraparound” result.
Consider:
>>> import torch
>>> torch.__version__
'2.5.1'
>>> A = torch.tenso… |
hao_xi | How does the softmax gradient in the pytorch framework calculate the gradient of the input data? I followed this linkhttps://community.deeplearning.ai/t/calculating-gradient-of-softmax-function/1897/3to implement the gradient derivative function, why are the gradients of the derivatives all 0? How do I correctly pass t... | KFrank | Hi Hao!
This isn’t true.
First note that applying softmax() to, say, a one-dimensional tensor returns a
one-dimensional tensor. You can’t compute a gradient of a tensor (of length greater
than one), so you have to take the gradient of some scalar function of the tensor.
If that scalar functio… |
laro | I’m wondering which activation function for multi class classification problem, give true probability.According to:ai.stackexchange.comAre softmax outputs of classifiers true probabilities?activation-functions, probability, softmax, probability-theoryasked bySnehal Patelon07:11PM - 14 Nov 22 UTCit seems that the output... | KFrank | Hi Amit!
The short answer is that softmax() and sigmoid() are used for different things.
It’s not that one is true and the other false or that one is more stable and the other
less stable – they’re just different.
Let me give you my perspective on this. (I haven’t looked at the links you poste… |
yuanhao | Is there any method (or what is the easiest way) to compute the matrix divergence.The matrix divergence is given by the following (Divergence - Wikipedia, and a screenshot is also attached)Screenshot_20240915_1116581519×583 96.7 KB | KFrank | Hi Hao!
Yes. The short story is that you can use func.jacfwd() to
compute the full jacobian of A with respect to x and then pick
out the specific partial derivatives that you need for the matrix
divergence.
First, a couple of comments:
Autograd performs differentiation with respect to entire… |
wasabi_linguist | Hi, I would like to train a network where the loss function uses the eigenvectors of two hermitian matrices to calculate a loss on them. However, as PyTorch’s documentation foreighsays, the computed eigenvalues/eigenvectors are not unique because of their phases. Is there any way to “force” theeighfunction to give eige... | KFrank | Hi Wasabi!
As noted in the documentation you posted a screen-shot of, what matters
is whether your loss function depends on the (non-unique) phase of your
eigenvectors. If it doesn’t, things will be fine and autograd will backpropagate
correctly trough eigh().
If your loss function does depen… |
Boltzmachine | In the documentation ofgumbel_softmax, the first parameterlogitslogits: `[..., num_features]` unnormalized log probabilitiesIt confused me a lot that why the logtis could be unnormalized. In the equation the torch function usessoftmax((log p_i - log (-log e_i)) / t)wherelog(-log e_i))is the gumbel noise,tis the tempera... | KFrank | Hi Weikang!
I do not have an opinion about whether or not pytorch’s gumbel_softmax()
is correct.
However, as a practical matter, if you are concerned about this issue, you
may pass the output of your “arbitrary network” through log_softmax()
before passing it to gumbel_softmax().
One way of l… |
MartensCedric | I have pretty simple codeimport torch
import random
image_width, image_height = 128, 128
def apply_ellipse_mask(img, pos, axes):
mask = torch.zeros_like(img)
for r in range(image_height):
for c in range(image_width):
val = ((c - pos[0])**2) / axes[0]**2 + ((r - pos[1])**2) / axes[1]**2
... | KFrank | Hi Cedric!
You have several problems here, but let me start with a core
conceptual issue:
In order to compute your ellipse-mismatch loss function, you
compare two zero-one mask images. The problem is that
such a loss function isn’t (usefully) differentiable. As you vary,
for example, ellips… |
Antonio_Lopez | Hi,I recently encountered a problem. I have a learnable matrixself.learnable_A = nn.Parameter(torch.empty(n, n))and an unlearnable matrix (just a tensor):self.unlearnable_B = torch.randn(m, m)where m >> n holds. Moreover, we also have an index vector v (list, with the size n)v = [2, 5, 11, 1, ..., 19]where each element... | KFrank | Hi Antonio!
You may use pytorch tensor indexing to write A into the
desired locations of B. (I don’t understand specifically what
you mean by “cols=v and row=v”.)
After you write A into B the “non-leaf” tensor B will carry
requires_grad = True and depend on the trainable leaf
tensor A. So … |
Timwolf01 | I have a question about the implementation of complex Layers, maybe its a duplicate, but havent found a similar.In linear Layer the forward Implementation is x @ w.T + b, made with torch.addmm.With complex data, weights and biases it could be formed to:(x.real @ w.real.T + b.real) - (x.imag @ w.imag.T + b.imag) + 1j * ... | KFrank | Hi Tim!
This just isn’t correct. Consider the case where everything, in
particular the bias, b, is purely real. Your result, as written, will
contain an incorrect imaginary term, 1j * b.real.
The bias, b, is a purely additive term, so the real component
of the result contains just b.real an… |
Vedant_Roy | Is it possible to write a custom autograd function that returns alistof tensors? For context, I’m trying to manually write the backward pass forall_gather.This code:class AllGatherFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, tensor: torch.Tensor, dim, reduce_dtype):
ctx.reduce_dtype... | KFrank | Hi Vedant!
Yes. For example:
>>> import torch
>>> torch.__version__
'2.4.0'
>>> class Func (torch.autograd.Function):
... @staticmethod
... def forward (ctx, t):
... return [t**2, t**3]
...
>>> Func().apply (torch.arange (3.))
[tensor([0., 1., 4.]), tensor([0., 1., 8.])]
Best.
K… |
max_mz | Hi everyone,There have been topics about the difference between torch.nn.Upsample and torch.nn.ConvTranspose2d but I don’t see anyone speaking about the difference between :1 :torch.nn.Upsample + torch.nn.Conv2d2 :torch.nn.ConvTranspose2dI am asking the question because i saw U-Net implementation using 1 and GAN/Autoen... | KFrank | Hi Max!
Upsample plus Conv2d and ConvTranspose2d would do similar
things, but they differ distinctly in detail.
Use Upsample (without Conv2d) if you want cheaper upsampling,
but without trainable parameters, and use ConvTranspose2d if you
want the trainable parameters.
Although you could add C… |
pkoch | Hi,I am currently trying to find the product of a 2nd order cross-derivative matrix and a vector. That is, (similar to a hessian-vector product) I want to findfor arbitrary b and h some function.Additionally, I want to do this in a way which doesn’t ever store the matrix directly, rather I just need the product (E.g. I... | KFrank | Hi Pkoch!
The short answer is that you when you use autograd to compute a second derivative,
you need to use create_graph = True so that the first derivative you compute has
a computation graph through which you can backpropagate.
Here is a script that illustrates this both with .backward() and… |
iftg | I get the following error:Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward passRuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [64, 1, 6]], which is output 0 of TanhBackward0, is at version 1; ... | KFrank | Hi iftg!
Most likely, the output of forward() is being modified inplace after
forward() has run.
self.activation(x) isn’t causing the inplace modification error, per se.
Rather, the presence of self.activation (x) in the computation graph
is causing an inplace modification – that exists with … |
Jacopo_Rizzi | I’m using torch.nn.functional.cross_entropy with one-hot vectors as target when I realized that it wants class probabilities or class indices as target, not one-hot vector.But my thought is, isn’t it the same? I mean, if I use one-hot vector as FloatTensor is like setting 100% probability on a class and 0% on the other... | KFrank | Hi Jacopo!
You understand this correctly, and there is nothing wrong with the
first approach. (To be clear, cross_entropy() accepts targets that
are either floating-point “probabilistic” targets – including floating-point
one-hot encoded targets – with a class dimension, or integer class
labe… |
rubencart | I have a tensorlogZthat’s the result of a computation. I want to use this tensor to compute 2 different losses used to update the parameters ofself.forward(input):One loss is computed as a function of the gradient oflogZw.r.t. another tensor, sayA.Another loss is computed directly fromlogZ.Would this be the right way t... | KFrank | Hi Ruben!
Yes, this is right (but I haven’t looked at your code in detail).
It’s probably a little more convenient to:
marginals = torch.autograd.grad (logZ.sum(), A, create_graph = True)[0]
because autograd.grad() doesn’t set the parameter gradients, so you
don’t need to then reset them.
Y… |
VictorSu33 | I’m currently trying to implement Physics Informed Neural Networks to solve ODEs. As part of it, I need to compute the derivative of the NN wrt to the inputs. So far I have used the codedy_dt = torch.autograd.grad(y,t, torch.ones_like(y), create_graph=True)[0]Where t is some tensor with shape [N,1].This worked for lear... | KFrank | Hi Victor!
I assume that N is the batch dimension of your input tensor.
I also assume that N is the batch dimension of your output tensor and
also that your model doesn’t mix batch elements together. That is, that
model (t)[i] only depends on t[i].
Based on my assumption that your model doe… |
tomsch420 | Hello,I am currently building a layered version of probabilistic circuits and for that I have to represent weighted edges using a tensor. In order to reduce memory consumption i would like to use a sparse tensor for that. However, i find it very difficult to work with those. For instance, the logarithm of a sparse tens... | KFrank | Hi Tom!
Well, if you say so.
But what, logically, do you want the semantics of my_sparse.log()
to be? log (0.0) is not 0.0, so how would it make sense for it to
stay zero?
Or, if you want to say that -inf somehow doesn’t count, what would
you want the semantics of my_sparse.cos() to be?
Yo… |
YuA | I think my model’s parameters are very small. The histgrams below shows that most of the parameters are < 0.1. I am worried that this makes my model sensitive to floating point precision.My model is a very typical autoregressive generative model with 12 decoder-only transformer layers (almost identical to GPT-2)Is the ... | KFrank | Hi Alpha (and Yu)!
This isn’t really right. Floating-point numbers with smaller magnitudes
aren’t any more subject to round-off error. (A single-precision float
does start to underflow at around 1.e-38, but this is underflow,
rather than round-off error.)
If you did successful computations w… |
kamat_mayur | class DeepR_v1(nn.Module):
def __init__(self, input_features, output_features, rest_pose, parent_indices, device):
super(DeepR_v1, self).__init__()
self.input_features = input_features
self.output_features = output_features
self.rest_pose = rest_pose
self.parent_indices = par... | KFrank | Hi Mayur!
This all points to:
global_transforms[:, bone_idx] = t
being the inplace modification that causes your error. (Writing into a
tensor using indexing counts as an inplace modification.) You could
check this by printing out the .shape and ._version of
global_transforms and see if the… |
layman | I am training a multilabel classifier on some imbalanced dataset where I am using pos weights on loss.Dataset looks likelabelcat1cat2cat3a100100100b100200400c100400800d1008001600And my corresponding loss# One-hot encoded trinary labels hence 12-dim output for 4 labels
nn.BCEWithLogitsLoss(pos_weight=torch.tensor([1, 1,... | KFrank | Hi Victor!
Okay, I understand what you’re trying to do now.
First off:
This isn’t right. You are working with a not-binary, multi-class problem
(which in your example, has three classes). You do not want to be using
BCEWithLogitsLoss nor any kind of one-hot encoding (even though
your probl… |
Rohan_Kolhe | I am trying to finetune CLIP by giving it 2 images and text as inputs. I keep getting an error (above) and I have looked at other posts on the forum but none of them seem to help. Here is the stacktrace:/usr/local/lib/python3.10/dist-packages/torch/autograd/init.py:251: UserWarning: Error detected in EmbeddingBackward0... | KFrank | Hi Rohan!
Depending on the details, you might be able to fix your issue using pytorch’ssweep-inplace-modification-errors-under-the-rugcontext manager.
You might try:
model = DDP (model, broadcast_buffers = False, device_ids = [rank])
Does your error occur only when you use DDP (or when y… |
Amos_Haviv_Hason | Running the following code:import torch
torch.manual_seed(47)
m = torch.rand([8, 8])
eigvals, eigvecs = torch.linalg.eig(m)
print(m.type(torch.complex64) @ eigvecs[0] - eigvals[0] * eigvecs[0]) # Should be close to →0.Results with output:tensor([ 2.2827+0.0995j, -0.9539-0.0442j, -1.9871-0.0204j, -0.6442-0.0372j,
... | KFrank | Hi Amos!
The individual eigenvectors are stored column-wise in you eigvecs tensor.
Consider:
>>> import torch
>>> torch.__version__
'2.3.0'
>>> _ = torch.manual_seed (47)
>>> m = torch.rand ([8, 8])
>>> eigvals, eigvecs = torch.linalg.eig (m)
>>> m.type(torch.complex64) @ eigvecs[0] - eigvals[0]… |
Ashima_Kalathingal | Hello,I am trying to implement a Neural ODE in pytorch and I am getting the following error. I am new to Pytorch and I am not able to understand where the error is coming from.The error is :one of the variables needed for gradient computation has been modified by an inplace operation: [torch.DoubleTensor [100, 3]] is a... | KFrank | Hi Ashima!
Just to be clear, to me “epoch” means that you have iterated over the
entire training set once, but that the training set consists of many batches.
Typically, you would perform one optimization step for each batch:
input, labels = get_batch (...) # one batch, not whole training s… |
lpolisi | Hi everyone,I’ve encountered an issue while training my model with a dataset that occasionally has samples withNonelabels. To handle these cases, I set the loss to 0 whenever the label isNoneby usingreduction="none"on the loss function. Here’s a simplified version of my approach:import torch
from torch import optim, nn... | KFrank | Hi Lpolisi!
You talk about labels with None values, but, in your example, you have
labels (your y) with nan values. None and nan are different. Following
your example, I will talk about nans, as they are the cause of your issue.
Yes. nans, by design, pollute everything. (For example, 0 * … |
dio_din | Hi, guys,I met a tensor shape issue when doing indexing.Suppose I have a tensor:a = torch.randn(2, 3, 4)a[[0,]]'s shape is (1, 3, 4)a[:, [0,]]'s shape is (2, 1, 4)then whya[[0,], [0,]]'s shape is (1, 4) instead of (1, 1, 4)? | KFrank | Hi Dio!
Two pieces of behavior combine together to produce the results you
are seeing.
First, the trailing dimensions of a that you are not indexing are simply
carried along unchanged. Another way of saying this is that the trailing
dimensions are implicitly sliced with full slices.
The dime… |
nitay_shlump | Below is my code for a UNET model. How can I change its backbone to the CNN model mobilenetv3_large_100? Also, the images I wish to train it on are grayscale.class double_conv(nn.Module):
def __init__(self, in_ch, out_ch):
super(double_conv, self).__init__()
self.conv = nn.Sequential(
nn... | KFrank | Hi Nitay!
Probably the most practical approach would be to rewrite your U-Net
to use MobileNet’s “depthwise separable convolutions” and follow its
structure in how much it downsamples in each block.
The issue is that you have to hold on to references to the outputs of the
downsampling blocks s… |
Lebourdais | The Threshold activation function doesn’t seem to be differentiable (Gradient should be 0 everywhere except on the jump where it’s non differentiable).How is handled the backpropagation with this type of activation function, is it ignored ? | KFrank | Hi Lebourdias!
Pytorch’sThresholdis (usefully) differentiable. When its input, x, is
greater than the threshold value, its output is x and the gradient is 1.0.
This description describes a step function (the Heaviside function),
rather than pytorch’s Threshold.
For a step function (whose … |
Aniruth_Sundararaja1 | This is my Visual Question Answering Modelclass VQAModel(nn.Module):definit(self, num_questions):super(VQAModel, self).init()self.cnn = models.resnet50(pretrained=True)
self.cnn.fc = nn.Identity()
self.question_embeddings = nn.Parameter(torch.randn(num_questions, 512))
self.fc = nn.Linear(2048 + 512, 1) ... | KFrank | Hi Aniruth!
Works for me.
Here is a script that contains your model, together with some code to run it:
import torch
print (torch.__version__)
import torchvision
print (torchvision.__version__)
from torch import nn
from torchvision import models
_ = torch.manual_seed (2024)
class VQAModel(nn.… |
Mahammad_Nabizade | I tried FocalLoss, TverskyLoss, Focal_Tversky_Loss, DiceLoss, BCEWithLogitsLoss , none of them work well for now. P.S I also have data problem, the number of images are few (around 4k for training, 1k for validation) and maybe that is the source of issue.What are some best case practices for binary segmentation with cl... | KFrank | Hi Mahammad!
Okay, as I understand it, you want to train on data from scene A.
But you want your model to work on data from scenes B, C, D and E, F, G.
Yes, given your use case, this could be considered a kind of data leak.
This is an issue all the time in the real world. Let’s say you train… |
isfet | Hi, im trying to train a convolutional autoencoder over a dataset composed by 20k samples. Each sample is an array of 65536 elements, each one is float value. i want to train the autoencoder to reduce the dimension of the dataset from 65536 → 1024 elements and than use the reduced dataset to train a DNN. The following ... | KFrank | Hi Michele!
Okay, in that case you do not want to use convolution layers – that’s
not how convolutional layers work.
I assume that your goal is to train your encoder somehow to get the
length-1024 output and that you’re using an autoencoder so that you
can train the encoder by using some sort … |
AlphaBetaGamma96 | How can I create atorch.distributionclass that samples an N-dimensional discrete space ofKclasses each?I initially thought of usingmultinomial(docs:here), but that would require initializing an array, which scales exponentially with respect to the number of dimensions (i.e. the sampling array would beK^Nin size).If I f... | KFrank | Hi Alpha!
If I understand what you are looking for, I think multinomial() will
work just fine for you. As I understand it, you are not looking for any
kind of correlation between class values in different dimensions, so
if this is the case, you should be able to “factor” the random sampling
a… |
roach | Hey everyone, i was doing some preprocessing on my data and realized that converting an array to a long torch tensor was consuming one of my classes. I’m pretty confused as to why this is happening. To give some context, my masks were created via VTK in C++ from cardiac contours.Anyone might have any idea why this is h... | KFrank | Hi Roach!
Your print precision is such that a number less that 2. is being displayed
as 2.. Your pytorch .long() conversion truncates this value down to 1
(as expected).
Consider:
>>> import torch
>>> torch.__version__
'2.3.1'
>>> import numpy as np
>>> np.__version__
'1.26.4'
>>> q = np.arra… |
Keahi | Hi, everyone! I’m currently working on a medical image detection task based on chest X-ray images as my undergraduate final project, in which the dataset is composed of Pneumonia with 4273 images, Normal class with 1583 images, COVID-19 with 576 images, and I used ViT(replicate by myself from scratch) as the model arch... | KFrank | Hi Keahi!
Check for bugs, of course, but it could simply be that you have to train for much
longer than thirty epochs.
Your dataset is imbalanced, but not ridiculously so. Your dataset is not particularly
large, but with 576 images in your smallest class I would think you would have enough
da… |
vlacerda | I am trying to sort a tensor first column-wise, preserve this sorting, and sort the second column accordingly. The tensors are always 2d, and they contain only torch.int64 elements.The intuitive way to think about it is that each row represents a sample, and I want to sort these samples in ascending order, first by the... | KFrank | Hi Victor!
Yes, stable will be part of the approach.
Because you want to reorder the rows themselves, rather than the elements within
a given column, you will need to index into a with the sorted-order indices given by
argsort().
Then, using a standard approach for sorting by a “primary” and “… |
peepeepoopoo | Hi! I recently ran into this issue where when using torch.nn.Softmax() under model init, I would find my output classifier without softmax applied.So in this case, when defining modelinit:class TestNet(nn.Module):
def __init__(self, num_classes=1000 ):
super(TestNet,self).__init__()
...
... | KFrank | Hi Xinan!
Works for me. Here is a script that tests your TestNet:
import torch
print (torch.__version__)
_ = torch.manual_seed (2024)
import torch.nn as nn
class TestNet(nn.Module):
def __init__(self, num_classes=1000 ):
super(TestNet,self).__init__()
# ...
## full… |
MLAlex1 | Hi,assuming I have computed the gradient of a loss of a neural network wrt an image of say shape (3, 224, 224), how do I then compute the corresponding orthogonal gradient?Thanks! | KFrank | Hi Alex!
If I understand correctly what you are asking, the problem is that @ is giving you
matrix multiplication, rather than a scalar dot product.
Consider:
>>> import torch
>>> torch.__version__
'2.3.0'
>>> imag = torch.randn (3, 224, 224)
>>> grad = torch.randn (3, 224, 224)
>>> orth = grad… |
Mohammed_Alruqimi | Can I fore pytorch to gradiant parameter values in restricted bound ?For example:I have this torch paramaterclass Model(nn.Module):
def __init__(self, args):
super(Model, self).__init__()
self.m = nn.Parameter(torch.tensor(0.02), requires_grad=True)I want to m values to be between 0.1 and 0.9 | KFrank | Hi Mohammed!
You ask about restricting gradients.
But then you ask about restricting the value of a Parameter itself. Let me assume
that you want to restrict the Parameter itself, rather than its gradient.
(Note that in your example, you are asking that m lie between 0.1 and 0.9, but
you are… |
LIUJUN | matmul799×270 24.2 KB | KFrank | Hi Jun!
If I understand your question correctly, you wish to apply some function, f(),
to each scalar product of the form m * n in your matrix multiplication before
you add them together.
That is, for A with shape [3, 2] and B of shape [2, 3] your product matrix
A @ B will have shape [3, 3], wh… |
Sohaib_Ahmed | In the official implementation of sift by Microsoft/Debertahere, they implemented symmetric_kl function as:def symmetric_kl(logits, target):
logit_stu = logits.view(-1, logits.size(-1)).float()
logit_tea = target.view(-1, target.size(-1)).float()
logprob_stu = F.log_softmax(logit_stu, -1)
logprob_tea = F.log_so... | KFrank | Hi Sohaib!
The Kullback-Leibler divergence is a particular measure of the dissimilarity
of two probability distributions. It is closely related to cross entropy. It takes
on its minimum of zero when the two probability distributions are the same.
The symmetric_kl() you are asking about is bas… |
imperialn00b | Hi, I want to compute the average of everyNelements in a 1D torch tensor of sizeM. As an example, if my tensor wastensor([7, 4, 8, 2, 6])andN = 3, I want the output to betensor([6.3333, 4.6667, 5.3333])- since(7+4+8)/3 = 6.3333,(4+8+2)/3 = 4.6667, and(8+2+6)/3 = 5.3333.To be precise, my input tensor has dimensions(d_0,... | KFrank | Hi Imperial!
Set up aConv1dthat has the desired kernel. For the example you give, you
would want a kernel_size of 3 and you would set all three kernel values to
0.33333.
If I understand what you want here correctly, you would first select out the idx
slice of dimension d_n. Then reshape() … |
mkorycinski | Hi,I am designing a NN layer which uses a function specified by a set of parameters. These parameters, which shall be updated in backprop, are not directly involved in logits computation. Hence, they are not updated out of the box.Is there a way to pass a gradient through them explicitly? | KFrank | Hi Mateusz!
It turns out that pad_size is greater than len(p_x) so your for i loop tries
to loop over a range() with a negative argument causing the body of the loop
not to be executed. kernel (which is basically WaveletLayer.low_pass and
WaveletLayer.high_pass) never gets assigned into result,… |
Fabrice_Auzanneau | HiI designed a classification model that I want to train on ‘noisy’ ground truth values. This means that for a given forward propagation, leading to say 10 output values, I’d like to create a ground truth tensor which is not one hot encoded, but made of one most important probability and 9 others that are not equal to ... | KFrank | Hi Fabrice!
Let me assume that you are using CrossEntropyLoss as your loss criterion.
CrossEntropyLoss takes two kinds of ground-truth targets. One consists
of integer class labels, with no class dimension. The second consist of
floating-point probabilities for each of the classes and has a … |
ranon-rat | Hello im trying to build a d3qn agent but i have problems when i try to train the model.4For some reason in the first iteration there is no problem but in the second one it gives me the next error:264 # some Python versions print out the first line of a multi-line function
265 # calls in the traceback and s... | KFrank | Hi Ranon!
I am going to speculate as follows:
The first time through, hidden doesn’t depend on the parameters of lstm.
However, the second time through the (old) hidden depends on the parameters
of lstm before they were updated by optimizer.step().
In general, optimizer.step() modifies inplace… |
leoseak2 | I tried to build my own loss function that uses the torch.sort (it is a sequential ranking problem). Here is the code:def loss_fn(output, target):sorted, indices =torch.sort(output,descending=True)loss = torch.mean((output - target)**2)loss2 = torch.mean((indices - target)**2)return loss2When I return the loss, there’s... | KFrank | Hi Leo!
The core problem is that indices consists of discrete integers (in particular,
longs), so it is not (usefully) differentiable.
This means that what you are trying to do probably doesn’t make sense.
But if it were to make sense somehow, you would have to find a usefully
differentiable p… |
akt42 | I’m trying to implement a learnable loss weight for a multi-task setup. (mostly inspired from:How to learn the weights between two losses?)The following snippet is a minimal example of a multi-task model and a mult-task loss with a learnable loss weight.The issue is the following implementation only updates the loss we... | KFrank | Hi akt42!
This line breaks the computation graph that links losses back to your
model parameters. So when you backpropagate, the .grad properties
of your model parameters remain None and your optimizer doesn’t update
the parameters.
Change the line to losses = torch.cat (losses) (or something… |
Yasin_K | Hi everyone,I’m encountering an issue while creating a tensor from an input matrix and performing further analysis on it in PyTorch. My code involves modifying a tensor withrequires_grad=True, but I’m running into aRuntimeErrorabout in-place operations.Code Snippet:import torch
def zero_dimension_Topology_computation... | KFrank | Hi Yasin!
When you create distance you are creating a new tensor that has
requires_grad set to True. This makes it a so-called “leaf Variable
that requires grad.” You are not allowed to modify such tensors in place
(as doing so messes up how autograd keeps track of what it is supposed
to be … |
sprakashdash | I have an index tensor like we send input to a bert model after tokenization, so the shape is[batch_size, seq_len]and I have to return a tensor with0’s and1’s (1’s where the indices are matched) of shape[batch_size, seq_len, vocab_size]. | KFrank | Hi Satya!
I believe that you are looking for torch.nn.functional.one_hot():
>>> import torch
>>> torch.__version__
'2.2.2'
>>> _ = torch.manual_seed (2024)
>>> x = 10 * torch.rand(4, 10) - 1
>>> x = torch.tensor(x, dtype=torch.int64)
<stdin>:1: UserWarning: To copy construct from a tensor, it is … |
FezTheImmigrant | When running the below code, I get the following issue:RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [8, 1]], which is output 0 of AsStridedBackward0, is at version 2; expected version 1 instead. Hint: enable anomaly detection to find th... | KFrank | Hi Sergio!
optimizer.step() modifies the parameters of your model inplace, and, in
your first version, causes the inplace-modification error.
For count = 0, you compute loss and assign it to loss_1. loss_1 is
linked to the parameters of model by the computation graph.
For count = 1, you comp… |
hzzt | Given a multidimensional tensor, I want to find the max position for each row in the last dimension, and then extract 50 elements before and after each max position.x = torch.rand(2, 4, 256)
peak, i = torch.max(x[...,50:-50], dim=-1)But when I try to slice according to indicesi, I get an errorx_subset = x[...,i-50 : i+... | KFrank | Hi hzzt!
gather() will do this if you prepare an index tensor and then offset it with
i (the argmax() of x):
>>> import torch
>>> print (torch.__version__)
2.1.2
>>>
>>> _ = torch.manual_seed (2024)
>>>
>>> x = torch.rand (2, 4, 256)
>>> peak, i = torch.max (x[..., 50:-50], dim = -1)
>>>
>>> ind… |
ElijahZh | In PointNet++, suppose the input point data shape is [1, 3, 1024, 32] where the 1024 the centroids, and 32 is the neighbors and 3 is xyz coordinate with batch size as 1.The input data is passed into nn.Conv2d(in_channels=3, out_channels=64, kernel_size=(1, 1))Can we use nn.Linear instead of nn.Conv2d:Change the input p... | KFrank | Hi Elijah!
Yes (although I’m not sure what the point would be).
Consider the following example (with fewer centroids and neighbors for
convenience):
>>> import torch
>>> print (torch.__version__)
2.2.1
>>>
>>> _ = torch.manual_seed (2024)
>>>
>>> conv = torch. nn.Conv2d (in_channels = 3, out_ch… |
v_kubicki_github | Is the formula presented atSGD — PyTorch 2.2 documentationfor each sample or for a mini-batch ? I ask because I want to know if for a mini-batch of size n, the formula used internally would be g_t ← g_t + n λ_{θ_t−1} instead of g_t ← g_t + λ_{θ_t−1}.Thanks | KFrank | Hi Vincent!
It’s neither. SGD is unaware of your batch size or even whether you used
a batch at all.
All SGD does is update your parameters with a gradient-descent step based
on the .grad properties of those parameters. It knows nothing about how
those .grads were set. They could come from … |
Veter | I’m currently using PyTorch on a AMD CPU Epyc Gen2. I notice that sometimes (with a batch of, for example, 200) it uses several cores, but not more than half.The next point worries me. When I call the top command (I work on Linux), I see that the processor is busy with the Python process.I expected that PyTorch would c... | KFrank | Hi Veter!
This is to be expected. When you run python (before you have python
execute a script that happens to run some pytorch stuff), the python
interpreter runs as a process. When you import pytorch (and maybe
when you actually execute some pytorch stuff), the python interpreter
executes … |
songsong0425 | Hi, thank you for your effort in establishing PyTorch.I have a general question about the sampling strategy in theDataLoader.When I have a very imbalanced dataset with binary classes for the link prediction task, the basic sampler returns the randomly sampled cases while preserving the original ratio of classes.(In det... | KFrank | Hi Songyeon!
Yes, forcing each batch to contain the same number of negative samples as
positive samples is a perfectly legitimate way to sample data when you have
unbalanced binary classes.
(You could also reweight the samples in your loss function, for example,
by using BCEWithLogitsLoss’s po… |
TTeuZ | Hello guys!I’m working on fine-tuning a MobileNetV3 for binary classification. My first attempt was to change the classification layer to output one feature and use BCEWithLogisticLoss as my loss function and torch.sigmoid for prediction.Now, I want to check if the result would be better if I change to output 2 feature... | KFrank | Hi Paulo!
As an aside, just to be clear, you do not want to pass the output of your
classification layer through sigmoid() and then to BCEWithLogitsLoss.
You do not want use BCELoss with a two-output classification layer. It is
true that by using a two-output layer you are logically performin… |
Brian_Krause | I was trying to implement a few versions of local image normalization, all involving some variation of a Gaussian blur, then subtracting that from the original image. I kept getting odd results such as occasional images filled with all 0s or all -1s or similar. After some investigation, I was able to narrow it down to ... | KFrank | Hi Brian!
By design, an instance of GaussianBlur will use a randomly chosen
value of sigma to generate its gaussian kernel every time it is applied
to an image. This is true regardless of whether or not you have set
torch.use_deterministic_algorithms (True).
When your instance of GaussianBlur … |
i4ata | I have the following expression:import torch
torch.manual_seed(0)
x = torch.rand(3,7,7,5)
mask1 = x[:,:,:,4] > .5 # <- [3,7,7]
x1, x2 = torch.rand_like(x), torch.rand_like(x)
mask2 = torch.rand(len(x[mask1])) > .5 # <- [74]
print(x[mask1].size(), mask2.size(), x1[mask1].size(), x2[mask1].size())
x[mask1] = torch.wher... | KFrank | Hi i4!
First, you have a typo in this line – you want x2[mask1] (rather than
x2[mask2]).
Your core problem is that the arguments you pass to where() don’t
have the same shapes, so where() tries tobroadcastthem, but the
shapes aren’t broadcastable.
Specifically, the last dimension of mask2 i… |
taha_entesari | I have tried to recreate the error that I get for a code in this simple code snippet.Why does the following code throw an error?If you run this code, it will run into an error the second time it goes into the training loop on line 18 (“self.matrix2 = result”) that “TypeError: cannot assign ‘torch.FloatTensor’ as parame... | KFrank | Hi Taha!
The short story is that Modules treat Parameters specially.
For example, quoting fromthe Parameter documentation:Parameters areTensorsubclasses, that have a very special property when used with Module s - when they’re assigned as Module attributes they are automatically added to th… |
Yedidya_kfir | I have a network which takes a vector size 10 and returns a vector size 20.I want to calculate the jacobian for the output of the network.I used the codetorch.autograd.functional.jacobian(func=network, inputs=x)to calculate it and it worked, I get the correct matrix size 20 * 10however when I try to do it over an entir... | KFrank | Hi Yedidya!
If I understand what you want to do, I believe that@AlphaBetaGamma96’s
post that uses vmap() and jacrev() will give you your “batch jacobian:”
Best.
K. Frank |
Siladittya_Manna | Suppose,his the output embedding vector of a network. Now, out of the D dimensions ofh, I multiply the last ‘dr’ dimensions with 0 before passing it to the loss function, while keeping the rest of the (D - dr) dimensions unchanged. That is,h = [h1, h2, h3, ... hk, 0, 0, 0, ..., 0, 0]This is done for all the output embe... | KFrank | Hi Siladittya!
Yes (because the gradient of zero is zero).
You can check this with a simple script:
>>> import torch
>>> torch.__version__
'2.2.1'
>>> t = torch.arange (1.0, 11.0, requires_grad = True)
>>> m = torch.ones (10)
>>> m[7:] = 0.0
>>> m
tensor([1., 1., 1., 1., 1., 1., 1., 0., 0., 0.])… |
BaeHann | Hi ,everyone. After I initialized the following class, no attribute can be found in the initialized member, let alone the subsequent training process. However, if I erase the nn.Module, not setting the InceptionTime as a subclass of nn.Module, the initialized member contain all the attributes as designed. I am curious... | KFrank | Hi Hann!
You need to explicitly initialize the superclass, Module, as well as the class
itself, InceptionTime.
Add super().__init__() to InceptionTime’s __init__() method. Doing
so will call the superclass’s (Module’s) __init__() method (with no explicit
arguments).
(Unlike some other langu… |
Liran_Ringel | I’m trying to get the gradient of each sample like that:grads = torch.autograd.grad(losses, model.parameters(), torch.eye(len(losses), device=losses.device), retain_graph=True, is_grads_batched=True, allow_unused=True)wherelossesis a vector of losses, one for each sample.It works. However, it is significantly slower th... | KFrank | Hi Liran!
This line of code computes a batch of gradients, one for each element of
losses. (It should be faster than a python loop because autograd.grad
presumably uses vmap() vectorization under the hood, but it still performs
multiple gradient computations.)
This line of code, however, com… |
Ilya_Kotlov | Hi, I get a strange error in the second iteration after the first iteration worked fine (PyTorch 2.1.2):Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass
RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have alread... | KFrank | Hi Ilya!
It is true that you only have one line of code that calls .backward(), but
that line of code exists in a loop that runs multiple times. When the second
iteration of the loop runs, you call .backward() a second time, causing
the error.
beta_init is a trainable parameter (as it has re… |
pretbc | Hello all,Ive a data as below:| clip | happy | sad | anger | surprise | disgust | fear | neutral |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 1 | 0.44 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 |
| 2 | 0.67 | 0.0 | 0.0 | 0.11 | 0.0 | 0.0 | 0.0 |
| 3 | 0.11 | 0.0 | 0.0 | 0.0 | 0.0 | 0.6 | 0.0 |
| 4 | 0.44 | 0.0 | ... | KFrank | Hi pretbc!
Because the score for each emotion ranges from zero to one (and there
is no constraint that the values sum to one), it is reasonable to treat each
emotion score as if it were a probability.
Because multiple emotions can occur for a single clip and the emotion
scores are (in some se… |
Etienne_Guichard | Is there any way to convolve a function channel-wise over a tensor?I have a tensor of sizeu = torch.size([8,16,32,32])= (N,C,H,W)and trainable parameters:mu = torch.Size([16])
sigma = torch.Size([16])Batch-wise, to every channel in the tensor I want to apply the function:def growth_func(self, u, mu, sigma):
ret... | KFrank | Hi Etienne!
I’m not sure what you mean by "“convolve.”
I think you are asking how to apply your function element-wise to your
tensor u, taking into account that each of the 16 channels has its own
value of mu and sigma.
(To me, “convolve” implies that you have a sliding window that mixes
neig… |
PytorchLearning | Hi all,I want to use ‘optimiser = optim.LBFGS(model.parameters(), lr=1e-4)’ instead of ‘optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)’but I didn’t know how to introduce ‘def closure():’can someone please explain to me how to modify the following code to use optim.LBFGShere is the code:def train_model(model,... | KFrank | Hi Py!
The short story: closure() basically packages the forward / backward
pass of the training loop that you would use for a “conventional” pytorch
optimizer such as SGD. But why?
You are optimizing (specifically minimizing) your loss as a function of
the parameters of your model.
With mo… |
yupeng_chou | I only backward once.Why this happen?If I don’t add detach on radical_template,this code can not run.radical_template = []
for step,img in enumerate(radical_dataloader):
backbone1.train()
img = torch.unsqueeze(img,dim=1)
img = img.to(device)
fe... | KFrank | Hi Yupeng!
I assume that backbone1 is a model with trainable parameters. If so, at
this point radical_template depends on backbone1 and is attached to
a computation graph that leads back to those parameters.
At this point, sim has been detach()ed from any and all computation graphs,
so it co… |
Gears_Gears | Hi Community,To compute the gradient of loss with autograd.grad(), do I need to say loss.backward() first? I need these gradients to help me update the model, but I’m doing two backward passes, so autograd is needed. I’m wondering if the additional backward pass using autograd also needs .backward().Many Thanks! | KFrank | Hi Gears!
No., no need to call loss.backward() first.
The two functions do similar things: autograd.grad() computes and returns
gradients with respect to its inputs argument, while loss.backward()
computes gradients with respect to the leaf variables of the graph of which
loss is the root and… |
Kore_ana | I want to compute $x^TAx$ where $x$ is a vector and A is a matrix (i.e. bilinear form). Although nn.Bilinear would work, in my case $A$ is block-diagonal. So, I wanted to create ann.Modulethat would compute this using much less memory and computation by only remembering the block diagonal matrices.For example, Below is... | KFrank | Hi Kore (aka Danny)!
I don’t believe that there is any way (without a loop) to perform your
computation with Bilinear that doesn’t have inefficiencies such as
multiplying things with the zero blocks.
Probably the simplest way to perform the necessary tensor multiplications
is to useeinsum().… |
shc443 | Hello I am currently sampling data from different kernels (Gaussian, Laplacian, Matern, etc)The issue is thattorch.distributions.multivariate_normal.MultivariateNormalraises aValueErrorsaying that my kernel is notPositiveDefinite()I check my kernel usingtorch.linalg.eigvals, and some of the eigenvalues are actually neg... | KFrank | Hi shc!
Scipy is most likely computing the eigenvalues in double precision, while
pytorch is most likely doing so in single precision. Try performing your
pytorch in double precision and see if that resolves (or at least reduces)
your issue.
If not, please post a simple, fully-self-contained,… |
mmitjans | Hi!I have a matrixKthat I represent with an LU factorization, such thatK = L @ U, andLandUare lower and upper triangular 2-D tensors respectively. I’m currently testing the functionality oftorch.linalg.lu_factorwithpivot=False, which enforcesP(the permutation matrix) to be the identity.In my sample code I have the foll... | KFrank | Hi Marc!
Even when you turn off pivoting, lu_factor() still performs the non-trivial
LU factorization and returns the “packed” factorization in LU_factor. So
LU_factor is not the original, unfactored K. (Why would it be?)
Here is a script that illustrates this by constructing the “packed” fac… |
alexgagnon | I’m trying to create a tensor of shape (n, m, o) from a normal distribution, but using a mean in the shape (m, o). It appears torch.normal only allows settingsizewhen mean and std are numbers. For example in the simple case, I’m trying to create shape 5, 1, 1.mean = torch.tensor([[0.0]])
std = torch.tensor([[1.0]])
pr... | KFrank | Hi Alex!
You can either expand() mean and std to add your “batch size” of n = 5
or use torch.distributions.Normal to whose .sample() method you
can pass n (packaged as a tuple):
>>> import torch
>>> print (torch.__version__)
2.1.1
>>>
>>> device = 'cuda'
>>>
>>> mean = torch.tensor ([[0.0]]).to… |
Xavier_Aramayo_Carra | Hello, I am trying to compute the gradient of the following quadratic expression: x.T@A@x where x is a vector with n samples and m features and A is a matrix m times m, the direct derivative of this expression with respect to x is x@(A + A.T), I am trying to get this derivative using autograd function but I couldn’t do... | KFrank | Hi Xavier!
It’s not entirely clear what you are trying to compute here. (Note that
here you have the transpose in the wrong place, but you have it correct
in your sample code.)
Correcting the transpose, your expression x @ A @ x.T has shape
[n_samples, n_samples], so it’s unclear what you wan… |
Seungdae_Han | Hi, I am training my network using accelerator, which based on torch distributed parallel.But strangely, I came across the ‘Inplace error’ when I use distributed training.I thought it over and over but I couldn’t find the reason why.Can someone help me for this problem?Codeimport torch
from torch import nn
import ein... | KFrank | Hi Seungdae!
Try the suggestions in the following post and see if they help with your
debugging:
Best.
K. Frank |
PeaBrane | I’m just curious iftorch.compileis able to performopt_einsumstyle optimizations, where the order of matrix multiplications is optimized to reduce compute.The minimal example here is@torch.compile
def matmul(A, B, C):
return A @ B @ CIn the case where, say,Ais 1000 x 100,Bis 100 x 10, andCis 10 x 1, it is clearly mo... | KFrank | Hi Pea!
This does not appear to be something that torch.compile optimizes.
It’s speculation on my part, but I don’t think that torch.compile knows
that it is doing matrix multiplication (nor realizes that matrix multiplication
is associative).
Note thattorch.linalg.multi_dot()has this matrix… |
RuiZhangJerry | Hi, everyone. I plan to calculate the derivative of the Bessel function via the “autograd” function, the code isScreenshot 2023-11-17 at 19.13.401962×828 93.1 KBbut I received an error:Screenshot 2023-11-17 at 19.14.581920×947 263 KBIf I add the “requires_grad_(true)” to the “y”, just like this:Screenshot 2023-11-17 at... | KFrank | Hi Rui!
As near as I can tell, pytorch does not implement backward() for
torch.special.bessel_j0() (nor torch.special.bessel_y0()),
although I cannot find this explicitly documented anywhere.
It seems like a number of functions in torch.special don’t have
backward() implemented. The only rela… |
dev1 | I know there are similar posts. I nearly checked them all. Tried.detach(). andretain_graph=Trueoptions. However I couldn’t solve it for my training loop of DCGAN. This is a fairly complex training loop for me so I wouold be glad for any help. I also checked the PyTorch tutorial and created this version.criterion = nn.B... | KFrank | Hi Uygar!
As a general principle, don’t just try things. Analyze the actual cause
of your specific issue and use the “option” that actually addresses that
cause.
Please look at the comments that I’ve added in line to your quoted code:
The key issue is that you are using discriminator_fake_ou… |
Bernardoolisan | I am attempting to implement the Proximal Policy Optimization (PPO) algorithm using PyTorch. My implementation is based on my understanding of how the PPO algorithm works. At a high level, the process of my implementation looks something like this:First, we need to initialize the Policy Network with random parameters.T... | KFrank | Hi Bernardo!
I assume that the outputs of your Value functions depend somehow on
your Policy Network and that you need to take these dependencies into
account when you optimize your Policy Network. (If not, you could get
rid of the retain_graph =True and .detach() the outputs of your Value
f… |
Aobo_Chen | When I was trying to add a perturbation to a model and optimize the perturbation itself but not the model parameters. I did like the following, which is very simple:import torch
import torch.nn as nn
import torch.optim as optim
# Define a simple model
class SimpleModel(nn.Module):
def __init__(self):
super... | KFrank | Hi Aobo!
The short answer is that the (public-facing) use of .data is deprecated and
can lead to errors.
More generally, pytorch really doesn’t like to let you modify Parameters
(such as self.linear.weight) while they are being tracked by autograd.
To fix this issue for the use case you posted… |
dev1 | Hi everyone. I’m trying to implement the code forDETRfrom the paperEnd-to-End Object Detection with Transformers. I need to useresnet50.The first part of the code looks like this:class DETR(nn.Module):
def __init__(self, num_classes, hidden_dim, nheads, num_encoder_layers, num_decoder_layers):
super().__init__()
... | KFrank | Hi Uygar!
First, a minor issue:
x = self.backbone([input]) is almost certainly a typo. input is a built-in
python function. You want inputs instead of input.
The bigger point is that inputs is a tensor – appropriate to pass into the
Conv2d that is the first layer of resnet50. But you are wr… |
bradbell | I tried posting this as a continuation of the following post and did not get a response:Reusing Jacobian and Hessian computational graphautogradIt seems that PyTorch is more or less at the level as JAX for the gradient computation
That’s good news, that needs that your ops are big enough that the creation of the grap... | KFrank | Hi Brad!
The short story is that you are using .data which is deprecated (in the
public-facing api) and can lead to errors (such as yours).
This works for your 2-by-2 case, in essence, by accident.
When you compute az, autograd stores some of the product tensors,
e.g., ax[1,1] * ax[2,2], as t… |
JosueCom | So, I have this function:def ode_residual(self,
time: th.DoubleTensor,
state: th.DoubleTensor) -> th.DoubleTensor:
dtheta = th.autograd.grad(state.sum(), time, retain_graph=True)[0]
d2theta = th.autograd.grad(dtheta.sum(), time, retain_graph=True)[0]wheretimeand 2 tensors ... | KFrank | Hi Josue!
MLP is basically a Sequential that consists solely of Linear layers with
no intervening non-linearities. It therefore collapses, in effect, into a single
Linear (1+2+2, 1+2+2) (with a bunch of redundant parameters) regardless
of the values of width and depth.
So the time component o… |
XFeiF | I’m using a linear layer to reduce the dimension of input tensors.I have two input tensors converted from numpy arrays, these two arrays:they are generated by a same function‘a1.npy’ is generated lonely‘b1.npy’ is generated with other dataa1 equals to b1 ( I tried a lot of methods to compare them)Then, I convert these ... | KFrank | Hi XFeiF!
Perhaps because a1 and b1 are created somewhat differently, their elements
are stored differently internally even though they are equal.
Consider (in pytorch, not numpy):
>>> import torch
>>> torch.__version__
'2.1.0'
>>> t1 = torch.tensor ([[1, 2, 3], [4, 5, 6]])
>>> t2 = torch.tenso… |
Sourabh_Patil | Hi,I have a pretrained model which has a linear layer. It had parameter bias=False while training. I want to make bias=True in the same model, as it has some dependencies while converting model to onnx. Is there any way to do it, so that performance stays the same. | KFrank | Hi Sourabh!
The simplest way to do this will be to replace the Linear in question with
a new Linear with bias = True and then initialize the new Linear’s weight
(and bias) with the values from the old Linear.
You need to get your hands on the Linear in question somehow. It will typically
be a… |
GoodarzMehr | Hi,I have a nested for loop that does some masking and summation as below:for i in range(200):
for j in range(200):
xlim = bev_limit - i * bev_resolution
ylim = bev_limit - j * bev_resolution
pcm_mask = (transformed_coordinates[0] <= xlim) & \
(transformed_coordinates[0] >= xli... | KFrank | Hi Goodarz!
Yes, at the cost of materializing a large mask tensor.
The idea is to perform the masking by multiplying with zeros and ones, rather
than selecting a subset of elements by “indexing” with a boolean tensor, and
use einsum() to perform the multiplications and summation.
Your example … |
rphellan | Hello, I am working on a lung nodule classification problem, as either benign or malignant. The inputs are CT volumes in 3D. We have segmentations for each nodule, so all other tissues around the nodule are removed.The dataset is highly imbalanced, with thousands of benign nodules samples, and only a few hundred malign... | KFrank | Hi Renzo!
Depending on the details of your use case and the complexity of your model,
a few hundred positive samples might not be enough to train effectively. (You
should be able to overfit and get “good” results on your training set, without
necessarily getting good results on your validation… |
Mehran_Ziadloo | This is a rather fundamental question and if I want to be honest, not really a PyTorch question.Let’s say that I have two linear layers:layer1 = nn.Linear(input_size, hidden_size)
layer2 = nn.Linear(hidden_size, output_size)I’m going to populate the input tensor like this:input = torch.randn(batch_size, arbitrary_size,... | KFrank | Hi Mehran!
If you have two Linears, one after the other without any intervening
nonlinear activations (such as relu() or sigmoid()), then they collapse,
in effect, into a single Linear (input_size, output_size).
The output in the two cases will be numerically equal, up to some floating-point
… |
Tanay_Rastogi | I am quite new to Pytorch and currently running into issues with Memory Overflow.Task:I have two 2D tensors of respective shapes A: [1000, 14] & B: [100000, 14].I have to find the distance of each row of tensor-A from all rows from tensor-B. Later using the calculated distance values, I find the mean of minimum/mea... | KFrank | Hi Tanay!
Use torch.cdist().
Consider this script:
import torch
print (torch.__version__)
print (torch.version.cuda)
print (torch.cuda.get_device_name())
_ = torch.manual_seed (2023)
A = torch.randn (1000, 14, device = 'cuda')
B = torch.randn (100000, 14, device = 'cuda')
print ('A.shape: … |
Steve-Stewart | Does pytorch have a function that calculates thepolar decompositionof a matrix likescipy.linalg.polar? The functiontorch.polaris an entirely different one. If not, why does pytorch choose to omit this feature? | KFrank | Hi Steve!
Not that I’m aware of.
Perhaps pytorch should provide polar decomposition. But it’s straightforward
enough to implement it in terms of pytorch’ssingular-value decomposition.Here is such a pytorch implementation in a script that verifies its result against
scipy and checks its aut… |
Met4physics | The detail error is:Traceback (most recent call last):
File "/root/DRIVE/main.py", line 147, in <module>
loss.backward()
File "/root/miniconda3/lib/python3.8/site-packages/torch/_tensor.py", line 363, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph, inputs=inputs)
File "/roo... | KFrank | Hi Met!
Spiking neural networks maintain some state. If in your SNN implementation,
that state hangs on to part of pytorch’s computation graph, it could plausibly
cause the error that you’re seeing.
It appears that this may be what’s happening with the SpikingJelly package
you are using. Quo… |
jerron | This is revisit thisold question: How about mean on the columns for 2D array? torch.mean can take parameter dim to return mean for each column. Can we do so with mask filtering out certain bad values? Although we can loop through each column like following, is there better way?for i in range(y['train'].shape[1]):
... | KFrank | Hi Jerron!
This looks like one of the use cases for which pytorch’s prototpyeMaskedTensorwas developed.
Here’s a simple example:
>>> import torch
>>> torch.__version__
'2.0.1'
>>> t = torch.arange (3.)
>>> t
tensor([0., 1., 2.])
>>> m = t != 2.
>>> m
tensor([ True, True, False])
>>> mt = tor… |
dots | I’m trying to make a tensor subclass that has an extra instance attribute to store data, and I need to store multiple of these subclass objects in a tensor. When I usetorch.stackto store them, the elements of the stacked tensor no longer have the extra attribute that they were assigned.Do you know how we can store mult... | KFrank | Hi Dots!
The core problem is that a Tensor is in no sense a collection (e.g., a list)
of Tensors (nor a collection of other objects). You can’t store a Tensor (nor
another object) “in” a Tensor.
A regular Tensor object does not have an extra attribute. But furthermore,
your tensorExtra obj… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.