user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
Luke_Bun | Hello,I want to use the pretrained GoogleNet, but when I compared it to the original paper cited in the PyTorch, I noticed that it was missing ReLU layers.According to the paper, “All the convolutions, including those inside the Inception modules, use rectified linear activation.” But when I run the following commands ... | ptrblck | Based onthe codethe functional API is used via F.relu which is why these modules do not show up in print(model). |
rinkujadhav2013 | I’m using stream context manager (with torch.cuda.stream(s)) to write my custom autograd function. If I do some data transfer from host to device usingto(device=d, non_blocking=True)or thecopy_function (again withnon_blocking=True), will the data be transferred using my streamsor will PyTorch create yet another stream ... | ptrblck | The kernel will use the current stream, so your custom stream assuming you are using the to() or copy_ op in the context manager based onthese lines of code. |
Florian_Bruckner | Why does torch.linalg.cross no longer support broadcasting like e.g.I am using expressions like:x = torch.linalg.cross(m, p)wheremis a vector field with shape (nx, ny, nz, 3) andpis a material parameter.pmay either be of the same shape asmor of shape (3) if the material is constant.Both versions worked with a previous ... | ptrblck | I think expanding is the right approach and something like this should work:
m = torch.randn(6, 5, 4, 3)
p = torch.randn(3)
x = torch.linalg.cross(m, p.expand_as(m)) |
new_to_dl | I will be using pytorch for a deep learning application. My computer has an NVIDIA GPU already.I installed CUDA followingCUDA Installation Guide for Microsoft WindowsFollowing that I installed pytorch in a conda environment with the pip command suggested onpytorch.orgpip3 install torch torchvision torchaudio --extra-in... | ptrblck | Yes, your setup will work since the PyTorch binaries ship with their own CUDA runtime (as well as other CUDA libs such as cuBLAS, cuDNN, NCCL, etc.). The locally installed CUDA toolkit (12.0 in your case) will only be used if you are building PyTorch from source or a custom CUDA extension.
The NVID… |
vilad | I’m trying to run the code using the GPU (cuda), but it gives me an error.I decided to check the result:As I understand it, I just can’t use the GPU…Here’s my video card just in case:NVIDIA GeForce GT 630MUsed:nvcc --versionOutput:nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2022 NVIDIA Corporation
Built on... | ptrblck | No, since Fermi (compute capability 2.1) was dropped in CUDA 9.0 while we are currently using 11.6-11.8. |
Dicko | Hello folks, I have a model that trained beautifully using cuda, the predictions look good.When I try to run on my local PC I get the error ‘AssertionError: Torch not compiled with CUDA enabled’ .I’ve tried with device = torch.device(‘cpu’), but still get the same error. Any ideas? | ptrblck | Which line of code raises this issue? PyTorch does not automatically assume you have a GPU so I assume you are explicitly trying to execute device code somewhere. |
nour | Hi, I’m new to pytorch and I’m trying to train Alexnet on 128x128 images. I modified my kernel sizes with respect tohere. But I get the error:RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [128, 4096]], which is output 0 of ReluBackw... | ptrblck | The error is raised by a disallowed inplace operation on a tensor which is needed for the gradient computation.
Based on your code snippet you are explicitly using inplace=True in Dropout layers. Set this argument to False for these layers and the code should work again. I would also guess the seco… |
carbocation | InSuper-Resolution using Convolutional Neural Networks without Any Checkerboard Artifacts, Sugawaraet alsuggest a solution to thecheckerboard problem noted by Odena, Dumoulin, and Olah. Interestingly, the solution has to do with initialization.It’s not super clear to me what the default initialization is for PyTorch’s ... | ptrblck | PyTorch’s nn.PixelShuffle layer does not contain any trainable parameters and thus does not initialize them with a specific method.
Based on the linked code snippets you shared it seems that at least FastAI implements a PixelShuffle_ICNR layer, which contains a ConvLayer as well as a PixelShuffle l… |
jun_suk_ha | import torch
import torchvision
# !pip install torchvision
from torchvision import datasets, transforms
mnist2 = torchvision.datasets.MNIST('mnist_data', train=True, download=True,
transform=transforms.Compose([
torchvision.transforms.Pad(18, fill=0, padding_mode='co... | ptrblck | The first code snippet uses the internal raw data which has a spatial shape of 28x28.
The second code snippet uses the DataLoader which adds the Pad transformation to each sample and thus increases the spatial shape to 28 + 18 + 18 = 64. |
cmetzner | Hello all,I am curious if you guys have a better (i.e., faster, computationally more efficient) solution than me.Situation:I have two tensors with size A=[bs, n, k] and B=[bs, m, k], where bs: batch size, n: number of low-level labels, m: number of high-level categories, and k: hidden dimension. I want to add the eleme... | ptrblck | Direct indexing should work:
A_ = torch.tensor([[0, 0, 0,], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]])
A_[torch.arange(len(indices))] += B[indices]
print((A_ == A).all())
# tensor(True) |
otakutyrant | This answersaid DataLoader will usedefault_collateto handle Dataset’s return value implicitly whencollate_fnis undefined, maybe. ButDataLoader’s default argument forcollate_fnis actuallyNone, inducing developer hard to find out that DataLoader will usedefault_collateimplicitly whencollate_fnis undefined. | ptrblck | The collate_fn is either set to detault_collate or default_convert based on the internal attribute self._auto_collation as seenherewhich is most likely the reason it’s set to None. |
otakutyrant | Seethe docthat lacks the note aboutvalueandthis tutorialwherevalueappeared. | ptrblck | Thanks for raising the discrepancy in the docs. Would you be interested in fixing this issue? |
Jack_Shi | I am usingtorch.nn.parallel.DistributedDataParallelto parallelize the training loop in a one-node multiple GPUs setting. When I’m just usingtorch.nn.parallel.DistributedDataParallelto wrap the model, I would get the following errorRuntimeError: Expected to have finished reduction in the prior iteration before starting ... | ptrblck | That’s not the case, as this argument will trigger an additional pass through the computation graph and mark unused parameters as ready to be reduced.
From thedocs:
find_unused_parameters (bool) – Traverse the autograd graph from all tensors contained in the return value of the wrapped module’s… |
rinkujadhav2013 | I’m trying to create a random tensor withmemory_format=torch.channels_last. I’m doing it as follows:_X = torch.rand(3, 3, 70, 70, requires_grad=True, dtype=torch.float32, pin_memory=True)
X = _X.to(memory_format=torch.channels_last)But I still get theThe .grad attribute of a Tensor that is not a leaf Tensor is being ac... | ptrblck | You can .detach() the tensor and call .requires_grad_() on the detached version to create a new leaf tensor:
_X = torch.rand(3, 3, 70, 70, requires_grad=True, dtype=torch.float32, pin_memory=True)
X = _X.to(memory_format=torch.channels_last).detach()
X.requires_grad_()
print(X.is_leaf)
# True |
shinihi | Hello, I currently have an Encoder-Decoder architecture using ResNet-34 as the CNN Encoder and an LSTM with Soft Attention as the Decoder. When I train my model on Google Colab everything works well during training, and I save the models’ state dicts accordingly. I then load the weights in the same runtime that I train... | ptrblck | I would probably start by verifying that the pretrained models are indeed loaded.
You are using a good approach to check if the state_dicts are available via:
if os.path.exists(ENCODER_PATH) and os.path.exists(DECODER_PATH):
encoder.load_state_dict(torch.load(ENCODER_PATH, map_location=DEVICE)… |
0piero | def train_loop(
epochs,
lr,
loss_fn,
train_dataset,
val_dataset,
pre_trained_model=False,
**model_args
):
if pre_trained_model == False:
model = MyLSTM(
model_args["input_size"],
model_args["embedding_size"],
model_args["hidden_size"]... | ptrblck | You are most likely trying to backpropagate through your states and might want to .detach() them in the training loop.
Also, using retrain_graph=True is usually wrong as users try to fix other (valid) errors with it and can also yield to these issues. |
laro | I’m dealing with the following senario:My input has the shape of:[batch_size, input_sequence_length, input_features]where:input_sequence_length = 10input_features = 3My output has the shape of:[batch_size, output_sequence_length]where:output_sequence_length = 5i.e: for each time slot of 10 units (each slot with 3 featu... | ptrblck | No, that’s not how a linear layer works.
Right now, you are using the 32 features of the last time step and pass them to the linear layer. The linear layer will apply a weight matrix (and bias) to this input and will “map” the 32 features to 5. The 5 output features are not ordered or sorted in any… |
amirtmgr | Hi! All,I recently tried to train aSplineCNNusingPytorch-Geometricas in example calledmnist_nn_conv.py. But, I got the following error.RuntimeError: The following operation failed in the TorchScript interpreter.Traceback of TorchScript (most recent call last):File “….conda\envs\dl23\lib\site-packages\torch_spline_conv\... | ptrblck | The error is raised inthis lineby pytorch_spline_conv. I’m unsure why the error message asks you to report a bug to PyTorch as the check is clearly in this 3rd party repository and I wouldn’t know how PyTorch could be responsible for this shape mismatch.
In any case, check what pseudo is and make… |
WowPy | Hello,I am working on a problem where the input space has different regions: R1, R2, and R3, and I have three datasets (D1, D2, and D3) sampled from the corresponding regions. The trick is that the loss function has three loss terms as well: L1, L2, and L3 (corresponding to the three regions of the input space), where ... | ptrblck | You could wrap each Dataset into a DataLoader, create the iterators manually, and iterate them by calling next. Something like this should work:
input1 = torch.rand((100,2))
input2 = torch.rand((120,2))
input3 = torch.rand((140,2))
output1 = torch.rand((100,1))
output2 = torch.rand((120,1))
outpu… |
amirtmgr | Hi! All,I recently usedCelebAdataset for image classification and usedtransfer learningfor this purpose, but the loss was highly negative (-5341) with accuracy of just around6-7%on100 epochs.NLLwas used as criterion. To find if there is any wrong with my code, I used the same code for CIFAR-10, it worked great with acc... | ptrblck | A negative loss sounds wrong. Could you explain what your model outputs contain? nn.NLLLoss expects log probabilities, so did you pass logits to the criterion instead?
model = nn.Linear(10, 10)
x = torch.randn(10, 10)
target = torch.randint(0, 10, (10,))
criterion = nn.NLLLoss()
# right
output = … |
bertrjul | Will the output be the same with or without torch.no_grad()? torch.no_grad() impacts the autograd engine and deactivates it, in order to speed up the computation. Does it also impact the results? In both cases, model.eval() is on. | ptrblck | torch.no_grad() will only disable Autograd and will avoid storing the forward activations. It will not change any behavior of the model. However, if the model has built-in randomness, which cannot be disabled via model.eval(), torch.no_grad() also won’t change it. |
Murad_Ali | I am reading the 1st 15 columns of a csv file for the prediction of a model. The 15th column has the scientific name of the plant that I am using in the task. When I run the code it shows an error “no such file or directory “Alliaria petiolata”” which is the scientific name of the plant. I don’t know how to solve this ... | ptrblck | It seems that list(img_list['imagepaths']) is failing to index the img_list. Make sure this key is valid and you will be able to read it before trying to assign it to model_output. |
dshin | TheEigenlibrary allows you to declareMatrixtypes whose dimensions are fixed, thus avoiding dynamic memory allocation when constructing such objects.Does PyTorch C++ have something similar? Or must allTensor’s incur the cost of dynamic memory allocation? | ptrblck | PyTorch doesn’t allow you to directly allocate memory via the Python frontend. However, if you are concerned about the costs to allocate GPU memory, you could initially allocate a large tensor, delete it, and allow PyTorch to reuse this memory as its internal cache. In C++ you would be able to alloc… |
malioboro | What is the best way to assign bias/weights of a specific layer to be half precision? This layer is a simple linear layer (no dropout or non-linear function).I code this and I don’t know why it works even without gradient scaling. But if I move thedtype=torch.float16to the weight (self.fc1w), it yields an error:class N... | ptrblck | Your current code might work if e.g. type promotion is used internally.
For a manual approach (assuming you don’t want to use the mixed-precisition training util. via torch.amp) you could either manually cast the tensors and parameters to the desired dtype in your forward method or you could also u… |
sashapiv | Hi,I try to use shared weights and display correct amount of parameters.A simple two linera layers network with the same weights.def __init__(self):
super(testModule, self).__init__()
self.fc1 = nn.Linear(10, 10, bias=True)
self.fc2 = nn.Linear(10, 10, bias=False)
# Remove the weights a... | ptrblck | I get the expected 110 total parameters using the latest version of torchinfo:
class MyModel(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(10, 10, bias=True)
self.fc2 = nn.Linear(10, 10, bias=False)
# Remove the weights as we override t… |
skyleaworlder | def save_gradient(module, grad_input, grad_output):
print(f"{module.__class__.__name__} input grad:\n{grad_input}")
print(f"{module.__class__.__name__} output grad:\n{grad_output}")
m = nn.LPPool2d(3, 2, stride=2)
m.register_backward_hook(save_gradient)
input = torch.tensor([float(i) for i in range(1, 50)], re... | ptrblck | Your code raises a warning:
# UserWarning: Using a non-full backward hook when the forward contains multiple autograd Nodes is deprecated and will be removed in future versions. This hook will be missing some grad_input. Please use register_full_backward_hook to get the documented behavior.
and I … |
Vedant_Roy | I’m doing inference in a loop. Think:for batch in dl:
outputs = model(batch)
np.savez(outputs.cpu().numpy())I’m trying to benchmark how long it takes for my code to do inference on a single batch.If I add atorch.cuda.synchronize()before thenp.savezline, will this slow down my inference code at all? | ptrblck | No, you should not see any additional slowdown by adding torch.cuda.synchronize() since pushing the CUDATensor to the CPU via outputs.cpu() will already synchronize your code. |
Jay_Li | I wrote some DL models in PyTorch, and fixed random seeds. Some unused functions affect the final model performance. For example, this is part of my code.…self.linear_1 = nn.Linear(27, d_model//2)self.linear_2 = nn.Linear(d_model//2, d_model)…Even if I wrote self.linear_1 & self.linear_2, they are not under forward com... | ptrblck | That’s expected since the order of calls into the pseudo-random number generator (PRNG) differs if you are randomly initializing these layers even if they are never used in the forward method.
Seeding will guarantee that the same sequence of PRNG calls will generate the same random number sequence. … |
LILAKKU | If my batch size is set to 16 and I have 4 devices, PyTorch will divide them into 4 batches of size 4, then send them off to different devices to make the forward call. But I want to access all hidden states of the 16 instances in the forward call, is it possible to do that? | ptrblck | You might be able to create a “global” dict and store the forward activations via a key which uses the layer name as well as the device id. Note that we generally recommend using DistributedDataParallel for a better performance, where one process per device would be used and would allow you to direc… |
setsailforfail | To better understand hownn.BatchNorm2dworks, I wanted to recreate the following lines of code:input = torch.randint(1, 5, size=(2, 2, 3, 3)).float()
batch_norm = nn.BatchNorm2d(2)
output = (batch_norm(input))
print(input)
print(output)
tensor([[[[3., 3., 2.],
[3., 2., 2.],
... | ptrblck | You could unsqueeze the stats tensors directly or add the missing dimensions via indexing with None as seen here:
input = torch.randint(1, 5, size=(2, 2, 3, 3)).float()
batch_norm = nn.BatchNorm2d(2)
output = (batch_norm(input))
print(input)
print(output)
mean = input.mean([0, 2, 3])
var = input.v… |
LTTc | I want to check if two tensors are exactly the same. You need to check that the nature of the tensors is the same, not allclose the same way.Does a functionfooexist that works like this?foomust not change the state of its input tensors.X = Tensor(...)
X2 = X.copy()
Y = nn.Parameter(X)
foo(X, X) == True
foo(X, Y) == Tru... | ptrblck | I guess you want to check the identity of the underlying data, so using .data_ptr() should work:
def foo(a, b):
if isinstance(a, nn.Parameter):
a = a.data
if isinstance(b, nn.Parameter):
b = b.data
return a.data_ptr() == b.data_ptr()
X = torch.randn(1)
X2 = X.clone(… |
Sohrabbeig | Hi,I have a simple module list like as follows:self.Linear = nn.ModuleList()
for i in range(self.channels):
self.Linear.append(nn.Linear(self.seq_len, self.pred_len))In the forward pass, I pass the input data to this module list sequentially, which is not efficient. It is worth mentioning that these modules are ind... | ptrblck | You could check vmap’s ensemble approach described inthis tutorial. |
graldij | Hi All,I am programming a transformer with Torch, on synthetic data, for a research project.I want to obtain reproducibility and therefore set the seed. I nevertheless noticed a - to me - very weird behavior.In the following snippet I get the expected behavior: model0 and model1 have exactly the same accuracy, and the ... | ptrblck | I don’t think that’s the case and the seed would still be the same you’ve set.
However,
explains that you are calling into the pseudo-random number generator (PRNG), which will thus create the divergence.
Once seeded the PRNG will create the same sequence of random numbers for the same order of… |
andreasceid | Hello,I am trying to automate the process of transposing a CNN. This basically means that I am trying to transfer the weights from a CNN to a NN with ConvTranspose layers (instead of Conv2d). Is there any automation or “hacky” way to do it? | ptrblck | You could permute the weight tensor and copy_ it to the transposed conv layer:
conv = nn.Conv2d(16, 32, (3, 4))
print(conv.weight.shape)
# torch.Size([32, 16, 3, 4])
conv_trans = nn.ConvTranspose2d(16, 32, (3, 4))
print(conv_trans.weight.shape)
# torch.Size([16, 32, 3, 4])
with torch.no_grad():
… |
Nikos_Spanos | I have concatenated three input layers using thetorch.concat()method. And I want to predict a binary classification sentiment value [0,1]. The output layer is a singlenn.Linear()layer with shape [64,1], where 64 (sentences per batch) and 1 (target 0 or 1).When I try to pass the concatenated layer to the single output l... | ptrblck | You are concatenating the activation tensors in the batch dimension, which is wrong:
input_layer = torch.concat([input_layer_average, input_layer_max, input_layer_min], dim=0)
and I assume you want to concatenate them in the “features” dimension (dim1 in this case).
After this change was made set… |
Dev2150 | I have NVIDIA GeForce GTX 950MI have installed CUDA 12 (cannot install older ones)I have installed cuDNNI have PyTorch 1.13.1+cpu“I ran pip3 install torch torchvision torchaudio --extra-index-urlhttps://download.pytorch.org/whl/cu116” | ptrblck | You’ve installed the CPU-only binaries, which is why torch.cuda.is_available() returns False. |
kevalmorabia97 | As per my understanding, callingtensor.contiguous()would not have any effect if the tensor is already contiguous.But the later case is 10x slower as shown below:import torch
x = torch.randn(128, 256, 3, 3)
assert x[:128].is_contiguous()
# 87 ns ± 0.222 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
_... | ptrblck | Based on your code you are timing the indexing. Remove it and you will see the same results:
y = x[:128]
%timeit _ = y.contiguous() |
shrbrh | I have a class ‘Feature_Extractor’ where I use the pre-trained VGG model for feature extraction. Below is a snippet of my code:vgg = nn.Sequential(*list(vgg.children())[:31])
feature_extractor = list(vgg.children())
self.layer_1 = nn.Sequential(*feature_extractor[:4])
self.layer_2 = nn.Sequential(*feature_extracto... | ptrblck | Yes, you need to initialize the Feature_Extractor with the needed input argument, since the internal self.layer_X modules are created based on feature_extractor. In encode these self.layer_X modules are then used to create the output so indeed the initialization of self.layer_X via feature_extractor … |
pauljurczak | I have CUDA 12.0 installed on Jetson AGX Orin (Aarch64). Following instruction onStart Locally | PyTorch, I run:pip3 install cuda-python
pip3 install torch torchvision torchaudioI expected to have Torch compiled with CUDA, but this script:import cuda, torch
print(cuda.__version__)
print(torch.__version__)
print(torch.... | ptrblck | The built binaries mentioned on the PyTorch website do not support Jetson Orin and you should usethese instructions. |
U2_COLDPLAY | I am trying to get the weights of conv2d layer of ConvNeXt model from torchvision.When I access the weights like the following:model.features[m][n].block[b].weightfor example, for this layerConv2d(192, 192, kernel_size=(7, 7), stride=(1, 1), padding=(3, 3), groups=192)The output weight is(192, 1, 7, 7)normally we would... | ptrblck | Yes, the groups=192 argument defines that each filter uses a single input channel to create the activation map (output channel) instead of using all input channels as would be in the default setup. |
3DTOPO | I need to load a checkpoint with four channels into an otherwise identical model with three channels and ignore say the 4th channel.I can’t train the model again since the compute is cost prohibitive. It seems like a fairly common issue with say RGBA <> RGB. It would also be handy for me to know how to use a single cha... | ptrblck | The weight attribute of a conv layer has the shape [out_channels, in_channels, height, width]. Since you are defining the out_channels of a conv layer, only the very first one uses the actual input channels of your input tensors.
I.e. look at the first layers of the resnet:
print(modelA)
ResNet(
… |
DickyA | I’m currently trying use inceptionv3 as a feature extractor but while trying to remove the last layer an error showed up which is the expected 3d or 4d in conv2d, here’s my code to remove the last layerdownload and initiate the inceptionv3 (this works)modelTuning = torchvision.models.inception_v3(pretrained=False)
mode... | ptrblck | If you only want to remove the self.fc layer you could instead replace it with an nn.Identity without any further modification to the model.
If your use case is more complicated, derive a custom nn.Module from the base model and rewrite the forward as you wish. |
maTal | I was trying the new torch.compile function when I encountered an error when compiling code that used autocast. I’m not sure if the behaviour is intended, if it is, it isn’t clear why.The following snippet should reproduce the error.import torch
def autocast():
with torch.autocast('cuda'):
return
... | ptrblck | I guess torch.compile is unhappy about the positional argument and might expect a keyword argument.
This works for me:
@torch.compile()
def opt_autocast():
with torch.autocast(device_type='cuda'):
return
opt_autocast() |
Tm4 | For using data parallelism, When I’m using data parallelism, I face with the error that CUDA memory is not enough. But one of the GPUs’ memory is occupied around 70 percent and the other one’s memory is occupied 10 percent. I think the main reason is related to the way that I move the tensors to the device because the ... | ptrblck | That’s a know disadvantage of DataParallel besides the communication overhead, which is why we recommend using DistributedDataParallel as it won’t suffer from these issues. |
Tm4 | For reducing the number of feature maps in a 4D tensor, it is possible to use Conv2d while keeping the height and width of that tensor as the same as before. To be clearer, For example for the following 4D tensor [batch_size, feature_maps, height,weight] I use the following approach for reducing the number of feature m... | ptrblck | You can use the same setup with a kernel size of 1 and no padding:
channel_reduction = nn.Conv3d(1024, 512, kernel_size=1, stride=1)
x = torch.randn(16, 1024, 16, 56, 56)
out = channel_reduction(x)
print(out.shape)
# torch.Size([16, 512, 16, 56, 56]) |
Ryan_Keathley1 | Some of pytorch’s build in modules have support for multiple ‘batch’ dimensions.For example, the input of the nn.TransformerEncoder module has shape (n_words, batch, dim_in).Although the first dim is notreallya batch dim, it does not change the number of params of the model and can be modified after instantiation of th... | ptrblck | nn.Linear accepts inputs in the shape [batch_size, *, in_features] where * denotes additional dimensions. |
ralph_20 | The parameters E and K are not getting updated when I try optimizing with a custom loss function. It does work on a simple loss like loss = E*KHow to fix this?Thanks# pytorch code to optimize two values E and K based on a loss function
\ | ptrblck | You are still re-creating tensors and are thus still detaching the computation graph.
Remove the torch.tensor calls in your code and use the tensors directly instead. |
davidw82 | Hi,What is the lowest version number of PyTorch that started supporting CUDA 11.8? Do I need to go all the way up to PyTorch 1.13 to get support?And to be clear, I’m always compiling from source.Cheers,David | ptrblck | I don’t see any CUDA 11.8 - specific changes to enable source builds (besides enabling the Hopper architecture, if needed) and we were using a 1.13.0-prerelease in our first 11.8 container as seenhere. |
aclifton314 | I have some basic questions about multi-class classification that keep tripping me up. I will outline the problem below while also providing a sample code snippet.I have created a dataset of fixed input size of 800 and feature size of 768. If it helps, you may think of this as something like word embeddings for fixed l... | ptrblck | Yes, you understood the issue correctly but would need to index the last timestep via:
out = out[..., -1] |
MarkW | What would be the easiest way to detect if any of the weights of a model isnan?Is there a built in function for that? | ptrblck | Besides the mentioned Anomaly detection util., this small code snippet would also check for NaNs in registered parameters:
model = models.resnet101()
is_nan = torch.stack([torch.isnan(p).any() for p in model.parameters()]).any() |
Arupreza | Dear Concern,Recently I have been trying to build an inception model. But it gives this error. Can anyone give me a solution? I really appreciate any help you can provide.training_data = []
def create_training_data():
for category in CATEGORIES_Train: # do dogs and cats
path = os.path.join(DATADIR_Train,... | ptrblck | Could you give us more information about which line of code is raising the issue and add missing pieces to the code snippet to make it executable, please? |
bryan123 | Let say I have:x = torch.randn(256,384)y = torch.randn(256, 384)Can you tell me how to get a variable z with a size of [2, 256, 384]? | ptrblck | torch.stack should work:
x = torch.randn(256,384)
y = torch.randn(256, 384)
z = torch.stack((x, y)) |
techkang | I ran the following code:import torch as t
import torchvision as tv
def main():
print('memory 1: ', t.cuda.mem_get_info(0)[0] / 1024 / 1024)
print('init model')
data = t.rand(1, 3, 224, 224).cuda()
model = tv.models.resnet50().cuda().eval()
print('memory 2: ', t.cuda.mem_get_info(0)[0] / 1024 / 10... | ptrblck | The CUDA context uses memory to initialize the driver, load the CUDA kernels etc. and will be lazily initialized during the first CUDA call. |
Mahdi_Amrollahi | I have a simple Linear model and I need to calculate the loss for it. I applied twoCrossEntropyLossandNLLLossbut I want to understand how grads are calculated on these both methods.On the output layer, I have 4 neurons which mean I am going to classify on 4 classes.L1 = nn.Linear(2,4)When I useCrossEntropyLossI get gra... | ptrblck | You can see the manual approach of these loss functionsherewhich would correspond to:
L1 = nn.Linear(2,4)
x = torch.randn(1, 2)
target = torch.randint(0, 4, (1,))
# PyTorch approach
criterion = nn.CrossEntropyLoss(reduction="sum")
ref = L1(x)
loss_ref = criterion(ref, target)
print(loss_ref)
# t… |
smathewmanuel | Hi, I am trying to save checkpoints during training using the following code:info_dict = {
'epoch' : epoch,
'numpy_random_state' : np.random.get_state(),
'torch_random_state' : torch.random.get_rng_state(),
'net_state' : net.module.state_di... | ptrblck | I don’t see the issue in your code, but the warning is raised if positional instead of keyword arguments are used as seen here:
model = nn.Linear(1, 1)
# no warning
state_dict = model.state_dict()
# still no warning if keyword argument is used
d = dict()
model.state_dict(destination=d)
# warning… |
kynthesis | Hi everyone, I have an immature question.For example, I got a tensor with the size of: torch.Size([2, 1, 80,64]).I need to turn it into another tensor with the size of: torch.Size([2, 1, 80,16]).Are there any right ways to achieve that? | ptrblck | I don’t think there is a single “right way” to achieve this as the proper approach would of course depend on your use case.
You could try these approaches and I’m sure I might miss others:
slice the tensor
y = x[..., :16]
print(y.shape)
# torch.Size([2, 1, 80, 16])
index it with a stride of 4
… |
Jack_Shi | A naive question about how BatchNorm2d works. Say I have an input size ofim = torch.rand(1000,1,2,2)
print(im.shape)
torch.Size([1000, 1, 2, 2])i.e. a batch size of 1000 2x2 matrices.Now say I initialize a BatchNorm2d layer and apply to my randomly generated tensorm = nn.BatchNorm2d(1, affine=False,eps=0)
im = m(im)whe... | ptrblck | You can see a manual (and slow) reference implementation inthis code snippetwhich I’ve created some time ago.
As can be seen there, the proper check would be:
im.mean([0, 2, 3])
Out[55]: tensor([-5.6028e-08])
im.var([0, 2, 3], unbiased=False)
Out[58]: tensor([1.0000]) |
ChristianV | Is there a way to have each layer in a network class do a weight update during its forward function? I am developing local learning algorithms and they need to update weights at every layer, and they don’t require gradient descent.I dont see anything about doing this on the documentation. Is there a way to do this, or ... | ptrblck | I’m not sure if I completely understand your use case, so feel free to correct me in case I’m missing something.
I assume this means you are never calling .backward() on any tensor associated with the model’s output tensor(s). In this case, your parameter update logic would compute the actual upda… |
Can_Nguyen | Hey guys,I’m working with a simple model which has to train 1 value only, namedself.my_weightsin my below code. The only new thing in my experiment is that I have to round that value when forwarding the input.In my observation, that value doesn’t change anything when training. Assume the loss function is working. Does ... | ptrblck | Yes, for two reasons:
Rounding a value will create a step function. While the output will still be attached to the computation graph, the gradient will be zero almost everywhere:
x = torch.linspace(0, 10, 1000)
y = torch.round(x)
plt.plot(x.numpy(), y.numpy())
Output:
[image]
Afterwards you a… |
tiramisuNcustard | As the title says, is it possible to load binary image data with ImageFolder? The documentation doesn’t mention anything in specific about this. Thanks in advance. | ptrblck | Yes, this is possible and the ImageFolder will then return target values in [0, 1].
Depending on your used criterion you might need to double check if the shape is correct and manipulate it if needed. |
gc625 | I have anidxtensor with shapetorch.Size([2, 80000, 3]), which corresponds to batch, points, and indices of 3 elements (from 0 to 512) from thefeattensor with shapetorch.Size([2, 513, 2]).I cant seem to find a way to usetorch.gatherto indexfeatwithidxwith a resulting tensor with shape[2,8000,3,2]. | ptrblck | Unfortunately you haven’t shared a reference code (even if slow) which I could use to compare my approach against, but this might work:
idx = torch.randint(0, 513, [2, 80000, 3])
x = torch.randn(2, 513, 2)
out = x[torch.arange(x.size(0))[:, None, None], idx]
print(out.shape)
# torch.Size([2, 80000… |
SU801T | What is the best way of randomly initialising but freezing the last layers of a densenet?I have the following code, where I am using a pretrained model but unfreezing the last denseblock4 and norm5 blocks for fine-tuning:model = models.densenet161(pretrained=True)
for param in model.parameters():
param.requires_gra... | ptrblck | You could remove the second loop, which “unfreezes” the parameters and call .reset_parameters() on the desired modules instead:
for module in submodules.modules():
if hasattr(module, "reset_parameters"):
module.reset_parameters()
or use a custom weight initialization via submodules.app… |
dsicahn | I’m attempting to save a large number of torch Data objects to disk in parallel with the following blockdef to_disk(r):
path = '/data/protein_data_dir/raw/' + r['ID'] + '.pt'
g = convert_nx_to_pyg(create_graph(r))
torch.save(g, path)
return g
NUM_CORE = 35
with mp.Pool(NUM_CORE) as pool:
out = list... | ptrblck | Yes, usually /dev/shm would use your RAM to allocate the temp. file storage filesystem.
Docker limits it by quite a bit (the default should be 64MB, not GB), so you might want to start your container with --ipc==host (or increase the shared memory usage directly via --shm-size). |
Ramansh_Sharma | Hi, I am trying to create a combined optimizer to train multiple neural networks simultaneously. But, this combined optimizer is updating the weights of networks that have not been used in computing a given loss, which I think is not supposed to happen. I share a simple reproducible example below.This is how I define a... | ptrblck | Adam (and other optimizers) is using internal states and will update the passed parameters even if their corresponding .grad attributes are set to zero.
As a workaround you could use optimizer.zero_grad(set_to_none=True), which will delete the .grad attribute and force the optimizer to step the pa… |
111414 | Thanks for noticing this post!I have an image denoising network (it is a CNN) that takes an image of size1*H*Was input and generates a smoothed image version of size1*H*W. Now I have four NVIDIA RTX 3090 GPUs and 100 large 8K images of size1*7680*4320. I want to run a test on them. However, the memory of one GPU seems ... | ptrblck | DataParallel will clone the model to all available devices and will not reduce the memory requirement, so I’m unsure why a) only a single device was used and b) why it was working at all since you were previously running our of memory.
Calling empty_cache() won’t reduce the GPUuu memory usage, bu… |
jasperhyp | Hi! I’ve been trying to usenn.DataParallelfor my model but am encountering this error:Traceback (most recent call last):
File "train.py", line 382, in <module>
main(args, hparams)
File "train.py", line 373, in main
train(model, train_dataset, val_dataset, retrieved_tokens, args.output_dir, hparams, device)... | ptrblck | You might be setting the env variable too late in your actual script. Once the CUDA context is created, this env variable won’t have any effect anymore, which is why I usually recommend to export it in your current terminal or prepend it to your python command in the terminal.
That is a good idea… |
sam_l | I have a 2d input tensor and a 2d index tensor with the same number of rows where each value represents the column index I want to select.I want as output a 2d tensor with the same number of rows as the input tensor and cols as the index tensor.I can do this by creating row and column index tensors, selecting from the ... | ptrblck | Direct indexing with torch.arange should work:
a[torch.arange(a.size(0)).unsqueeze(1), idx]
# tensor([[ 1, 3],
# [ 4, 5],
# [10, 11]]) |
koochak-mehdi | Hi,I’m trying to implement Gaussian Process with pytorch, and faced some wierd behavior in using torch.matmul function which wonderd me whether i’m using it in correct way!k1 = tensor([[1.0000, 1.0000, 0.9998],
[1.0000, 1.0000, 1.0000],
[0.9998, 1.0000, 1.0000]], dtype=torch.float64)
k2 = ten... | ptrblck | Your k1 and k2 kernels have a numerical mismatch of 1e-5 in their diagonal:
kernel = SQE(l, sf, 1e-5)
k1 = kernel(x_1, x_1)
k2 = kernel(x_1, x_2)
print(k2[:, :3] - k1)
# tensor([[-1.0000e-05, 0.0000e+00, 0.0000e+00],
# [ 0.0000e+00, -1.0000e-05, 0.0000e+00],
# [ 0.0000e+00, 0.… |
actuallyaswin | Hello, I’m trying to build a custom GRU with some additional weights and biases. The following code block in its entirety reproduces the issue. I’m using PyTorch version1.8.2+cu111.import math
import warnings
import torch
import torch.nn
from typing import Optional, Union
from torch.nn.utils.rnn import PackedSequence
... | ptrblck | I don’t know which additional weights and biases you are introducing, but I guess your new model architecture might not be compatible with the cuDNN definition, so disabling the parameter flattening and using the native approach might be the proper way to implement your custom module. |
carbocation | This question was askedabout 5 years agobut I feel like it might be appropriate to revisit it:Can we build a learnable bias layer that will work for arbitrary-sized input? (E.g., a single parameter that is added to every element of a scalar or an image or a video, depending on input tensor shape.)Is the answer just to ... | ptrblck | Yes, your idea to create a custom layer with the trainable bias (containing a single value) and broadcast it to the input shape sounds valid. |
kdeary | Beginner here. I am having trouble with target size and how to reshape for CrossEntropyLoss.I received this error:**RuntimeError** : Expected target size [100, 4], got [100].I’ve seen that many have had this same issue, but still do not understand the other posts. How do I reshape?# define model
class Model(nn.Module):... | ptrblck | @J_Johnson’s suggestion of flattening the input sounds reasonable so did you try to fix the issue with it? |
alex234321 | Hello, new to pytorch I am trying to create a model using the script found underDec 01 9:08 AM - Codesharebut when I run this code I get the errorRuntimeError: mat1 and mat2 shapes cannot be multiplied (64x38850 and 259x512)I am not sure where the 38850 comes from (which is 150 * 259). Any ideas? | ptrblck | I would recommend to checkthis tutorialwhich explains how a neural network can be defined for the MNIST dataset and you could also play around with this dataset first to get familiar with the dimensions of the input tensors etc. as I believe the tensor shapes and dimensions are what’s causing the … |
keineahnung2345 | Hi, just one quick question.I’ve built PyTorch master branch on 2022/12/5 and I expect its version is 2.0, but what I found is 1.14.0a0.Also in thelinkprovided bypytorch 2.0 installation instruction page, it only provides wheel liketorch-1.14.0.dev20221007+cpu-cp310-cp310-linux_x86_64.whl.So where can I get 2.0? Or 2.0... | ptrblck | Yes, I would assume 1.14.0+commit will be bumped into 2.0 eventually (I believe the same happened with 0.5.0+commit and 1.0.0). |
LongWU | Dear all,I have a time series data, recorded by 10 sensors, in shape [32,10,500] (batch size, sensor number, time points). I would like to use the same 1d kernel to filter these 10 sensor data (just like the wavelet filter), like below:input=torch.ones((32,10,1,500))m=nn.Conv2d(in_channels=10, out_channels=10, kernel_s... | ptrblck | Your approach would work, but you could also use a parametrization as seen here:
conv = nn.Conv1d(3, 10, 10)
print(conv.weight)
class WeightReuse(nn.Module):
def forward(self, w):
out_channels = w.size(0)
w = w[0, ...].expand(out_channels, -1, -1)
return w
torch.nn.uti… |
Sarah_Khaleel | This is my custom transform function that I want to apply over the whole dataset.class normalization(object):
def __call__(self, sample):
image, label = sample['image'], sample['labels']
fmin= torch.min (image)
fm = image- fmin
image = 255*fm/torch.max(fm)
return ... | ptrblck | Yes, change the custom normalization method to work on a single input tensor only and it should work.
I.e. in particular something like this should work:
class normalization(object):
def __call__(self, x):
fmin = torch.min(x)
fm = image - fmin
image = 255 * fm / t… |
sooh | I am trying to reproduce experimental results of one paper.The authors specify “requirements.txt” for Python versionsclick
matplotlib
numpy
opencv-python==4.5.1.48
pandas
pathy==0.4.0
PyYAML==5.4.1
scikit-learn
scipy
seaborn
torch==1.7.1
torchvision==0.8.2
tqdm
urllib3==1.26.3But this does not work on A100 GPU beca... | ptrblck | Thanks for the update and indeed interesting findings!
Are you using tensors as inputs to the transformations or PIL.Images?
In the latter case, could you check if the PIL version also changes between both setups? |
Aeryan | I want to pad with zeros a tensor along different dimensions at the same time.For example, given a tensor of shape[3,3,3,7], I want to obtain a tensor of shape[5,5,5,7], where the new entries contain a constant value (e.g., zero). For example, the value at the index [2,4,2,6] would contain 0.0.Additionally, I would lik... | ptrblck | F.pad should work:
x = torch.randn(3, 3, 3 ,7, requires_grad=True)
out = F.pad(x, (0, 0, 1, 1, 1, 1, 1, 1), mode="constant", value=0.0)
print(out.shape)
# torch.Size([5, 5, 5, 7])
print(out[2,4,2,6])
# tensor(0., grad_fn=<SelectBackward0>)
loss = out.mean().backward()
print(x.grad[1,0,2,4])
# te… |
archocron | First im new to pytorh and DL, I want to create a simple non linear regression model, but apparently is not converging, i tried to change some hyperparams without sucess. This is the code, i guess im making wrong something obvius.import torch
x1 = torch.arange(1,600,1, dtype=torch.float32).view(-1,1)
y1 =... | ptrblck | Your code works fine if I use Adam and increase the number of epochs.
The loss starts with a huge value since you are not normalizing the inputs (and outputs), which could help training the model.
E.g. if I use this native normalization:
x1 = torch.arange(1,600,1, dtype=torch.float32).view(-1,1)… |
Debojyoti_Biswas | I am trying to save the output from thefc1 layerof the model. Below is my model formulation:model_ft = models.resnet50(pretrained=True)
num_ftrs = model_ft.fc.out_features
model_ft.fc1 = nn.ReLU(nn.Linear(num_ftrs, 512))
model_ft.fc2 = nn.Linear(num_ftrs, num_classes)
model_ft = model_ft.to(device)
criterion = nn.Cro... | ptrblck | model_ft.fc1 and model_ft.fc2 are new attributes, which are never used in the original forward method.
If you want to replace the original model_ft.fc with these two new layers, assign them to the same attribute and wrap them into an nn.Sequential container:
model_ft = models.resnet50(pretrained=F… |
noctildon | Pytorch sees cuda and runs well on GPU, but nvcc appears to be not foundimport torch
torch.cuda.is_available() # True
torch.cuda.device_count() #1
torch.cuda.current_device() # 0
torch.cuda.get_device_name(0) # NVIDIA GeForce RTX 3090$ nvidia-smi
+---------------------------------------------------------------... | ptrblck | The PyTorch binaries ship with their own CUDA runtime (as well as cuDNN, NCCL etc.) and don’t need a locally installed CUDA toolkit to execute code but only a properly installed NVIDIA driver.
Your local CUDA toolkit (with the compiler) will be used if you build PyTorch from source or a custom CUDA… |
malfonsoarquimea | Hi!I am now working on a problem where I must read my data from a table-like h5 fileThe problem is that, given how I am providing the sampling (with a batch_sampler) and how the h5 file is structured, the time to read one item is almost the same as the time to read the whole batch (25k items).I would like to know if th... | ptrblck | You could use a BatchSampler and pass all indices directly to Dataset.__getitem__ which would allow you to load multiple samples.This codeshares an example. |
Rancho_Xia | Hi, everyone. I’m training a transformer for my research work. Here’s theScaledDotAttentionmodule:def forward(self, Q, K, V, d_k, attn_mask=None):
scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k)
if attn_mask is not None:
assert scores.shape == attn_mask.shape
scores.... | ptrblck | You would have to check if the manipulated tensor is needed in its original form for the gradient calculation, which disallows inplace operations on it.This postshows you a simple example. |
gifted_spence | Hey,I don’t understand why my transformations lead to my model failing to run (RuntimeError: mat1 and mat2 shapes cannot be multiplied (4x44944 and 400x120)). Generally, I stick to the documentation of training a classifier (Training a Classifier — PyTorch Tutorials 1.13.0+cu117 documentation) only that I transformed m... | ptrblck | The tutorial uses CIFAR10 where samples have a spatial size of 32x32 while you are resizing your samples to 224x224 and are thus increasing the number of features in the flattened activation. |
Tariq | Hello all,I recently added AMP support for my code training a segmentation model with a resnet-50 backbone.Everything seems to be working well at the beginning, except that the loss diverges after some iterations.losses1930×610 56.7 KBThe orange curve corresponds to the training loss w.o mixed precision, the grey one u... | ptrblck | A large scaling factor is beneficial as long as no overflows are seen as it would avoid underflows in the gradient calculation. Once the scaling factor is increased and is indeed causing overfllows, the optimizer.step() method will be skipped in scaler.step and the scale factor decreased again, thus… |
hanglearning | I’ve learned that stochastic gradient descent (SGD) updates weights one sample after another in random order. Then I saw the following code example. My understanding is that, within one iteration, this code extracts a batch of data, say 10 samples if the batch size is set to 10, and then SGD will update weights one sam... | ptrblck | Yes, the post is correct and the entire batch will be used to compute the gradients in the loss.backward() call. The optimizer will then use the .grad attribute of each parameter to perform the actual parameter update step. |
tolry418 | Hello. I got a error like below.I have no idea what is wrong . I tried to save my model with torch.save but the error come out.My learning enviornment is based on nvcr 21.11-py3What make that error?Traceback (most recent call last):File “main.py”, line 231, inmain()File “main.py”, line 152, in maintorch.save({File “/op... | ptrblck | I can reproduce the issue using:
import torch
import torchvision.models as models
model = models.resnet50()
optimizer = torch.optim.Adam(model.parameters(), lr=1.)
scheduler = torch.optim.lr_scheduler.CyclicLR(optimizer, base_lr=1., max_lr=10, step_size_up=10, cycle_momentum=False)
torch.save({'m… |
Ali_Aghababaei | Hi everyone,I have developed a convolutional autoencoder neural network for extracting features of an image dataset. The current architecture of the encoder is as follows (the decoder part is the reverse, obviously):class Encoder (nn.Module):
def __init__ (self):
super ().__init__()
self.encoder_conv = nn.Se... | ptrblck | You could create two separate optimizers, one for each model, or alternatively you could try to create the state_dict for the encoder optimizer from the saved checkpoint.
To do so, create a fake optimizer for the encoder only, check its state_dict, and try to recreate the same dict structure from t… |
mgpoirot | Hi all,I’m looking to chop an exciting network up in parts so I could later chain different parts together, eg.model = densenet121()
first_half = densenet121[:6]
second half = densenet121[6:]However, this has not been so easy, I’ve tried splitting the model using model.parameters, model.modules and model.features, but ... | ptrblck | I would recommend to derive a custom class using the Densenet121 implementation as the parent class. Inside the __init__, you could try to split the self.features sequential module and create your own forward method using these splits.
Your code snippet would work for very simple models, which can … |
mgpoirot | Hi all,I’m trying to back prop a model using the gradients acquired in the front and backprop of a copy of the exact same model. I acquire the gradient using a hook:# define the models
class ANet(nn.Module): ...
class BNet(nn.Module):
def __init__(self):
... layers ...
self.grad = None
def for... | ptrblck | You could most likely copy the gradients to a2net and apply the optimizer afterwards to update the model.
Here is a small example of this workflow:
model1 = nn.Sequential(
nn.Linear(10, 10),
nn.ReLU(),
nn.Linear(10, 1)
)
model2 = copy.deepcopy(model1)
# Compare parameters
for param1, … |
Ivano_Donadi | Hi, I am using torch 1.7.1 and I noticed that vectorized sums are different from sums in a loop if the indices are repeated. For example:import torch
indices = torch.LongTensor([0,1,2,1])
values = torch.FloatTensor([1,1,2,2])
result = torch.FloatTensor([0,0,0])
looped_result = torch.zeros_like(result)
for i in range... | ptrblck | Since you are using duplicated indices, the behavior is UB and you should use index_put_ instead with accumulate=True:
result.index_put_((indices,), values, accumulate=True) |
Tycho_van_der_Oudera | Is there an easy way to let BatchNorm2d at train time calculate the variance of a batch w.r.t. the running_mean instead of the mean of that batch? That is, to use variance = mean(x - running_mean) instead of mean(x - mean(x)^2).I need this feature for batch_size>1. However, I expect this to be generally very useful sin... | ptrblck | You could take a look at mymanual batchnorm implementationand manipulate it as you wish.
I would also recommend to try scripting your module afterwards to allow e.g. nvFuser to code-gen the (fused) kernels to speed it up again. |
John4 | Hello, I wrote a code in Jupyter Notebook and I get the following error:FileNotFoundError: [WinError 3] Impossibile trovare il percorso specificato:
'UPM_UNIPV_colab_NEMESIS_HSI_images/Datasets/'That means it’s impossible to find the specified path. How can I import a path in Jupyter?I ... | ptrblck | It seems you are using a relative path so either change it to an absolute path or make sure you can reach the file from your current working directory. |
mmg | I created a test_train split usingtorch.utils.data.Subset. How do I apply different train/test transforms on these before passing them as an argument to the Dataloader? | ptrblck | One approach would be to write a simple custom Dataset, which just applies your transformation to the internal subset as describedhere. |
Ali_Aghababaei | Hi everyone,I have been working with Pytorch and recently wanted to use CUDA of my PC to benefit from GPU capabilities. I figured out that a few versions of CUDA had been installed on the Windows, which made me decide to uninstall all the versions and re-install a new one. Also, previously I had installed PyTorch via t... | ptrblck | I don’t know which documentation you are following, but you should just uninstall the previously installed packages.
E.g. in:
conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c nvidia
you’ve installed pytorch, torchvision, and torchaudio, with the CUDA 11.7 dependency.
… |
Krishna_Garg | I have two parallel datasetsdataset1anddataset2and following is my code to load them in parallel usingSubsetRandomSamplerwhere I providetrain_indicesfor dataloading.P.S. Even after settingnum_workers=0and seeingnp.random, the samples do not get loaded in parallel. Any suggestions are heartily welcome including methods ... | ptrblck | Since you are using a random sampler, the random indices are expected.
If you want to yield the same (shuffled) indices from both DataLoaders, create the indices first, and use a custom sampler:
class MySampler(torch.utils.data.sampler.Sampler):
def __init__(self, indices):
self.indice… |
Z_Huang | i am trying to load my training image data stored in two folders named “data/train1” and “data/train2”. how could i do that? i need some coding help. thanks. | ptrblck | The tutorial explains the Dataset class and the required steps you would need to implement to write a custom Dataset:
load data, paths, set transformations etc. in its __init__ method
load and process a single sample in the __getitem__ using the passed index
return the length of the dataset (numb… |
dhan | Hi there, I’ve already notice that ‘detach()’ prevent backward process.Is there any method to replace the ‘detach().cpu().numpy()’ but, preserve the gradient ?Operation want to be :Tensor(GPU) feature → CPU → Numpy(or something) with Gradient(which could backward)It is okay if there is other choice than Numpy, like... | ptrblck | No, since detach() explicitly detaches the tensor from the computation graph as indicated by the function name. If you need to use a 3rd party library for some computations (e.g. numpy), you could implement a custom autograd.Function and write the backward pass manually as describedhere. |
bach97 | Hi,I am trying to train a GAN to generate both image and labels. The generator has a common backbone and then two heads to generate image and label. I have two different discriminator: one for the images and one for labels.Here a snippet illustrating a training iteration:############################
# (1) Update D netw... | ptrblck | In the generator update you are accidentally reusing a discriminator output:
output_img = netD_image(fake_img).view(-1)
output_lmask = netD_label(fake_label).view(-1)
# Calculate G's loss based on this output
adv_loss_img = criterion(output_image, label)
Note the adv_loss_img calculation, which us… |
Arupreza | Dear Concern,What will be the transpose parameter for the grayscale image for conv2d?training_data = []
def create_training_data():
for category in CATEGORIES_Train: # do dogs and cats
path = os.path.join(DATADIR_Train,category) # create path attack
class_num = CATEGORIES_Train.index(category) ... | ptrblck | np.transpose permutes the dimensions in the same way torch.permute works. In your use case it is unrelated to the alpha channel, as this would be an additional 4th channel making the input RGBA.
As explained, the code permutes the dimensions from [H, W, C] (channels-last) to [C, H, W] (channels-fi… |
dasturge | I’m curious how the dataloader behaves differently if it’s instructed to use multiple workers but also told that the dataset will take care of batching. Does this mean each worker will load separate batch? | ptrblck | I would expect to see the same behavior, i.e. each worker is responsible to load, process, and create a single batch. If your Dataset is now responsible to create the full batch already, I guess the number of calls into Dataset.__getitem__ would differ:
In the default use case each worker would ca… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.