user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
LeanderK
I have a 2d-matrix and I want to split it using a checkerboard pattern. example:1, 2, 3, 4 5, 6, 7, 8 9, 10, 11, 12into1, 3, 5, 7, 9, 11,and2, 4 6, 8 10, 12this should be:a = x[:, :, 0::2, :]andb = x[:, :, 1::2, :]but now if I haveaandb, how can I revert the transformation?
tom
Depending on your style preferences, there are x = torch.empty(a.size(0), a.size(1), 2*a.size(2), a.size(3), dtype=a.dtype, device=a.device) x[:, :, 0::2, :] = a x[:, :, 1::2, :] = b and x = torch.stack([a, b], 3).view(a.size(0), a.size(1), 2*a.size(2), a.size(3)) you could try. The latter work…
LeanderK
I have a polynomial and I need to evaluate it element-wise across a tensor.For example f(x) = ax^3 + bx^2 +cx + d for some [a,b,c,d].[a,b,c,d] are constants.Is this possible with pytorch?
tom
You mean like x**arange(coeffs.size(0)-1, -1, -1)*coeffs when coeffs = torch.tensor([a,b,c,d])? Best regards Thomas
Mona_Jalal
How can I input a sentence and extract the feature vector from the layer before the last layer from BERT? I think it should be length 768.
tom
You can look at what theBertForSequenceClassification model does in it’s forward. The pooled_output obtained from self.bert would seem to be the features you are looking for. Best regards Thomas
youngminpark2559
Hi, I searched that I’d need to use clone() to avoid inplace operation issue.So, I cloned pred_R_imgs but I still have error.When I commented them out, error would disappear.Why does clone() work in this case?pred_R_imgs=Net(O_img_tc) pred_R_imgs[pred_R_imgs.clone()==0.0]=0.0001 pred_R_imgs[pred_R_imgs.clone()==-0.0]=0...
tom
Yes, but you haven’t changed pred_R_imgs but only it’s clones. What you likely want is something like pred_R_imgs = torch.where(pred_R_imgs.abs()>1e-4 , pred_R_imgs, torch.tensor(1e-4)) Best regards Thomas
farazk86
Hi,I’m struggling with a dataset here as I only have the original 3D images of size512*512*30. The dataset represents a series of bright spots in 3D space which is my area of interest. The spots are of varying sizes across the z-plane.I want to train a network to segment these spots. But to do that I need a label or ta...
tom
Sorry for the delay. So I used indexing because I can never figure out scatter for more than one dimension, but this is what I had in mind import torch import math size = 100 coords = torch.randint(0,size, (50,3)) coords[:, 2] %= 30 # lazy trick, won't be uniformly distributed... t = torch.zeros…
Andrei_Sirazitdinov
Is there any efficient way to compute forward (f_i+1,j - f_i,j ) or backward (f_i,j - f_i-1,j ) differences on the tensor, for example, x = torch.rand(Bs, Nc ,Nx, Ny), where Bs - batch size, Nc-number of channels, Nx, Ny - dimensions in X and Y direction?
tom
You can either express these as convolutions with the stencils as weights (and number of groups=number of hannels) or do the slicing yourself e.g. dx = x[:,:,1:]-x[:,:,:-1]. This generally will give you the differences. To make them forward or backward, you would (zero-?) pad at the beginning or the…
Farhan_Samir
class MyLayer(nn.module): def __init__(self, num_units): self.weight = Parameter(torch.rand(num_units, num_units))I want to optimize all of the weights in the tensor except for the ones across the diagonal (i.e. the weights across the diagonal should stay fixed). What is the simplest way to exclude these we...
tom
After loss.backward() and before optimizer.step(), you can do model.layer.weight.grad.diagonal().zero_(). Having gradient entries constant to zero on every invocation should leave the values fixed with most optimizers. Sophisticated people might mention backward hooks, but I am not one of them. B…
Heizkessel
I’m using torch version 1.0.0.I am trying to perform a gradient descent optimization using two different optimizers: SGD and Adam from the optim package. Strangely, while the loss function obtained by Adam converges and is steadily decreasing, the loss with SGD increases dramatically from the start and contains nan aft...
tom
Due to the normalization implicit in Adam, the learning rates aren’t comparable to SGD, and you probably use a much too high learning rate for SGD. Best regards Thomas
kevin-ssy
Hey guys, I want to sum every k consecutive channels of a variable together. Assume that the input before summing is with the shape like NxCxWxH, and the output after the summation should be Nx(C/k)xWxH. I implemented the method using the code below. the function sum_up is called in the network’s forward function, but ...
tom
You can split the channel dimension with a view/reshape and sum n,c,h,w = input.size() res = input.reshape(n, c//k, k, h, w).sum(2) Best regards Thomas
KevNull
I’ve seen people say they’ve successfully build with GCC 5.4.0, and so have I, but has anyone built with anything more recent on Linux?I’m having problems integrating into a larger project that I think is due to using such different compilers, and the larger project does not compile with 5.4, hence why I’m asking. Any ...
tom
I’ve been one of the people who used GCC 5 for a long time. With recent cuda (I’m currently on 9.2) supporting newer GCC I had switched to 6 and this week (because I had trouble with MKLDNN’s use of -werror) to gcc 7. For my (CPU only) laptop, I always use the default compiler of Debian/unstable,…
torch_rookie
following is the definition of torch.addmm 's parameters:torch.addmm(beta=1,mat,alpha=1,mat1,mat2,out=None) → Tensorfromtorch — PyTorch 2.1 documentationbut under it there is an example:M = torch.randn(2, 3)mat1 = torch.randn(2, 3)mat2 = torch.randn(3, 3)torch.addmm(M, mat1, mat2)tensor([[-4.8716, 1.4671, -1.3746],[ 0....
tom
What happens here is that the addmm does have “overloads” to implement the behaviour that, as you correctly note, would not be possible using a single plain Python function. The twist is that the one using keyword only alpha and beta arguments is the preferred one (defined in aten/src/ATen/native/n…
beneyal
Hi there,I was looking through the PyTorch source code for LSTM and GRU, and I don’t see where their equations are in the code. Can anyone point me in the right direction?Thanks!
tom
They map to C++ code inATen/native/RNN.cpp, the same in thecudnn subdirectoryornative cuda kernels in the cuda subdirectory’s RNN.cu. You can see by following the same method asdescribed in my Selective excursion into PyTorch internalsblog post, with a little detour at the beginning from tor…
wwiiiii
I want to do the forward pass first, then repeatingregister backward hook=>backward propagation=>clear gradient and remove hook=>register another backward hook…to use several backward hook functions, those should not be registered simultaneously.However, it seems the backward hook function is handled in calling forward...
tom
The backward hook as is is essentially the same as a backward hook on the output variable. If you have a non-trivial module (i.e. one which performs more than one operation) then you won’t get input gradients of the module, but those of the last operation in the module. Best regards Thomas
mfajcik
I trained my model using arbitrary initial seed for randomness. I have printed the seed, (it is a large number,13248873089935215612). Now as I want to reproduce the training results, I want to set manual seed viatorch.manual_seed(13248873089935215612), but this throws me error intorch/random.pyat line 35 when executing...
tom
The seed is a signed 64 bit integer on the C++ side, so the maximum is (1<<63)-1. You could use “13248873089935215612 & ((1<<63)-1)” if you wanted to. Itend to be cautiousabout trying to be clever with random seeds, I’m not certain that your seed is any better than, say, 42. Best regards Thom…
AK47
Consider a nxm matrix A and a n-dimensional vector x whose entry is an integer from 0 to m-1. I’d like to mask A in a way such that A[i][j] is masked iff j > x[i]. I’m seeking for a method that utilizes GPU and PyTorch. I don’t think torch.gather is applicable here.
tom
How about mask = (A < torch.arange(0, A.size(1), device=A.device, dtype=A.dtype).unsqueeze(0)) masked_A = torch.where(mask, A, torch.zeros(1,1, dtype=A.dtype, device=A.device)) where the arange will give you a vector of j and unsqueezing makes is broadcasteable to As shape, the comparison gives …
jjery2243542
I want to use high-order gradient with LSTMCell. However, this function is not supported. So I want to implement the cell with linear layer. Also, I want to initialize my lstm cell to a well-trained lstm cell.But I cannot find the order of the gates. The following is my implementation. I am wondering what is the order ...
tom
The order within the parameters is the same as for LSTM, so you can consult theVariables section in the LSTM documentation. Best regards Thomas
venkatasg
I have a custom Module with certain parameters. One of them is a ModuleDict() which has 2 parameters(Linear modules) for key values say ‘a’ and ‘b’ . Depending on the training example(one minibatch) provided, only one of these parameters should be used per minibatch in the forward pass - they key value for the moduledi...
tom
You’re not using an optimizer with momentum by chance? For those, the momentum will cause updates even when the gradients are zero. (It’s also doing funny things to the statistics, probably, but with dropout we rarely think about it too much.) As a trick you can (at least you could last time I c…
amankhandelia
I have this question aboutnn.CTCLoss, I would be grateful if anybody can answer the same.Example:loss = nn.CTCLoss() label = 'aman' label_dict = {<blank>:0, 'a':1, 'm':2, 'n':3}so should encode the label like thisencoded_label = [1, 2, 1, 3]or like thisencoded_label = [0, 1, 0, 2, 0, 1, 0, 3, 0]Note: Theseencoded_lab...
tom
You want encoded_label = torch.tensor([1, 2, 1, 3]), otherwise the CTC loss will tip over. The CTCLoss implementation does follow the alignment with the enlarged sequence, but does this “padding” on the fly. Best regards Thomas
soshishimada
I am thinking if using multiple optimizers can change the performance of the network comparing to having one optimizer.Say, I have Encoder-Decoder network but it has three encoders and three decoders in it.In this case, should I define each architecture and optimize separately as below?encoder1_optimizer = optim.Adam(e...
tom
There isn’t much point in having several optimizers of the same class, as the per-Parameter-computations will be the same. If you want different learning rates/other parameters, you can define parameter groups in one optimizer (you can see this e.g. infast.aiwho advocate using different learning …
lightG
Hi, recently I read a paper named “Large Scale GAN Training for High Fidelity Natural Image Synthesis”, where the scale and bias value are not learned by training, but come from Generation Conditions (Class label embedding and Noise z).However, I didn’t find any cues to implement this trick/architecture after reading P...
tom
There are better experts to answer questions about this paper on the forums, but for the batch norm: You can reuse the existing parts and add your own, for inspirations you might look at theconditional batch norm comments, and this one in particular. Best regards Thomas
lxtGH
I meet this error as following, is there some actions is not differentiable or in-place operation cause this error. I want to know how to debug this error.Traceback (most recent call last):File “training/train_super_pixel_net.py”, line 370, inmain(args)File “training/train_super_pixel_net.py”, line 103, in mainavg_loss...
tom
I would probably first try to establish where the exact location is. Due to the asynchronous nature of GPU computing, the error is usually reported later.A while ago, I wrote a quick howto for this.There some operations that may cause errors like this when used with invalid data, e.g. indexing fun…
Ingenieur
Hi everybody,I’m currently trying to figure out how to use PyTorch to optimize an angle representing the angular part of an axis/angle rotation of one vector set into another. That is, I have two sets of vectors of, let’s say, shape (100, 3). One is the input, the other is the target. The target is equal to the input, ...
tom
You need to declare your parameters in the __init__, but put all computation (except for constants) in the forward pass. You shouldn’t have to do requires_grad_ in the forward. You should not use tensor or Tensor within your calculation. This will break the graph. It isn’t entirely clear to me wh…
TheShadow29
I am not knowledgeable about building extensions. I see that torch.utils.ffi has been deprecated. I am wondering how to convert this code:https://github.com/yhenon/pytorch-retinanet/blob/master/lib/nms/build.pywhich uses ffi to cpp extension.Any directions would be helpful
tom
I think that yes, to use a cpp extension, you need to move to .cpp and ATen. It’s a bit of work, but it certainly is a nicer interface once you get used to it (I think you can cut the size of the code by quite a bit and just keep a couple of files or three.) Not that I know of. Best regards Tho…
J_Mark_Hou
so, I’m looking through the torch source code because I’m curious what exactly torch.tensor() doesit appears that it’s somewhere in/torch/_C.cpython-36m-x86_64-linux-gnu.so, which I’m assuming means it’s somewhere inpytorch/torch/csrc/, but I looked in the obvious places, and somehow wasn’t able to find where it was?wo...
tom
That’s a great question! As I had written something about how the “regular” functions arrive in PyTorch, I added a bit on torch.tensor() at the bottom. It’s in section odds and ends in myselective tour through PyTorch internals. If you have feedback, I’d be most happy to hear about it. Best rega…
Naman-ntc
I am working on adversarial attacks in pytorch. I am performing iterative gradient sign based attacks, but as cudnn is not deterministic the input gradient sign may vary and over many iterations this accumulates and gives very different results. For detailed discussion lookdiscussion - 1anddiscussion - 2.I looked at ot...
tom
Good catch with the Upsample.I think there currently is no-one systematically investing in determinism. (For most cases the problem is much less severe because of a continuous dependence on gradients, but the “fast gradient sign” is very discontinuous by design.) Best regards Thomas
o2h4n
I want to implement my own version of LSTM but I have a question to ask.I am using this code (basic LSTM cell):https://github.com/jihunchoi/recurrent-batch-normalization-pytorch/blob/master/bnlstm.pyto modify the LSTM cell.My question is if I use my version of LSTM and LSTM cell, willloss.backward()update weights. Same...
tom
At first glance, the code you link assembles the LSTM from typical NN-functions like linear. Autograd will provide gradients, but they will be slower than a custom-made gradient – in the PyTorch C++ extension tutorial, you get a ~20% performance boost from moving from Autograd components to a custom…
Naman-ntc
What should happen on not using loss.item() for logging the loss values.I was usingAverageMeter(fromimagenet tutorial) to store losses and I forgot using loss.item(). I believed it should have increased my GPU util and caused error.But instead somethin strange happened. It started increasing RAM utilization and literal...
tom
Tensors come with metadata (information about stride, size, type, …) in CPU memory and you probably kept a lot of these around, possibly also some graphs to be used in gradient calculations. When you only have a scalar value, the CPU memory usage probably exceeds the GPU memory use by quite a margin…
zippeurfou
Hi,I am trying to implement the power mean in pytorch followingthis paper.It is pretty straight forward to do it in numpy:def gen_mean(vals, p): p = float(p) return np.power( np.mean( np.power( np.array(vals, dtype=complex), p), axis=0), 1 ...
tom
Well, -(378**(1/3))is a root, too, so I’d start with that. If not, you can precompute -1**(1/3) to (0.5+0.866j) and “outer” multiply 378**(1/3) (or whatever outcome you have by a two-tensor tensor([0.5, 0.866]) if it is negative and tensor([1.0, 0]) if the mean is positive. Best regards Thomas
zpaines
I’m going throughthistutorial and I’m a bit stuck on the final exercise. I’ve seen lots of solutions that look likethisone, where they simply have a single linear layer that maps the embedding fromnn.Embeddingto an output layer ofvocab_size.Does thenn.Embeddingclass get updated by backpropagation? In other words, is it...
tom
The nn.Embedding class is a lookup table mapping each index to a vector. In effect it is a matrix, the weight matrix of the embedding module. Changing the vectors by a little bit will change the following computation by a small amount and eventually the (cross-entropy, typically) loss. Thus the vec…
successar
I have a simple LSTM where I want to get the gradient of hidden state at particular time step with respect to all other time steps. A simple example as follows :x = torch.randn(5, 4, 2) lstm = torch.nn.LSTM(2, 2, batch_first=True, bidirectional=True) h, (_, _) = lstm(x) h.retain_grad() h[:, 1].sum().backward() print(...
tom
For this you need to spell out the time loop using LSTMCell. That makes you pass the hidden state at each timestep and you can use hx.retain_grad() etc. Best regards Thomas
tomguluson92
Hello, I just can’t figure out the waynn.Conv2dcalculate the output . The result calculated from torch is not the same as some machine learning course had taught.For example, likes the code below:>> m = torch.nn.Conv2d(1, 1, 3, padding=0) >> m(input) tensor([[[[ 0.5142, 0.3803, 0.2687], [-0.4321, 1.1637, ...
tom
If you state down thedocumentationhard enough, you find that Conv2d has a bias parameter by default that your numpy calculation does not consider (see the formula in the doc), padding documented to be is (implicit) zero padding. This matches my experience. Best regards Thomas
wsdgh
One official tutorial has below comment# An alternative way is to operate on **weight.data** and **weight.grad.data**. # Recall that tensor.data gives a tensor that shares the storage with # tensor, but doesn't track history.https://github.com/pytorch/tutorials/blob/7f48ac827389f3438113c1604ac416cca3c1090e/beginner_sou...
tom
As you observe, in many circumstances, a.grad will not require gradient. This is, however, not universally true: a= torch.randn((5,5), requires_grad=True) (a**2).sum().backward(create_graph=True) print(a.grad.requires_grad) Note that.detach() is universally better than .data, except when you use…
hzhwcmhf
I am working on a network need regularize the gradient, so I must get a second derivative.But I got an error ofRuntimeError: the derivative for _cudnn_rnn_backward is not implementedI minimize my code to reproduce the errorcell = nn.GRUCell(10, 10).cuda() parameters = list(cell.parameters()) x = torch.rand(1, 10).cuda(...
tom
I’d probably implement a gru cell from nn.Linear. Best regards Thomas
PTA
I have a list of sequences and I padded it to the same length (emb_len). I have a separate tensor that I want to concat it to every data point in the sequences.Intuitively, it is something like thisa b c d e f g 0 0 0u u u u u u u u u uh i j k l 0 0 0 0 0u u u u u u u u u ubut the correct one (I suppose) would bea b c ...
tom
I think you are looking fortorch.nn.utils.rnn.pad_sequence. If you want to do this manually: One greatly underappreciated (to my mind) feature of PyTorch is that you can allocate a tensor of zeros (of the right type) and then copy to slices without breaking the autograd link. This is what pad_se…
hughperkins
Outside of an autograd function, the following code shows thatbrequires_grad, as I’d expect to happen:import numpy as np import torch from torch import nn, optim N = 5 K = 3 a = nn.Parameter(torch.rand(N, K)) idxes = torch.from_numpy(np.random.choice(N, K, replace=True)) print('a.requires_grad', a.requires_grad) ...
tom
Similar to your other question, you need with torch.enable_grad(): if you want to record the graph within the forward or backward of a autograd.Function. Best regards Thomas
hughperkins
The following autograd function attempts to calculate some auxiliary loss and backprop it. However I get an errorelement 0 of tensors does not require grad and does not have a grad_fn, even thoughxrequires a gradient. Why?import numpy as np import torch from torch import nn, optim, autograd def run3(): class my_...
tom
Within the forward and backward of an autograd.Function, autograd tracing is disabled by default (similar to when you do with torch.no_grad():), so aux_loss does not require gradient. If you wrap the aux_loss with with torch.enable_grad(): your code seems to run. (You don’t return anything from the …
aldopareja
Issue descriptionIt seems that pytorch has a memory leak when doing in-place slicing with tensors that require gradients. In the code bellow I just sample some data and multiply the sample by a single parameter, then I just leave the biggest values (as in doing k-beam), the autograd does not drop the references properl...
tom
This is your setup doing it. I don’t think there is much that PyTorch can do for you here, because your operation is not inplace. When you do pars*sample that requires grad. In turn the cat produces a tensor that requires grad and refers to pars*sample and the previous out as inputs. Then leaveTopK…
linyu
Now, I have a system of linear equations Ax = y, where A is a strictly upper triangular matrix, I want to solve x efficiently by using the special structure of A. Pay attention to that, in general, this can be solved by x = torch.gesv(y, A), but this function can not utilize the strictly upper triangular structure of A...
tom
Doestorch.trtrsfit your purpose? Best regards Thomas
Naman-ntc
I have the following networkresnet18 = models.resnet18(pretrained=True) fc_ftrs = resnet18.fc.in_features resnet18.fc = nn.Linear(fc_ftrs,self.numClasses)I want to use small learning rate at for the base of my network (finetuning) and different for the fully connected.If my optimizer is defined as follows :RMSprop([{re...
tom
Sorry for posting a wrong solution before. The reason it does not work as expected is because python’s in tries to use ==, and that will not identify tensors. Using the parameter names will work (you could also hack around it by keeping a set of p.data_ptr() and filter by that, but that is ugly…): …
omers66
Hey, I’m trying to do the following:I have a single N input data samples of dimension of 1 and a corresponding N output samples with dimension 1.I want to train an LSTM model that is fed with a sequence of say 10 samples with overlapping, i.e:in iteration 1 we feed: x[1:11] and perform BPTT and parameters update.in ite...
tom
You could apply the first step separately. Most times I have seen this, people used non-overlapping samples an cached the states (see e.g. fast.ai’s lecture on language models). Best regards Thomas
shivangi
Can someone give an idea on how to implement k-means clustering loss in pytorch?Also I am using Pytorch nn.mse() loss. Is there a way to add L2 reguarization to this term. In short, if I want to use L2-Reg. loss.
tom
If you use triple backticks (```python) before and just the backtics (```) after your code, it will be well-formatted. In Jupyter: import torch class KMeansClusteringLoss(torch.nn.Module): def __init__(self): super(KMeansClusteringLoss,self).__init__() def forward(self, encode_ou…
shivangi
import torchfrom torch.autograd import Variablefrom common.constants import Constantsimport torch.nn.functional as Fclass Cluster_Assignment_Hardening_Loss(torch.nn.Module):def __init__(self): super(Cluster_Assignment_Hardening_Loss,self).__init__() def forward(self,encode_output, centroids): # Calculate q_ij...
tom
I write the dimensions in the comments. Given: z = torch.randn(7,5) # i, d use torch.stack([list of z_i], 0) if you don't know how to get this otherwise. mu = torch.randn(6,5) # j, d nu = 1.2 you do # I don't use norm. Norm is more memory-efficient, but possibly less numerically stable in bac…
justusschock
Hi,As mentioned inthis tutorialI currently have to provide a manual backward function in a cpp extension.From my understanding, this backward would be the same as it would be evaluated by autograd in python (just implemented in C++) or am I mistaken here?Is there any possibility to show the functions which are actually...
tom
Don’t take my word for it though. That might be a part. So if a, say, 10% speedup is worth writing it in C++, do try. But I think you don’t get 30% just from moving to C++, but a larger part of that is the custom backward (which you could do similarly in Python).
junjie.qian
Hi, I have a huge 1-dimension sparse array (e.g. [0,0,…,0,1,0,0,…,0]) to feed into PyTorch for training. Is there an efficient way to define the input?I have looked at the torch.sparse, but that seems is for 2-D.Besides, the targets are also sparse array, is there an efficient way to compare the output of the training ...
tom
You can use sparse arrays with 1d as well. Subtracting sparse array should work. Best regards Thomas
Kenneth_Miller
I am using the C++ code of pytorch because I have a project in C++, and I need to know where the python code and functions are mapped to C++ functions in the pytorch repository.Could anybody tell me?
tom
This is autogrenerated. Do follow the build instructions for PyTorch and then look in torch/csrc/autograd/generated. The autogeneration code is in tools/autograd (including the template/Function.cpp that includes a lot of backwards definitions). It draws from .cwrap and .yaml files in aten/src/ATen …
hughperkins
Minimumal-ish example code:import torch from torch import nn N = 5 seq_len = 3 vocab_size = 7 embedding_size = 8 embedding = nn.Embedding(vocab_size, embedding_size) h = nn.Linear(embedding_size * seq_len, vocab_size) encoded = torch.rand(seq_len, N, embedding_size, requires_grad=True) out_probs = torch.zeros(seq_l...
tom
I think you are running in the casedescribed in the PyTorch 0.4 migration guide. .detach() is safer in that it catches inplace modifications that will cause autograd to give wrong results when backpropagating through the graph that you have “detached from”. Consider the following more minimal exa…
William_Aptom
image395×629 25.6 KBThis image is from the tutorial atNLP From Scratch: Translation with a Sequence to Sequence Network and Attention — PyTorch Tutorials 2.2.0+cu121 documentation.When deriving the attention weights, the input of “attn” is the concatenation of previous decoder hidden state andcurrent decoder input, out...
tom
I think that that is just a simplification in the implementation. The blue box note below the AttnDecoderRNN alludes to the fact that this approach is more limited than others. What happens with the overly long attention weights is that they will get multiplied by the 0s in decoder_outputs. Having…
Shani_Gamrian
How does the random function calculation depend on the seed? What If I used seed=1 and now I want different values, does it matter whether I choose seed=2 or seed=300 next?
tom
In answering a question, John Cook writes: So as far as we know, it’s OK for CPU and without looking into it, I would guess that the GPU RNG also qualifies. Best regards Thomas
Shani_Gamrian
I have a 4x4 matrix (let’s say it consists v1,v2,v3,v4) and I want to learn 4 parameters (a1,a2,a3,a4) that sum to 1 and multiply them and the matrix in order to learn which of the vectors are more important (normalized weight vector). Which is the best way to do that in PyTorch?
tom
So the v-matrix is fixed? You could use a nn.Parameter for pre-normalized a, softmax and then broadcasting: v_weighted = v * a.softmax(0).unsqueeze(0)) if you want to weight the columns of v or .unsqueeze(1) if you want to weight the rows. v would be a variable (or a buffer if you want to have it s…
adham
Letxandembbe 2D matrices of size(bsz, n)and(n, m)respectively.x = torch.FloatTensor([[0,1,2], [3,4,5]]) emb = torch.FloatTensor([[0,1,2,3], [4,5,6,7], [8,9,10,11]]) # x # tensor([[ 0., 1., 2.], # [ 3., 4., 5.]]) # emb # tensor([[ 0., 1., 2., 3.], # [ 4., 5., 6., 7.], # [ 8.,...
tom
I like to use indexing and broadcasting for this: out = x[:, :, None] * emb[None, :, :] Indexing with None inserts a new dimension (“unsqueeze” or “view” could achieve the same, but I like to use the above to help me see the alignment). For more advanced uses,torch.einsumcan be useful, too. Her…
gspr
In April,Tensors and Variables merged. It is my understanding from the example code that the following should work:x = torch.ones(1, requires_grad=True) y = torch.ones(1, requires_grad=True) z = x+y z.backward() print(z.grad)Yetz.gradisNone. What gives?
tom
z is an intermediate, whose .grad is not usually retained (x,y do have grads). If you want the grad for z as well, use z.retain_grad() after z = x + y. Best regards Thomas
Vannila
In the seq2seq tutorial and many other NLP related tutorials of PyTorch, I see that people often use RNN in a loop and set sequence length to 1. I would like to ask if there is any different if RNN is run on the entire sequence without the loop. In addition, if RNN can be used that way, how is it different from RNNCell...
tom
Many interesting RNN architectures use things besides what can be done with the “vanilla” RNN/GRU/LSTM - the classic is when one timestep’s output has an impact on the next timestep’s input - one prominent example is attention. Once you have things like that, you cannot use the multi-timesteps anym…
timniven
I have a tensor of shape(batch_size, num_steps, hidden_size). For each row vector in each matrix(num_steps, hidden_size)I want to compute the element-wise product with every other row vector, yielding a tensor of shape(batch_size, num_steps, num_steps, hidden_size).Is there a built-in way to do this that avoids for loo...
tom
You can use broadcasting. For example: y = x[:, :, None, :] * x[:, None, :, :] There also istorch.einsumfor fancy stuff (torch.einsum("iaj,ibj->iabj", [x, x]), works in PyTorch self-compiled master), but in your case the above seems to be what looks most straightforward and transparent to me (th…
MahdiNazemi
Assume there is a non-differentiablenn.Parameterin an equation whose gradient needs to be estimated using a straight-through estimator (STE) before the parameter can be updated. For example,y = 0.5(|x| - |x - alpha| + alpha)y_q = round(y * (2 ** k - 1) / alpha) * alpha / (2 ** k - 1).In this equation,alphais a trainabl...
tom
y_q_diffable is y_q ( = y + y_q - y) for the forward. But during backwards, the gradients propagate as if y_q_diffable were y. Best regards Thomas
Dr_John
I want to use the VGG16 pretrained network to classify a dataset of 1000 images into two classes. I also want the weights in the classifier part of the network to be initialized by Xavier initialization. How can I access the weights of the classifier part?I have tried the following lines of code, but “model.classifier....
tom
for p in model.classifier.parameters() nn.init.xavier_normal_(p) (without the _ for pre 0.4). Note that it might be an alternative to explicitly target weights, but not bias (and init this by 0 or something.) Here nn.init.xavier_normal_(features[-1].weight) Best regards Thomas
isalirezag
I am trying t understand how contiguous() and permute() work in pytorch, but im not smart enough to get it.Can anyone please provide explanations and example to make it clear for me?Thanks
tom
Use stride and size to track the memory layout: a = torch.randn(3, 4, 5) b = a.permute(1, 2, 0) c = b.contiguous() d = a.contiguous() # a has "standard layout" (also known as C layout in numpy) descending strides, and no memory gaps (stride(i-1) == size(i)*stride(i)) print (a.shape, a.stride(), a.d…
chenglu
Intuitively, DoubleTensor will bring more accuracy than FloatTensor, but FloatTensor will bring less Calculation than DoubleTensor. Are there any principles or best practices about how to chose the right dtype for deep learning?
tom
If you are on a GPU and FloatTensor works, take that. If it doesn’t work (e.g. large covariance matrices arising in Gaussian Processes can be tricky), try double, potentially selectively. GPU with double means a giant performance hit. If you are on (x86) CPU, they say that the speed issue is much l…
Naman-ntc
If I try to load pytorch 0.3 or 0.2 version in pytorch 0.4, batchnorm gives the track running status error.Are torchvision pretrained models trained everytime when new release occurs or do the transfer weights ‘in some way’ across versions?
tom
This is relatively rare and most likely considered a bug. In your casePyTorch master has a bugfix to help BatchNorm load older snapshots, don’t tell anyone, but you might try just copypasting from that. Best regards Thomas
acgtyrant
(e) .env In [1] import torch (e) .env In [2] from torch.autograd import Function (e) .env In [3] from torch.cuda import comm (e) .env In [4] a = [torch.tensor([0], device=torch.device(i), requires_grad=True) for i in range(4)] (e) .env In [5] class Reduce(Function): @stat...
tom
The inner workings of applycheck whether an argument is a Tensor (using THPVariable_Check) and needs grad. The list passed in the first version isn’t a Tensor. The second version unpacks the list and passes Tensors as arguments. Best regards Thomas
Naman-ntc
I have a fully connected layer, I want to multiply first half of weights by a numberKthat has itself to be learnt.As in suppose the weight of fully connected network isW [mxn]and I have a another parameter K that is initialized to say 0.5.I want to performW[:m//2,:] = W[:m//2,:] * Kand I need K to change as wellIs ther...
tom
Modifying parameters this way doesn’t work. In my opinion the best way to do this is to create your own layer using W and K as parameters and using torch.nn.functional.linear in the forward. for the multiplication, (provided m is even), I’d probably suggest mul = torch.ones(2, 1, 1, device=K.d…
Shani_Gamrian
I’m transferring a matrices addition code from Tensorflow to Pytorch. The matrices shapes are (1,25,256) and (1,1,256). On Tensorflow it works but on Pytorch I get the error:RuntimeError: inconsistent tensor sizeI know that the shapes doesn’t match but this code works on Tensorflow and I wonder if it can work on Pytorc...
tom
0.1.12 doesn’t have broadcasting, so you have to use expand/expand_as. In Richard’s example x + y.expand_as(x). Best regards Thomas
ichuuh
Hi, I have successfully completed training a BiLSTM model which has been saved as model.model. When I loaded it using load_state_dict(torch.load()), it gives me an error says:Unexpected key(s) in state_dict: “layer1.lstm.weight_ih_l1”, “layer1.lstm.weight_hh_l1”, “layer1.lstm.bias_ih_l1”, “layer1.lstm.bias_hh_l1”, “lay...
tom
Maybe your trained model had two or more layers in the layer1.lstm (l1 is the second) and the model you’re loading it to only one? Best regards Thomas
ChengzheXu
Hi, I came across some problems about gradient update when training my network. I built a CNN network with “two” weights, the original float weight “self.weight” and a binarized one “self.Bi_weight”, I created them as the same:if transposed: # If transposed, [in, out, [kernal size]] self.weight = Parame...
tom
In self.Bi_weight = Parameter(torch.Tensor(self.weight.shape)).cuda() the .cuda() is computation and you don’t have a Parameter in self.Bi_weight. Use self.Bi_weight = Parameter(torch.Tensor(self.weight.shape).cuda()) or better yet just leave the .cuda() alone and do model.cuda() at the end. Bes…
agadetsky
In previous versions we did something like:for p in model.parameters(): p.data.add_(-lr, p.grad.data)Migration guide says that now using .data is unsafe, so how to rewrite this using .detach()?
tom
Hi, for p in model.parameters(): p = (p - lr * p.grad).detach() No! Don’t do that! Apologies for the bold font. If you assign p, you will just overwrite the name and the model parameter will be unchanged. Now, if you look at the source code of an optimizer, saySGD, you find that the update r…
yamano
Hi,Since switching from PyTorch 0.3->0.4 my cpu usage has jumped from single-core (25% utilization) to ~100%, however the prediction/training performance has not jumped more than 5-10% in my use-case (Small dense networks without GPU, for example 3x64 units)This is limiting my ability to run multiple processes in paral...
tom
Hello, it would seem that you are looking fortorch.set_num_threads. In ancient versions of pytorch (<0.3.1), there had beenan issue with MKL threadsbut that seems long solved. Best regards Thomas
Michael.C
Is it possible to add weights to every entry in the input for CrossEntropyLoss, using only python code while maintaining efficiency?Alternatively, I looked at the underlying C code: ClassNLLCriterion.c and it seems that it may be modified to make use of the class weights to do entry weighting. Is this feasible for run...
tom
Do try and if it doesn’t do what you want, print the shapes of the loss, weights, and targets and then we’ll see. Best regards Thoas
taha
I tried the following standard custom function example fromthe documentation here:class LinearFunction(Function): @staticmethod # bias is an optional argument def forward(ctx, input, weight, bias=None): ctx.save_for_backward(input, weight, bias) output = input.mm(weight.t()) if bias...
tom
For pytorch 0.3.1, the forward uses Tensors, but the backward uses Variables, so use ctx.saved_variables instead of ctx.saved_tensors. On master (the documentation of which you link) it is ctx.saved_tensors again. Best regards Thomas
jpcenteno
pytorch 0.4: CUDA OOM when concatenating after running inferenceBefore upgrading to pytorch 0.4, I used to be able to run inference on hundreds of 2D images, concatenate them on GPU, and then move on to the next stage of my pipeline. With the 0.4 version, I run into “cuda runtime error (2) : out of memory at…”, so I ha...
tom
You want wrap everything into with torch.no_grad(): for pytorch 0.4. Best regards Thomas
Harshana
I work in python 2.7 , I noticed when summing a logical values as a byte tensor sometimes Torch.sum() gives wrong values which resolves when the logical is type casted to int etc . Can Somebody give me a reason for this . Thank You
tom
If you don’t need the count, you can use .any(). (There is .all(), too.) Best regards Thomas
MeowLady
hi all,I’m new to pytorch and got in trouble testing with my pre-trained model. I think I get the input with correct format while it returns error ‘RuntimeError: Input type (CUDALongTensor) and weight type (CUDAFloatTensor) should be the same’. Here is the partial code:net = DSN_net()net = torch.load(args.weight)input_...
tom
Your net only takes cuda floats as input, so your data preparation does not match the expectation of later processing stages when it casts to long. The solution to that depends on what you want to achieve, leaving as float or one-hot-encoding your integer in a real vector are common things to do. B…
Reid_Hayes
To make a transformed distribution I want to implement an inverse softplus functionlog(exp(x)-1).To do this i would need to implement something like thisif x > 20: return x else: return (x.exp() - 1).log()torch.nn.functional.thresholdwould be promising, except it doesn’t support tensors in itsvalueargument.torc...
tom
You could clip the term somewhere outside the range and then multiply, even if it isn’t the most efficient solution. Best regards Thomas
ddrevicky
I built PyTorch from source runningpython setup.py clean python setup.py installas describedherewhich mentions a similar problem.I still getTypeError: clamp() got an unexpected keyword argument 'out'after calling either of the following:x.clamp(-1, 0, out=x) torch.clamp (x, -1, 0, out=x)
tom
x.clamp is not expected to take out, but per the documentation it is a bug that torch.clamp does not. For your case, the inplace x.clamp_ might work. Best regards Thomas
saero
I installed pytorch gpu ver. on my mac with eGPU.Tensor and Variable are separated with cpu. However, with gpu, Tensor is not created but Variable.I have not seen yet any error about this issue e.g. dataset or dataloader.Why does it happen?Will not there be any problems?test code followingx = torch.randn(2,2) print(x) ...
tom
Pytorch 0.4 overcomes the separation of Variable and Tensor. Nothing to worry about. Best regards Thomas
saan77
I am using pre-trained inceptionv3 model in my script. I normalize tensor with following mean and std:mean=[0.485, 0.456, 0.406] std=[0.229, 0.224, 0.225]I would like to know how can I perform reverse operation. Currently, I perform this op in the following way:#first-remove batch dimension img[0] = img[0] * 0.229 img[...
tom
Hi, you can vectorize it: mt = torch.FloatTensor(mean).view(3,1,1), st similar allows you to do img*mt. This is by virtue of the broadcasting implemented in PyTorch. As PyTorch automatically prepends dimensions, it even works if img is a batch of images. Best regards Thomas
dpernes
I am developing a model where, for some technical reasons, my minimization objective is actually the squared norm of the gradient of some loss function:In the following toy example, I am implementing this for a very simple case (least-squares linear regression from the 2-dimensional space to the 1-dimensional space):im...
tom
The usual way is to use torch.autograd.grad instead of backward for the derivative you want to include in your loss. Best regards Thomas
kkjh0723
I wonder if it is possible to implement stochastic pooling as in thispaper, “Stochastic Pooling for Regularization of Deep Convolutional Neural Networks” or “fractional average pool” as inTensorflow?If possible, what is the most efficient way? Do I need to add custom C module?(It is nice if it’s possible with only pyth...
tom
Hello, thank you for asking! Stochastic pooling as in the paper with stride = pool size is easy to implement using view (so that the indices to be pooled are in their own dimension e.g. x.view(x.size(0),x.size(1)//2,2)), sampling random coordinates from multinomial and using that for indexing. T…
Nicholas_Wickman
I’m trying to load a model withmodel.load_state_dict(torch.load('Automatter_test.pth'))It was saved out usingtorch.save(model.state_dict, 'Automatter_test.pth')Traceback is:Traceback (most recent call last): File "/usr/share/pycharm/helpers/pydev/pydev_run_in_console.py", line 78, in <module> globals = run_file(f...
tom
model.state_dict is a function, so very likely you want to call it as model.state_dict(). Best regards Thomas
serhii
Hello everyone.Does anyone know how to maketrilwork on tensor without using a loop as suggestedhere? I would appreciate any help.
tom
I used numpy’s triu_indices to set things to 0 above the diagonal (see below). An alternative can be you could also use a mask. Best regards Thomas
kaushalshetty
Hi all,I just shifted from keras and finding some difficulty to validate my code. Currently I am training a LSTM networkfor text generation on a character level but I observe that my loss is not decreasing. I am now doubting whether my model is wrongly built. Kindly someone help me with this.Heres the code:class CharLe...
tom
Zero the grad before the backward, bot after. Best regards Thomas
Ben_Usman
Hi,I have been trying to figure out why my code crashes after several batches because of cuda memory error. I understand that probably there is some variable(s) that is not freed because I keep it in the graph. The question is how to debug that kind of thing?I have wrote a simple line profiler that examines amount of G...
smth
In python, you can use the garbage collector’s book-keeping to print out the currently resident Tensors. Here’s a snippet that shows all the currently allocated Tensors: # prints currently alive Tensors and Variables import torch import gc for obj in gc.get_objects(): try: if torch.is_t…
baizhen
I want to submit a pytorch question about the model structure of GoogLeNet provided by pytorch. When using GoogLeNet provided by pytorch, I found that there is a problem with the structure of the model. The specific situation is as follows,The following figure shows the structure of the model mentioned in the GoogLeNet...
smth
Please see the following issue and linked issues / comments / PRs:I find some error in googlenet.py ? · Issue #906 · pytorch/vision · GitHubIt is a known bug/deviation from the original, and we did not commit to fixing it…
Geremia
¿Why when I run:file = open('/tmp/big.bin', 'rb') file_bytes = file.read() mytensor = torch.frombuffer(file_bytes, dtype=torch.float32).reshape(a, b)do I get this:UserWarning: The given buffer is not writable, and PyTorch does not support non-writable tensors. This means you can write to the underlying (supposedly non-...
smth
you’ve opened the file in rb mode which stands for read-only binary mode. And what does the file buffer’s writability have to do with the tensor’s writability? from_buffer uses Python’s buffer interface and attempts to directly map to the underlying buffer without copying the data. So, the tenso…
tim_s
Hi,as of today (Dec. 2023): Is the recommended way to export models from PyTorch to be deployed in c++ stilljit.trace/jit.scriptas outlined in [1]?There seem to be many concepts related to this flying aroung:torch.export[2] states “this graph can then be saved, loaded, and run in different environments and languages”.[...
smth
With 2.2, we released documentation of torch.export, along with showing exported models in C++ runtime. Please seeAOTInductor: Ahead-Of-Time Compilation for Torch.Export-ed Models — PyTorch main documentation
Rhett-Ying
We are building a library upon libtorch. I am wondering if it’s ok that we build the library upon torch 2.2.0 and run such library upon torch 2.2.x(such as 2.2.1, 2.2.2). Namely, we build upon the major version of torch(such as 2.0, 2.1, 2.2) and run upon any following minor versions(such as 2.0.x, 2.1.x, 2.2,x). Is it...
smth
PyTorch does not follow semantic versioning. There could be API changes between minor versions as well (thought we try very hard not to introduce such changes)
farihachaiti
My model architecture:def _make_grid_(input): # Get the width and height of the output feature map _, height, width = input.size() # Determine the size of each grid cell grid_size = height // 4 grid_cells = [] boxes = torch.zeros(4, 4, 4) for i in range(4): for j in range(4): ...
smth
you seem to have two functions with similar names _make_grid_ and _make_grid. You can delete _make_grid_ as it doesn’t seem to be used anywhere else. About the error message, it looks like you need to modify _make_grid to output 64 sized patches instead of what they are outputing now which is 77 …
XZRRRRRR
When I try to compile Pytorch with Caffe2 on Ubuntu, I get one problem like this:[ 98%] Building CXX object test_tensorexpr/CMakeFiles/test_tensorexpr.dir/test_ir_printer.cpp.o/home/xiangzhaorui/miniconda3/envs/swts/bin/…/lib/gcc/x86_64-conda-linux-gnu/10.3.0/…/…/…/…/x86_64-conda-linux-gnu/bin/ld: CMakeFiles/context_gp...
smth
i can confirm that pytorch with caffe2 won’t build anymore. caffe2 codepath is no longer maintained and is removed from testing and builds.
mst72
I’m having some trouble writing transfoemer code in the computational attention module,I can define a class to compute attention in forward like this:class CalculateAttention(nn.Module): def __init__(self): super().__init__() def forward(self,q, k, v, mask=None, e=1e-12): ........I can also define...
smth
if you have state (such as weights and other buffers) that is alive in between computations, write a Module – because you can keep this state as a member of the Module (like self.weight). If not and you are writing stateless logic, write a function.
Zhang_Jiguo
EnvironmentPython 3.10.9torch 2.0.1gpu: Tesla P40import torch import torch.nn.functional as F a = torch.randn(1, 256, 3072, 3072).cuda() # need 9G+ b = torch.randn(256, 256, 3, 3).cuda() c = torch.randn(256).cuda() ...
smth
yes, as@ptrblckreplied, the Conv is so large that CuDNN doesn’t support it, Hence it is still running via the slow_conv2d path that takes lots of working memory. One way you can solve this is by tiling the convolution into patches. Each individual patch of convolution actually ends up using CuDN…
Tonis
I use a server to run Stable Video diffusion models on RTX A6000, then I find that with different batch sizes, the generated videos are slightly different (all the random seeds are fixed). Then I run the same sampling on my RTX 3090, the results are the same for different batch sizes, and the results are different with...
smth
@Tonisone thing you should keep in mind is that we don’t guarantee the RNG to be consistent across GPU models. So, for the same seed, you get different random numbers across A6000 versus 3090. One test you can do is to change the code to generate randn on CPU, and then move it over to GPU, so tha…
weitaoliu
Hey,I am trying to use at::Tensor & clamp_min_ function which takes two arguments, one is the tensor passed by reference and the other one is the scalar passed by the const reference.The inline function is:inline at::Tensor & clamp_min_(at::Tensor & self, const at::Tensor & min) { return at::_ops::clamp_min__Tenso...
smth
if there’s a trailing underscore, its a member of the tensor. Can you try this instead: yPreds_ts.clamp_min_(testmin)
cbd
Image is read as [1,3,256,256].(1) How can i find maximum pixel value in each channel (max value of each RGB channel) and(2) Pixel value with maximum RGB valueFor example, if i have two pixel with value (255,250,190) and (240,240,240) then in first case output should be (255,250,240) and in second case (240,240,240).
smth
image = torch.tensor([[255, 250, 190], [240, 240, 240]], dtype=torch.int32).T.view(1, 3, 2, 1) # 1. Maximum Pixel Value in Each RGB Channel max_per_channel = torch.amax(image, dim=(0, 2, 3)) # 2. Pixel Value with Maximum RGB Value # Reshape to separate each pixel and sum across channels sum_per_pi…
AwePhD
Hello,In the directory/opt/conda/libthere arepython3.1andpython3.10directories, for the torch images using Python 3.10. The 3.1 directory is a symbolic link to the 3.10 folder. I have other images,pytorch/pytorch:1.8.0-cuda11.1-cudnn8-develfor example, and there is a singlepython3.8directory in the/opt/conda/lib.So I w...
smth
So I would like to new the reason of the python3.1 folder. Is it to solve thissetuptoolsissue in the case where an old package would be installed in the python3.1 instead of python3.10 ? It is likely this reason. I can’t think of another reason why we’d do that.
Pab_Peter
Hi,Now I am using keras with a simplified interface of data parallisim sync version of parallelism.Now I wish to know if pytorch has similar function, seems like PyTorch is trying to advocate in “Speed”, so it had better support Multi-GPU just for a single node.Thanks,Shawn
smth
Hi Shawn, Yes we support multi-GPU on a single machine. Check out our examples: https://github.com/pytorch/examples/tree/master/imagenet https://github.com/pytorch/examples/tree/master/dcgan Also check out corresponding documentation:http://pytorch.org/docs/nn.html#multi-gpu-layers
ender.wieczorek
Does the CUDA version I have installed on my system need to match the CUDA version of the torch wheel?
smth
if you have dynamically compiled cu files, then you do have to match pytorch cuda version and system cuda version
se7en.dreams
I have two tensors:a = torch.tensor([1, 2, 3]) b = torch.tensor([4, 5, 6])I’d like to obtain a matrix of shapea x b, where each value is obtained using a custom function. For the sake of the example, let’s sayf(a,b) = a * b + 2.So, my output would be:f(1,4) | f(1,5) | f(1,6) f(2,4) | f(2,5) | f(2,6) f(3,4) | f(3,5) | f...
smth
without loops, this is best done by first replicating tensors and then doing the operations: a.view(-1, 1).repeat(1, 3) * b.view(1, -1).repeat(3, 1) + 2
justinyue1643
Hello, I know that this is a question probably asked quite often on this forum, but after going through the forum posts, I still am perplexed and could use some clarification. I am running Pytorch 1.6.0 on Ubuntu 20.04 with Cuda Toolkit 11.0 installed (hopefully, that’s all I needed to get everything running smoothly),...
smth
it’s normal. the GPU is driven by CPU code, and it’s normal for the CPU to spin while driving the GPU
zeakey
I have a complicated CNN model that contains many layers, I want to copysome of the layerparameters from external data, such as anumpy array.So how can I set one specific layer’s parameters by the layer name, say “conv3_3” ?In pytorch I get the model parameters via:params = list(model.parameters()) for p in params: ...
smth
you can get the params via: params = model.state_dict() and then they will be a dictionary whose name will be similar to conv3_1
yunjey
In GAN, i want to find latent vector z corresponding to the real image. One way to do this is to train z to minimize the error between sampled image and real image.However, when i ran the code below, Error message appeared: “ValueError: can’t optimize a non-leaf Variable”.targets # target images of shape (b...
smth
you have a mistake in this code. It should be: z = Variable(torch.randn(batch_size, 100).cuda(), requires_grad=True)
kl_divergence
Even I’m facing this issue withQuadro RTX 8000. The official recommendation is to build from source. But I don’t get it, why is not supported ?
smth
okay, I got an update.@seemethereis fixing the issue and re-uploading the cuda 10.1 binaries asap, like in ~3 hours or so
RahimEntezari
Hi,I am trying to change the resnet20 architecture to modify the kernel size from 3 in each convolution to 7.I simply replace kernel_size=3 to 7 and change the padding=1 to 3 to take care of size changes:import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init from torch.autograd...
smth
yea it’s a reasonable way to change kernel size.