user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
weight_theta
Dear community,I am currently writing my own rnn for a smple sqeuential mnist classification task and while I do not experience an issure during training, I am wondering why the following if statement in theforward passin theRnnCell Classis not triggering:if hidden_state is None: hidden_state = torch.zeros(...
ptrblck
You are calling the RnnCells with a hidden state via: if layer == 0: hidden_l = self.rnn_cell_list[layer](input[:, t, :], hidden[layer]) else: hidden_l = self.rnn_cell_list[layer](hidden[layer - 1],hidden[layer]) which is previously defined as: if hidden_state is None: …
Omroth
I’m baffled on this one.I am training with this core loop (batch size is 1):for image_data_s, demographics_s, actual_age_s in train_loader: image_data_s = image_data_s.to(device) demographics_s = demographics_s.to(device) actual_age_s = actual_age_s.to(device) predicted_ages = model(image_data_...
ptrblck
I guess because your model is always saturating the outputs which explains also the static output during training if no parameters are updated. If you call optimizer.step() in each iteration the output will change slightly and the training loop looks as if the outputs are improving while you might …
grmpf291
Hello, I tried to adapt one of the distributed pytorch geometric examples to fsdp, but failed. I get the error message:Traceback (most recent call last): File "/home/asdf/.local/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 69, in _wrap fn(i, *args) File "/home/asdf/test1/pytorch_geometric/e...
ptrblck
The issue seems to be the same as the one describedhereas both are PyG-related. The user already created an issue on GitHub which you could track or update with your use case.
GuillaumeTong
Hi, I am looking into different ways to optimize the running speed of my code, and one of these is looking at the speed of memory transfers between CPU and GPU, and the performances that I have measured do not seem to match up to the hardware’s theoretical one. I have written the following script:(note: I decided to re...
ptrblck
I would recommend reading through the linked blog post about memory transfers and and to run a few benchmarks if you are interested in profiling your system (without PyTorch to reduce the complexity of the entire stack). Using pinned memory would avoid a staging copy and should perform better a…
raj-rishav
Hello Guys, I am trying to finetune the FasterRCNN model. Dataset I got has 3 different labesl for objectsvehicle,traffic_lightandpedestrian.class CustomDataset(torch.utils.data.Dataset): def __init__(self, root, transforms): self.root = root self.transforms = transforms # load all image fil...
ptrblck
Try to set num_workers=0 and rerun the code as the stacktrace is still missing the actual error message.
divinho
Here you can see Computation/Communication Overview and Synchronizing/Communication Overview. What does “other” represent in the left plot? Why could the sync times in the right be so high? Or maybe that’s normal?Screen Shot 2023-03-09 at 11.44.30 PM1920×532 55.1 KBAnd here the overview for a single node, notice the hi...
ptrblck
I’m not familiar enough with the native PyTorch profiler and don’t know how to properly interpret the results, but would recommend to also profile your code with Nsight Systems to see if the actual kernel execution is slow (I doubt relu is that slow) or is the launch is blocked by e.g. synchronizin…
ANS_CENTER
Traceback (most recent call last): File "C:\Users\abdul\smartparking\Project_smartparking\m.py", line 4, in number_plate_detection_and_reading = pipeline("number_plate_detection_and_reading", File "C:\Users\abdul\smartparking\Project_smartparking\nomeroff_net\pipelines_init_.py", line 115, in pipeline return pipeline_c...
ptrblck
Your Lightning version seems to expect a 'pytorch-lightning_version' key in the state_dict whcih is missing. I don’t know if this is caused by a version mismatch between the lightning release which was used to create the checkpoints vs. the one used to load it, but maybe adding this key to your stat…
brunoj
Hello. I have 3 folders with images subfolders as train, test and validate. I have used T.Grayscale(1) to convert into grayscale but when I show the image , its like this. I dont understand why? Here is the image which Im gettingimage1920×1080 226 KBmy code is here:import matplotlib.pyplot as pltimport torch.nn.functio...
ptrblck
I would guess channels-last data layout is expected so permute your tensor into [height, width, channels] and it should work.
Forceless
My custom function, which runs before every conv layer and only contains one addition and division operation, slowed inference about 2x the original inference time.I want to know how to accelerate it as fast as I can.Thank youexamplefrom torchvision import models import torch def zscore_dr_hook(module: torch.nn.Module...
ptrblck
Yes, scripting the model or using torch.compile might speed up your code. To further debug your script I would recommend profiling the actual run to see where a bottleneck might still be as explained in the link in my first post here.
Jonas_N
Hi,I am trying to train a seq2seq model on MPS on an M1 Mac, but during loss.backward() I get the following error:RuntimeError: Expected a proper Tensor but got None (or an undefined Tensor in C++) for argument #0 'grad_yI do not get the error on CPU or on a Google Colab GPU. I think my error is similar tothispost. Doe...
ptrblck
If you are seeing the same error using the latest nightly binary, could you create an issue onGitHubso that the code owners could track and fix it, please?
Saguaro
When building PyTorch 1.4.0 on Ubuntu 20.02 with CUDA 11.3, cuDNN 8.8.0.121 I get... [1682/3492] Building NVCC (Device) object caffe2/CMakeFiles/torch.dir/__/aten/src/ATen/native/sparse/cuda/torch_generated_SparseCUDABlas.cu.o FAILED: caffe2/CMakeFiles/torch.dir/__/aten/src/ATen/native/sparse/cuda/torch_generated_Spars...
ptrblck
PyTorch 1.40 was released in January 2020 while CUDA 11.3 was released in April 2021, which might explain the error. Use a newer PyTorch release, which would support CUDA 11.3, or downgrade your CUDA toolkit if you really want to build this old PyTorch version.
NearsightedCV
I wanted to compare my model to RESNET in terms of number of parameters. RESNET had 22M…using the statementpytorch_total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)I got 129M! I am using a basic UNET with feature layers [64,128,256,512,1024]. Why is it so large?class UNet(nn.Module): de...
ptrblck
The parameter count seems to be expected and you can take a look at some large layers via: model = UNet() nb_params = 0 for name, param in model.named_parameters(): print("parameter {} contains {} elements".format(name, param.nelement())) nb_params += param.nelement() print(nb_params / 1e6…
ksreenivasan
Wrapping a model with DDP when the model’s weights are half-precision seems to change the weights. I noticed this issue when I was loading checkpoints and I’ve boiled it down to this minimal example.In the code below, I instantiate a simple model with a singlenn.Linearlayer and then wrap it with theDDPconstructor. This...
ptrblck
The issue is not caused by DDP, but by using float16 on the CPU, which might not use a wider accumulation dtype for norm. Here is a small example: lin = nn.Linear(512, 512, bias=False, dtype=torch.float16) lin.weight.norm() # tensor(5.6562, dtype=torch.float16, grad_fn=<LinalgVectorNormBackward0>) …
granth_jain
Hi,I have a LSTM-CNN model to train my timeseries data.My training loss does is not decreasing much, I also tried increasing the size of model but still the train loss does not decrease.Already done scaling and resampling.class LSTMNet(nn.Module):def __init__(self, size, input_shape): super(LSTMNet, self).__init__...
ptrblck
Based on your PyTorch code I assume you are using nn.BCELoss as the criterion and apply torch.sigmoid on the outputs. Could you remove the torch.sigmoid call and use nn.BCEWithLogitsLoss for a better numerical stability and check if this would help training the model?
thebeginning_isnigh
I’m trying to understand something about loops in PyTorch. I timed this function (modified from docs):for batch, (X, y) in enumerate(dataloader): print("Shape: ", X.shape) X, y = X.to(device), y.to(device) for i in range(10000): # Compute prediction error pred = ...
ptrblck
CUDA operations are executed asynchronously and since your code is mussing synchronizations it will profile the dispatching and kernel launch overheads at best. You are right that the CPU is used to schedule the work and especially if your actual GPU workload is tiny these overheads might be visibl…
Marcus_Wong
torch : 1.13.1+cu117torchvision : 0.14.1+cu117Python: 3.10.6Env: WSL2After running below :import torch from torch import hub # resnet18_model = hub.load('pytorch/vision:master', # 'resnet18', # pretrained=True) from torchvision import models resnet18_model = hub.load...
ptrblck
Double post fromhere.
granth_jain
I am trying to train a timeseries model with X_train shape =(-1, length, features), y_train shape=(-1)But I am getting error on creating the dataset out of it. Below is my codeX_train = load(open(r"X_train_"+str(dataset_idx)+"_"+str(model_idx)+".pkl", 'rb')) y_train = load(open(r"y_train_"+str(dataset_idx)+"_"+str(mode...
ptrblck
I guess you are passing numpy arrays to your TensorDataset instead of tensors: a = np.random.randn(10) a.size(0) # TypeError: 'int' object is not callable a.size # 10 x = torch.randn(10) x.size(0) # 10 which will then raise the error since size is an attribute for numpy arrays and a method for te…
tomcc
I am ensembing two models with mean pooling but also want to weight the loss of each seperate model at the same time so the less accurate model will contribute less to the final prediction.Here is a simple example of what I am trying to achieve.class WeightLoss(nn.Module): def __init__(self, n): super().__i...
ptrblck
Your code seems to work generally and reduces the weight for the larger loss to decrease the overall global loss: class WeightLoss(nn.Module): def __init__(self, n): super().__init__() self.n = n self.param = nn.Parameter(torch.empty(n), requires_grad=True) self…
swilliams2000
I am trying to calculate training and validation loss however I am getting an extremely high amount that is not converging‘’'transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.5,), (0.5,))])batch_size = 32cifar10 = torchvision.datasets.CIFAR10(root=‘./data’, download=True, transform=torchvisi...
ptrblck
range(0) is an empty range and this val_set_1 is also empty, so your code snippet doesn’t change anything. You could either remove the sorting, split the train and val indices manually by making sure both sets see all classes, or you could also use e.g. sklearn.model_selection.train_test_split with…
Nick_Halden
Hey,I know batch normalization uses different statistics on eval() mode and train() mode, but, whenI make those statistics the same, it still gives me different values.Here’s the code to reproduce what I am talking aboutimport torch import torch.nn.functional as F import torch.nn as nn a = torch.tensor([[[1,2], ...
ptrblck
Your code returns the expected mismatches: torch.abs(one - two) Out[15]: tensor([[[[5.9605e-08, 0.0000e+00], [5.9605e-08, 5.9605e-08]]], [[[0.0000e+00, 0.0000e+00], [0.0000e+00, 0.0000e+00]]]], grad_fn=<AbsBackward0>) torch.abs(one - three) Out[16]: tensor([[[[0.059…
MikeTensor
For the training of my project I use two models, which means I have to outputs.They use the following loss_fn:ModelA:nn.CrossEntropyLoss()ModelB:nn.SmoothL1Loss(reduction='mean')I am a bit confused about their needed tensor_shapes.Just wanted to reassure:loss_A_fn will get:predictedTensor: [BATCH, VALUE] like [8,1]labe...
ptrblck
Yes to 1. and 2., which is also explained in the docs for both loss functions. Yes, reshape can be used to add an additional dimension, but you could also use the more explicit .unsqueeze(1) operation. I would add these ops into the Dataset.__getitem__ and make sure all tensors are already in …
Teddy_Salas
(‘’‘’'I am having an error in data visualization code,this is the code:import torchfrom torch import nnimport matplotlib.pyplot as pltweight =0.7bias=0.3X = torch.arange(0,3,0.02)Y = weight * X * biasTraining_Set = int(0.8 * len(X))Training_SetofX = len(X[:Training_Set])Testing_SetofX = len(X[Training_Set:])Training_Se...
ptrblck
Your code is not formatted properly (you can post code snippets by wrapping them into three backticks ```), but generally it should work as seen here: Training_SetofX = np.random.randn(10, 10) def plot_predictions(train_data = Training_SetofX, predictions = None): plt.figu…
papoo13
Is AvgPool2d is non-deterministic?Only using this causes reproducibility issues in my model.o have set all the seeds and determinism=True as well. when I run the code, I don’t get any errors regarding having a non-deterministic function but the results are affected. Does anyone have any idea about this? if it is, why?...
ptrblck
Bitwise-identical results between different setups are not guaranteed since e.g. different code paths could be used based on the GPU capability. Using deterministic settings should make sure to yield deterministic outputs on the same setup. You should also note that both setups will run into the s…
gathierry
Hi, I’m building a model that will freeze some layers after several training steps. But the weights which should be frozen are still updated.Here’s a piece of code to reproduce the issue. The printedself.conv1.weightkeeps changing even though it’s already detachedimport torch from torch import nn class Net(nn.Module):...
ptrblck
You are right and weight_decay should still update the parameters even with a zero gradient.@gathierryyou could disable this behavior by using optimizer.zero_grad(set_ton_none=True) which will delete the .grad attribute and thus skip the parameter update. In newer PyTorch version set_to_none is T…
Brando_Miranda
I came up with this code but it’s resulting in never ending bugs:def get_device_via_env_variables(deterministic: bool = False, verbose: bool = True) -> torch.device: device: torch.device = torch.device("cpu") if torch.cuda.is_available(): if 'CUDA_VISIBLE_DEVICES' not in os.environ: device: ...
ptrblck
CUDA_VISIBLE_DEVICES is used to specify the desired available GPUs which will be mapped to cuda:0, cuda:1, etc. inside the application. Based on the error message you are seeing I guess you expect something like this to work: CUDA_VISIBLE_DEVICES=3 python script.py # inside script.py x = torch.ran…
Oliver
Hi all,I am using colab and sometimes kaggle instances and noticed that the GPU memory is often quite full but the system memory rarely runs above 4 gb and has a lot of space.Is there some way that I can use the system memory more efficiently?I am reading images from the disk, should I prefetch some and put them in mem...
ptrblck
The DataLoader will not move (or prefetch) data on the GPU by default and depends on the behavior implemented in the Dataset.__getitem__ method. Usually you would load each sample into the host RAM and thus the DataLoader’s workers will also prefetch these batches on the host. Besides that you shou…
core-not-dumped
I found that thetorch.nn.functional.relufunction callstorch.reluand ‘torch.relu_’def relu(input: Tensor, inplace: bool = False) -> Tensor: r"""relu(input, inplace=False) -> Tensor Applies the rectified linear unit function element-wise. See :class:`~torch.nn.ReLU` for more details. """ if has_torch_...
ptrblck
The CPU kernel can be foundhereand the CUDA kernelhere.
qm-intel
I have two tensors# losses_q tensor(0.0870, device='cuda:0', grad_fn=<SumBackward0>) # this_loss_q tensor([0.0874], device='cuda:0', grad_fn=<AddBackward0>)when I am trying to concat them, pytorch raises an error:losses_q = torch.cat((losses_q, this_loss_q), dim=0) RuntimeError: zero-dimensional tensor (at position 0)...
ptrblck
unsqueeze should work as it will add a dimension to the tensor: losses_q = torch.cat((losses_q.unsqueeze(0), this_loss_q), dim=0)
johnny69
I’m trying to train afasterrcnn_resnet50_fpnfor object detection.I’ve created my data loader, with the input as 224x224 colour image, and the output as targets with boxes and corresponding labels.# BATCH_SIZE = 1 images, targets = next(iter(test_dataloader)) print(f"Feature shape: {images[0].shape}") print("Feature") p...
ptrblck
It seems you are appending the losses tensor, which is still attached to the computation graph, in this line of code: train_loss += losses Could you detach() this tensor and call item() on it to only accumulate the plain floating point value instead of the tensor and see if this would help?
Maryam_Haghifam
I have implemented a GAN to generate graphs (basically I am generating the adjacency matrix). The implementation of the training GAN:def train_gan(loader, discriminator, generator, optimizer_d, optimizer_g, _noise_dim=500, _epochs=100): lossesG = [] lossesD = [] for epoch in range(1, _epochs): for d...
ptrblck
You are rewrapping the outputs into new tensors which will break the computation graph. Use the output tensors directly instead and make sure both tenors are attached to a computation graph and show a valid .grad_fn attribute.
kvtzn
Hi,I was wondering if using a single optimizer object to train multiple models is plausible. Particularly, I would like to use atorch.optim.SGDobject on models deriving fromtorch.nn.Module.I would like to make sure that the models are optimized independently. Is passing the parameters of each model as a separate parame...
ptrblck
Yes, passing the parameters from each model into a new param_group allows you to specify the optimizer parameters separately for each group, such as the learning rate. If you don’t want to use different arguments in your optimizer for each model you can also pass all parameters into a single param_…
Vladislav_Korecky
When calculating a loss (with themse_lossfunction), should I call.detach()on thetargettensor if it has grad_fn on it? And does it even matter?
ptrblck
I would assume the gradient calculation would be more expensive than calling .detach() on a tensor. In any case, you could also directly wrap the target computation into a with torch.no_grad() guard to avoid creating the computation graph in the first place.
Niraja
I am facing this problem at the time of testing. While training the data it works fine, but at the time of testing the data it arise this error.‘’’class test_dataset(Dataset):definit(self, age_label_test, gen_label_test, img_test):self.age_label_test = np.array(age_label_test)self.gen_label_test = np.array(gen_label_te...
ptrblck
Based on the error message the input tensor might be in the channels-last memory layout during testing while channels-first is expected. I don’t know why the memory layout differs between training and testing, but you could permute the input via: x = x.permute(0, 3, 1, 2) before passing it to the…
DongkyuLee
HiCan I declare activation function in class(Module) constructor?There are example using torch::nn::sequential and using torch::functional::(kinds of activation functions) in forward function directly, but I can’t find example about activation function declaration in class.Please let me know how to declare activation f...
ptrblck
You should be able to register torch::nn::ReLU() as any other module (e.g. torch::nn::Linear) in your custom class via register_module.
GLZhu
Hi community, I have built pt2.0 with gpu. The code I used is from github repo.I used python setup.py install and when run python -m torch.utils.collect_env I cannot find triton.Hence I tried to build triton with .github/scripts/build_triton_wheel.py.However during the process it is downloading cuda 12.0.I know from pr...
ptrblck
I used python .github/scripts/build_triton_wheel.py --py-version 3.8 which created pytorch_triton-2.0.0+b8b470bc59-cp38-cp38-linux_x86_64.whl and which matches the pinned commit in .github/ci_commit_pins/triton.txt. I think you are correct and you would need to build pytorch-triton as a dependency …
111357
As the title says, if not who should I report it to?
ptrblck
Yes, you can contribute to PyTorch by sending a PR for fixes. Take a look atthis Contribution Guideto get an overview and let us know if you get stuck.
The_Snail
So I created the following simple function for evaluating the trained model:import torch from torch.utils.data import DataLoader from torchmetrics import MeanAbsolutePercentageError, MeanSquaredError, MeanAbsoluteError, R2Score def compute_metrics(y_pred, y_true, device): mape = MeanAbsolutePercentageError().to(de...
ptrblck
Could you keep the last batch and check how large the difference would be?
mkserge
Hi,I can’t figure out how to make the model register my params if they are initialized as values in a dict.Example code,import torch class EmbeddingModel(torch.nn.Module): def __init__(self): super(EmbeddingModel, self).__init__() self.embeddings = { 'source': None, 'targe...
ptrblck
That’s expected and you would need to use nn.ModuleDict instead of a plain Python dict.
francesco_patane
hi there. i’m new in pytorch and i’m trying to predict membrane protein topology with a lstm but i have an issue with the embedding layer (i think).I set embedding_dim = 64 but it seems that after every cycle, the dimension grows up. If I adapt the embedding dim empirically the RAM memory goes out max capacity.I took d...
ptrblck
The error is raised in: embeds = self.word_embeds(sentence).view(len(sentence), 1, -1) lstm_out, self.hidden = self.lstm(embeds, self.hidden) as it seems embeds has an invalid shape. I’m a bit confused about your explanation stating: as it seems you are working with a sequence length of 1321 an…
vdw
I’ve tried my hands on hooks, and get the basic idea how to add hooks (I’m using forward hooks) to each layer/module. This allows me, e.g., to print the input and output shapes of the tensor coming and and going out of the layer.Is there also a way to tell from which module a subsequent module got its input?
ptrblck
I believe libraries visualizing the computation graph would also trace or script the model internally (but I might also be wrong).@tomcreatedthis great notebooka while ago which does exactly this. Based in the code the model is also traced and I assume this is a requirement.
ruka
Suppose I have a tensor indicating which column should be 1 for each row, for example,index = torch.tensor([3,1,0,0,2])and I would like to construct a mask tensor from above one and get this result:mask = torch.tensor([[0,0,0,1,0],[0,1,0,0,0],[1,0,0,0,0],[1,0,0,0,0],[0,0,1,0,0]])Is there any pytorch api can help me fin...
ptrblck
scatter_ should work: index = torch.tensor([3,1,0,0,2]) torch.zeros(index.size(0), 5).scatter_(1, index.unsqueeze(1), 1.) # tensor([[0., 0., 0., 1., 0.], # [0., 1., 0., 0., 0.], # [1., 0., 0., 0., 0.], # [1., 0., 0., 0., 0.], # [0., 0., 1., 0., 0.]]) I don’t know ho…
hahaznewbie
I wish to work with pytorch v1.9.0. I have already downloaded CUDA 11.3 as well as visual studios 2019. I am unsure of which version of cuDNN would allow me to utilise pytorch in anaconda.
ptrblck
I assume you are interested in installing a binary for this old PyTorch release? If so, then note that the PyTorch 1.9 binaries were built with CUDA 10.2, which shipped with cuDNN 7.6.5, and CUDA 11.3, which used cuDNN 8.3.2 and you can install this binary using the supported commands fromhere. In…
oasjd7
Hi, all.I want to move the BN values ​​of model_1 to model_2.The test results before and after changing the BN value are the same. So I think something went wrong somewhere, but I don’t know what the problem is.def save_bn_stats(model): model_encoder_dict = model.encoder.state_dict() cur_encoder_dict = Ordered...
ptrblck
You are storing references in save_bn_stats and would need to clone the data or use copy.deepcopy instead.
cakeislife100
When running with atorch.compile()model with PyTorch 2.0 and CUDA 11.6, my code is segfaulting with just some sample code. When I removetorch.compile(), the code executes just fine. Any insight into what might be going on would be greatly appreciated.Here is my CUDA environment:NVIDIA-SMI 470.161.03 Driver Version: 4...
ptrblck
Yes, the binaries with CUDA 11.6 will be deprecated soon and the PyTorch 2.0 binary release will support CUDA 11.7 and 11.8 as describedhere. Note that you will still be able to build PyTorch from source with other CUDA versions and the “deprecation” only means the pip wheels and conda binaries wi…
sepfins
I’m trying to train a BERT model using ‘sentence-transformers/distiluse-base-multilingual-cased-v1’ as the base. While inspecting nvidia-smi I’ve noticed that loading the model with ‘AutoModel.from_pretrained()’ takes up 400MB more GPU memory when done in script. The larger issue, however, is that when I calculate text...
ptrblck
No, I don’t know what might be causing it as I haven’t this behavior before (but I also usually don’t use Jupyter). One debugging step I would try is to disable lazy module loading from the CUDA driver, which is on by default in PyTorch using CUDA >= 11.7. You can disable it via export CUDA_MODULE_…
Julian_Buchel
Hi,on the torch.compile page, it says thattorchtritonmight need to be installed viapip install torchtriton --extra-index-url "https://download.pytorch.org/whl/nightly/cu117"I tried that, but when I wanted to compile my model, torch was complaining that I don’t have a backend installed and that I should check out the tr...
ptrblck
The pytorch-triton binary will be installed as a dependency when the nightly binaries are installed. Also note that torchtriton is the name of the old binaries, which you shouldn’t install manually. Unfortunately, it seems the nightly binaries are broken right now and you can track the issuehere.
Theo
I’m trying to train a very simple transformer which is supposed to translate sentences to another language and I’m having trouble getting rid of padding index when training my model.Here is my training loop(simplified for clarity):for source, target in data: # Source and target Shape [ max_len ] source, target = so...
ptrblck
As the error message explains, the ignore_index argument is invalid for (the new) floating point targets. Assuming you don’t want to use “soft” target values and could use class indices, you could transform the current target to class indices via: target = torch.tensor([[ .0, .0, 1.0, …
KimberleyJensen
I am trying to take someone elses code and replace multiplication with concatenation because it’s supposed to improve performance.The only line i changed from the original code isx *= ds_outputs[-i - 1] to x = torch.cat((x, ds_outputs[-i - 1]), 1)and I get the errorRuntimeError: Given groups=1, weight of size [160, 160...
ptrblck
In x = torch.cat((x, ds_outputs[-i - 1]), 1) you are concatenating two tensors, which seems to increase the channel dimension from 160 to 320 and thus yields this error. Check which conv layer raises this error and change its in_channels to 320.
tyam
I want to make a Deep Autoencoder using Resnet34.Based on these sites(https://www.kaggle.com/code/khoongweihao/resnet-34-pytorch-starter-kit/notebook,https://medium.com/pytorch/implementing-an-autoencoder-in-pytorch-19baa22647d1), I try to make autoencoder code for my understanding.Unfortunately, my code has a bug abou...
ptrblck
In AE you are assigning references to the EncoderResNet34 class instead of creating objects: self.encoder = EncoderResNet34 self.decoder = EncoderResNet34 # Temporary use self.encoder = EncoderResNet34() self.decoder = EncoderResNet34() # Temporary and this error should be solved.
nima_pw
Hi,I have a model from github, that assumes input images are 128*128:class MISLNet_v2(torch.nn.Module): def __init__(self, num_classes, is_constrained=False): super().__init__() self.is_constrained = is_constrained if is_constrained: self.conv0 = nn.Conv2d(in_channels=3, out_chan...
ptrblck
You won’t be able to make the inputs “dynamic” by passing another in_feautres dimension to the __init__ method since this new feature size would fit only the new input shape. To allow for variable input shapes you should use an adaptive pooling layer, which allows you to define the output size of t…
Jamesswiz
Suppose my model has 3 convolutional layers where I want to randomly train all or only one of the layers during forward pass.class myConv(nn.Module): self.conv1 = nn.conv2d() self.conv2 = nn.conv2d() self.conv3 = nn.conv2d() def forward(x): z = torch.randint(0,4,(1,)) if z == 0: out = self.co...
ptrblck
In the branches where layers are not used you might not need to freeze their parameters since Autograd won’t compute gradients for them. Since these parameters were not used in the forward pass they were never added to the computation graph and are thus irrelevant in the backward pass. If you expl…
Pranav_Belhekar
I’m trying to input the features in 3 parallel model architecture( 2*CNN + transformer encoder).# change nn.sequential to take dict to make more readable class parallel_all_you_want(nn.Module): # base module # Define all layers present in the network def __init__(self, num_emotions): super().__in...
ptrblck
Sure, here is the full code: import torch import torch.nn as nn class parallel_all_you_want(nn.Module): # base module # Define all layers present in the network def __init__(self, num_emotions): super().__init__() # initializes internal module state. …
ajrheng
I have a use case where I need to calculate the gradients of parameters of a NN on a per sample basis, i.e., batch size of 1, and I wantparams.gradafterloss.backward(). I want to speed this up withDistributedDataParallel, so I have each process take in a batch of 1 and perform the calculation.The problem isloss.backwar...
ptrblck
I thinkDistributedDataParallel.no_sync()should work for your use case: A context manager to disable gradient synchronizations across DDP processes. Within this context, gradients will be accumulated on module variables, which will later be synchronized in the first forward-backward pass exiting …
Rane90
Hi,I have a tensor of shape(7, 4, 1, 80, 2)and I would like to modify some of its indices. I’ve tried to do this in two different indexing steps.index relevant indices at dimension 1 (of size 4)x[torch.arange(x.size(0)).unsqueeze(1), idx]whereidxis of shape(7,3), meaning I index3out of4indices.index relevant indices at...
ptrblck
You might need to remove the chained indexing and use a single indexing operation to manipulate x.
perf
If I have created a tensor on the CPU, and I want to move it to the GPU.Is there a way to check whether there’s enough memory available on the GPU?
ptrblck
No, I don’t think so unless you disable our caching mechanism and use cudaMemGetInfo from torch.cuda.cudart(). In the default setup the caching allocator will be used to be able to reuse already allocated device memory without using the slow and synchronizing cudaMalloc/cudaFree calls excessively. …
mmg
I read somewhere (don’t remember, a slack channel maybe) that torchscript is not maintained anymore and model.compile is the way forward. Is there some truth to this?P.S. I only use torchscript when I want to generate MAR files for torchserve…
ptrblck
This threadwith some linked posts might be helpful.
Aelderian
Hi I am kind of new in pytorch. I was trying run this benchmark code in pytorch on Mac M2 but i am geting user warning.Benchmark Codeimport torch from torch import nn from torch.utils.data import DataLoader from torchvision.datasets import MNIST from torchvision.transforms import ToTensor print(f"PyTorch version: {tor...
ptrblck
This warning was added inthis PRrecently and mentions the internal downcasting of int64 values to int32 due to the lack of reduction ops natively supporting int64. This warning should be raised only once but I don’t know if you could also suppress it without disabling all warnings.
Adex
I have the following implementation in my pytorch based code which involves a nested for loop. The nested for loop along with if condition makes the code very slow to exceute. I attempted to avoid the nested loop to involve the broadcasting concepts in numpy and pytorch but that didnot yield any result. Any help regard...
ptrblck
This should work: # create reference batch_size=32 mask=torch.FloatTensor(batch_size).uniform_() > 0.8 teacher_count=40 student_count=50 feature_dim=60 student_output=torch.zeros([batch_size,student_count]) teacher_output=torch.zeros([batch_size,teacher_count]) student_adjacency_mat=torch.randint…
dev2y
Hi, I wanted to my own model and I took this example from github,github.comimport torch import torch.nn as nn from torch.utils.data import DataLoader import torchvision.transforms as transforms from Model import CNN from Dataset import CatsAndDogsDataset from tqdm import tqdm device = ("cuda" if torch.cuda.is_availab...
ptrblck
Your criterion is nn.BCELoss() which expects a model output and target in the same shape. You should thus .unsqueeze the tensor in dim1 and the error should disappear: labels = labels.unsqueeze(1) Also, I would recommend replacing nn.BCELoss with nn.BCEWithLogitsLoss for better numerical stabilit…
Sumit_Anil_Kshirsaga
NVIDIA GeForce RTX 4090 with CUDA capability sm_89 is not compatible with the current PyTorch installation.The current PyTorch install supports CUDA capabilities sm_37 sm_50 sm_60 sm_61 sm_70 sm_75 compute_37.If you want to use the NVIDIA GeForce RTX 4090 GPU with PyTorch, please check the instructions atStart Locally ...
ptrblck
Based on the error message you have installed PyTorch binaries with CUDA 10.2, which is incompatible with your 4090. Install the latest or nightly release with CUDA 11.7 or 11.8 (I would recommend using the nightly release with CUDA 11.8 for the best performance) using the install commands fromher…
Cai_Py
I am new to PyTorch and I’m attempting to train a transformer model on biological sequences to output a binary classification. I have a functional training regiment in the sense that it iterates without errors, however my loss function never decreases and my validation accuracy is constant at 50%. Inspecting the tensor...
ptrblck
I can properly overfit random samples using your model: model = NeuralNetwork() optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) criterion = nn.BCEWithLogitsLoss() x = torch.randn(8, 100, 4) target = torch.randint(0, 2, (8,)).float() for _ in range(1000): optimizer.zero_grad() ou…
patatessever
Hi everyone, I am aware that this sort of questions are already discussed but I couldnt make it work, so I have 3 channel 256x256 images and 7 classes for a semantic segmentation task.RuntimeError: Expected target size [4, 256], got [4, 256, 256, 1] I am getting this error write now.class CustomImageDataset(Dataset): ...
ptrblck
The input data shape looks wrong as PyTorch uses the channels-first memory layout by default. The inputs are thus expected to have the shape [batch_size, channels, height, width] and you might need tom .permute the input tensor. In a multi-class segmentation use case using nn.CrossEntropyLoss the …
JungHwang
Hi,I am trying to install pytorch preview version with cuda 11.8 on my conda virtual env,but it is stuck at downloading pytorch-2.0.0.dev202 at 0%.Is there anyone else facing this issue?My environments are following:OS : ubuntu 22.04GPUs : 4090 x 4NVIDIA-SMI : 525.85.05CUDA :12PYTHON : 3.8
ptrblck
Thanks for sharing the command! It looks correct and in case the download gets stuck you might be able to directly download the desired version fromhereand conda install it from the local file. I’ve just ran your provided command and while it also took some time to download the packages, it worke…
Niki
Hi everyone,I want to select only 10% of imagenet from datasets.ImageFolder as follows:image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x]) for x in ['train', 'val']}I know I should usetorch.utils.data.Subset, but I am not sure how I should feed image_datasets to this, espacially be...
ptrblck
Here is an example: image_datasets = {x: TensorDataset(torch.randn(100, 1)) for x in ["train", "val"]} lens = {x: len(image_datasets[x]) for x in ["train", "val"]} image_datasets = {x: torch.utils.data.Subset(image_datasets[x], indices=torch.randperm(int(lens[x]*0.1))) for x in ["train", "val"]} …
goodboy-hub
I met a problem about memory when i was training a model. Because the memory of my computer is small, so i monitor the memory use during training. I found that as i began to train, there will be a big increase in memory use. (about 4G increased), but the parameters were only ~0.5G(estimated by torchsummary). So , where...
ptrblck
I guess this memory increase could come from the intermediate forward activations which are needed for the gradient computation. You could take a look atthis postto get an estimation of the memory usage.
hubsiiiii
Hello,I am a little bit confused about the reproducibility and random state of PyTorch. I set seeds in my code, and everything is deterministic and reproducible. If I start my experiments with the same input, I get the same output. This is how I set the seeds:if args.deterministic: cudnn.benchmark = False ...
ptrblck
That’s expected since the _BaseDataLoaderIter sets its _base_seedherevia: self._base_seed = torch.empty((), dtype=torch.int64).random_(generator=loader.generator).item()
tgangs
Are there Pytorch operations that could reverse the effect ofrepeat_interleavein the following statement:y = x.repeat_interleave(x)For example, if y = tensor([1, 2, 2, 2, 2, 3, 3, 3, 1]), could we recover x = tensor([1, 2, 2, 3, 1])?
ptrblck
I think unique_consecutive can be used as seen here: x = torch.tensor([1, 2, 2, 3, 1]) y = x.repeat_interleave(x) u, c = y.unique_consecutive(return_counts=True) repeat = c / u out = u.repeat_interleave(repeat.long()) print(out) # tensor([1, 2, 2, 3, 1])
Dhruv_Shah
Hello Thank you for viewing my post,I have error in finding dy/dx for the following case:y = [2,3,4] ( This values are determined by function f(x) this may be different every time they are called)and I have x = [3,4,5] …What I mean to say is y is not directly a function of x (All the Examples I found on Youtube/Google...
ptrblck
In this case you might either need to implement the FEM in a differentiable way or try to calculate the gradinets somehow analytically. I don’t know how PyTorch or rather Autograd would be able to compute the backward pass without the actual computation graph.
Paul_Vandame
Hi,I need the float128 precision (which not need cuda or any GPU development).I try this code :a = np.zeros(10,dtype=np.float128)b = torch.tensor(a)Traceback (most recent call last):File “”, line 1, inTypeError: can’t convert np.ndarray of type numpy.float128. The only supported types are: float64, float32, float16, c...
ptrblck
Thanks for describing your use case in detail. I think one possible approach would be to stick to numpy and write custom Autograd.Functions wrapping these operations as described e.g.here. The disadvantage would be the need to implement the backward pass for each operation manually as Autograd doe…
tkuser
I’m trying to train a model using multi-task learning. For this I defined some random data to first check if the loss is converging. Unfortunately the loss remains constant. For this I assume that I’m trying to output two tasks (assuming image data of shape (1,28,28) and process it a convolutional network (hard-paramet...
ptrblck
nn.CrossEntropyLoss expects raw logits while you are applying F.softmax on the model outputs and are thus creating probabilities. Remove the softmax calls and check if this helps in training the model.
big_old
Hi, I am trying to get the gradients when I train Resnet50 model provided by DeepLearningExamples. And the problem is successfully solved by calling this function “print(self.model.module.conv1.weight.grad)”. But I found there are too many ‘…’ in gradients. Although I set “np.set_printoptions(threshold=sys.maxsize)”, t...
ptrblck
Using np.set_printoptions won’t change the behavior of PyTorch and you should use torch.set_printoptions(threshold=...) instead. The .grad attributes are None if they were not computed and will be filled during the backward call assuming the corresponding parameter was used to calculate the model o…
thoom08
I’m trying to train two sequential neural networks in one optimizer. I read that this can be done by defining the optimizer as follows:optimizer_domain = torch.optim.SGD(list(sentences_model.parameters()) + list(words_model.parameters()),lr=0.001)This also works for simple models after testing. However, my model is a b...
ptrblck
Yes, this is correct. Yes, this is also correct. The comparison will create aBoolTensor, which will be detached from the computation graph. However, even if the result would be a FloatTensor with an attached backward function, the gradients would be zero everywhere but the exact point when the c…
tsly123
Hi,I am trying to run the following code and it givesself.weight_mask.gradandself.bias_mask.gradisNoneI have checked many posts related to thisgrad is Noneproblem. Fromun-differentiable functiontois_leafandretain_grad(). None of them works in this case.class FC_DropConnect(nn.Module): def __init__(self, dim, mlp_hi...
ptrblck
fc.weight_mask was never used in a differentiable way, but fc.fc was. Here: self.fc.weight.data *= self.binary(self.weight_mask) #weight_mask self.fc.bias.data *= self.binary(self.bias_mask) # bias_mask you are using the deprecated .data attribute to manipulate the trainable param…
Imahn
Hi,I have a PyTorch tensor and usetorch.utils.data.TensorDatasetto make it atorch.utils.data.Datasetobject. Then I throw it into aDataLoaderand loop over it, yet the data I obtain is alist, but a tensor, and I don’t get yet why. Here an MWE:import torch data_geant_eval = torch.ones(256) test_loader = torch.utils.data...
ptrblck
The default_collate function of your DataLoader is creating the list: dataset = torch.utils.data.TensorDataset(data_geant_eval) print(type(dataset[0])) # <class 'tuple'> torch.utils.data._utils.collate.default_collate([dataset[0], dataset[1]]) # [tensor([1., 1.])] while the dataset does return th…
Zelreedy
I am working on a CNN multi-class classification of different concentrations (10uM, 30uM, etc.) I create my dataset to include the images as the features and the concentrations as labels. Note that the concentrations are left as a string. When running the code, I am getting the following error:TypeError: cross_entropy_...
ptrblck
It depends on your targets and what kind of information they contain. E.g. I don’t see a reason why your target should be a tuple assuming it only contains a single string. In case you want to map strings to integers you could use a dict: class_to_index = { "70uM": 0, "71uM": 1, "80uN…
Menan
Hi!I am new to pytorch, in my research i have a multimodal task. Where i have to load face images and its respective landmarks as input to the model. Is there any resources i can refer to achieve this using Dataset class of pytorch?
ptrblck
Yes, dicts are often used for multiple outputs as also seen in the linked tutorial.
hwanguc
Hi, I’m quite new to deep learning and I’m trying to do a transfer learning on a pretrained 3d convolutional network that classifies brain images into multiple labels (i.e., the behavioural task a participant performed while they were scanned). I loaded the pretrained model and froze parameters in every layer except fo...
ptrblck
Your model works fine for me using: model = DeepBrain() criterion = nn.CrossEntropyLoss() for param in model.parameters(): param.requires_grad = False n_inputs = 64 model.post_conv = nn.Conv3d(128, n_inputs, kernel_size=(5, 6, 5)) optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) h…
ForBo7
Hello.I’m trying to usetorchaudio.Transforms.TimeStretch, on a logarithmic spectrogram by following thePyTorch docs, but get the following error:RuntimeError: The size of tensor a (1025) must match the size of tensor b (201) at non-singleton dimension 1Full Traceback-----------------------------------------------------...
ptrblck
Based on the error message it seem the number of filter banks defined by n_freq in TimeStretch is not correct and you would have to correct it.
omid_khalafbeigi
Hi there.I’m using PyTorch for making a CNN model to classify images (labels are 0 & 1).My problem is when I’m using torch.flatten() in forward function, model parameters become zero.For example, here is my model structure and training pipeline:class Model(nn.Module): def __init__(self): super(Model, self).__init...
ptrblck
I guess you might run into some numerical issues since you are using torch.sigmoid + nn.BCELoss. Could you remove the torch.sigmoid usage and use nn.BCEWithLogitsLoss instead for a better numerical stability?
MartinZhang
Hi, Today I try use the named_modules to get the all layer from the netlike this:for name, layer in net.named_module(): print(name, layer)this can’t print the all layer ?
ptrblck
.named_module is not a valid method and you should use .named_modules instead which will print all registered modules as seen here: model = models.resnet18() for name, layer in model.named_modules(): print(name, layer)
xianxiaogao
Hello, brothersAs a beginner in photovoltaic prediction, I used the layers neural network to make probability prediction, which produced the result as shown in the figure. I found that the prediction result fluctuated frequently, as did the generated probability interval. What might be the cause?Input time step = one d...
ptrblck
You did not attach any images, just the “Uploading…” message.
Mah_Neh
I have read that YOLO, Retina with Resnet, SSD, etc can do Object Detection.Now I struggle Implementing these from scratch, so I wonder if it is possible to re train some implementation of these from Pytorch, but with a new dataset not included in the pre-trained classes.I am looking for some NNs that would run in not ...
ptrblck
MaybeSSDLitewould work for you. I don’t think Yolo is available in torchvision.
tshmak
My model trains without memory issues, but when being deployed, it has a memory leak which I cannot track down. I’m not sure whether it’s related to pytorch. But to help me narrow down the options, I would just like to know, for example, in a loop such as the following, is there potential for memory leak in pytorch? If...
ptrblck
Your code is a bit odd as it’s recreating the model in a loop, but this should not leak memory as the garbage collector should be cleaning the old variables after they were replaced by the new objects.
savvy
I am trying to understand the architechture of a pretrained model (deeplabv3) trained on mxnet and am trying to implement the same on pytorch.this is the architechture i have when I use print(model)(a lot of architecture which is similar) (head): _DeepLabHead( (aspp): _ASPP( (concurent): HybridConcurrent( ...
ptrblck
I assume the model is not a pure sequential container, but uses some functional API calls which might not be shown in the print statement. E.g.hereit seems that MXNet is resizing the activation before passing it to theauxlayer. You would have to recreate the actual forward method in PyTorch, too…
alireza_samadi
I have written a collate function to pad and stack data in the batch. when I call the custom_collate_function simply as a function passing a list of inputs , it performs well and outputs what I expect ( it can also stack the entire dataset all together ). However, when it is called in the data loader, it says it cannot...
ptrblck
Isn’t this the same issue as described in yourprevious post? In your code snippet it seems you are still using the PyG DataLoader: from torch_geometric import loader ... train_loader = loader.DataLoader(train_dataset, batch_size=batch_size, shuffle=False, collate_fn=collate_my_dataset)
Anita
Hi,Do I need to validate the model after each epoch while using DDP only on rank = 0, or should it be on all processes? With the current code I get validation loss on all processes. Which is the correct way to validate with DDP? This is my code: (I am still prototyping so validation and training loop have the same data...
ptrblck
No, I don’t think both approaches would be equal. The first one uses different samples on each device and reduces the loss, so that both devices have the same loss sum from samples [1, 2, 3, 4]. Afterwards, both devices will calculate the loss of sample 5 and add it to their local and already reduc…
Suraj520
RuntimeError: CUDA error: CUBLAS_STATUS_EXECUTION_FAILED when calling `cublasLtMatmul( ltHandle, computeDesc.descriptor(), &alpha_val, mat1_ptr, Adesc.descriptor(), mat2_ptr, Bdesc.descriptor(), &beta_val, result_ptr, Cdesc.descriptor(), result_ptr, Cdesc.descriptor(), &heuristicResult.algo, workspace.data_ptr(), works...
ptrblck
Unfortunately, your current code does not reproduce the issue, so that I won’t be able to debug it. I doubt it and would claim your input tensors might contain vocabulary indices which might be out of bounds for e.g. your embeddings. The error reporting might be broken if you are using torch==1.…
alexeybelkov
I compared x.detach().clone() and x.data.clone() for some random x with requires_grad=True in terms of computational time and detach().clone() seems a bit faster. But why?
ptrblck
I don’t see a difference using: x = torch.randn(1024, 1024, requires_grad=True) %timeit x.data.clone() %timeit x.detach().clone() but note that the .data attribute is deprecated and using .detach().clone() is the right approach.
rikonaka
I found a very strange problem, I have a trained modelnetand five test images, if I input the whole five images into the model and separately a single image into the model, I get completely different output, even the number of labels is different (four1and one8vs one1and four8).What is going on here?image1556×768 118 ...
ptrblck
Check if you are using batchnorm layers (or other layers which use a batch size - dependent operation), since the normalization of the input activation would change depending on the batch size. Please avoid this colloquial language.
AlbertZeyer
I thinkNamed Tensorsis a very promising concept. However, I wonder about its status in PyTorch. It has been around for quite a while (a few years, not sure since when exactly). But it still says:WARNING: The named tensor API is a prototype feature and subject to change.Why is this still the case? Why is it not stable b...
ptrblck
Based onthis responsefrom June 2021 it seems the development stopped. I don’t know what the current plan is and if the current implementation will be deprecated in favor of another approach or eventually dropped.
Dr_Vladyslav_Danilov
Dear torchers,I have a short comment/thought on printing pytorch tensors. The thing is that usually these tensors are big, and print function in python shows a shortened version of the tensor, which makes sense.For example:embs_txt = tensor([[ 0.0010, 0.0058, -0.0007, …, 0.0090, -0.0016, 0.0083],[-0.0112, 0.0075,...
ptrblck
You could use torch.set_printoptions(precision=...) to increase the printed precision of the values in case that’s needed.
Divyansh_Rastogi
Hi!The docs (torch.utils.data — PyTorch 1.13 documentation) define prefetch_factor as the “Number of batches loaded in advance by each worker,” implying that if I haveWworkers andPprefetch factor, the total batches loaded would beWxP, although are all of these batches that have to be loaded in advance? Or are these the...
ptrblck
This code snippetalso illustrates your description in case it’s helpful.
Goldname
I’m working on a project which requires me to rewrite the implementation of backpropagation, so I’d like to modify the current implementation of pytorch backprop. I took a look at the source code and found that it uses:Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass...Howe...
ptrblck
run_backward is definedherefor the C++ backend andherefor the Python frontend. Yes, modifying internals could cause a lot of issues, but it depends on your actual use case in the end and what you are trying to achieve.
902003b7648b9e4c4217
In order to classify images with pytorch, I modified my local data while using ImageFolder based on the following URLhttps://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.htmlHowever,”RuntimeError: shape ‘[-1, 400]’ is invalid for input of size” is displayed and I do not know the cause.I asked you because I do ...
ptrblck
It seems taht the offset and v_length calculation combined with the slicing of theta is wrong. As you can see here: torch.randn([10])[10:20].view(48) > RuntimeError: shape '[48]' is invalid for input of size 0 you are most likely creating an empty tensor in theta[offset: offset+v_length] while th…
J_W
I am attempting to use a package that employs pytorch and I keep getting errors when asking it to select GPUs 0 and 1, saying there are not that many GPUs.CUDA call failed lazily at initialization with error: device >= 0 && device < num_gpus INTERNAL ASSERT FAILED at "/opt/conda/conda-bld/pytorch_1670525552411/work/ate...
ptrblck
You cannot use multiple MIG instances in the same process and need to select one via CUDA_VISIBLE_DEVICES.
jagac
I followed the documentation hereModels and pre-trained weights — Torchvision main documentationand was wondering how can we print for example the top 3 predicted categories for ResNet50?
ptrblck
You could use torch.topk on the model outputs and check the .indices attribute.
peony
I stored the average of my losses over each epoch:losses = AverageMeter()and now I wish to plot them, so I did something like:plt.plot((float(losses))but I get this error:TypeError: float() argument must be a string or a number, not 'AverageMeter'If so, how do we convert AverageMeter to a number?Thank you in advance
ptrblck
I don’t know which implementation of AverageMeter you are using but I would assume you could access its internal attributes such as .val etc.
Sam_Lerman
Does a call to something likeloss.backwards()cause the CPU code to block?loss.backwards() print(5)Does5get printed concurrently with or afterloss.backwards()is finished executing?I tried running the following example to test it myself:import torch from torch import nn print('net') net = nn.Linear(100000, 1) print('loss...
ptrblck
Since your code is purely performed on the CPU each call would be “blocking”. Onc you move the model to the GPU its execution will be asynchronous and the CPU will only block if you are explicitly synchronizing the code or if data is moved explicitly or implicitly to the CPU.
jxtps
I’m working with images, and sometimes it’s useful to view them as one int per pixel, and sometimes as four bytes per pixel.Is there a way to convert between these two views in pytorch?Specifically I’m looking to go from four bytes per pixel to one int per pixel. Ideally while re-using the underlying memory.Thanks!
ptrblck
Would view work? >>> a = torch.tensor([1, 2, 3, 4]).to(torch.uint8) >>> a tensor([1, 2, 3, 4], dtype=torch.uint8) >>> a.view(torch.int32) tensor([67305985], dtype=torch.int32) >>> a = torch.tensor([4, 3, 2, 1]).to(torch.uint8) >>> a.view(torch.int32) tensor([16909060], dtype=torch.int32)
luuus
I have a fresh installation of PyTorch on my windows 10 laptop with all the necessaries for cuda usage. I am a new user on the forum so I can’t post images, buthere is a link to imgur showing that the cuda versions match.But when i execute some training my gpu isnt’ being used at all by python. Even though i don’t thin...
ptrblck
The CUDA version in nvidia-smi corresponds to the driver and your PyTorch binary with CUDA 11.7 should work correctly. The output also shows a GPU utilization of 56% and different processes using GPU memory. The Python process would then correspond to your PyTorch script and the GPU is thus used.