instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
Converting PyTorch transforms.compose method into Keras
I understand that we use transforms.compose to transform images via torch.transforms. I want to do the same in Keras and spending hours on internet I couldnt get how to write a method in keras that can do the same. Below is the Torch way: # preprocessing data_transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=[.5], std=[.5]) ]) Can someone please point me in the right direction.
It is a bit trivial in Tensorflow. Tensorflow recommends using the pre-processing/augmentation as part of the model itself. I do not have your complete code but I assume you would be using tf.data.Dataset API to create your dataset. This is the recommended way of building the dataset in Tensorflow. Having said that you can just prepend augmentation layers in your model. # Following is the pre-processing pipeline for e.g # Step 1: Image resizing. # Step 2: Image rescaling. # Step 3: Image normalization # Having Data Augmentation as part of the input pipeline. # Step 1: Random flip. # Step 2: Random Rotate. pre_processing_pipeline = tf.keras.Sequential([ layers.Resizing(IMG_SIZE, IMG_SIZE), layers.Rescaling(1./255), layers.Normalization(mean=[.5], variance=[.5]), ]) data_augmentation = tf.keras.Sequential([ layers.RandomFlip("horizontal_and_vertical"), layers.RandomRotation(0.2), ]) # Then add it to your model. # This would be different in your case as you might be using a pre-trained model. model = tf.keras.Sequential([ # Add the preprocessing layers you created earlier. resize_and_rescale, data_augmentation, layers.Conv2D(16, 3, padding='same', activation='relu'), layers.MaxPooling2D(), # Rest of your model. ]) For a complete list of layers check out this link. The above-given code can be found on the website here.
https://stackoverflow.com/questions/71095771/
Failing to compile project using CUDA 11.0, Python 3.8, Torch 1.8
I am trying to compile DiffDVR, a differentiable renderer. This requires running cmake first, so I had to install some dependencies. I want to use the same dependencies as the ones in the repo. I'm on Linux Mint 20.3, which is based on Ubuntu 20.04. In order, I have installed: CUDA 11.0 (using the official runfile) cuDNN v8.1.1 (the highest version compatible with 11.0, as per the cuDNN archive) created a Python 3.8 environment with Torch 1.8.0 (based on the environment.yml file in the repo) libglm-dev, libglfw3-dev and libglew-dev as they were needed for compilation. The error I get when going to the build dir and running cmake .. is: CMake Error: The following variables are used in this project, but they are set to NOTFOUND. Please set them or make sure they are set and tested correctly in the CMake files: TORCH_LIB_c10 linked by target "Renderer" in directory /home/andrei/PycharmProjects/DiffDVR/renderer linked by target "Gui" in directory /home/andrei/PycharmProjects/DiffDVR/gui TORCH_LIB_c10_cuda linked by target "Renderer" in directory /home/andrei/PycharmProjects/DiffDVR/renderer linked by target "Gui" in directory /home/andrei/PycharmProjects/DiffDVR/gui TORCH_LIB_torch_cpu linked by target "Renderer" in directory /home/andrei/PycharmProjects/DiffDVR/renderer linked by target "Gui" in directory /home/andrei/PycharmProjects/DiffDVR/gui TORCH_LIB_torch_cuda linked by target "Renderer" in directory /home/andrei/PycharmProjects/DiffDVR/renderer linked by target "Gui" in directory /home/andrei/PycharmProjects/DiffDVR/gui TORCH_LIB_torch_python linked by target "Renderer" in directory /home/andrei/PycharmProjects/DiffDVR/renderer linked by target "Gui" in directory /home/andrei/PycharmProjects/DiffDVR/gui Scrolling up in the output reveals the following problem: Torch: full library list: /usr/lib/libtorch.so;TORCH_LIB_c10-NOTFOUND;TORCH_LIB_c10_cuda-NOTFOUND;/usr/lib/libtorch.so;TORCH_LIB_torch_cpu-NOTFOUND;TORCH_LIB_torch_cuda-NOTFOUND;TORCH_LIB_torch_python-NOTFOUND So it seems like these libraries are not found. I tried to sudo apt-get install libtorch3-dev but apt says it's already installed (I assume it happened when conda installed the pytorch package?), and there are no libraries available with the c10, c10_cuda etc suffixes. How would I make sure these libraries are found, so I can compile the project? I made some progress with the following (hacky) solution: sudo ln -s /home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch/lib/libc10.so libc10.so sudo ln -s /home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch/lib/libc10_cuda.so libc10_cuda.so sudo ln -s /home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch/lib/libtorch_cpu.so libtorch_cpu.so sudo ln -s /home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch/lib/libtorch_cuda.so libtorch_cuda.so sudo ln -s /home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch/lib/libtorch_python.so libtorch_python.so Which fixed the previous errors. Unfortunately, I'm now encountering the following error: CMake Error at renderer/CMakeLists.txt:92 (add_library): CUDA_STANDARD is set to invalid value '17' More progress: Managed to run cmake successfully by uninstalling it via apt and reinstalling it via snap (because the apt version was too old). Unfortunately, make fails now, with the error: [ 46%] Building CXX object renderer/CMakeFiles/Renderer.dir/volume.cpp.o In file included from /opt/project/renderer/volume.cpp:1: /opt/project/renderer/volume.h:9:10: fatal error: torch/types.h: No such file or directory 9 | #include <torch/types.h> | ^~~~~~~~~~~~~~~ compilation terminated. make[2]: *** [renderer/CMakeFiles/Renderer.dir/build.make:76: renderer/CMakeFiles/Renderer.dir/volume.cpp.o] Error 1 make[1]: *** [CMakeFiles/Makefile2:244: renderer/CMakeFiles/Renderer.dir/all] Error 2 make: *** [Makefile:91: all] Error 2
Update: specifying all the paths manually worked. In my case, this was: cmake .. -DTORCH_PATH=/home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch -DTorch_DIR=/home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch/share/cmake/Torch -DPYTHON_LIBRARY=/home/andrei/miniconda3/envs/py38torch18/lib/libpython3.8.so -DPYTHON_EXECUTABLE=/home/andrei/miniconda3/envs/py38torch18/bin/python
https://stackoverflow.com/questions/71101695/
Unable to load .pb while converting PyTorch model to tf.keras
Context I'm using tf.keras for a personal project and I need to retrieve a pretrained Alexnet model. Unfortunately, this model is not directly accessible using tf.keras only, so I downloaded the pretrained model using PyTorch, converted it into an onnx file and then exported it as a .pb file with the following code : torch_pretrained = torchvision.models.alexnet() torch_pretrained.load_state_dict(torch.load("alexnet.pth")) dummy_input = Variable(torch.randn(1, 3, 224, 224)) torch.onnx.export(torch_pretrained, dummy_input, "alexnet_pretrained.onnx") onnx_pretrained = onnx.load("alexnet_pretrained.onnx") onnx_pretrained = prepare(onnx_pretrained) onnx_pretrained.export_graph('alexnet') Issue I'm now trying to retrieve the .pb file using keras as explained here with the following code : model = tf.keras.models.load_model("alexnet") model.summary() And i get an error : AttributeError: '_UserObject' object has no attribute 'summary' I also get a warning while loading the model, but I don't think it's relevant : WARNING:tensorflow:SavedModel saved prior to TF 2.5 detected when loading Keras model. Please ensure that you are saving the model with model.save() or tf.keras.models.save_model(), NOT tf.saved_model.save(). To confirm, there should be a file named "keras_metadata.pb" in the SavedModel directory. The loaded model has a very obscure type as you can see : <tensorflow.python.saved_model.load.Loader._recreate_base_user_object.._UserObject object at 0x0000023137981BB0> While doing my researches, I found this which means I'm not the only one to face this issue. Question The easiest way would be to solve this specific issue, but if anyone knows of another way to load a pretrained Alexnet model to tf.keras, this would also solve my actual problem. Specs Windows 10 python 3.9.7 tensorflow 2.6.0 torch 1.10.2 torchvision 0.11.3 onnx 1.10.2 onnx-tf 1.9.0
Solution I followed the suggestion of Jakub : I installed "pytorch2keras" (see this). I just ran the function to convert directly the pytorch model into a keras model, and it actually worked. I only had to modify the code of the module as there were some depencies issues (they are using onnx.optimizer, which is now called onnxoptimizer) so I just changed the import line in : from from onnx import optimizer to import onnxoptimizer as optimizer
https://stackoverflow.com/questions/71101993/
What is validation set for yolov5 training and is it necessary?
I'm training a yolov5 model and I have a dataset but I couldn't understand the differences between validation and test data. Should I split my dataset to train/test/val or just train/test?
The validation dataset provides an unbiased assessment of a fitted model on the training dataset while fitting the model's hyper-parameters (e.g. the number of hidden units - layers and layer widths - in a neural network). Validation datasets can be used for early stop regularization (stopping training when the error in the validation dataset increases, as this is a sign of overfitting to the training dataset)
https://stackoverflow.com/questions/71102661/
Save MNIST dataset with added noise
I want to save the new MNIST dataset tensors after adding noise. mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.ToTensor()) def add_noise(dataset): for data in dataset: img, _ = data[0], data[1] noisy_data = torch.tensor(random_noise(img, mode='gaussian', mean=0, var=0.05, clip=True)) return noisy_data train_gauss = add_noise(mnist_trainset) The code above only saves one image of the MNIST dataset, how can I save all tensors at once?
Your return is inside the for loop, so at the end of the first iteration it already returns the noisy_data. You should take it out of the for loop and then you could use a list to return the whole dataset at once, like so: mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transforms.ToTensor()) def add_noise(dataset): noisy_data = [] for data in dataset: img, _ = data[0], data[1] noisy_data += torch.tensor(random_noise(img, mode='gaussian', mean=0, var=0.05, clip=True)) return noisy_data train_gauss = add_noise(mnist_trainset)
https://stackoverflow.com/questions/71105059/
RuntimeError: expected scalar type Float but found Double error torch.nn.CrossEntropyLoss Pytorch
I am trying to train a pytorch model. The loss function is: cn_loss = torch.nn.CrossEntropyLoss(weight=train_label_weight, reduction='mean') Code fragment from the training function: for sents, targets in batch_iter(df_train, batch_size=train_batch_size, shuffle=True, bert=bert_size): train_iter += 1 optimizer.zero_grad() batch_size = len(sents) pre_softmax = model(sents) float_targets=torch.tensor(targets, dtype=torch.float, device=device) loss = cn_loss(pre_softmax, float_targets) loss.backward() optimizer.step() Data types of both pre_softmax and float_targets is torch.float32. (In the original code data type of the targets has been converted to torch.int64 using torch.tensor(targets, dtype=torch.long, device=device). However as I get the RuntimeError: expected scalar type Float but found Double error I converted the data type of targets to torch.float32) Even though both parameters in cn_loss() function are torch.float32, I get the below error when I run the code: loss = cn_loss(pre_softmax, float_targets) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\nn\modules\module.py", line 1102, in _call_impl return forward_call(*input, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\nn\modules\loss.py", line 1152, in forward label_smoothing=self.label_smoothing) File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\nn\functional.py", line 2846, in cross_entropy return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing) RuntimeError: expected scalar type Float but found Double I checked the data types multiple times and changed the data type of float_targets using torch.FloatTensor(targets) also. But I get the same error.
As pointed out by @aretor in comments, the data type of train_label_weight was torch.float64. When converted it to torch.float32 and changed targets to torch.long back again, the code worked perfectly
https://stackoverflow.com/questions/71108905/
How to translate the tensor type into numpy type?
import torch x = torch.linspace(-5, 5, 200) x_np = x.numpy() it return: UserWarning: Failed to initialize NumPy: No module named 'numpy.core._multiarray_umath' (Triggered internally at ..\torch\csrc\utils\tensor_numpy.cpp:68.) _dtype_to_storage = {data_type(0).dtype: data_type for data_type in _storages} RuntimeError: Numpy is not available environment; python3.7 pytorch==1.10.2
You need numpy installed pip install numpy --upgrade
https://stackoverflow.com/questions/71112548/
Pytorch - vanilla Gradient Visualization
I trained a neural network on MNIST using PyTorch: class MnistCNN(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d( 1, 16, 3, stride = 1, padding = 2) self.pool1 = nn.MaxPool2d(kernel_size = 2) self.conv2 = nn.Conv2d(16, 32, 3, stride = 1, padding = 2) self.pool2 = nn.MaxPool2d(kernel_size = 2) self.dropout = nn.Dropout(0.5) self.lin = nn.Linear(32 * 8 * 8, 10) def forward(self, x): # conv block x = F.relu(self.conv1(x)) x = self.pool1(x) # conv block x = F.relu(self.conv2(x)) x = self.pool2(x) # dense block x = x.view(x.size(0), -1) x = self.dropout(x) return self.lin(x) I would like to implement vanilla Gradient Visualization (see reference below) on my model. Simonyan, K., Vedaldi, A., Zisserman, A. Deep inside convolutional networks: Visualising image classification models and saliency maps. arXiv preprint arXiv:1312.6034 (2013) Question: How can I implement this method in PyTorch? If I understand correctly, vanilla gradient visualization consists in computing the partial derivatives of the loss of my model w.r.t all the pixels in my input image. So to make it short, I need to tweek my self.conv1 layer so that it computes the gradient over its input pixels instead of the gradient over its weights. Please correct me if I'm wrong.
You do not need to change anything about your conv layer. Each layer computes gradients both w.r.t. parameters (for updates) and w.r.t. inputs (for "downstream" gradients by the chain rule). Therefore, all you need is to set your input image's x gradient property to true: x, y = ... # get one image from MNIST x.requires_grad_(True) # indicate to pytorch that you would like to look at these gradients pred = model(x) loss = criterion(pred, y) loss.backward() # propagate gradients x.grad # <- here you should have the gradients of the loss w.r.t pixels
https://stackoverflow.com/questions/71113245/
How to define a normal distribution using tensors?
I want to define multivariate normal distribution with mean [0, 0, 0, 0] and variance - covariance matrix with only ones on diagonal. My code was: import torch import torch.distributions as td td.Normal(loc=torch.tensor(np.zeros(4)), scale=torch.tensor(np.diag(np.repeat(1, 4)), dtype = float)) But I obtain Value Error: ValueError: The parameter scale has invalid values what should I do for proper definition?
torch.distributions.Normal is the univariate normal distribution. It handles tensor arguments by computing the results as an array of univariate distributions (using broadcasting). For example, in the following, normal implements two univariate normal distributions, one with mean 0 and std. dev 1, and the other with mean 9 and std. dev. 0.25: In [89]: normal = td.Normal(loc=torch.tensor([0.0, 9.0]), ...: scale=torch.tensor([1, 0.25])) Draw 5 samples from each distribution: In [90]: normal.rsample(sample_shape=[5]) Out[90]: tensor([[ 0.2460, 8.6748], [-0.8655, 9.0666], [ 0.6386, 8.7980], [ 0.5817, 9.1428], [-0.1418, 8.5777]], dtype=torch.float64) For the multivariate normal distribution, use torch.distributions.multivariate_normal.MultivariateNormal. For example, In [98]: mvn = td.multivariate_normal.MultivariateNormal( ...: loc=torch.zeros(4, dtype=torch.float64), ...: covariance_matrix=torch.eye(4, dtype=torch.float64)) In [99]: mvn.rsample([5]) Out[99]: tensor([[ 0.6445, 1.3138, -2.1718, 1.1653], [-1.7391, -1.0428, 0.3636, 0.1957], [ 1.9167, -0.2738, -0.1590, 0.7170], [ 0.0691, -0.5422, 1.8694, 0.7470], [ 0.3545, 1.0585, -0.1825, -1.9955]], dtype=torch.float64)
https://stackoverflow.com/questions/71118320/
How to define plenty of diagonal matricies?
Let's consider tensor: scale = torch.tensor([[1.0824, 1.0296, 1.0065, 0.9395, 0.9424, 1.0260, 0.9805, 1.0509], [1.1002, 1.0358, 1.0112, 0.9466, 0.9454, 0.9942, 0.9891, 1.0485], [1.1060, 1.0157, 1.0216, 0.9544, 0.9378, 1.0160, 0.9671, 1.0240]]) which has shape : scale.shape torch.Size([3, 8]) I want to have a tensor of shape [3, 8, 8] where in which I have three diagonal matricies using values from tensor scale. In other words, first matrix will have diagonals only using scale[0], second one scale[1] and last one scale[2]. We can do it brainless: import torch temp = torch.tensor([]) for i in range(0, 3): temp = torch.cat([temp, torch.diag(scale[i])]) temp = temp.view(3, 8, 8) temp But I'm wondering if there is any other more efficient way to do this.
I think you are looking for diag_embed: temp = torch.diag_embed(scale) For example: scale = torch.arange(24).view(3,8) torch.diag_embed(scale) tensor([[[ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 1, 0, 0, 0, 0, 0, 0], [ 0, 0, 2, 0, 0, 0, 0, 0], [ 0, 0, 0, 3, 0, 0, 0, 0], [ 0, 0, 0, 0, 4, 0, 0, 0], [ 0, 0, 0, 0, 0, 5, 0, 0], [ 0, 0, 0, 0, 0, 0, 6, 0], [ 0, 0, 0, 0, 0, 0, 0, 7]], [[ 8, 0, 0, 0, 0, 0, 0, 0], [ 0, 9, 0, 0, 0, 0, 0, 0], [ 0, 0, 10, 0, 0, 0, 0, 0], [ 0, 0, 0, 11, 0, 0, 0, 0], [ 0, 0, 0, 0, 12, 0, 0, 0], [ 0, 0, 0, 0, 0, 13, 0, 0], [ 0, 0, 0, 0, 0, 0, 14, 0], [ 0, 0, 0, 0, 0, 0, 0, 15]], [[16, 0, 0, 0, 0, 0, 0, 0], [ 0, 17, 0, 0, 0, 0, 0, 0], [ 0, 0, 18, 0, 0, 0, 0, 0], [ 0, 0, 0, 19, 0, 0, 0, 0], [ 0, 0, 0, 0, 20, 0, 0, 0], [ 0, 0, 0, 0, 0, 21, 0, 0], [ 0, 0, 0, 0, 0, 0, 22, 0], [ 0, 0, 0, 0, 0, 0, 0, 23]]]) If you insist on using a loop and torch.cat, you can use a list comprehension: temp = torch.stack([torch.diag(s_) for s_ in scale])
https://stackoverflow.com/questions/71122005/
How to understand torch.arange(0, 3).view(-1, *[1]*3)
In Pytorch, for the code: torch.arange(0, 3).view(-1, *[1]*3) The result is: tensor([[[[0]]], [[[1]]], [[[2]]]]) torch.Size([3, 1, 1, 1]) Where [1] * 3 = [1, 1, 1], but I don`t understand the * before [1] * 3. What is the meaning of it? Thanks.
While links provided in the comments describe parts of the solution, whole thing might be missing, hence, let’s disentangle this view method: .view(-1,...) Means “all the elements”, in your case it is 3 as you have [0, 1, 2] with length of 3. Next: [1] * 3 Is a Python trick to create new list with single element repeated multiple times. It is the same as [1, 1, 1] Now unpacking with asterisk “unpacks” values as arguments to function, in this case: .view(-1, [1, 1, 1]) Becomes: .view(-1, 1, 1, 1) And the whole thing is (according to first step): .view(3, 1, 1, 1) BTW. Please don't do that under most circumstances, it’s pretty hard to follow as one can see above.
https://stackoverflow.com/questions/71128216/
Pytorch's gather, sequeeze and unsqueeze to Tensorflow Keras
I am migrating a code from pytorch to tensorflow, and in the function that calculates the loss, I have the below line that I need to migrate to tensorflow. state_action_values = net(t_states_features).gather(1, actions_v.unsqueeze(-1)).squeeze(-1) I found tf.gather and tf.gather_nd and I am not sure which is more suitable and how it could be used, also unsqueeze's alternative is maybe tf.expand_dims? In an attempt to get a clearer view of the line's result, I split it into multiple parts with print statements. print("net result") state_action_values = net(t_states_features) print(state_action_values) print("gather result") state_action_values = state_action_values.gather(1, actions_v.unsqueeze(-1)) print(state_action_values) print("last squeeze") state_action_values = state_action_values.squeeze(-1) net result tensor([[ 45.6878, -14.9495, 59.3737], [ 33.5737, -10.4617, 39.0078], [ 67.7197, -22.8818, 85.7977], [ 94.7701, -33.2053, 120.5519], [ nan, nan, nan], [ 84.7324, -29.2101, 108.0821], [ 67.7193, -22.7702, 86.9558], [113.6835, -38.7149, 142.6167], [ 61.9260, -20.1968, 79.8010], [ 51.6152, -17.7391, 66.0719], [ 73.6565, -21.5699, 98.9463], [ 84.0761, -26.5016, 107.6888], [ 60.9459, -20.1257, 76.4105], [103.2883, -35.4035, 130.4503], [ 37.1156, -13.5180, 47.1067], [ nan, nan, nan], [ 55.6286, -18.5239, 71.9837], [ 55.3858, -18.7892, 71.1197], [ 50.2419, -17.2959, 66.7059], [ 82.5715, -30.0302, 108.4984], [ -0.8662, -1.1861, 1.6033], [112.4620, -38.6416, 142.4556], [ 57.8702, -19.8080, 74.7656], [ 45.8418, -15.7436, 57.3367], [ 81.6596, -27.5002, 104.6002], [ 57.1507, -21.8001, 67.7933], [ 35.0414, -11.8199, 47.6573], [ 67.7085, -23.1017, 85.4623], [ 40.6284, -12.4578, 58.9603], [ 68.6394, -23.1481, 87.0832], [ 27.0549, -8.6635, 34.0150], [ 25.4071, -8.5511, 34.0285], [ 62.9161, -22.1693, 78.7965], [ 85.4505, -28.1487, 108.6252], [ 67.6665, -23.2376, 85.7117], [ 60.7806, -20.2784, 77.1022], [ 66.5209, -21.5674, 88.5561], [ 61.6637, -20.9891, 72.3873], [ 45.1634, -15.4678, 61.4886], [ 66.8119, -23.1250, 85.6189], [ nan, nan, nan], [ 67.8166, -24.8342, 84.6706], [ 86.2114, -29.5941, 107.8025], [ 66.2716, -23.3309, 83.9700], [101.2122, -35.3554, 127.4772], [ 61.0749, -19.4720, 78.5588], [ 50.4058, -16.1262, 63.1010], [ 27.7543, -9.3767, 35.7448], [ 67.7810, -23.4962, 83.6030], [ 35.0103, -11.7238, 44.7983], [ 55.7402, -19.0223, 70.3627], [ 67.9733, -22.0783, 85.1893], [ 60.5253, -20.3157, 79.7312], [ 67.2404, -21.5205, 81.4499], [ 57.9502, -20.7747, 70.9109], [ 87.6536, -31.4256, 112.6491], [ 90.3668, -30.7755, 116.6192], [ 59.0660, -19.6988, 75.0723], [ 50.0969, -17.4135, 62.6556], [ 28.8703, -9.0950, 34.5749], [ 68.4053, -22.0715, 88.2302], [ 69.1397, -21.4236, 84.7833], [ 23.8506, -8.1834, 30.8318], [ 58.4296, -20.2432, 73.8116], [ 87.5317, -29.0606, 110.0389], [ nan, nan, nan], [ 88.6387, -30.6154, 112.4239], [ 51.6089, -16.1073, 66.2757], [ 94.3989, -32.1473, 119.0358], [ 82.7449, -30.7778, 102.8537], [ 74.3067, -26.6585, 98.2536], [ 77.0881, -26.5706, 98.3553], [ 28.5688, -9.2949, 41.1165], [ 86.1560, -26.9364, 107.0244], [ 41.8914, -16.9703, 57.3840], [ 88.8886, -29.7008, 108.2697], [ 61.1243, -20.7566, 77.2257], [ 85.1174, -28.7558, 107.3853], [ 81.7256, -27.9047, 104.5006], [ 51.2663, -16.5880, 67.1428], [ 46.9150, -12.7457, 61.3240], [ 36.1758, -12.9769, 47.7178], [ 85.5846, -29.4141, 107.9649], [ 59.9424, -20.8349, 75.3359], [ 62.6516, -22.1235, 81.6903], [104.7664, -34.5876, 129.9478], [ 64.4671, -23.3980, 83.9093], [ 69.6928, -23.6567, 89.6024], [ 60.4407, -19.6136, 75.9350], [ 33.4921, -10.3434, 44.9537], [ 57.9112, -19.4174, 74.3050], [ 24.8262, -9.3637, 30.1057], [ 85.3776, -28.9097, 110.1310], [ 63.8175, -22.3843, 81.0308], [ 34.6040, -12.3217, 46.0356], [ 88.3740, -29.5049, 110.2897], [ 66.8196, -22.5860, 85.5386], [ 58.9767, -22.0601, 78.7086], [ 83.2090, -26.3499, 113.5105], [ 54.8450, -17.7980, 68.1161], [ nan, nan, nan], [ 85.0846, -29.2494, 107.6780], [ 76.9251, -26.2295, 98.4755], [ 98.2907, -32.8878, 124.9192], [ 91.1387, -30.8262, 115.3978], [ 73.1062, -24.9450, 90.0967], [ 27.6564, -8.6114, 35.4470], [ 71.8508, -25.1529, 95.5165], [ 69.7275, -20.1357, 86.9620], [ 67.0907, -21.9245, 84.8853], [ 77.3163, -25.5980, 92.7700], [ 63.0082, -21.0345, 78.7311], [ 68.0553, -22.4280, 84.8031], [ 5.8148, -2.3171, 8.0620], [103.3399, -35.1769, 130.7801], [ 54.8769, -18.6822, 70.4657], [ 58.4446, -18.9764, 75.5509], [ 91.0071, -31.2706, 112.6401], [ 84.6577, -29.2644, 104.6046], [ 45.4887, -15.8309, 59.0498], [ 56.3384, -18.9264, 78.8834], [ 63.5109, -21.3169, 81.5144], [ 79.4635, -29.8681, 100.5056], [ 27.6559, -10.0517, 35.6012], [ 76.3909, -24.1689, 93.6133], [ 34.3802, -11.5272, 45.8650], [ 60.3553, -20.1693, 76.5371], [ 56.0590, -18.6468, 69.8981]], grad_fn=<AddmmBackward0>) gather result tensor([[ 59.3737], [-10.4617], [ 67.7197], [ 94.7701], [ nan], [-29.2101], [ 67.7193], [-38.7149], [-20.1968], [ 66.0719], [ 98.9463], [107.6888], [-20.1257], [-35.4035], [ 47.1067], [ nan], [ 55.6286], [-18.7892], [ 66.7059], [-30.0302], [ 1.6033], [112.4620], [ 74.7656], [-15.7436], [ 81.6596], [-21.8001], [ 35.0414], [-23.1017], [ 40.6284], [ 68.6394], [ 34.0150], [ 34.0285], [ 78.7965], [-28.1487], [ 67.6665], [-20.2784], [-21.5674], [ 72.3873], [-15.4678], [ 85.6189], [ nan], [-24.8342], [-29.5941], [-23.3309], [101.2122], [-19.4720], [-16.1262], [ -9.3767], [-23.4962], [-11.7238], [ 70.3627], [-22.0783], [-20.3157], [ 67.2404], [-20.7747], [112.6491], [-30.7755], [-19.6988], [ 50.0969], [ 34.5749], [ 88.2302], [-21.4236], [ -8.1834], [ 73.8116], [110.0389], [ nan], [112.4239], [-16.1073], [-32.1473], [-30.7778], [ 98.2536], [ 98.3553], [ 28.5688], [107.0244], [-16.9703], [-29.7008], [ 77.2257], [-28.7558], [-27.9047], [ 67.1428], [-12.7457], [ 47.7178], [-29.4141], [ 59.9424], [-22.1235], [129.9478], [-23.3980], [-23.6567], [ 75.9350], [-10.3434], [-19.4174], [ 30.1057], [ 85.3776], [ 63.8175], [ 46.0356], [-29.5049], [-22.5860], [-22.0601], [113.5105], [-17.7980], [ nan], [-29.2494], [ 76.9251], [-32.8878], [115.3978], [-24.9450], [ 35.4470], [ 95.5165], [ 86.9620], [-21.9245], [-25.5980], [ 78.7311], [-22.4280], [ 5.8148], [103.3399], [ 70.4657], [ 58.4446], [ 91.0071], [104.6046], [ 45.4887], [-18.9264], [ 63.5109], [ 79.4635], [-10.0517], [ 76.3909], [ 34.3802], [-20.1693], [-18.6468]], grad_fn=<GatherBackward0>) last squeeze tensor([ 59.3737, -10.4617, 67.7197, 94.7701, nan, -29.2101, 67.7193, -38.7149, -20.1968, 66.0719, 98.9463, 107.6888, -20.1257, -35.4035, 47.1067, nan, 55.6286, -18.7892, 66.7059, -30.0302, 1.6033, 112.4620, 74.7656, -15.7436, 81.6596, -21.8001, 35.0414, -23.1017, 40.6284, 68.6394, 34.0150, 34.0285, 78.7965, -28.1487, 67.6665, -20.2784, -21.5674, 72.3873, -15.4678, 85.6189, nan, -24.8342, -29.5941, -23.3309, 101.2122, -19.4720, -16.1262, -9.3767, -23.4962, -11.7238, 70.3627, -22.0783, -20.3157, 67.2404, -20.7747, 112.6491, -30.7755, -19.6988, 50.0969, 34.5749, 88.2302, -21.4236, -8.1834, 73.8116, 110.0389, nan, 112.4239, -16.1073, -32.1473, -30.7778, 98.2536, 98.3553, 28.5688, 107.0244, -16.9703, -29.7008, 77.2257, -28.7558, -27.9047, 67.1428, -12.7457, 47.7178, -29.4141, 59.9424, -22.1235, 129.9478, -23.3980, -23.6567, 75.9350, -10.3434, -19.4174, 30.1057, 85.3776, 63.8175, 46.0356, -29.5049, -22.5860, -22.0601, 113.5105, -17.7980, nan, -29.2494, 76.9251, -32.8878, 115.3978, -24.9450, 35.4470, 95.5165, 86.9620, -21.9245, -25.5980, 78.7311, -22.4280, 5.8148, 103.3399, 70.4657, 58.4446, 91.0071, 104.6046, 45.4887, -18.9264, 63.5109, 79.4635, -10.0517, 76.3909, 34.3802, -20.1693, -18.6468], grad_fn=<SqueezeBackward1>) Edit 1: print of actions_v actions_v tensor([2, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 2, 0, 2, 0, 1, 2, 0, 2, 1, 1, 0, 2, 1, 0, 0, 2, 1, 1, 1, 0, 1, 0, 1, 1, 2, 1, 1, 2, 1, 0, 2, 1, 2, 0, 2, 2, 0, 0, 1, 2, 0, 1, 2, 0, 0, 1, 1, 2, 0, 0, 2, 0, 0, 1, 1, 2, 0, 1, 0, 2, 0, 1, 0, 0, 0, 0, 1, 2, 0, 2, 0, 1, 1, 2, 1, 2, 2, 2, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 2, 1, 1, 0, 1, 0, 1, 2, 2, 1, 0, 2, 0, 0, 2, 1])
gather_nd takes inputs that have the same dimension as the input tensor, and will output a tensor of values being at those indices (which is what you want). gather will output slices (but you can give as indice shape whatever you want, the output tensor will just be a bunch of slices that are structured accordingly to the shape of indices) which is not what you want. So you should first make the indices match the dimensions of the initial matrix: indices = tf.transpose(tf.stack((tf.range(tf.shape(state_action_values)[0]),actions_v))) And then gather_nd: state_action_values = tf.gather_nd(state_action_values,indices) Keivan
https://stackoverflow.com/questions/71133832/
How to fix "Boolean value of Tensor with more than one value is ambiguous"?
I am trying to create a Model, but i'm getting a RuntimeError "Boolean value of Tensor with more than one value is ambiguous". I've searched already on other posts about this but could find a working solution so here is my own try. I am following a tutorial, which is working with the tutorial set of Data. The code looks as follows: #%% import file df = pd.read_csv('coordinates.csv', sep='\;', engine='python') df #%% cleanup df=df[[ 'CATEGORY','LEFT_ANGLE']] print(df) df.apply(pd.to_numeric) #%% from tkinter import Variable import numpy as np from sklearn.preprocessing import MinMaxScaler def sliding_windows(data, seq_length): x = [] y = [] for i in range(len(data)-seq_length-1): _x = data[i:(i+seq_length)] _y = data[i+seq_length] x.append(_x) y.append(_y) return np.array(x),np.array(y) #%% sc = MinMaxScaler() training_data = sc.fit_transform(df) seq_length = 4 x, y = sliding_windows(training_data, seq_length) train_size = int(len(y) * 0.67) test_size = len(y) - train_size dataX = Variable(torch.Tensor(np.array(x))) dataY = Variable(torch.Tensor(np.array(y))) trainX = Variable(torch.Tensor(np.array(x[0:train_size]))) trainY = Variable(torch.Tensor(np.array(y[0:train_size]))) testX = Variable(torch.Tensor(np.array(x[train_size:len(x)]))) testY = Variable(torch.Tensor(np.array(y[train_size:len(y)]))) This is the DataFrame i want to use for training and the error: [300 rows x 2 columns] 6 CATEGORY LEFT_ANGLE 0 0 160 1 0 162 2 0 160 3 0 157 4 0 146 ... ... ... 295 4 163 296 4 176 297 4 132 298 4 150 299 4 176 300 rows × 2 columns Cleanup done --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-12-2bfe2346f838> in <module> 8 test_size = len(y) - train_size 9 ---> 10 dataX = Variable(torch.Tensor(np.array(x))) 11 dataY = Variable(torch.Tensor(np.array(y))) 12 331 raise TypeError("name must be a string") 332 global _varnum --> 333 if not master: 334 master = _default_root 335 self._root = master._root() RuntimeError: Boolean value of Tensor with more than one value is ambiguous In the first place i dont understand what the class Variable is for and why the Tensor does not accept my array. I hope someone can help me. Thanks in advance and sorry if my englisch is not the best.
Short answer: Remove the Variable() Explanation: I believe your answer is in you question. If you don't know what Variable is, why are you using it? But more importantly you are importing it from tkinter which is an interface package and I'm pretty sure that's not what you want. What you want is to use the one from torch. I was looking for it in the doc but it is actually deprecated, the Variable() API from torch now returns a Tensor so it is not useful anymore. see here
https://stackoverflow.com/questions/71138474/
Pytorch : different behaviours in GAN training with different, but conceptually equivalent, code
I'm trying to implement a simple GAN in Pytorch. The following training code works: for epoch in range(max_epochs): # loop over the dataset multiple times print(f'epoch: {epoch}') running_loss = 0.0 for batch_idx,(data,_) in enumerate(data_gen_fn): # data preparation real_data = data input_shape = real_data.shape inputs_generator = torch.randn(*input_shape).detach() # generator forward fake_data = generator(inputs_generator).detach() # discriminator forward optimizer_generator.zero_grad() optimizer_discriminator.zero_grad() #################### ALERT CODE ####################### predictions_on_real = discriminator(real_data) predictions_on_fake = discriminator(fake_data) predictions = torch.cat((predictions_on_real, predictions_on_fake), dim=0) ######################################################### # loss discriminator labels_real_fake = torch.tensor([1]*batch_size + [0]*batch_size) loss_discriminator_batch = criterion_discriminator(predictions, labels_real_fake) # update discriminator loss_discriminator_batch.backward() optimizer_discriminator.step() # generator # zero the parameter gradients optimizer_discriminator.zero_grad() optimizer_generator.zero_grad() fake_data = generator(inputs_generator) # make again fake data but without detaching predictions_on_fake = discriminator(fake_data) # D(G(encoding)) # loss generator labels_fake = torch.tensor([1]*batch_size) loss_generator_batch = criterion_generator(predictions_on_fake, labels_fake) loss_generator_batch.backward() # dL(D(G(encoding)))/dW_{G,D} optimizer_generator.step() If I plot the generated images for each iteration, I see that the generated images look like the real ones, so the training procedure seems to work well. However, if I try to change the code in the ALERT CODE part , i.e., instead of: #################### ALERT CODE ####################### predictions_on_real = discriminator(real_data) predictions_on_fake = discriminator(fake_data) predictions = torch.cat((predictions_on_real, predictions_on_fake), dim=0) ######################################################### I use the following: #################### ALERT CODE ####################### predictions = discriminator(torch.cat( (real_data, fake_data), dim=0)) ####################################################### That is conceptually the same (in a nutshell, instead of doing two different forward on the discriminator, the former on the real, the latter on the fake data, and finally concatenate the results, with the new code I first concatenate real and fake data, and finally I make just one forward pass on the concatenated data. However, this code version does not work, that is the generated images seems to be always random noise. Any explanation to this behavior?
Why do we different results? Supplying inputs in either the same batch, or separate batches, can make a difference if the model includes dependencies between different elements of the batch. By far the most common source in current deep learning models is batch normalization. As you mentioned, the discriminator does include batchnorm, so this is likely the reason for different behaviors. Here is an example. Using single numbers and a batch size of 4: features = [1., 2., 5., 6.] print("mean {}, std {}".format(np.mean(features), np.std(features))) print("normalized features", (features - np.mean(features)) / np.std(features)) >>>mean 3.5, std 2.0615528128088303 >>>normalized features [-1.21267813 -0.72760688 0.72760688 1.21267813] Now we split the batch into two parts. First part: features = [1., 2.] print("mean {}, std {}".format(np.mean(features), np.std(features))) print("normalized features", (features - np.mean(features)) / np.std(features)) >>>mean 1.5, std 0.5 >>>normalized features [-1. 1.] Second part: features = [5., 6.] print("mean {}, std {}".format(np.mean(features), np.std(features))) print("normalized features", (features - np.mean(features)) / np.std(features)) >>>mean 5.5, std 0.5 >>>normalized features [-1. 1.] As we can see, in the split-batch version, the two batches are normalized to the exact same numbers, even though the inputs are very different. In the joint-batch version, on the other hand, the larger numbers are still larger than the smaller ones as they are normalized using the same statistics. Why does this matter? With deep learning, it's always hard to say, and especially with GANs and their complex training dynamics. A possible explanation is that, as we can see in the example above, the separate batches result in more similar features after normalization even if the original inputs are quite different. This may help early in training, as the generator tends to output "garbage" which has very different statistics from real data. With a joint batch, these differing statistics make it easy for the discriminator to tell the real and generated data apart, and we end up in a situation where the discriminator "overpowers" the generator. By using separate batches, however, the different normalizations result in the generated and real data to look more similar, which makes the task less trivial for the discriminator and allows the generator to learn.
https://stackoverflow.com/questions/71140227/
Pytorch error: RuntimeError: 1D target tensor expected, multi-target not supported
I am currently working on an neuronal network that can classify cats and dog and everything thats not cat nor dog. And my programm has this: error i can't solve: " File "/home/johann/Schreibtisch/NN_v0.01/classification.py", line 146, in train(epoch) File "/home/johann/Schreibtisch/NN_v0.01/classification.py", line 109, in train loss = criterion(out, target) File "/home/johann/.local/lib/python3.8/site-packages/torch/nn/modules/module.py", line 889, in _call_impl result = self.forward(*input, **kwargs) File "/home/johann/.local/lib/python3.8/site-packages/torch/nn/modules/loss.py", line 1047, in forward return F.cross_entropy(input, target, weight=self.weight, File "/home/johann/.local/lib/python3.8/site-packages/torch/nn/functional.py", line 2693, in cross_entropy return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction) File "/home/johann/.local/lib/python3.8/site-packages/torch/nn/functional.py", line 2388, in nll_loss ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index) RuntimeError: 1D target tensor expected, multi-target not supported" The code: import os from torchvision import transforms from PIL import Image from os import listdir import random import torch.optim as optim from torch.autograd import Variable import torch.nn.functional as F import torch.nn as nn import matplotlib.pyplot as plt from tqdm import tqdm normalize = transforms.Normalize( mean = [0.485, 0.456, 0.406], std = [0.229, 0.224, 0.225]) transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(256), transforms.ToTensor(), normalize]) train_data_list = [] target_list = [] train_data = [] waited = False files = listdir('catsanddogs/train/') for i in range(len(listdir('catsanddogs/train/'))): if len(train_data) == 58 and not waited: waited = True continue f = random.choice(files) files.remove(f) img = Image.open("catsanddogs/train/" + f) img_tensor = transform(img) train_data_list.append(img_tensor) isSomething = 0 isCat = 1 if 'cat' in f else 0 isDog = 1 if 'dog' in f else 0 if isDog == 0 and isCat == 0: isSomething = 1 target = [isCat, isDog, isSomething] #, isSomthing target_list.append(target) if len(train_data_list) >= 256: train_data.append((torch.stack(train_data_list), target_list)) train_data_list = [] target_list = [] print('Loaded batch ', len(train_data), 'of ', int(len(listdir('catsanddogs/train/')) / 64)) print('Percentage Done: ', 100 * len(train_data) / int(len(listdir('catsanddogs/train/')) / 64), '%') if len(train_data) > 2: break class Netz(nn.Module): def __init__(self): super(Netz, self).__init__() self.conv1 = nn.Conv2d(3, 6, kernel_size=(5, 5)) self.conv2 = nn.Conv2d(6, 12, kernel_size=(5, 5)) self.conv3 = nn.Conv2d(12, 18, kernel_size=(5, 5)) self.conv4 = nn.Conv2d(18, 24, kernel_size=(5, 5)) self.fc1 = nn.Linear(3456, 1000) self.fc2 = nn.Linear(1000, 3) def forward(self, x): x = self.conv1(x) x = F.max_pool2d(x, 2) x = F.relu(x) x = self.conv2(x) x = F.max_pool2d(x, 2) x = F.relu(x) x = self.conv3(x) x = F.max_pool2d(x, 2) x = F.relu(x) x = self.conv4(x) x = F.max_pool2d(x, 2) x = F.relu(x) x = x.view(-1, 3456) x = F.relu(self.fc1(x)) x = self.fc2(x) return F.softmax(x, dim=1) model = Netz() #if os.path.isfile('catdognetz.pt'): #model = torch.load('catdognetz.pt') optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9) def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) count_parameters(model) train_losses = [] train_accu = [] def train(epoch): print('\nEpoch : %d' % epoch) model.train() running_loss = 0 correct = 0 total = 0 for data, target in tqdm(train_data): target = torch.Tensor(target) data = Variable(data) target = Variable(target) optimizer.zero_grad() out = model(data) criterion = nn.CrossEntropyLoss() loss = criterion(out, target) loss.backward() optimizer.step() running_loss += loss.item() predicted = out.max(1) total += target.size(0) correct += predicted.eq(target).sum().item() train_loss = running_loss / len(train_data) accu = 100. * float(correct) / total train_accu.append(accu) train_losses.append(train_loss) print('Train Loss: %.3f | Accuracy: %.3f' % (train_loss, accu)) def test(): model.eval() file = listdir('catsanddogs/test/') f = random.choice(file) img = Image.open('catsanddogs/test/' + f) img_eval_tensor = transform(img) img_eval_tensor.unsqueeze_(0) data = Variable(img_eval_tensor) out = model(data) what = "It's a cat" print(out.data.max(1, keepdim=True)[1].cpu().numpy()[0]) if out.data.max(1, keepdim=True)[1].cpu().numpy()[0] != 0: what = "It's a Dog" if out.data.max(1, keepdim=True)[1].cpu().numpy()[0] != 0 and out.data.max(1, keepdim=True)[1].cpu().numpy()[0] != 1: what = "Neither" print(what) img.show() #x = input('') epochs = 10 for epoch in range(1, epochs + 1): train(epoch) #test() torch.save(model, 'catdognetz.pt') plt.plot(train_accu,'-o') plt.xlabel('epoch') plt.ylabel('accuracy') plt.legend(['Kurve: Training']) plt.title('Train Accuracy') plt.show() plt.plot(train_losses,'-o') plt.xlabel('epoch') plt.ylabel('loss bzw. Verlust') plt.legend(['Kruve : Training']) plt.title('Train Loss') plt.show()```
The reason behind this error is that your targets list are list of lists like that: target = [[1,0,0],[0,1,0],[0,0,1],...] You should use an 1D tensor instead of the one-hot code list because CrossEntropyLoss does not accept one-hot coded tensor. For example, you can use this: target = torch.tensor([0, 1, 2, 2, 1, 0, 0, ...]) # cat = 1, dog=2, something else= 2 You can automatically convert your targets from a one-hot coded list to a tensor of classes by: target = torch.tensor(target) target= torch.argmax(target ,axis=1) Or you can change your algorithm to create a 1D tensor instead of a list of lists. You can read more the documentation of CrossEntropyLoss here
https://stackoverflow.com/questions/71142953/
Upsampling images in frequency domain using Pytorch
I'm trying to upsample an RGB image in the frequency domain, using Pytorch. I'm using this article for reference on grayscale images. Since Pytorch processes the channels individually, I figure the colorspace is irrelevant here. The basic steps outlined by this article are: Perform FFT on the image. Pad the FFT with zeros. Perform inverse FFT. I wrote the following code for the same: import torch import cv2 import numpy as np img = src = cv2.imread('orig.png') torch_img = torch.from_numpy(img).to(torch.float32).permute(2, 0, 1) / 255. fft = torch.fft.fft2(torch_img, norm="forward") fr = fft.real fi = fft.imag fr = F.pad(fr, (fft.shape[-1]//2, fft.shape[-1]//2, fft.shape[-2]//2, fft.shape[-2]//2), mode='constant', value=0) fi = F.pad(fi, (fft.shape[-1]//2, fft.shape[-1]//2, fft.shape[-2]//2, fft.shape[-2]//2), mode='constant', value=0) fft_hires = torch.complex(fr, fi) inv = torch.fft.ifft2(fft_hires, norm="forward").real print(inv.max(), inv.min()) img = (inv.permute(1, 2, 0).detach()).clamp(0, 1) img = (255 * img).numpy().astype(np.uint8) cv2.imwrite('hires.png', img) The original image: The upscaled image: Another interesting thing to note is the maximum and minimum values of the image pixels after performing IFFT: they are 2.2729 and -1.8376 respectively. Ideally, they should be 1.0 and 0.0. Can someone please explain what's wrong here?
The usual convention for the DFT is to treat the first sample as 0Hz component. But you need to have the 0Hz component in the center in order for padding to make sense. Most FFT tools provide a shift function to circularly shift your result so that the 0Hz component is in the center. In pytorch you need to perform torch.fft.fftshift after the FFT and torch.fft.ifftshift right before taking the inverse FFT to put the 0Hz component back in the upper left corner. import torch import torch.nn.functional as F import cv2 import numpy as np img = src = cv2.imread('orig.png') torch_img = torch.from_numpy(img).to(torch.float32).permute(2, 0, 1) / 255. # note the fftshift fft = torch.fft.fftshift(torch.fft.fft2(torch_img, norm="forward")) fr = fft.real fi = fft.imag fr = F.pad(fr, (fft.shape[-1]//2, fft.shape[-1]//2, fft.shape[-2]//2, fft.shape[-2]//2), mode='constant', value=0) fi = F.pad(fi, (fft.shape[-1]//2, fft.shape[-1]//2, fft.shape[-2]//2, fft.shape[-2]//2), mode='constant', value=0) # note the ifftshift fft_hires = torch.fft.ifftshift(torch.complex(fr, fi)) inv = torch.fft.ifft2(fft_hires, norm="forward").real print(inv.max(), inv.min()) img = (inv.permute(1, 2, 0).detach()).clamp(0, 1) img = (255 * img).numpy().astype(np.uint8) cv2.imwrite('hires.png', img) which produces the following hires.png
https://stackoverflow.com/questions/71143279/
Using RNN Trained Model without pytorch installed
I have trained an RNN model with pytorch. I need to use the model for prediction in an environment where I'm unable to install pytorch because of some strange dependency issue with glibc. However, I can install numpy and scipy and other libraries. So, I want to use the trained model, with the network definition, without pytorch. I have the weights of the model as I save the model with its state dict and weights in the standard way, but I can also save it using just json/pickle files or similar. I also have the network definition, which depends on pytorch in a number of ways. This is my RNN network definition. import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import random torch.manual_seed(1) random.seed(1) device = torch.device('cpu') class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size,num_layers, matching_in_out=False, batch_size=1): super(RNN, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.output_size = output_size self.num_layers = num_layers self.batch_size = batch_size self.matching_in_out = matching_in_out #length of input vector matches the length of output vector self.lstm = nn.LSTM(input_size, hidden_size,num_layers) self.hidden2out = nn.Linear(hidden_size, output_size) self.hidden = self.init_hidden() def forward(self, feature_list): feature_list=torch.tensor(feature_list) if self.matching_in_out: lstm_out, _ = self.lstm( feature_list.view(len( feature_list), 1, -1)) output_space = self.hidden2out(lstm_out.view(len( feature_list), -1)) output_scores = torch.sigmoid(output_space) #we'll need to check if we need this sigmoid return output_scores #output_scores else: for i in range(len(feature_list)): cur_ft_tensor=feature_list[i]#.view([1,1,self.input_size]) cur_ft_tensor=cur_ft_tensor.view([1,1,self.input_size]) lstm_out, self.hidden = self.lstm(cur_ft_tensor, self.hidden) outs=self.hidden2out(lstm_out) return outs def init_hidden(self): #return torch.rand(self.num_layers, self.batch_size, self.hidden_size) return (torch.rand(self.num_layers, self.batch_size, self.hidden_size).to(device), torch.rand(self.num_layers, self.batch_size, self.hidden_size).to(device)) I am aware of this question, but I'm willing to go as low level as possible. I can work with numpy array instead of tensors, and reshape instead of view, and I don't need a device setting. Based on the class definition above, what I can see here is that I only need the following components from torch to get an output from the forward function: nn.LSTM nn.Linear torch.sigmoid I think I can easily implement the sigmoid function using numpy. However, can I have some implementation for the nn.LSTM and nn.Linear using something not involving pytorch? Also, how will I use the weights from the state dict into the new class? So, the question is, how can I "translate" this RNN definition into a class that doesn't need pytorch, and how to use the state dict weights for it? Alternatively, is there a "light" version of pytorch, that I can use just to run the model and yield a result? EDIT I think it might be useful to include the numpy/scipy equivalent for both nn.LSTM and nn.linear. It would help us compare the numpy output to torch output for the same code, and give us some modular code/functions to use. Specifically, a numpy equivalent for the following would be great: rnn = nn.LSTM(10, 20, 2) input = torch.randn(5, 3, 10) h0 = torch.randn(2, 3, 20) c0 = torch.randn(2, 3, 20) output, (hn, cn) = rnn(input, (h0, c0)) and also for linear: m = nn.Linear(20, 30) input = torch.randn(128, 20) output = m(input)
Basically implementing it in numpy and copying weights from your pytorch model can do the trick. For your usecase you will only need to do a forward pass so we just need to implement that only #Set Parameters for a small LSTM network input_size = 2 # size of one 'event', or sample, in our batch of data hidden_dim = 3 # 3 cells in the LSTM layer output_size = 1 # desired model output num_layers=3 torch_lstm = RNN( input_size, hidden_dim , output_size, num_layers, matching_in_out=True ) state = torch_lstm.state_dict() # state will capture the weights of your model Now for LSTM in numpy these functions will be used: got the below code from this link: https://towardsdatascience.com/the-lstm-reference-card-6163ca98ae87 ### NOT MY CODE import numpy as np from scipy.special import expit as sigmoid def forget_gate(x, h, Weights_hf, Bias_hf, Weights_xf, Bias_xf, prev_cell_state): forget_hidden = np.dot(Weights_hf, h) + Bias_hf forget_eventx = np.dot(Weights_xf, x) + Bias_xf return np.multiply( sigmoid(forget_hidden + forget_eventx), prev_cell_state ) def input_gate(x, h, Weights_hi, Bias_hi, Weights_xi, Bias_xi, Weights_hl, Bias_hl, Weights_xl, Bias_xl): ignore_hidden = np.dot(Weights_hi, h) + Bias_hi ignore_eventx = np.dot(Weights_xi, x) + Bias_xi learn_hidden = np.dot(Weights_hl, h) + Bias_hl learn_eventx = np.dot(Weights_xl, x) + Bias_xl return np.multiply( sigmoid(ignore_eventx + ignore_hidden), np.tanh(learn_eventx + learn_hidden) ) def cell_state(forget_gate_output, input_gate_output): return forget_gate_output + input_gate_output def output_gate(x, h, Weights_ho, Bias_ho, Weights_xo, Bias_xo, cell_state): out_hidden = np.dot(Weights_ho, h) + Bias_ho out_eventx = np.dot(Weights_xo, x) + Bias_xo return np.multiply( sigmoid(out_eventx + out_hidden), np.tanh(cell_state) ) We would need the sigmoid function as well so def sigmoid(x): return 1/(1 + np.exp(-x)) Because pytorch stores weights in stacked manner so we need to break it up for that we would need the below function def get_slices(hidden_dim): slices=[] breaker=(hidden_dim*4) slices=[[i,i+3] for i in range(0, breaker, breaker//4)] return slices Now we have the functions ready for lstm, now we create an lstm class to copy the weights from pytorch class and get the output from it. class numpy_lstm: def __init__( self, layer_num=0, hidden_dim=1, matching_in_out=False): self.matching_in_out=matching_in_out self.layer_num=layer_num self.hidden_dim=hidden_dim def init_weights_from_pytorch(self, state): slices=get_slices(self.hidden_dim) print (slices) #Event (x) Weights and Biases for all gates lstm_weight_ih='lstm.weight_ih_l'+str(self.layer_num) self.Weights_xi = state[lstm_weight_ih][slices[0][0]:slices[0][1]].numpy() # shape [h, x] self.Weights_xf = state[lstm_weight_ih][slices[1][0]:slices[1][1]].numpy() # shape [h, x] self.Weights_xl = state[lstm_weight_ih][slices[2][0]:slices[2][1]].numpy() # shape [h, x] self.Weights_xo = state[lstm_weight_ih][slices[3][0]:slices[3][1]].numpy() # shape [h, x] lstm_bias_ih='lstm.bias_ih_l'+str(self.layer_num) self.Bias_xi = state[lstm_bias_ih][slices[0][0]:slices[0][1]].numpy() #shape is [h, 1] self.Bias_xf = state[lstm_bias_ih][slices[1][0]:slices[1][1]].numpy() #shape is [h, 1] self.Bias_xl = state[lstm_bias_ih][slices[2][0]:slices[2][1]].numpy() #shape is [h, 1] self.Bias_xo = state[lstm_bias_ih][slices[3][0]:slices[3][1]].numpy() #shape is [h, 1] lstm_weight_hh='lstm.weight_hh_l'+str(self.layer_num) #Hidden state (h) Weights and Biases for all gates self.Weights_hi = state[lstm_weight_hh][slices[0][0]:slices[0][1]].numpy() #shape is [h, h] self.Weights_hf = state[lstm_weight_hh][slices[1][0]:slices[1][1]].numpy() #shape is [h, h] self.Weights_hl = state[lstm_weight_hh][slices[2][0]:slices[2][1]].numpy() #shape is [h, h] self.Weights_ho = state[lstm_weight_hh][slices[3][0]:slices[3][1]].numpy() #shape is [h, h] lstm_bias_hh='lstm.bias_hh_l'+str(self.layer_num) self.Bias_hi = state[lstm_bias_hh][slices[0][0]:slices[0][1]].numpy() #shape is [h, 1] self.Bias_hf = state[lstm_bias_hh][slices[1][0]:slices[1][1]].numpy() #shape is [h, 1] self.Bias_hl = state[lstm_bias_hh][slices[2][0]:slices[2][1]].numpy() #shape is [h, 1] self.Bias_ho = state[lstm_bias_hh][slices[3][0]:slices[3][1]].numpy() #shape is [h, 1] def forward_lstm_pass(self,input_data): h = np.zeros(self.hidden_dim) c = np.zeros(self.hidden_dim) output_list=[] for eventx in input_data: f = forget_gate(eventx, h, self.Weights_hf, self.Bias_hf, self.Weights_xf, self.Bias_xf, c) i = input_gate(eventx, h, self.Weights_hi, self.Bias_hi, self.Weights_xi, self.Bias_xi, self.Weights_hl, self.Bias_hl, self.Weights_xl, self.Bias_xl) c = cell_state(f,i) h = output_gate(eventx, h, self.Weights_ho, self.Bias_ho, self.Weights_xo, self.Bias_xo, c) if self.matching_in_out: # doesnt make sense but it was as it was in main code :( output_list.append(h) if self.matching_in_out: return output_list else: return h Similarly for fully connected layer, class fully_connected_layer: def __init__(self,state, dict_name='fc', ): self.fc_Weight = state[dict_name+'.weight'][0].numpy() self.fc_Bias = state[dict_name+'.bias'][0].numpy() #shape is [,output_size] def forward(self,lstm_output, is_sigmoid=True): res=np.dot(self.fc_Weight, lstm_output)+self.fc_Bias print (res) if is_sigmoid: return sigmoid(res) else: return res Now we would need one class to call all of them together and generalise them with respect to multiple layers You can modify the below class if you need more Fully connected layers or want to set false condition for sigmoid etc. class RNN_model_Numpy: def __init__(self, state, input_size, hidden_dim, output_size, num_layers, matching_in_out=True): self.lstm_layers=[] for i in range(0, num_layers): lstm_layer_obj=numpy_lstm(layer_num=i, hidden_dim=hidden_dim, matching_in_out=True) lstm_layer_obj.init_weights_from_pytorch(state) self.lstm_layers.append(lstm_layer_obj) self.hidden2out=fully_connected_layer(state, dict_name='hidden2out') def forward(self, feature_list): for x in self.lstm_layers: lstm_output=x.forward_lstm_pass(feature_list) feature_list=lstm_output return self.hidden2out.forward(feature_list, is_sigmoid=False) Sanity check on a numpy variable: data = np.array( [[1,1], [2,2], [3,3]]) check=RNN_model_Numpy(state, input_size, hidden_dim, output_size, num_layers) check.forward(data) EXPLANATION: Since we just need forward pass, we would need certain functions that are required in LSTM, for that we have the forget gate, input gate, cell gate and output gate. They are just some operations that are done on the input that you give. For get_slices function, this is used to break down the weight matrix that we get from pytorch state dictionary (state dictionary) is the dictionary which contains the weights of all the layers that we have in our network. For LSTM particularly have it in this order ignore, forget, learn, output. So for that we would need to break it up for different LSTM cells. For numpy_lstm class, we have init_weights_from_pytorch function which must be called, what it will do is that it will extract the weights from state dictionary which we got earlier from pytorch model object and then populate the numpy array weights with the pytorch weights. You can first train your model and then save the state dictionary through pickle and then use it. The fully connected layer class just implements the hidden2out neural network. Finally our rnn_model_numpy class is there to ensure that if you have multiple layers then it is able to send the output of one layer of lstm to other layer of lstm. Lastly there is a small sanity check on data variable. IMPORTANT NOTE: PLEASE NOTE THAT YOU MIGHT GET DIMENSION ERROR AS PYTORCH WAY OF HANDLING INPUT IS COMPLETELY DIFFERENT SO PLEASE ENSURE THAT YOU INPUT NUMPY IS OF SIMILAR SHAPE AS DATA VARIABLE. Important references: https://pytorch.org/docs/stable/generated/torch.nn.LSTM.html https://christinakouridi.blog/2019/06/19/backpropagation-lstm/
https://stackoverflow.com/questions/71146140/
Pytorch getting accuracy of train_loop doesn't work
I want to get the accuracy of my train section of my neuronal network But i get this error: correct += (prediction.argmax(1) == y).type(torch.float).item() ValueError: only one element tensors can be converted to Python scalars With this code : def train_loop(dataloader, model, optimizer): model.train() size = len(dataloader.dataset) correct = 0, 0 l_loss = 0 for batch, (X, y) in enumerate(dataloader): prediction = model(X) loss = cross_entropy(prediction, y) optimizer.zero_grad() loss.backward() optimizer.step() correct += (prediction.argmax(1) == y).type(torch.float).sum().item() loss, current = loss.item(), batch * len(X) l_loss = loss print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]") correct /= size accu = 100 * correct train_loss.append(l_loss) train_accu.append(accu) print(f"Accuracy: {accu:>0.1f}%") I don't understand why it is not working becaus in my test section it work perfektly fine with execly the same code line.
item function is used to convert a one-element tensor to a standard python number as stated in the here. Please try to make sure that the result of the sum() is only a one-element tensor before using item(). x = torch.tensor([1.0,2.0]) # a tensor contains 2 elements x.item() error message: ValueError: only one element tensors can be converted to Python scalars Try to use this: prediction = prediction.argmax(1) correct = prediction.eq(y) correct = correct.sum() print(correct) # to check if it is a one value tensor correct_sum += correct.item()
https://stackoverflow.com/questions/71155542/
Why does Anaconda install pytorch cpuonly when I install cuda?
I have created a Python 3.7 conda virtual environment and installed the following packages using this command: conda install pytorch torchvision torchaudio cudatoolkit=11.3 matplotlib scipy opencv -c pytorch They install fine, but then when I come to run my program I get the following error which suggests that a CUDA enabled device is not found: raise RuntimeError('Attempting to deserialize object on a CUDA ' RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU. I have an NVIDIA RTX 3060ti GPU, which as far as I am aware is cuda enabled, but whenever I go into the Python interactive shell within my conda environment I get False when evaluating torch.cuda.is_available() suggesting that perhaps CUDA is not installed properly or is not found. When I then perform a conda list to view my installed packages: # packages in environment at /home/user/anaconda3/envs/FGVC: # # Name Version Build Channel _libgcc_mutex 0.1 main _openmp_mutex 4.5 1_gnu blas 1.0 mkl brotli 1.0.9 he6710b0_2 bzip2 1.0.8 h7b6447c_0 ca-certificates 2021.10.26 h06a4308_2 cairo 1.16.0 hf32fb01_1 certifi 2021.10.8 py37h06a4308_2 cpuonly 1.0 0 pytorch cudatoolkit 11.3.1 h2bc3f7f_2 cycler 0.11.0 pyhd3eb1b0_0 dbus 1.13.18 hb2f20db_0 expat 2.4.4 h295c915_0 ffmpeg 4.0 hcdf2ecd_0 fontconfig 2.13.1 h6c09931_0 fonttools 4.25.0 pyhd3eb1b0_0 freeglut 3.0.0 hf484d3e_5 freetype 2.11.0 h70c0345_0 giflib 5.2.1 h7b6447c_0 glib 2.69.1 h4ff587b_1 graphite2 1.3.14 h23475e2_0 gst-plugins-base 1.14.0 h8213a91_2 gstreamer 1.14.0 h28cd5cc_2 harfbuzz 1.8.8 hffaf4a1_0 hdf5 1.10.2 hba1933b_1 icu 58.2 he6710b0_3 imageio 2.16.0 pypi_0 pypi imageio-ffmpeg 0.4.5 pypi_0 pypi imutils 0.5.4 pypi_0 pypi intel-openmp 2021.4.0 h06a4308_3561 jasper 2.0.14 hd8c5072_2 jpeg 9d h7f8727e_0 kiwisolver 1.3.2 py37h295c915_0 lcms2 2.12 h3be6417_0 ld_impl_linux-64 2.35.1 h7274673_9 libffi 3.3 he6710b0_2 libgcc-ng 9.3.0 h5101ec6_17 libgfortran-ng 7.5.0 ha8ba4b0_17 libgfortran4 7.5.0 ha8ba4b0_17 libglu 9.0.0 hf484d3e_1 libgomp 9.3.0 h5101ec6_17 libopencv 3.4.2 hb342d67_1 libopus 1.3.1 h7b6447c_0 libpng 1.6.37 hbc83047_0 libstdcxx-ng 9.3.0 hd4cf53a_17 libtiff 4.2.0 h85742a9_0 libuuid 1.0.3 h7f8727e_2 libuv 1.40.0 h7b6447c_0 libvpx 1.7.0 h439df22_0 libwebp 1.2.0 h89dd481_0 libwebp-base 1.2.0 h27cfd23_0 libxcb 1.14 h7b6447c_0 libxml2 2.9.12 h03d6c58_0 lz4-c 1.9.3 h295c915_1 matplotlib 3.5.0 py37h06a4308_0 matplotlib-base 3.5.0 py37h3ed280b_0 mkl 2021.4.0 h06a4308_640 mkl-service 2.4.0 py37h7f8727e_0 mkl_fft 1.3.1 py37hd3c417c_0 mkl_random 1.2.2 py37h51133e4_0 munkres 1.1.4 py_0 ncurses 6.3 h7f8727e_2 networkx 2.6.3 pypi_0 pypi ninja 1.10.2 py37hd09550d_3 numpy 1.21.2 py37h20f2e39_0 numpy-base 1.21.2 py37h79a1101_0 olefile 0.46 py37_0 opencv 3.4.2 py37h6fd60c2_1 openssl 1.1.1m h7f8727e_0 packaging 21.3 pyhd3eb1b0_0 pcre 8.45 h295c915_0 pillow 8.4.0 py37h5aabda8_0 pip 21.2.2 py37h06a4308_0 pixman 0.40.0 h7f8727e_1 py-opencv 3.4.2 py37hb342d67_1 pyparsing 3.0.4 pyhd3eb1b0_0 pyqt 5.9.2 py37h05f1152_2 python 3.7.11 h12debd9_0 python-dateutil 2.8.2 pyhd3eb1b0_0 pytorch 1.7.0 py3.7_cpu_0 [cpuonly] pytorch pywavelets 1.2.0 pypi_0 pypi qt 5.9.7 h5867ecd_1 readline 8.1.2 h7f8727e_1 scikit-image 0.19.1 pypi_0 pypi scipy 1.7.3 py37hc147768_0 setuptools 58.0.4 py37h06a4308_0 sip 4.19.8 py37hf484d3e_0 six 1.16.0 pyhd3eb1b0_1 sqlite 3.37.2 hc218d9a_0 tifffile 2021.11.2 pypi_0 pypi tk 8.6.11 h1ccaba5_0 torchaudio 0.7.0 py37 pytorch torchvision 0.8.1 py37_cpu [cpuonly] pytorch tornado 6.1 py37h27cfd23_0 typing_extensions 3.10.0.2 pyh06a4308_0 wheel 0.37.1 pyhd3eb1b0_0 xz 5.2.5 h7b6447c_0 zlib 1.2.11 h7f8727e_4 zstd 1.4.9 haebb681_0 There seems to be a lot of things saying cpuonly, but I am not sure how they came about, since I did not install them. I am running Ubuntu version 20.04.4 LTS
I believe I had the following things wrong that prevented me from using Cuda. Despite having cuda installed the nvcc --version command indicated that Cuda was not installed and so what I did was add it to the path using this answer. Despite doing that and deleting my original conda environment and using the conda install pytorch torchvision torchaudio cudatoolkit=11.3 matplotlib scipy opencv -c pytorch command again I still got False when evaluating torch.cuda.is_available(). I then used this command conda install pytorch torchvision torchaudio cudatoolkit=10.2 matplotlib scipy opencv -c pytorch changing cudatoolkit from verison 11.3 to version 10.2 and then it worked! Now torch.cuda.is_available() evaluates to True Unfortunately, Cuda version 10.2 was incompatible with my RTX 3060 gpu (and I'm assuming it is not compatible with all RTX 3000 cards). Cuda version 11.0 was giving me errors and Cuda version 11.3 only installs the CPU only versions for some reason. Cuda version 11.1 worked perfectly though! This is the command I used to get it to work in the end: pip install torch==1.9.0+cu111 torchvision==0.10.0+cu111 torchaudio==0.9.0 -f https://download.pytorch.org/whl/torch_stable.html
https://stackoverflow.com/questions/71162459/
Attribute Error: `loss.backward()` returns None
I'm trying to implement the Learner object and its steps and facing an issue with the loss.backward() function as it raises and AttributeError: 'NoneType' object has no attribute 'data' The entire process works when I follow the Chapter 04 MNIST Basics. However, implementing within a class raises this error. Could anybody guide me on why this occurs and ways to fix this? Here's the code below: class Basic_Optim: def __init__(self, params, lr): self.params = list(params) self.lr = lr def step(self): for p in self.params: p.data -= self.lr * p.grad.data def zero(self): for p in self.params: p.grad = None class Learner_self: def __init__(self, train, valid, model, loss, metric, params, lr): self.x = train self.y = valid self.model = model self.loss = loss self.metric = metric self.opt_func = Basic_Optim(params, lr) def fit(self, epochs): for epoch in range(epochs): self.train_data() score = self.valid_data() print(score, end = ' | ') def train_data(self): for x, y in self.x: preds = self.model(x) loss = self.loss(preds, y) loss_b = loss.backward() print(f'Loss: {loss:.4f}, Loss Backward: {loss_b}') self.opt_func.step() self.opt_func.zero() def valid_data(self): accuracy = [self.metric(xb, yb) for xb, yb in self.y] return round(torch.stack(accuracy).mean().item(), 4) learn = Learner_self(dl, valid_dl, simple_net, mnist_loss, metric=batch_accuracy, params=linear_model.parameters(), lr = 1) learn.fit(10) OUTPUT from the print statement inside the train_data prints: Loss: 0.0516, Loss Backward: None and then raises the Attribute error shared above. Please let me know if you want any more details. Every other function such as mnist_loss, batch_accuracy, simple_net are exactly the same from the book. Thank you in advance.
It seems like your optimizer and your trainer do not work on the same model. You have model=simple_net, while the parameters for the optimizer are those of a different model params=linear_model.parameters(). Try passing params=simple_net.parameters() -- that is, make sure the trainer's params are those of model.
https://stackoverflow.com/questions/71162609/
PyTorch high-dimensional tensor through linear layer
I have a tensor of size (32, 128, 50) in PyTorch. These are 50-dim word embeddings with a batch size of 32. That is, the three indices in my size correspond to number of batches, maximum sequence length (with 'pad' token), and the size of each embedding. Now, I want to pass this through a linear layer to get an output of size (32, 128, 1). That is, for every word embedding in every sequence, I want to make it one dimensional. I tried adding a linear layer to my network going from 50 to 1 dimension, and my output tensor is of the desired shape. So I think this works, but I would like to understand how PyTorch deals with this issue, since I did not explicitly tell it which dimension to apply the linear layer to. I played around with this and found that: If I input a tensor of shape (32, 50, 50) -- thus creating ambiguity by having two dimensions along which the linear layer could be applied to (two 50s) -- it only applies it to the last dim and gives an output tensor of shape (32, 50, 1). If I input a tensor of shape (32, 50, 128) it does NOT output a tensor of shape (32, 1, 128), but rather gives me an error. This suggests that a linear layer in PyTorch applies the transformation to the last dimension of your tensor. Is that the case?
In the nn.Linear docs, it is specified that the input of this module can be any tensor of size (*, H_in) and the output will be a tensor of size (*, H_out), where: * means any number of dimensions H_in is the number of in_features H_out is the number of out_features To understand this better, for a tensor of size (n, m, 50) can be processed by a Linear module with in_features=50, while a tensor of size (n, 50, m) can be processed by a Linear module with in_features=m (in your case 128).
https://stackoverflow.com/questions/71165093/
Fastest, best (fastest) way to modify data in in a pytorch loss function?
I want to experiment with creating a modified Loss function for 4 channel image data. What is the best way to split torch.Size([64, 4, 128, 128]) to torch.Size([64, 3, 128, 128]) torch.Size([64, 1, 128, 128])
You can either slice the second axis and extract two tensors: >>> a, b = x[:, :3], x[:, 3:] >>> a.shape, b.shape (64, 3, 128, 128), (64, 1, 128, 128) Alternatively you can apply torch.split on the first dimension: >>> a, b = x.split(3, dim=1) >>> a.shape, b.shape (64, 3, 128, 128), (64, 1, 128, 128)
https://stackoverflow.com/questions/71166112/
HuggingFace: ValueError: expected sequence of length 165 at dim 1 (got 128)
I am trying to fine-tune the BERT language model on my own data. I've gone through their docs, but their tasks seem to be not quite what I need, since my end goal is embedding text. Here's my code: from datasets import load_dataset from transformers import BertTokenizerFast, AutoModel, TrainingArguments, Trainer import glob import os base_path = '../data/' model_name = 'bert-base-uncased' max_length = 512 checkpoints_dir = 'checkpoints' tokenizer = BertTokenizerFast.from_pretrained(model_name, do_lower_case=True) def tokenize_function(examples): return tokenizer(examples['text'], padding=True, truncation=True, max_length=max_length) dataset = load_dataset('text', data_files={ 'train': f'{base_path}train.txt', 'test': f'{base_path}test.txt', 'validation': f'{base_path}valid.txt' } ) print('Tokenizing data. This may take a while...') tokenized_dataset = dataset.map(tokenize_function, batched=True) train_dataset = tokenized_dataset['train'] eval_dataset = tokenized_dataset['test'] model = AutoModel.from_pretrained(model_name) training_args = TrainingArguments(checkpoints_dir) print('Training the model...') trainer = Trainer(model=model, args=training_args, train_dataset=train_dataset, eval_dataset=eval_dataset) trainer.train() I get the following error: File "train_lm_hf.py", line 44, in <module> trainer.train() ... File "/opt/conda/lib/python3.7/site-packages/transformers/data/data_collator.py", line 130, in torch_default_data_collator batch[k] = torch.tensor([f[k] for f in features]) ValueError: expected sequence of length 165 at dim 1 (got 128) What am I doing wrong?
I fixed this solution by changing the tokenize function to: def tokenize_function(examples): return tokenizer(examples['text'], padding='max_length', truncation=True, max_length=max_length) (note the padding argument). Also, I used a data collator like so: data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=True, mlm_probability=0.15 ) trainer = Trainer( model=model, args=training_args, data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset )
https://stackoverflow.com/questions/71166789/
IndexError: tensors used as indices must be long, byte or bool tensors - Pytorch
I'm using a pre-trained image captioning model from this Repository, but I'm getting this error although I changed the type to long !! Error : File "caption.py", line 213, in seq, alphas = caption_image_beam_search(encoder, decoder, args.img, word_map, args.beam_size) File "caption.py", line 111, in caption_image_beam_search seqs = torch.cat([seqs[prev_word_inds].long(), next_word_inds.unsqueeze(1)], dim=1) # (s, step+1) IndexError: tensors used as indices must be long, byte or bool tensors Code : def caption_image_beam_search(encoder, decoder, image_path, word_map, beam_size=3): k = beam_size vocab_size = len(word_map) # Read image and process img = imageio.imread(image_path) if len(img.shape) == 2: img = img[:, :, np.newaxis] img = np.concatenate([img, img, img], axis=2) img = skimage.transform.resize(img, (256, 256)) img = img.transpose(2, 0, 1) img = img / 255. img = torch.FloatTensor(img).to(device) normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) transform = transforms.Compose([normalize]) image = transform(img) # (3, 256, 256) # Encode image = image.unsqueeze(0) # (1, 3, 256, 256) encoder_out = encoder(image) # (1, enc_image_size, enc_image_size, encoder_dim) enc_image_size = encoder_out.size(1) encoder_dim = encoder_out.size(3) # Flatten encoding encoder_out = encoder_out.view(1, -1, encoder_dim) # (1, num_pixels, encoder_dim) num_pixels = encoder_out.size(1) # We'll treat the problem as having a batch size of k encoder_out = encoder_out.expand(k, num_pixels, encoder_dim) # (k, num_pixels, encoder_dim) # Tensor to store top k previous words at each step; now they're just <start> k_prev_words = torch.LongTensor([[word_map['<start>']]] * k).to(device) # (k, 1) # Tensor to store top k sequences; now they're just <start> seqs = k_prev_words # (k, 1) # Tensor to store top k sequences' scores; now they're just 0 top_k_scores = torch.zeros(k, 1).to(device) # (k, 1) # Tensor to store top k sequences' alphas; now they're just 1s seqs_alpha = torch.ones(k, 1, enc_image_size, enc_image_size).to(device) # (k, 1, enc_image_size, enc_image_size) # Lists to store completed sequences, their alphas and scores complete_seqs = list() complete_seqs_alpha = list() complete_seqs_scores = list() # Start decoding step = 1 h, c = decoder.init_hidden_state(encoder_out) # s is a number less than or equal to k, because sequences are removed from this process once they hit <end> while True: embeddings = decoder.embedding(k_prev_words).squeeze(1) # (s, embed_dim) awe, alpha = decoder.attention(encoder_out, h) # (s, encoder_dim), (s, num_pixels) alpha = alpha.view(-1, enc_image_size, enc_image_size) # (s, enc_image_size, enc_image_size) gate = decoder.sigmoid(decoder.f_beta(h)) # gating scalar, (s, encoder_dim) awe = gate * awe h, c = decoder.decode_step(torch.cat([embeddings, awe], dim=1), (h, c)) # (s, decoder_dim) scores = decoder.fc(h) # (s, vocab_size) scores = F.log_softmax(scores, dim=1) # Add scores = top_k_scores.expand_as(scores) + scores # (s, vocab_size) # For the first step, all k points will have the same scores (since same k previous words, h, c) if step == 1: top_k_scores, top_k_words = scores[0].topk(k, 0, True, True) # (s) else: # Unroll and find top scores, and their unrolled indices top_k_scores, top_k_words = scores.view(-1).topk(k, 0, True, True) # (s) # Convert unrolled indices to actual indices of scores prev_word_inds = top_k_words / vocab_size # (s) next_word_inds = top_k_words % vocab_size # (s) # Add new words to sequences, alphas seqs = torch.cat([seqs[prev_word_inds].long(), next_word_inds.unsqueeze(1)], dim=1) # (s, step+1) seqs_alpha = torch.cat([seqs_alpha[prev_word_inds].long(), alpha[prev_word_inds].unsqueeze(1)], dim=1) # (s, step+1, enc_image_size, enc_image_size) # Which sequences are incomplete (didn't reach <end>)? incomplete_inds = [ind for ind, next_word in enumerate(next_word_inds) if next_word != word_map['<end>']] complete_inds = list(set(range(len(next_word_inds))) - set(incomplete_inds)) # Set aside complete sequences if len(complete_inds) > 0: complete_seqs.extend(seqs[complete_inds].tolist()) complete_seqs_alpha.extend(seqs_alpha[complete_inds].tolist()) complete_seqs_scores.extend(top_k_scores[complete_inds]) k -= len(complete_inds) # reduce beam length accordingly # Proceed with incomplete sequences if k == 0: break seqs = seqs[incomplete_inds] seqs_alpha = seqs_alpha[incomplete_inds] h = h[prev_word_inds[incomplete_inds]] c = c[prev_word_inds[incomplete_inds]] encoder_out = encoder_out[prev_word_inds[incomplete_inds]] top_k_scores = top_k_scores[incomplete_inds].unsqueeze(1) k_prev_words = next_word_inds[incomplete_inds].unsqueeze(1) # Break if things have been going on too long if step > 50: break step += 1 i = complete_seqs_scores.index(max(complete_seqs_scores)) seq = complete_seqs[i] alphas = complete_seqs_alpha[i] return seq, alphas
You have cast the wrong part to long: seqs[prev_word_inds].long() should be: seqs[prev_word_inds.long()] which is also present in the next line calculating seqs_alpha. Although i'm not entirely sure how you'll convert these to long (non-decimal) as in the line above you're deriving prev_word_inds as: prev_word_inds = top_k_words / vocab_size seqs = torch.cat([seqs[prev_word_inds.long()], \ next_word_inds.unsqueeze(1)], dim=1) # (s, step+1) when pytorch already gives the second output of topk as a long? Why are you dividing by the vocab size?
https://stackoverflow.com/questions/71167139/
concat datasets in pytorch
I have a few datasets in folders, I am concating them using concat datasets. So, I have data folders like so (note that folders 1 and 2 only have 1 class rather than 2): - denotes subfolders folder0 -cats -dogs folder1 -cats folder2 -cats folder3 -dogs and then I do this: trainset1 = datasets.ImageFolder(folder0, loader=my_loader, transform=SomeAug()) trainset2 = datasets.ImageFolder(folder1, loader=my_loader, transform=SomeAug()) trainset3 = datasets.ImageFolder(folder2, loader=my_loader, transform=SomeAug()) trainset = torch.utils.data.ConcatDataset([trainset1, trainset2, trainset3]) Is this the legit way of doing this? When I look at the total images via: len(train_loader.dataset)) it adds up correctly. However, when I do: print(trainset.classes) it throws me: AttributeError: 'ConcatDataset' object has no attribute 'classes' which it does not when I use just one dataset. I just wanted to ensure that there no gotchas in using thie concat dataset method.
ImageFolder inherits from DatasetFolder which has a class method find_classes that is called in the constructor to initialize the variable DatasetFolder.classes. Thus, you can call trainset.classes without error. However, ConcatDataset does not inherit from ImageFolder and more generally does not implement the classes variable by default. In general, it would be difficult to do this because the ImageFolder method for finding classes relies on a specific file structure, whereas ConcatDataset doesn't assume such a file structure such that it can work with a more general set of datasets. If this functionality is essential to you you could write a simple dataset type that inherits from ConcatDataset, expects ImageFolder datasets specifically, and stores the classes as a union of the possible classes from each constituent dataset.
https://stackoverflow.com/questions/71173583/
Pytorch tensor indexing error for sizes M < 32?
I am trying to access a pytorch tensor by a matrix of indices and I recently found this bit of code that I cannot find the reason why it is not working. The code below is split into two parts. The first half proves to work, whilst the second trips an error. I fail to see the reason why. Could someone shed some light on this? import torch import numpy as np a = torch.rand(32, 16) m, n = a.shape xx, yy = np.meshgrid(np.arange(m), np.arange(m)) result = a[xx] # WORKS for a torch.tensor of size M &gt;= 32. It doesn't work otherwise. a = torch.rand(16, 16) m, n = a.shape xx, yy = np.meshgrid(np.arange(m), np.arange(m)) result = a[xx] # IndexError: too many indices for tensor of dimension 2 and if I change a = np.random.rand(16, 16) it does work as well.
To whoever comes looking for an answer: it looks like its a bug in pyTorch. Indexing using numpy arrays is not well defined, and it works only if tensors are indexed using tensors. So, in my example code, this works flawlessly: a = torch.rand(M, N) m, n = a.shape xx, yy = torch.meshgrid(torch.arange(m), torch.arange(m), indexing='xy') result = a[xx] # WORKS I made a gist to check it, and it's available here
https://stackoverflow.com/questions/71176095/
PyTorch C++ Frontend: Registering New Modules and using them during Forward
I am creating a model that is empty like so: struct TestNet : torch::nn::Module { TestNet() { } torch::Tensor Forward(torch::Tensor x) { return x; } }; I then register new modules to the model: auto net = std::make_shared&lt;TestNet&gt;(); torch::nn::ModuleHolder&lt;ConvLayer&gt; conv(1, 1, 3, 1, 1); net-&gt;register_module(&quot;conv1&quot;, conv); Where ConvLayer is a Module with a convolutional layer: struct ConvLayer : torch::nn::Module { ConvLayer() {} ConvLayer(int in_ch, int out_ch, int kernel, int pad, int stride) : conv1(torch::nn::Conv2dOptions(in_ch, out_ch, kernel) .stride(stride) .padding(pad) .bias(false)) { register_module(&quot;Conv1&quot;, conv1); } torch::Tensor Forward(torch::Tensor x) { return conv1(x); } torch::nn::Conv2d conv1{ nullptr }; }; I can print out the parameters of TestNet now and see the convolutional layer, however I can not utilize it in a forward pass. What am I missing to do this?
I found a way to do this using torch::nn::Sequential, hope this helps anyone else: struct TestNet2 : torch::nn::Module { TestNet2() { layers = register_module(&quot;layers&quot;, torch::nn::Sequential()); } template &lt;typename T&gt; void sequentialLayer(T Layer) { layers-&gt;push_back(Layer); } torch::Tensor Forward(torch::Tensor x) { return layers-&gt;forward(x); } torch::nn::Sequential layers; }; ... auto net = std::unique_ptr&lt;TestNet2&gt;(); auto convLayer = torch::nn::Conv2d(torch::nn::Conv2dOptions(1, 1, 3) .stride(1) .padding(1) .bias(false)); net-&gt;sequentialLayer(convLayer);
https://stackoverflow.com/questions/71176554/
Unrealistic results using F1Score from torchmetrics
I have trained a segmentation NN model for a binary classification problem in Pytorch Lightning. In order to achieve this I used BCEWithLogitsLoss. The shape for both my ground truth and predictions are (BZ, 640, 256) their content is (0, 1) [0, 1] respectively. Now, I am trying to calculate the F1 score over batched data on my validation dataset with F1Score from torchmetrics and then accumulate with pytroch lightning's log_dict by from torchmetrics import F1Score self.f1 = F1Score(num_classes=2) where my validation step looks like this: def validation_step(self, batch, batch_idx): t0, t1, mask_gt = batch mask_pred = self.forward(t0, t1) mask_pred = torch.sigmoid(mask_pred).squeeze() mask_pred = torch.where(mask_pred &gt; 0.5, 1, 0) f1_score_ = self.f1(mask_pred, mask_gt) metrics = { 'val_f1_score': f1_score_, } self.log_dict(metrics, on_epoch=True) This gives me ridiculously high F1 scores at the end of each epoch (even on the sanity validation check before the training starts), ~0.99, which make me think that I am not using F1Score together with log_dict the right way. I have tried several arguments (https://github.com/PyTorchLightning/metrics/blob/master/torchmetrics/classification/f_beta.py#L181-L310) with no luck. What am I doing wrong?
It turns out I have en extremely unbalanced dataset where the &quot;False&quot; class is over-represented 40 times more than the &quot;True&quot; class. The model is very good at detecting the &quot;False&quot; class, hence the issues in detecting the &quot;True&quot; class are shadowed by taking the macro F1 average of both (with equal weights for each class).
https://stackoverflow.com/questions/71176911/
In pytorch, torch.unique is returning repititions
I have this 2-D tensor: tmp = torch.tensor([[ 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 20, 20, 20, 21, 21, 21, 22, 22, 22, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 29, 30, 30, 30, 31, 31, 31, 31], [ 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 15, 0, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 20, 20, 20, 21, 21, 21, 22, 22, 22, 23, 23, 23, 24, 24, 24, 25, 25, 25, 26, 26, 26, 27, 27, 27, 28, 28, 28, 29, 29, 29, 30, 30, 30, 31, 31, 31, 31]]) So there is 0 in the 50th column of row 2. When I apply torch.unique along dim=1, I get: a,c = torch.unique(tmp,dim=1,return_counts=True) a tensor([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31], [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]]) It can be seen that the second row of the output has two 0s and the first row has two 16s. Am I doing something wrong here or this is suspicious?
It is because you specified dim=1. PyTorch is thus checking for unique pairs (which it correctly does). Like (0, 0), (1, 1), (16, 0): these are the unique pairs that it generated. In general the pair (temp[0,i], temp[1,i]) is unique for all i. If you want all the elements to be unique, just throw away the dim: torch.unique(tmp). If you need to maintain the two list structure, the output cannot be stored as a single tensor because their sizes might not match. You can do something like output1 = torch.unique(tmp[0]) and output2 = torch.unique(tmp[1]).
https://stackoverflow.com/questions/71178104/
Attribute Error When Saving Pytorch Model
I want to save pytorch model in one .py file and use it in another .py file, but I get AttributeError: 'function' object has no attribute 'copy' Here is what I have: train.py data = { &quot;model_state&quot;: model.state_dict, &quot;optimizer_state&quot;: optimizer.state_dict, &quot;input_size&quot;: input_size, &quot;output_size&quot;: output_size, &quot;hidden_size&quot;: hidden_size, &quot;all_words&quot;: all_words, &quot;tags&quot;: tags } file = &quot;data.pth&quot; torch.save(data, file) use.py file = &quot;data.pth&quot; data = torch.load(file) input_size = data['input_size'] output_size = data['output_size'] hidden_size = data['hidden_size'] all_words = data['all_words'] tags = data['tags'] model_state = data['model_state'] model = NeuralNet(input_size, hidden_size, output_size) model.load_state_dict(model_state) model.eval() NeuralNet is a class I defined elsewhere for building a model. The error happens with the second to last line of use.py.
In fact, what you have done is save a function (AKA method in OOP) then load it in a variable utilizing deepcopy which is not available for functions! The only change you need to make is adding () to state_dict. Let's assume this is the model import copy from torch import nn import torch class MyModel(nn.Module): def __init__(self): super().__init__() self.layer1=nn.Linear(10,4) self.act1=nn.Sigmoid() def forward(self,x): x=self.layer1(x) x=self.act1(x) return x type of state_dict vs type of state_dict(): print('Type With (): ', type(model.state_dict()), '\nType Without (): ', type(model.state_dict)) #Type With (): &lt;class 'collections.OrderedDict'&gt; #Type Without (): &lt;class 'method'&gt; reproducing the error: model = MyModel() torch.save(model.state_dict, 'model_state.pth') device = torch.device(&quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;) model.load_state_dict(copy.deepcopy(torch.load(&quot;model_state.pth&quot;,device))) # AttributeError: 'function' object has no attribute 'copy' the correct way: model = MyModel() torch.save(model.state_dict(), 'model_state.pth') device = torch.device(&quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;) model.load_state_dict(copy.deepcopy(torch.load(&quot;model_state.pth&quot;,device)))
https://stackoverflow.com/questions/71182110/
ModuleNotFoundError: No module named 'skimage.measure.simple_metrics'
I am using google colab. I installed scikit-image. When I execute this code, I am getting error: ModuleNotFoundError: No module named 'skimage.measure.simple_metrics' import math import torch import torch.nn as nn import numpy as np import cv2 from skimage.measure.simple_metrics import compare_psnr def weights_init_kaiming(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: nn.init.kaiming_normal(m.weight.data, a=0, mode='fan_in')\ elif classname.find('Linear') != -1: nn.init.kaiming_normal(m.weight.data, a=0, mode='fan_in') elif classname.find('BatchNorm') != -1: # nn.init.uniform(m.weight.data, 1.0, 0.02) m.weight.data.normal_(mean=0, std=math.sqrt(2./9./64.)).clamp_(-0.025,0.025) nn.init.constant(m.bias.data, 0.0) def batch_PSNR(img, imclean, data_range): Img = img.data.cpu().numpy().astype(np.float32) Iclean = imclean.data.cpu().numpy().astype(np.float32) PSNR = 0 for i in range(Img.shape[0]): PSNR += compare_psnr(Iclean[i,:,:,:], Img[i,:,:,:], data_range=data_range) return (PSNR/Img.shape[0])
Since scikit-image version 0.16, that function was renamed from skimage.measure.compare_psnr to skimage.metrics.peak_signal_noise_ratio. Please check your scikit-image version to confirm it. https://scikit-image.org/docs/0.19.x/api/skimage.metrics.html?highlight=peak_signal_noise_ratio#peak-signal-noise-ratio
https://stackoverflow.com/questions/71182396/
What is the type annotation for return value of __getitem__?
I was making a dataset class by inheriting torch.utils.data.Dataset and came across the following issue. Unlike previous functions which returns a fixed type of values, __getitem__ doesn't. For example, class MyExample: def __init__(self, some_list: list[int]): self.some_list = some_list def __getitem__(self, index): return self.some_list[index] MyExample[&lt;index&gt;] will return int, while MyExample[&lt;slice&gt;] will return slice of int. VScode intellisense automatically write T_co for its type annotation, but I don't understand what this means. How should I annotate such a function? What do I need to learn in order to understand such an annotation?
For this you can use Unions as the actual annotation of the function and overload to allow you type checker to know that a slice is only returned when a slice is given and an int is given when only an int is given. from typing import overload, Union class MyExample: def __init__(self, some_list: list[int]): self.some_list = some_list @overload def __getitem__(self, index: int) -&gt; int: ... @overload def __getitem__(self, index: slice) -&gt; list[int]: ... def __getitem__(self, index: Union[slice, int]) -&gt; Union[list[int], int]: # Or Slice[int] if that's a thing return self.some_list[index] If your example is not only for list of ints but for general lists, you can change to Generic types. For details check out overload document. ... is actual code.
https://stackoverflow.com/questions/71182977/
Understand Adam optimizer intuitively
According the pseudo code of Adam: I wrote some code: from matplotlib import pyplot as plt import numpy as np # np.random.seed(42) num = 100 x = np.arange(num).tolist() # The following 3 sets of g_list stand for 3 types of gradient changes: # g_list = np.random.normal(0,1,num) # gradient direction changes frequently in positive and negtive # g_list = x # gradient direction always positive and gradient value becomes larger gradually g_list = [10 for _ in range(num)] # gradient direction always positive and gradient value always the same m = 0 v = 0 beta_m = 0.9 beta_v = 0.999 m_list = [] v_list = [] for i in range(1,num+1): g = g_list[i-1] m = beta_m*m + (1 - beta_m)*g m = m/(1-beta_m**i) v = beta_v*v + (1 - beta_v)*(g**2) v = v/(1-beta_v**i) m_list.append(m) v_list.append(np.sqrt(v)) mv = np.array(m_list)/(np.array(v_list) +0.001) print(&quot;==&gt;&gt; mv: &quot;, mv) plt.plot(x, g_list, x, mv) Run the code, i got following plot: For me, I think it's counter-intuitive, because I think that when the gradient direction is always positive, and the gradient value is constant, the coefficient of the learning rate(i.e. mv) should be close to 1, but the 100th mv I got is 3.40488818e-70 which is nearly close to zero. If I change the some of the code: # m = m/(1-beta_m**i) if i == 1: m = m/(1-beta_m**i) # v = v/(1-beta_v**i) if i == 1: v = v/(1-beta_v**i) the result I get is this: This is more in line with my intuition. Can someone tell me if my code above is correct, and if correct, does it fit your intuition to get something like above ?
Your code implementation is almost there, but one difference you should note between your implementation and the algorithm is that you are erroneously accumulating the bias correction term m/(1-beta_m**i) with the variable m. You should assign a separate variable m_hat for bias correction. The same applies to v: assign the bias corrected value to another variable like v_hat. Doing this will avoid including the bias correction in the accumulation of m and v. Your code can stay the same, but change the calculation of the bias corrected values along with the list appends. If you do this, you will get the result you're after. for i in range(1,num+1): g = g_list[i-1] # calculate m and v m = beta_m*m + (1 - beta_m)*g v = beta_v*v + (1 - beta_v)*(g**2) # assign bias corrected values to m_hat and v_hat respectively m_hat = m/(1-beta_m**i) v_hat = v/(1-beta_v**i) # append to lists m_list.append(m_hat) v_list.append(np.sqrt(v_hat))
https://stackoverflow.com/questions/71185171/
Tensorflow implementation of Pytorch code: adding convolutional layers
I'd like to implement this PyTorch code in Tensorflow, but am a newbie, and am looking for some assistance/resources. The code in Pytorch combines two convolutions in forward propagation: class PytorchLayer(nn.Module): def __init__(self, in_features, out_features): super(PytorchLayer, self).__init__() self.in_features = in_features self.out_features = out_features self.layer1 = nn.Conv1d(in_features, out_features, 1) self.layer2 = nn.Conv1d(in_features, out_features, 1, bias=False) def forward(self, x): return self.layer1(x) + self.layer2(x - x.mean(dim=2, keepdim=True)) How can I do this in tensorflow? I understand that I can do a 1D Convolution likeso: tf.keras.layers.Conv1D(in_features, kernel_size = 1, strides=1) I also understand that I can create a feedforward network like so: tf.keras.Sequential([tf.keras.layers.Conv1D(in_features, kernel_size = 1, strides=1)]) However, in tensorflow, how do I implement this line from the Pytorch code, that transforms the convolutions: self.layer1(x) + self.layer2(x - x.mean(dim=2, keepdim=True)) Apologies for the amateur question. I searched for a long time, but couldn't see a similar post to mine.
You may find the Keras tutorials: The Functional API Making new layers and models via subclassing informative for this task. Using the Keras functional model API, this might look something like: out_features = 5 # Arbitrary for the example layer1 = tf.keras.layers.Conv1D( out_features, kernel_size=1, strides=1, name='Conv1') layer2 = tf.keras.layers.Conv1D( out_features, kernel_size=1, strides=1, use_bias=False, name='Conv2') subtract = tf.keras.layers.Subtract(name='SubtractMean') mean = tf.keras.layers.Lambda( lambda t: tf.reduce_mean(t, axis=2, keepdims=True), name='Mean') # Connect the layers in a model. x = tf.keras.Input(shape=(5,5)) average_x = mean(x) normalized_x = subtract([x, average_x]) y = tf.keras.layers.Add(name='AddConvolutions')([layer1(x), layer2(normalized_x)]) m = tf.keras.Model(inputs=x, outputs=y) m.summary() &gt;&gt;&gt; Model: &quot;model&quot; &gt;&gt;&gt; __________________________________________________________________________________________________ &gt;&gt;&gt; Layer (type) Output Shape Param # Connected to &gt;&gt;&gt; ================================================================================================== &gt;&gt;&gt; input_1 (InputLayer) [(None, 5, 5)] 0 [] &gt;&gt;&gt; &gt;&gt;&gt; Mean (Lambda) (None, 5, 1) 0 ['input_1[0][0]'] &gt;&gt;&gt; &gt;&gt;&gt; SubtractMean (Subtract) (None, 5, 5) 0 ['input_1[0][0]', &gt;&gt;&gt; 'Mean[0][0]'] &gt;&gt;&gt; &gt;&gt;&gt; Conv1 (Conv1D) (None, 5, 5) 30 ['input_1[0][0]'] &gt;&gt;&gt; &gt;&gt;&gt; Conv2 (Conv1D) (None, 5, 5) 25 ['SubtractMean[0][0]'] &gt;&gt;&gt; &gt;&gt;&gt; AddConvolutions (Add) (None, 5, 5) 0 ['Conv1[0][0]', &gt;&gt;&gt; 'Conv2[0][0]'] &gt;&gt;&gt; &gt;&gt;&gt; ================================================================================================== &gt;&gt;&gt; Total params: 55 &gt;&gt;&gt; Trainable params: 55 &gt;&gt;&gt; Non-trainable params: 0 &gt;&gt;&gt; __________________________________________________________________________________________________
https://stackoverflow.com/questions/71185950/
Pytorch tensor changing colors
I would appreciate any help on that. Why after putting tensor of 3d (image) into 4d tensor, the image colors changed. p = &quot;path/to/image&quot; p = Image.open(p) p = transforms.PILToTensor()(p) transforms.ToPILImage()(p).show() # ok (left pic) temp = torch.zeros(4, p.size()[0], p.size()[1], p.size()[2]) temp[0] = p transforms.ToPILImage()(temp[0]).show() # not ok (right pic)
The reason is that the first tensor p is an integer tensor and values range between 0 - 255. The second image is a float tensor and the values range between 0.0 - 255.0. imshow function expects integer values between 0 - 255 or float values between 0 - 1, you can read more here. To fix this problem, you have two options either add the dtype=torch.uint8 when you define a temp tensor or divide the values of the tensor by 255 to scale it between 0 -1. # cell 1 from PIL import Image from torchvision import transforms import torch from matplotlib import pyplot as plt p = Image.open(&quot;pi.png&quot;) p = transforms.PILToTensor()(p).permute(1, 2, 0) plt.imshow( p ) #ok # cell 2 temp = torch.zeros(4, p.size()[0], p.size()[1], p.size()[2], dtype=torch.uint8) temp[0] = p plt.imshow(temp[0]) # or you can use plt.imshow(temp[0]/255)
https://stackoverflow.com/questions/71187415/
PyTorch infinite loop in the training and validation step
Dataset and DataLoader's parts are ok, I recycled from another code that I built, but got an infinite loop at that part in my code: def train(train_loader, MLP, epoch, criterion, optimizer): MLP.train() epoch_loss = [] for batch in train_loader: optimizer.zero_grad() sample, label = batch #Forward pred = MLP(sample) loss = criterion(pred, label) epoch_loss.append(loss.data) #Backward loss.backward() optimizer.step() epoch_loss = np.asarray(epoch_loss) print('Epoch: {}, Loss: {:.4f} +/- {:.4f}'.format(epoch+1, epoch_loss.mean(), epoch_loss.std())) def test(test_loader, MLP, epoch, criterion): MLP.eval() with torch.no_grad(): epoch_loss = [] for batch in train_loader: sample, label = batch #Forward pred = MLP(sample) loss = criterion(pred, label) epoch_loss.append(loss.data) epoch_loss = np.asarray(epoch_loss) print('Epoch: {}, Loss: {:.4f} +/- {:.4f}'.format(epoch+1, epoch_loss.mean(), epoch_loss.std())) Than, I put it to iterate over the epochs: for epoch in range(args['num_epochs']): train(train_loader, MLP, epoch, criterion, optimizer) test(test_loader, MLP, epoch, criterion) print('-----------------------') As it doesn't print even the first loss data, I believe that the logic error is in the training function, but I don't know where it is. Edit: Here is my MLP Class, the problem can be here too: class BikeRegressor(nn.Module): def __init__(self, input_size, hidden_size, out_size): super(BikeRegressor, self).__init__() self.features = nn.Sequential(nn.Linear(input_size, hidden_size), nn.ReLU(), nn.Linear(hidden_size, hidden_size), nn.ReLU()) self.out = nn.Sequential(nn.Linear(hidden_size, out_size), nn.ReLU()) def forward(self, X): hidden = self.features(X) output = self.out(hidden) return output Edit 2: Dataset and Dataloader: class Bikes(Dataset): def __init__(self, data): #data is a Dataframe from Pandas self.datas = data.to_numpy() def __getitem__(self, idx): sample = self.datas[idx][2:14] label = self.datas[idx][-1:] sample = torch.from_numpy(sample.astype(np.float32)) label = torch.from_numpy(label.astype(np.float32)) return sample, label def __len__(self): return len(self.datas) train_set = Bikes(ds_train) test_set = Bikes(ds_test) train_loader = DataLoader(train_set, batch_size=args['batch_size'], shuffle=True, num_workers=args['num_workers']) test_loader = DataLoader(test_set, batch_size=args['batch_size'], shuffle=True, num_workers=args['num_workers'])
I experienced the same problem and the problem is that jupyter notebook might not work properly with multiprocessing as documented here: Note Functionality within this package requires that the __ main __ module be importable by the children. This is covered in Programming guidelines however it is worth pointing out here. This means that some examples, such as the Pool examples will not work in the interactive interpreter. You have three options to solve your problem: Set the num_worker = 0 in train_loader and test_loader. (easiest one) Move your code to google colab. It works with me with num_worker = 6 but I think it depends on how much memory your program will use. Thus, try to increase num_worker gradually until your program cashes telling you that your program is out of memory. Adapt your program in jupyter to support multiprocessing, these resources 1, 2 can help.
https://stackoverflow.com/questions/71187661/
PyTorch Installation - PiP - Erorr
When trying to install PyTorch, by entering the command: pip3 install torch==1.10.2+cu113 torchvision==0.11.3+cu113 torchaudio===0.10.2+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html I get the following Error Error - &quot;The Package index page used does not have a proper HTML doctype declaration.&quot; it also says to contact the owner of the package index, to get this fixed. https://github.com/pypa/pip/issues/10825 Any solutions for this? I want to install PyTorch EDIT: I downloaded the latest version of pip, pip 22.0.3
Seems like it's an ongoing issue with pip==22.0.{0,1,2,3} (confirm your pip version using pip3 --version or pip --version). They started a migration process to remove an HTML parser 1, but it seems like PyTorch didn't notice and now they're trying to solve it (this is the GitHub issue where they're tracking the progress on this matter). At the moment, it seems like you have these options: Try to use the pip install command by adding this flag: --use-deprecated=html5lib. For example: pip3 install --use-deprecated=html5lib torch==1.10.2+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html Downgrade pip to a &quot;non-22.0.*&quot; version. It seems like the recommended way is to use a version that comes with your Python version 2: python -m pip uninstall pip &amp;&amp; python -m ensurepip Then, use the pip install ... command normally. Install PyTorch using a different technique.
https://stackoverflow.com/questions/71189626/
How to register a dynamic backward hook on tensors in Pytorch?
I'm trying to register a backward hook on each neuron's weights in a network. By dynamic I mean that it will take a value and multiply the associated gradients by that value. From here it seem like it's possible to register a hook on a tensor with a fixed value (though note that I need it to take a value that will change). From here it also seems like it's possible to register a hook on all of the parameters -- they use it to do gradients clipping (though note that I'm trying to only do it on each neuron's weights). If my network is as follows: class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.fc1 = nn.Linear(3,5) self.fc2 = nn.Linear(5,10) self.fc3 = nn.Linear(10,1) def forward(self, x): x = torch.relu(self.fc1(x)) x = torch.relu(self.fc2(x)) x = torch.relu(self.fc3(x)) return x The first layer has 5 neurons with 3 associated weights for each. Hence, this layer should have 5 hooks that modifies (i.e change the current gradient by multiplying it) their 3 associated weights gradients during the backward step. Training pseudo-code example: net = Model() for epoch in epochs: out = net(data) loss = criterion(out, target) optimizer.zero_grad() loss.backward() for hook in list_of_hooks: #not sure if there's a more &quot;pytorch&quot; way of doing this without a for loop hook(random_value) optimizer.step()
What about exploiting lambdas closure over names? A short example: import torch net_params = torch.rand(5, 3, requires_grad=True) msg = &quot;Hello!&quot; t.register_hook(lambda g: print(msg)) out1 = net_params * 2. loss = out1.sum() loss.backward() # Activates the hook and prints &quot;Hello!&quot; msg = &quot;How are you?&quot; # The lambda is affected by this change out2 = t ** 4. loss2 = out2.sum() loss2.backward() # Activates the hook again and prints &quot;How are you?&quot; So a possible solution to your problem: net = Model() # Replace it with your computed values rand_values = torch.rand(net.fc1.out_features, net.fc1.in_features) net.fc1.weight.register_hook(lambda g: g * rand_values) for epoch in epochs: out = net(data) loss = criterion(out, target) optimizer.zero_grad() loss.backward() # fc1 gradients are multiplied by rand_values optimizer.step() # Update rand_values. The lambda computation will change accordingly rand_values = torch.rand(net.fc1.out_features, net.fc1.in_features) Edit To make things clearer, if you specifically want to multiply each set of weights i by a single value vi you can exploit broadcasting semantic and define values = torch.tensor([v0, v1, v2, v3, v4]).reshape(5, 1), then the lambda becomes lambda g: g * values
https://stackoverflow.com/questions/71190012/
How could I fix this torch.zero() problem?
I'm trying to write a Logistic Regression by myself, but I found an error while initializing this torch.zero(). code: w = torch.normal(0, 0.01, size=(2,1), requires_grad=True) b = torch.zeros(1,require_grad=True) # Error occured here Error message: Traceback (most recent call last): File &quot;linearRegression.py&quot;, line 37, in &lt;module&gt; b = torch.zeros(1,require_grad=True) TypeError: zeros() received an invalid combination of arguments - got (int, require_grad=bool), but expected one of: * (tuple of ints size, *, tuple of names names, torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad) * (tuple of ints size, *, Tensor out, torch.dtype dtype, torch.layout layout, torch.device device, bool pin_memory, bool requires_grad)
You have a typo, change require_grad to requires_grad.
https://stackoverflow.com/questions/71192464/
PyTorch: count the number of tensor values that are near (+/- a tolerance) the values of a reference tensor
I have 2 tensors of an arbitrary shape with several dimensions. target_tensor predicted_tensor I want to count the number of values in the predicted_tensor that are near to the values of the target tensor. With a for loop it shall be something like this: targets = torch.flatten(target_tensor) predicted = torch.flatten(predicted_tensor) correct_values = 0 tolerance = 0.1 for i, prediction in enumerate(predicted): target = targets[i] if (target - tolerance &lt; prediction &lt; target + tolerance): correct_values =+ 1 However, a for loop is not a really good idea for performances. I'm looking for a vectorized solution. I tried : torch.sum(target - tolerance &lt; prediction &lt; target + tolerance) But I got: RuntimeError: Boolean value of Tensor with more than one value is ambiguous In Julia it would be just adding a dot to precise that it is element wise. Any idea on how to implement that with PyTorch with a short vectorized solution? Thanks
I think you are looking for torch.isclose: correct_values = torch.isclose(prediction, target, atol=tolerance, rtol=0).sum()
https://stackoverflow.com/questions/71195131/
Why is my custom dataset giving attribute error?
I am trying the create a custom dataset and if I call neither the getitem or len functions as object.len() or object.getitem(index) I get this error File ~/Library/Python/3.9/lib/python/site-packages/torch/utils/data/dataset.py:83, in Dataset.__getattr__(self, attribute_name) 81 return function 82 else: ---&gt; 83 raise AttributeError the code itself is like the following, class CustomDataset(Dataset): def __init__(self, path_to_images, transform_extra=None, img_size=128): self.images= createimages(path, img_size) def __len__(self): return len(self.images) def __getitem__(self, idx): return self.images[idx][0], self.images[idx][1] Images is a 2d list of Pillow images and string labels and the createimages function works outside of the class. I am not very familiar with Python so I was wondering what is going wrong here.
These functions are part of a subset of special functions in python colloquially called &quot;magic methods&quot; which are denoted by the leading and trailing double underscore. The exact meaning of this differs slightly for different functions but in general the double underscore is meant to distinguish these functions from others with similar names as they have special usage in python. Other examples include __next__(), __dir__, etc. See similar question. Let cd be an instance of CustomDataset. As somewhat of a peculiarity, the __len__ function is called as len(cd) (or you can do cd.__len__().) The __getitem__ function is generally called as cd[i] where i indexes is passed as the indexing variable to __getitem__, (but likewise you could do cd.__getitem__()).
https://stackoverflow.com/questions/71196992/
Google Cloud Function Gen 1 Deployment Failure
This is mostly for the community, because it took me quite a while to figure out. I have a python 3.9 environment stateless Google Cloud Function using pytorch. The initial deployment and function creation has no errors/issues. Requirements.txt looks like this: torch==1.10.2 However, when I edit even the smallest, innocuous change and save, the deployment fails with the error: Build failed: Collecting torch==1.10.2; Error ID: c84b3231 How do you redeploy with pytorch?
I still do not know the reason why installing pytorch on redeploy fails, but this is how I got Google Cloud Function to consistently redeploy without fail. I directly input the specific version of PyTorch link: linux, cpu-based, version. Go to the latest versions of PyTorch: PyTorch Latest Releases. Search for the desired version (currently, the latest is 1.10.2). I chose torch-1.10.2%2Bcpu-cp39-cp39-linux_x86_64.whl. Copy link and paste in requirements.txt by replacing torch==1.10.2. If anybody knows why Google Cloud Function Gen 1 rejects redeployment with the conventional distribution of torch, feel free to edit. Hope this saves someone time.
https://stackoverflow.com/questions/71198801/
PyTorch NN not as good as sklearn MLP
I am comparing the accuracy of sklearn's MLPRegressor with an equivalent net in PyTorch but the PyTorch model is always much worse. I can't figure out why. Here is my code for both below. poly = PolynomialFeatures(2,interaction_only=True) X_train, X_test, y_train, y_test = train_test_split(poly.fit_transform(X),y.ravel(), test_size=0.15, random_state=0,shuffle=True) #print(X_train) layers = (78,22,8,3,3,1) regr_nn = MLPRegressor(hidden_layer_sizes=layers,random_state=0, max_iter=20000, solver='lbfgs', activation='tanh',alpha=1e-5) regr_nn.fit(X_train, y_train) y_predict_test_nn = regr_nn.predict(y_test) y_predict_train_nn = regr_nn.predict(y_train) test_score = regr_nn.score(X_test, y_test) train_score = regr_nn.score(X_train, y_train) poly = PolynomialFeatures(2,interaction_only=True) X_train, X_test, y_train, y_test = train_test_split(poly.fit_transform(X), y.ravel(),test_size=0.15, random_state=0) # torch can only train on Variable, so convert them to Variable x_test, y_test = torch.from_numpy(X_test.astype('float')), torch.from_numpy(y_test) y_test = y_test.reshape((y_test.shape[0], 1)) x_train, y_train = torch.from_numpy(X_train.astype('float')), torch.from_numpy(y_train) y_train = y_train.reshape((y_train.shape[0], 1)) class Train_set(torch.utils.data.Dataset): def __init__(self, X, y): if not torch.is_tensor(X) and not torch.is_tensor(y): self.X = torch.from_numpy(X) self.y = torch.from_numpy(y) else: self.X = X self.y = y def __len__(self): return len(self.X) def __getitem__(self, i): return self.X[i], self.y[i] class Net(torch.nn.Module): def __init__(self, n_feature): super(Net, self).__init__() self.regress = nn.Sequential(nn.Linear(n_feature,78),nn.Tanh(), nn.Linear(78, 22),nn.Tanh(), nn.Linear(22, 8),nn.Tanh(), nn.Linear(8, 3),nn.Tanh(), nn.Linear(3,3), nn.Tanh(),nn.Linear(3, 1)) def forward(self, x): return self.regress(x.float()) # activation function for hidden layer net = Net(n_feature=x_train.size(1)) net.to(cuda) # print(net) # net architecture optimizer = torch.optim.LBFGS(net.parameters(), max_iter=20000, lr=1e-5, tolerance_grad=1e-07,tolerance_change=1e-05) loss_func = torch.nn.MSELoss() # this is for regression mean squared loss train_set = Train_set(x_train,y_train) trainloader = DataLoader(train_set, batch_size=10, shuffle=True) CL = [] # train the network for t in tqdm(range(10)): for i, data in enumerate(trainloader, 0): def closure(): # Get and prepare inputs inputs, targets = data inputs, targets = inputs.float(), targets.float() inputs, targets = inputs.to(cuda), targets.to(cuda) targets = targets.reshape((targets.shape[0], 1)) # Zero the gradients optimizer.zero_grad() # Perform forward pass outputs = net(inputs) # Compute loss loss = loss_func(outputs, targets) # Perform backward pass loss.backward() return loss optimizer.step(closure) # apply gradients prediction_train = net(x_train.to(cuda)) prediction_test = net(x_test.to(cuda)) train_score = r2_score(y_train.data.numpy(), prediction_train.data.numpy()) test_score = r2_score(y_test.data.numpy(), prediction_test.data.numpy()) The R^2 score from sklearn is above 0.9 and the parity plot looks like a line but the scores from PyTorch are close to zero and the parity plot looks awful. Sklearn result PyTorch result I would really appreciate any help. Thank you!
I think your closure function needs to be inside the trainloader loop: for t in tqdm(range(10)): for i, data in enumerate(trainloader, 0): def closure(): # Get and prepare inputs inputs, targets = data inputs, targets = inputs.float(), targets.float() inputs, targets = inputs.to(cuda), targets.to(cuda) targets = targets.reshape((targets.shape[0], 1)) # Zero the gradients optimizer.zero_grad() # Perform forward pass outputs = net(inputs) # Compute loss loss = loss_func(outputs, targets) # Perform backward pass loss.backward() return loss optimizer.step(closure) #&lt;&lt;&lt; this is applied to the END of `closure` I can't say for sure as I haven't used LBFGS too much, but i believe your current method will only step once per epoch.
https://stackoverflow.com/questions/71199036/
How to train a Pytorch model with a custom dataset on a TPU?
FYI, I can only spare the initial 300$ since I'm a student so I need to minimize the trial &amp; error phase. I have my Pytorch-based model which currently runs on local GPU with a ~100GB of frames dataset that is in my local storage, I'm looking for a guide that shows how to set up a machine to train &amp; test my model with TPUs on the dataset which will be in my Google Drive(?)(or any other recommended cloud storage). The guides I found don't match up to my description, most of them either run on GPU or TPU with a dataset that is included in a dataset library, I prefer not to waste time and budget on trying to assemble a puzzle from those pieces.
First, to use TPUs on Google Cloud TPUs you have to use the PyTorch/XLA library, as its enable the support to use TPUs with PyTorch. There is some options to do so, you can use code lab or create an environment on GCP to this. I understand that you may want to know how is to work in a &quot;real environment&quot; besides working on codelab, but there will be no much difference, and codelab is often used as main environment for ml development. About your dataset, I recommend you to upload it Google Cloud Storage and access it via gs url like gs://bucket_name/data.csv. It also have a free tier Also, keep mind that with a TPU instance and a notebook to code in a notebook in GCP will drain your 300 $ in a fell days (or hours). Just the TPU v3 ready for pytorch you cost around $ 6k/month. On colab: Just follow the examples on PyTorch/XLA GitHub . On GCP: Enable the TPU API and create a TPU instance. Create a notebook to write your code. Se the XRT_TPU_CONFIG env variable with the IP of your TPU on he code: os.environ[&quot;XRT_TPU_CONFIG&quot;]=&quot;tpu_worker;0;10.0.200.XX:8470&quot; Follow the code examples on how to import correctly and use the libraries.
https://stackoverflow.com/questions/71205189/
Using torchtext vocab with torchscript
I'm trying to use the torchtext vocab layer along with torchscript but I'm getting some errors and I was wondering if someone here has made it work. My current model is class VocabText(torch.nn.Module): def __init__(self): super(VocabText, self).__init__() self.embedding = torch.nn.Embedding(10,128) vocab = ['This', 'is', 'a', 'test'] counter = Counter(vocab) self.lookup = text.vocab.vocab(counter) self.tensor = torch.Tensor def forward(self, x: str): x_mapped = self.lookup(x) x_mapped = self.tensor(x_mapped).int() x_mapped = self.embedding(x_mapped) return x That works when I do a pass of the model like this: example_str = [&quot;is&quot;] model(example_str) But when I try to compile it with torchscript it fails: model_scripted = torch.jit.script(model) model_scripted.save('model_scripted.pt') With the following error: RuntimeError: Unknown builtin op: aten::Tensor. Here are some suggestions: For when I map the result of the lookup layer during the forward function I think is due to typing as the vocab layer expects strings as input but the embedding layer will use tensors. Im doing a cast in the middle of the forward. I have a working notebook in colab to reproduce this issue if anybody wants: https://colab.research.google.com/drive/14nZF5X8rQrZET_7iA1N2MUV3XSzozpeI?usp=sharing
Turns out I had to change the function to built the tensor, found at https://discuss.pytorch.org/t/unknown-builtin-op-aten-tensor/62389
https://stackoverflow.com/questions/71205484/
It is possible to get only the names of the parent components in PyTorch model
All pretrained models in Pytorch contain &quot;parent&quot; submodules with predefines names, for example AlexNet contains 3 &quot;parent&quot; submodules: features, avgpool and classifier: model = torch.hub.load('pytorch/vision:v0.10.0','resnet101',pretrained=True) AlexNet( (features): Sequential( (0): Conv2d(3, 64, kernel_size=(11, 11), stride=(4, 4), padding=(2, 2)) (1): ReLU(inplace=True) (2): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=False) (3): Conv2d(64, 192, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2)) (4): ReLU(inplace=True) (5): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=False) (6): Conv2d(192, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (7): ReLU(inplace=True) (8): Conv2d(384, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (9): ReLU(inplace=True) (10): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (11): ReLU(inplace=True) (12): MaxPool2d(kernel_size=3, stride=2, padding=0, dilation=1, ceil_mode=False) ) (avgpool): AdaptiveAvgPool2d(output_size=(6, 6)) (classifier): Sequential( (0): Dropout(p=0.5, inplace=False) (1): Linear(in_features=9216, out_features=4096, bias=True) (2): ReLU(inplace=True) (3): Dropout(p=0.5, inplace=False) (4): Linear(in_features=4096, out_features=4096, bias=True) (5): ReLU(inplace=True) (6): Linear(in_features=4096, out_features=1, bias=True) ) ) Is there a method to get only these components' like mo = model.get_subs() # mo=['features','avgpool','classifier']?
You can use this: import torch import torchvision.models as models model = models.alexnet(pretrained=True) parents = [parent[0] for parent in model.named_children()] # get parents names print(parents) Output: ['features', 'avgpool', 'classifier']
https://stackoverflow.com/questions/71208261/
Expand the tensor by several dimensions
In PyTorch, given a tensor of size=[3], how to expand it by several dimensions to the size=[3,2,5,5] such that the added dimensions have the corresponding values from the original tensor. For example, making size=[3] vector=[1,2,3] such that the first tensor of size [2,5,5] has values 1, the second one has all values 2, and the third one all values 3. In addition, how to expand the vector of size [3,2] to [3,2,5,5]? One way to do it I can think is by means of creating a vector of the same size with ones-Like and then einsum but I think there should be an easier way.
You can first unsqueeze the appropriate number of singleton dimensions, then expand to a view at the target shape with torch.Tensor.expand: &gt;&gt;&gt; x = torch.rand(3) &gt;&gt;&gt; target = [3,2,5,5] &gt;&gt;&gt; x[:, None, None, None].expand(target) A nice workaround is to use torch.Tensor.reshape or torch.Tensor.view to do perform multiple unsqueezing: &gt;&gt;&gt; x.view(-1, 1, 1, 1).expand(target) This allows for a more general approach to handle any arbitrary target shape: &gt;&gt;&gt; x.view(len(x), *(1,)*(len(target)-1)).expand(target) For an even more general implementation, where x can be multi-dimensional: &gt;&gt;&gt; x = torch.rand(3, 2) # just to make sure the target shape is valid w.r.t to x &gt;&gt;&gt; assert list(x.shape) == list(target[:x.ndim]) &gt;&gt;&gt; x.view(*x.shape, *(1,)*(len(target)-x.ndim)).expand(target)
https://stackoverflow.com/questions/71208527/
How does it work for me to call an object in a function that doesnt have it as a parameter in python/pytorch?
Im learning neural network in PyTorch and i came across with that: #Loss function criterion = nn.MSELoss() #Optimizer from torch import optim optimizer = optim.Adam(MLP.parameters(), lr=args['lr'], weight_decay=args['weight_decay']) def train(train_loader, MLP, epoch): #MLP is the model MLP.train() start = time.time() epoch_loss = [] for batch in train_loader: sample, label = batch optimizer.zero_grad() #Forward pred = MLP(sample) loss = criterion(pred, label) epoch_loss.append(loss.data) #Backward loss.backward() optimizer.step() epoch_loss = np.asarray(epoch_loss) end = time.time() print('Epoch: {}, Loss: {:.4f} +/- {:.4f}, Time: {}'.format(epoch+1, epoch_loss.mean(), epoch_loss.std(), end-start)) return epoch_loss.mean() Well, &quot;criterion&quot; and &quot;optimizer&quot; are objects that i didnt pass as parameters for my function &quot;train&quot; like i did with the model (MLP), but it worked. Does it work for any function or is it just a PyTorch's thing?
This is not a Pytorch thing, these are called global (as opposed to local) variables. I would advise to get more familiar with the Python language and programming in general, if you want to get a grip on Pytorch.
https://stackoverflow.com/questions/71209425/
Speeding-up inference of T5-like model
I am currently using a model called T0pp (https://huggingface.co/bigscience/T0pp) in production and would like to speed up inference. I am running the following code on an on-demand EC2 g4dn.12xlarge instance (4 Nvidia T4 GPUs): from transformers import AutoTokenizer, AutoModelForSeq2SeqLM tokenizer = AutoTokenizer.from_pretrained(&quot;bigscience/T0pp&quot;) model = AutoModelForSeq2SeqLM.from_pretrained(&quot;bigscience/T0pp&quot;) model.parallelize() input_dict = tokenizer(generation_input.inputs, return_tensors=&quot;pt&quot;, padding=True) inputs = input_dict.input_ids.to(&quot;cuda:0&quot;) attention_mask = input_dict.attention_mask.to(&quot;cuda:0&quot;) with torch.no_grad(): outputs = model.generate(inputs, attention_mask=attention_mask) tokenizer.batch_decode(outputs, skip_special_tokens=True) I wanted to know which alternative you would try in order to speed-up inference, and if you knew good tutorials to do so. The main alternatives I see to speed-up inference would be to use the underlying Pytorch models with: ONNX Deepspeed or using fp16 instead of fp32 parameters (with the main drawback of losing some quality) Would someone have experience in using these tools, and would know which is the best / simplest option? All this is quite new for me, and I must admit I've been a bit lost in ONNX and Deepspeed tutorials. PS: I already tried SageMaker, but this is not working for huge models like T0pp (40Gb). Batching speeds up things, allowing to go from 1-2 seconds for batch size 1, to 16 seconds for batch size 32. In an ideal world, even batch size 32 would be under 1 or 2 seconds.
Maybe you could try OpenVINO? It allows you to convert your model into Intermediate Representation (IR) and then run on the CPU with the FP16 support. OpenVINO is optimized for Intel hardware but it should work with any processor. I cannot guarantee your model will be faster on CPU than Nvidia GPU but it's worth giving it a try. Some NLP models are fast enough (like this BERT). You can find a full tutorial on how to convert the PyTorch model here (FastSeg) and here (BERT). Some snippets below. Install OpenVINO The easiest way to do it is using PIP. Alternatively, you can use this tool to find the best way in your case. pip install openvino-dev[pytorch,onnx] Save your model to ONNX OpenVINO cannot convert PyTorch model directly for now but it can do it with ONNX model. This sample code assumes the model is for computer vision. dummy_input = torch.randn(1, 3, IMAGE_HEIGHT, IMAGE_WIDTH) torch.onnx.export(model, dummy_input, &quot;model.onnx&quot;, opset_version=11) Use Model Optimizer to convert ONNX model The Model Optimizer is a command line tool that comes from OpenVINO Development Package so be sure you have installed it. It converts the ONNX model to OV format (aka IR), which is a default format for OpenVINO. It also changes the precision to FP16 (to further increase performance). The accuracy drop, in most cases, is insignificant. Run in command line: mo --input_model &quot;model.onnx&quot; --input_shape &quot;[1, 3, 224, 224]&quot; --mean_values=&quot;[123.675, 116.28 , 103.53]&quot; --scale_values=&quot;[58.395, 57.12 , 57.375]&quot; --data_type FP16 --output_dir &quot;model_ir&quot; Run the inference on the CPU The converted model can be loaded by the runtime and compiled for a specific device e.g. CPU or GPU (integrated into your CPU like Intel HD Graphics). If you don't know what is the best choice for you, just use AUTO. # Load the network ie = Core() model_ir = ie.read_model(model=&quot;model_ir/model.xml&quot;) compiled_model_ir = ie.compile_model(model=model_ir, device_name=&quot;CPU&quot;) # Get output layer output_layer_ir = compiled_model_ir.output(0) # Run inference on the input image result = compiled_model_ir([input_image])[output_layer_ir] It's worth mentioning that Runtime can process the ONNX model directly. In that case, just skip the conversion (Model Optimizer) step and give onnx path to the read_model function. Disclaimer: I work on OpenVINO.
https://stackoverflow.com/questions/71210238/
Problem with pytorch hooks? Activation maps allways positiv
I was looking at the activation maps of vgg19 in pytorch. I found that all the values of the maps are positive even before I applied the ReLU. This seems very strange to me... If this would be correct (could be that I not used the register_forward_hook method correctly?) why would one then apply ReLu at all? This is my code to produce this: import torch import torchvision import torchvision.models as models import torchvision.transforms as transforms from torchsummary import summary import os, glob import matplotlib.pyplot as plt import numpy as np # settings: batch_size = 4 # load the model model = models.vgg19(pretrained=True) summary(model.cuda(), (3, 32, 32)) model.cpu() # how to preprocess??? See here: # https://discuss.pytorch.org/t/how-to-preprocess-input-for-pre-trained-networks/683/2 normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) transform = transforms.Compose( [transforms.ToTensor(), normalize]) # build data loader trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=2) # show one image dataiter = iter(trainloader) images, labels = dataiter.next() # set a hook activation = {} def get_activation(name): def hook(model, input, output): activation[name] = output.detach() return hook # hook at the first conv layer hook = model.features[0].register_forward_hook(get_activation(&quot;firstConv&quot;)) model(images) hook.remove() # show results: flatted_feat_maps = activation[&quot;firstConv&quot;].detach().numpy().flatten() print(&quot;All positiv??? --&gt; &quot;,np.all(flatted_feat_maps &gt;= 0)) plt.hist(flatted_feat_maps) plt.show() ---------------------------------------------------------------- Layer (type) Output Shape Param # ================================================================ Conv2d-1 [-1, 64, 32, 32] 1,792 ReLU-2 [-1, 64, 32, 32] 0 Conv2d-3 [-1, 64, 32, 32] 36,928 ReLU-4 [-1, 64, 32, 32] 0 MaxPool2d-5 [-1, 64, 16, 16] 0 Conv2d-6 [-1, 128, 16, 16] 73,856 ReLU-7 [-1, 128, 16, 16] 0 Conv2d-8 [-1, 128, 16, 16] 147,584 ReLU-9 [-1, 128, 16, 16] 0 MaxPool2d-10 [-1, 128, 8, 8] 0 Conv2d-11 [-1, 256, 8, 8] 295,168 ReLU-12 [-1, 256, 8, 8] 0 Conv2d-13 [-1, 256, 8, 8] 590,080 ReLU-14 [-1, 256, 8, 8] 0 Conv2d-15 [-1, 256, 8, 8] 590,080 ReLU-16 [-1, 256, 8, 8] 0 Conv2d-17 [-1, 256, 8, 8] 590,080 ReLU-18 [-1, 256, 8, 8] 0 MaxPool2d-19 [-1, 256, 4, 4] 0 Conv2d-20 [-1, 512, 4, 4] 1,180,160 ReLU-21 [-1, 512, 4, 4] 0 Conv2d-22 [-1, 512, 4, 4] 2,359,808 ReLU-23 [-1, 512, 4, 4] 0 Conv2d-24 [-1, 512, 4, 4] 2,359,808 ReLU-25 [-1, 512, 4, 4] 0 Conv2d-26 [-1, 512, 4, 4] 2,359,808 ReLU-27 [-1, 512, 4, 4] 0 MaxPool2d-28 [-1, 512, 2, 2] 0 Conv2d-29 [-1, 512, 2, 2] 2,359,808 ReLU-30 [-1, 512, 2, 2] 0 Conv2d-31 [-1, 512, 2, 2] 2,359,808 ReLU-32 [-1, 512, 2, 2] 0 Conv2d-33 [-1, 512, 2, 2] 2,359,808 ReLU-34 [-1, 512, 2, 2] 0 Conv2d-35 [-1, 512, 2, 2] 2,359,808 ReLU-36 [-1, 512, 2, 2] 0 MaxPool2d-37 [-1, 512, 1, 1] 0 AdaptiveAvgPool2d-38 [-1, 512, 7, 7] 0 Linear-39 [-1, 4096] 102,764,544 ReLU-40 [-1, 4096] 0 Dropout-41 [-1, 4096] 0 Linear-42 [-1, 4096] 16,781,312 ReLU-43 [-1, 4096] 0 Dropout-44 [-1, 4096] 0 Linear-45 [-1, 1000] 4,097,000 ================================================================ Total params: 143,667,240 Trainable params: 143,667,240 Non-trainable params: 0 ---------------------------------------------------------------- Input size (MB): 0.01 Forward/backward pass size (MB): 5.25 Params size (MB): 548.05 Estimated Total Size (MB): 553.31 ---------------------------------------------------------------- Could it be that I somehow did not use the register_forward_hook correctly?
You should clone the output in def get_activation(name): def hook(model, input, output): activation[name] = output.detach().clone() # return hook Note that Tensor.detach only detaches the tensor from the graph, but both tensors will still share the same underlying storage. Returned Tensor shares the same storage with the original one. In-place modifications on either of them will be seen, and may trigger errors in correctness checks. IMPORTANT NOTE: Previously, in-place size / stride / storage changes (such as resize_ / resize_as_ / set_ / transpose_) to the returned tensor also update the original tensor. Now, these in-place changes will not update the original tensor anymore, and will instead trigger an error. For sparse tensors: In-place indices / values changes (such as zero_ / copy_ / add_) to the returned tensor will not update the original tensor anymore, and will instead trigger an error.
https://stackoverflow.com/questions/71211228/
PyTorch to ONNX export, ATen operators not supported, onnxruntime hangs out
I want to export roberta-base based language model to ONNX format. The model uses ROBERTA embeddings and performs text classification task. from torch import nn import torch.onnx import onnx import onnxruntime import torch import transformers from logs: 17: pytorch: 1.10.2+cu113 18: CUDA: False 21: device: cpu 26: onnxruntime: 1.10.0 27: onnx: 1.11.0 PyTorch export batch_size = 3 model_input = { 'input_ids': torch.empty(batch_size, 256, dtype=torch.int).random_(32000), 'attention_mask': torch.empty(batch_size, 256, dtype=torch.int).random_(2), 'seq_len': torch.empty(batch_size, 1, dtype=torch.int).random_(256) } model_file_path = os.path.join(&quot;checkpoints&quot;, 'model.onnx') torch.onnx.export(da_inference.model, # model being run model_input, # model input (or a tuple for multiple inputs) model_file_path, # where to save the model (can be a file or file-like object) export_params=True, # store the trained parameter weights inside the model file opset_version=11, # the ONNX version to export the model to operator_export_type=torch.onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK, do_constant_folding=True, # whether to execute constant folding for optimization input_names = ['input_ids', 'attention_mask', 'seq_len'], # the model's input names output_names = ['output'], # the model's output names dynamic_axes={'input_ids': {0 : 'batch_size'}, 'attention_mask': {0 : 'batch_size'}, 'seq_len': {0 : 'batch_size'}, 'output' : {0 : 'batch_size'}}, verbose=True) I know there maybe problems converting some operators from ATen (A Tensor Library for C++11), if included in model architecture PyTorch Model Export to ONNX Failed Due to ATen. Exports succeeds if I set the parameter operator_export_type=torch.onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK which means 'leave as is ATen operators if not supported in ONNX'. PyTorch export function gives me the following warning: Warning: Unsupported operator ATen. No schema registered for this operator. Warning: Shape inference does not support models with experimental operators: ATen It looks like the only ATen operators in the model that are not converted to ONNX are situated inside layers LayerNorm.weight and LayerNorm.bias (I have several layers like that): %1266 : Float(3, 256, 768, strides=[196608, 768, 1], requires_grad=0, device=cpu) = onnx::ATen[cudnn_enable=1, eps=1.0000000000000001e-05, normalized_shape=[768], operator=&quot;layer_norm&quot;] (%1265, %model.utterance_rnn.base.encoder.layer.11.output.LayerNorm.weight, %model.utterance_rnn.base.encoder.layer.11.output.LayerNorm.bias) # /opt/conda/lib/python3.9/site-packages/torch/nn/functional.py:2347:0 Than model check passes OK: model = onnx.load(model_file_path) # Check that the model is well formed onnx.checker.check_model(model) # Print a human readable representation of the graph print(onnx.helper.printable_graph(model.graph)) I also can visualize computation graph using Netron. But when I try to perform inference using exported ONNX model it stalls with no logs or stdout. So this code will hang the system: model_file_path = os.path.join(&quot;checkpoints&quot;, &quot;model.onnx&quot;) sess_options = onnxruntime.SessionOptions() sess_options.log_severity_level = 0 ort_providers: List[str] = [&quot;CUDAExecutionProvider&quot;] if use_gpu else ['CPUExecutionProvider'] session = InferenceSession(model_file_path, providers=ort_providers, sess_options=sess_options) Is there any suggestions to overcome this problem? From official documentation I see that torch.onnx models exported this way are probably runnable only by Caffe2. This layers are not inside the base frozen roberta model, so this is additional layers that I added by myself. Is it possible to substitute the offending layers with similar ones and retrain the model? Or Caffe2 is the best choice here and onnxruntime will not do the inference? Update: I retrained the model on the basis of BERT cased embeddings, but the problem persists. The same ATen operators are not converted in ONNX. It looks like the layers LayerNorm.weight and LayerNorm.bias are only in the model above BERT. So, what is your suggestions to change this layers and enable ONNX export?
Have you tried to export after defining the operator for onnx? Something along the lines of the following code by Huawei. On another note, when loading a model, you can technically override anything you want. Putting a specific layer to equal your modified class that inherits the original, keeps the same behavior (input and output) but execution of it can be modified. You can try to use this to save the model with changed problematic operators, transform it in onnx, and fine tune in such form (or even in pytorch). This generally seems best solved by the onnx team, so long term solution might be to post a request for that specific operator on the github issues page (but probably slow).
https://stackoverflow.com/questions/71220867/
Pytorch error when modifying unpacked tensor
I have an error when modifying an unpacked tensor. import torch a1, a2 = torch.tensor([1,2], dtype = torch.float64) b = torch.rand(2, requires_grad = True) a1 += b.sum() This code produces the following error: RuntimeError: A view was created in no_grad mode and is being modified inplace with grad mode enabled. This view is the output of a function that returns multiple views. Such functions do not allow the output views to be modified inplace. You should replace the inplace operation by an out-of-place one. However, I didn't receive that error when I created a1 and a2 separately as follows: a1 = torch.tensor([1], dtype = torch.float64) a1 += b.sum() I have no idea why unpacking a tensor would lead to that error. Any help is greatly appreciated
The error message is clear and explains that: You created two views a1 and a2 in no_grad mode and view b in grad mode enabled. Such functions (unpacking) do not allow the output views (a1,a2) to be modified inplace (inplace operation +=) Solution: you should replace the inplace operation by an out-of-place one. You can clone a1 to a before this operation as follows: a = a1.clone() a += b.sum() That is because tensor.clone() creates a copy of the original tensor with requires_grad field. Thus, you will find now a and b have requires_grad. If you print the print(a.requires_grad) #True print(b.requires_grad) #True print(a1.requires_grad) #False You can read more about inplace operation 1 2
https://stackoverflow.com/questions/71223747/
detach().cpu() kills kernel
Background I am trying to plot an image noise using pytorch, however, when I reach to that point, the kernel dies. I am attempting the same code at Google Colab where I do get results Result at Google Colab Result at Jupyter I do not think that it has something to do with the code itself, but I am posting the function to plot the grid: def Exec_ShowImgGrid(ObjTensor, NumCh=1, NumSizeData=(28,28), NumImgs=16): #tensor: 128(pictures at the time ) * 784 (28*28) Objdata= ObjTensor.detach().cpu().view(-1,NumCh,*NumSizeData) #128 *1 *28*28 Objgrid= make_grid(Objdata[:NumCh],nrow=4).permute(1,2,0) #1*28*28 = 28*28*1 #Mathplot library isnt the saame as pytorch, we are accomodating the args Objpyplot.imshow(Objgrid) Objpyplot.show() I set a pdb and I can notice it does not run the Objdata line, so I am assuming it has to do with the detach().cpu() These are the libraries from the environment used, which I think may be the culprit name: GPUBase channels: - pytorch - defaults dependencies: - argon2-cffi=21.3.0=pyhd3eb1b0_0 - argon2-cffi-bindings=21.2.0=py39h2bbff1b_0 - async_generator=1.10=pyhd3eb1b0_0 - attrs=21.4.0=pyhd3eb1b0_0 - backcall=0.2.0=pyhd3eb1b0_0 - blas=1.0=mkl - bleach=4.1.0=pyhd3eb1b0_0 - ca-certificates=2021.10.26=haa95532_4 - certifi=2021.10.8=py39haa95532_2 - cffi=1.15.0=py39h2bbff1b_1 - colorama=0.4.4=pyhd3eb1b0_0 - cpuonly=2.0=0 - cudatoolkit=11.3.1=h59b6b97_2 - debugpy=1.5.1=py39hd77b12b_0 - decorator=5.1.1=pyhd3eb1b0_0 - defusedxml=0.7.1=pyhd3eb1b0_0 - entrypoints=0.3=py39haa95532_0 - freetype=2.10.4=hd328e21_0 - importlib_metadata=4.8.2=hd3eb1b0_0 - intel-openmp=2021.4.0=haa95532_3556 - ipykernel=6.4.1=py39haa95532_1 - ipython=7.31.1=py39haa95532_0 - ipython_genutils=0.2.0=pyhd3eb1b0_1 - jedi=0.18.1=py39haa95532_1 - jinja2=3.0.2=pyhd3eb1b0_0 - jpeg=9d=h2bbff1b_0 - jsonschema=3.2.0=pyhd3eb1b0_2 - jupyter_client=7.1.2=pyhd3eb1b0_0 - jupyter_core=4.9.1=py39haa95532_0 - jupyterlab_pygments=0.1.2=py_0 - libpng=1.6.37=h2a8f88b_0 - libtiff=4.2.0=hd0e1b90_0 - libuv=1.40.0=he774522_0 - libwebp=1.2.0=h2bbff1b_0 - lz4-c=1.9.3=h2bbff1b_1 - markupsafe=2.0.1=py39h2bbff1b_0 - matplotlib-inline=0.1.2=pyhd3eb1b0_2 - mistune=0.8.4=py39h2bbff1b_1000 - mkl=2021.4.0=haa95532_640 - mkl-service=2.4.0=py39h2bbff1b_0 - mkl_fft=1.3.1=py39h277e83a_0 - mkl_random=1.2.2=py39hf11a4ad_0 - nbclient=0.5.3=pyhd3eb1b0_0 - nbconvert=6.1.0=py39haa95532_0 - nbformat=5.1.3=pyhd3eb1b0_0 - nest-asyncio=1.5.1=pyhd3eb1b0_0 - notebook=6.4.8=py39haa95532_0 - numpy-base=1.21.5=py39hc2deb75_0 - olefile=0.46=pyhd3eb1b0_0 - openssl=1.1.1m=h2bbff1b_0 - packaging=21.3=pyhd3eb1b0_0 - pandocfilters=1.5.0=pyhd3eb1b0_0 - parso=0.8.3=pyhd3eb1b0_0 - pickleshare=0.7.5=pyhd3eb1b0_1003 - pip=21.2.4=py39haa95532_0 - prometheus_client=0.13.1=pyhd3eb1b0_0 - prompt-toolkit=3.0.20=pyhd3eb1b0_0 - pycparser=2.21=pyhd3eb1b0_0 - pygments=2.11.2=pyhd3eb1b0_0 - pyrsistent=0.18.0=py39h196d8e1_0 - python=3.9.7=h6244533_1 - python-dateutil=2.8.2=pyhd3eb1b0_0 - pytorch-mutex=1.0=cpu - pywin32=302=py39h827c3e9_1 - pywinpty=2.0.2=py39h5da7b33_0 - pyzmq=22.3.0=py39hd77b12b_2 - send2trash=1.8.0=pyhd3eb1b0_1 - setuptools=58.0.4=py39haa95532_0 - six=1.16.0=pyhd3eb1b0_1 - sqlite=3.37.2=h2bbff1b_0 - terminado=0.13.1=py39haa95532_0 - testpath=0.5.0=pyhd3eb1b0_0 - tk=8.6.11=h2bbff1b_0 - tornado=6.1=py39h2bbff1b_0 - traitlets=5.1.1=pyhd3eb1b0_0 - typing_extensions=3.10.0.2=pyh06a4308_0 - tzdata=2021e=hda174b7_0 - vc=14.2=h21ff451_1 - vs2015_runtime=14.27.29016=h5e58377_2 - wcwidth=0.2.5=pyhd3eb1b0_0 - wheel=0.37.1=pyhd3eb1b0_0 - wincertstore=0.2=py39haa95532_2 - winpty=0.4.3=4 - xz=5.2.5=h62dcd97_0 - zipp=3.7.0=pyhd3eb1b0_0 - zlib=1.2.11=h8cc25b3_4 - zstd=1.4.9=h19a0ad4_0 - pip: - absl-py==1.0.0 - astunparse==1.6.3 - cachetools==5.0.0 - charset-normalizer==2.0.12 - cycler==0.11.0 - docutils==0.18.1 - flatbuffers==2.0 - fonttools==4.29.1 - gast==0.5.3 - google-auth==2.6.0 - google-auth-oauthlib==0.4.6 - google-pasta==0.2.0 - grpcio==1.44.0 - h5py==3.6.0 - htmlmin==0.1.12 - idna==3.3 - imagehash==4.2.1 - importlib-metadata==4.11.1 - ipywidgets==7.6.5 - joblib==1.0.1 - jupyterlab-widgets==1.0.2 - keras==2.8.0 - keras-preprocessing==1.1.2 - keyring==23.5.0 - kiwisolver==1.3.2 - libclang==13.0.0 - markdown==3.3.6 - matplot==0.1.9 - matplotlib==3.5.1 - missingno==0.5.0 - multimethod==1.7 - networkx==2.6.3 - numpy==1.22.2 - oauthlib==3.2.0 - opt-einsum==3.3.0 - pandas==1.4.1 - pandas-profiling==3.1.0 - phik==0.12.0 - pillow==9.0.1 - pkginfo==1.8.2 - protobuf==3.19.4 - pyasn1==0.4.8 - pyasn1-modules==0.2.8 - pydantic==1.9.0 - pyloco==0.0.139 - pyparsing==3.0.7 - pytz==2021.3 - pywavelets==1.2.0 - pywin32-ctypes==0.2.0 - pyyaml==6.0 - readme-renderer==32.0 - requests==2.27.1 - requests-oauthlib==1.3.1 - requests-toolbelt==0.9.1 - rfc3986==2.0.0 - rsa==4.8 - scikit-learn==1.0.2 - scipy==1.8.0 - seaborn==0.11.2 - simplewebsocketserver==0.1.1 - tangled-up-in-unicode==0.1.0 - tensorboard==2.8.0 - tensorboard-data-server==0.6.1 - tensorboard-plugin-wit==1.8.1 - tensorflow==2.8.0 - tensorflow-gpu==2.8.0 - tensorflow-io-gcs-filesystem==0.24.0 - termcolor==1.1.0 - tf-estimator-nightly==2.8.0.dev2021122109 - threadpoolctl==3.1.0 - torch==1.10.2 - torchaudio==0.7.2 - torchutils==0.0.4 - torchvision==0.8.2+cu110 - tqdm==4.62.3 - twine==3.8.0 - typing==3.7.4.3 - typing-extensions==4.1.1 - urllib3==1.26.8 - ushlex==0.99.1 - visions==0.7.4 - webencodings==0.5.1 - websocket-client==1.2.3 - werkzeug==2.0.3 - widgetsnbextension==3.5.2 - wrapt==1.13.3 - xlwings==0.26.3 Question How can I be able to plot as in google colab for the function stated?
After a few days I was able to find the solution Firstly, my code needed to be fixed to correctly call the params needed with the proper name def Exec_ShowImgGrid(ObjTensor, ch=1, size=(28,28), num=16): #tensor: 128(pictures at the time ) * 784 (28*28) Objdata= ObjTensor.detach().cpu().view(-1,ch,*size) #128 *1 *28*28 Objgrid= make_grid(Objdata[:num],nrow=4).permute(1,2,0) #1*28*28 = 28*28*1 #Mathplot library isnt the saame as pytorch, we are accomodating the args Objpyplot.imshow(Objgrid) Objpyplot.show() The Kernel was dying still, the only solution was to install numba in the environment as this answer states. I only had to append the from numba import cuda statement at my declarations.
https://stackoverflow.com/questions/71225998/
In a Pytorch LSTM, does the base class take care of a hidden layer on its own, or must it be defined (additional questions)
Let's take the following code: ''' LSTM class ''' import torch import pandas as pd import numpy as np import torch.nn.CrossEntropyLoss class LSTM(nn.Module): def __init__(self, input_size, hidden_size, num_layers): super (LSTM, self).__init__() self.hidden_size = hidden_size self.lstm = nn.LSTM(input_size, hidden_size, num_layers) def forward(self, x): # receive an input, create a new hidden state, return output? # reset the hidden state? hidden = (torch.zeros(num_layers, hidden_size), torch.zeros(num_layers, hidden_size)) x, hidden = self.lstm(x, hidden) #since our observation has several sequences, we only want the output after the last sequence of the observation''' x = x[:, -1] return x I have several questions here, and if permitted would rather ask them all at once rather than waiting 90 minutes between singular posts. I've seen and followed quite a few examples of LSTMs in pytorch and each example seems to treat different pieces a bit differently. Since i'm not in expert in either python, or neural networks, this has lead me to a lot of confusion. I'll ask my question sequentially in order of how they appear in the code above. I've seen the hidden layer both defined, zeroed, left out and ignored entirely in a few different implementations. I know what its for, but in the implementation i've produced (which is itself an amalgamation of several tutorials) the hidden layer doesn't appear to be connected to anything. in the forward function we take a single input pass it to the hidden layer (which is first zero'd) then call self.lstm on it. Is this the equivalent of letting lstm &quot;handle&quot; the hidden layer itself? Will this properly produce a hidden state? Am I correct that the optimization only occurs during the training loop? I was using this particular tutorial as an example: https://pytorch.org/tutorials/beginner/basics/optimization_tutorial.html def train_loop(dataloader, model, loss_fn, optimizer): size = len(dataloader.dataset) for batch, (X, y) in enumerate(dataloader): # Compute prediction and loss pred = model(X) loss = loss_fn(pred, y) # Backpropagation optimizer.zero_grad() loss.backward() optimizer.step() in the optimizer tutorial, i assume y is the true label for the observation, is that correct? My intention is to use cross entropy loss, as that seems like the right one to define what i'm doing with my data (the labels are not discrete, and are real positive floats with a range, and there are 3 of them), so the output size should be 3. Given the optimizer tutorial, all i need to do is hand the loss function the output from the training step, and the correct label, and then backpropagate. Is that correct as well? I know there's a lot here, so i'd appreciate answers to any of the questions from anyone inclined to help, even if you cannot answer all of them. Thank you for your time.
I've had a talk with a colleague and I've been able to answer some of my own questions, so I'll post those, since it may help others. The hidden state zero-out is NOT modifying the hidden_layer, it is zero-ing out the hidden state at the start because the cells start empty, as you'd expect in any language object-oriented. It turns out this is unnecessary, since for quite some time the pytorch default is to zero out these values if they're not initialized manually. This simple implementation will produce a hidden state as written. The answer to this is yes. We don't &quot;grade&quot; the result of network until we get to the optimization section, or, more specifically, the loss function. y is the true label, it was not identified in the tutorial. Also, important to note, pred is not a &quot;prediction&quot; but a pytorch object that points to the result of the network acting upon the observation that was fed in. In other words, printing out &quot;pred&quot; would not show you a vector of values that represents a prediction This is also correct. Pytorch handles the &quot;distance measure&quot; between the true label and the predicted label, on its own.
https://stackoverflow.com/questions/71226727/
Cannot transfer torch.Tensor to torch.cuda.Tensor
I use the following code to turn the torch.Tensor into torch.cuda.Tensor import torch import numpy as np a = np.random.randn(1, 1, 2, 3) t2 = torch.tensor(a) t2 = t2.cuda() t3 = torch.tensor(a, device=torch.device('cuda')) print(type(t3), t3.device, type(t2), t2.device) And its output is &lt;class 'torch.Tensor'&gt; cuda:0 &lt;class 'torch.Tensor'&gt; cuda:0 I expect the class is 'torch.cuda.Tensor'. I don't know why this happens. My torch version is 1.6.0 and the corresponding cuda version is 10.2
That is because there is no such class as torch.cuda.Tensor in PyTorch 1.6.0. The t3.device and t2.device in print(type(t3), t3.device, type(t2), t2.device) prints cuda:0 which means your tensors are already on GPU.
https://stackoverflow.com/questions/71231008/
Shape Error while implementing U-Net (Encoder Part) in Pytorch
I am trying to learn build a U-NET architecture from scratch. I have written this code but the problem is that when I try to run to check the output of the encoder part, I am having issues with it. When you the run the code below , you'll get import torch import torch.nn as nn batch = 1 channels = 3 width = 512 # same as height image = torch.randn(batch, channels, width, width) enc = Encoder(channels) enc(image) RuntimeError: Given groups=1, weight of size [128, 64, 3, 3], expected input[1, 3, 512, 512] to have 64 channels, but got 3 channels instead Below is the code: class ConvolutionBlock(nn.Module): ''' The basic Convolution Block Which Will have Convolution -&gt; RelU -&gt; Convolution -&gt; RelU ''' def __init__(self, in_channels, out_channels, upsample:bool = False,): ''' args: upsample: If True, then use TransposedConv2D (Means it being used in the decoder part) instead MaxPooling batch_norm was introduced after UNET so they did not know if it existed. Might be useful ''' super().__init__() self.network = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size = 3, padding= 1), # padding is 0 by default, 1 means the input width, height == out width, height nn.ReLU(), nn.Conv2d(out_channels, out_channels, kernel_size = 3, padding = 1), nn.ReLU(), nn.MaxPool2d(kernel_size = 2, stride = 2) if not upsample else nn.ConvTranspose2d(out_channels, out_channels//2, kernel_size = 2, ) # As it is said in the paper that it TransPose2D halves the features ) def forward(self, feature_map_x): ''' feature_map_x could be the image itself or the ''' return self.network(feature_map_x) class Encoder(nn.Module): ''' ''' def __init__(self, image_channels:int = 1, repeat:int = 4): ''' In UNET, the features start at 64 and keeps getting twice the size of the previous one till it reached BottleNeck ''' super().__init__() in_channels = [image_channels,64, 128, 256, 512] out_channels = [64, 128, 256, 512, 1024] self.layers = nn.ModuleList( [ConvolutionBlock(in_channels = in_channels[i], out_channels = out_channels[i]) for i in range(repeat+1)] ) def forward(self, feature_map_x): for layer in self.layers: out = layer(feature_map_x) return out EDIT: Running the code below gives me expected info too: in_ = [3,64, 128, 256, 512] ou_ = [64, 128, 256, 512, 1024] width = 512 from torchsummary import summary for i in range(5): cb = ConvolutionBlock(in_[i], ou_[i]) summary(cb, (in_[i],width,width)) print('#'*50)
There was a code logic mistake in the forward of Encoder I did: for layer in self.layers: out = layer(feature_map_x) return out but I was supposed to use feature_map_x as the input because the loop was iterating over the original feature map before but it was supposed to get the output of previous layer. for layer in self.layers: feature_map_x = layer(feature_map_x) return feature_map_x
https://stackoverflow.com/questions/71232961/
Pytorch lightning print accuracy and loss at the end of each epoch
In tensorflow keras, when I'm training a model, at each epoch it print the accuracy and the loss, I want to do the same thing using pythorch lightning. I already create my module but I don't know how to do it. import torch import torch.nn as nn from residual_block import ResidualBlock import pytorch_lightning as pl from torchmetrics import Accuracy class ResNet(pl.LightningModule): def __init__(self, block, layers, image_channels, num_classes, learning_rate): super(ResNet, self).__init__() self.in_channels = 64 self.conv1 = nn.Conv2d( image_channels, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU() self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer( block, layers[0], intermediate_channels=64, stride=1) self.layer2 = self._make_layer( block, layers[1], intermediate_channels=128, stride=2) self.layer3 = self._make_layer( block, layers[2], intermediate_channels=256, stride=2) self.layer4 = self._make_layer( block, layers[3], intermediate_channels=512, stride=2) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(512 * 4, num_classes) self.learning_rate = learning_rate self.train_accuracy = Accuracy() self.val_accuracy = Accuracy() self.test_accuracy = Accuracy() def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = x.reshape(x.shape[0], -1) x = self.fc(x) return x def configure_optimizers(self): optimizer = torch.optim.Adam(self.parameters(), lr=self.learning_rate) return optimizer def training_step(self, train_batch, batch_idx): images, labels = train_batch outputs = self(images) criterion = nn.CrossEntropyLoss() loss = criterion(outputs, labels) self.train_accuracy(outputs, labels) self.log('train_loss', loss) self.log('train_accuracy', self.train_accuracy) return loss def validation_step(self, val_batch, batch_idx): images, labels = val_batch outputs = self(images) criterion = nn.CrossEntropyLoss() loss = criterion(outputs, labels) self.val_accuracy(outputs, labels) self.log('val_loss', loss) self.log('val_accuracy', self.val_accuracy) def test_step(self, test_batch, batch_idx): images, labels = test_batch outputs = self(images) criterion = nn.CrossEntropyLoss() loss = criterion(outputs, labels) self.test_accuracy(outputs, labels) self.log('test_loss', loss) self.log('test_accuracy', self.test_accuracy) def _make_layer(self, block, num_residual_blocks, intermediate_channels, stride): identity_downsample = None layers = [] if stride != 1 or self.in_channels != intermediate_channels * 4: identity_downsample = nn.Sequential(nn.Conv2d(self.in_channels, intermediate_channels * 4, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(intermediate_channels * 4),) layers.append( block(self.in_channels, intermediate_channels, identity_downsample, stride)) self.in_channels = intermediate_channels * 4 for i in range(num_residual_blocks - 1): layers.append(block(self.in_channels, intermediate_channels)) return nn.Sequential(*layers) @classmethod def ResNet50(cls, img_channels, num_classes, learning_rate): return ResNet(ResidualBlock, [3, 4, 6, 3], img_channels, num_classes, learning_rate) @classmethod def ResNet101(cls, img_channels, num_classes, learning_rate): return ResNet(ResidualBlock, [3, 4, 23, 3], img_channels, num_classes, learning_rate) @classmethod def ResNet152(cls, img_channels, num_classes, learning_rate): return ResNet(ResidualBlock, [3, 8, 36, 3], img_channels, num_classes, learning_rate) I just want to print the training and validation accuracy and loss at the end of each epoch.
self.log(&quot;train_loss&quot;, loss, prog_bar=True, on_step=False, on_epoch=True) The above code logs train_loss to the progress bar. https://pytorch-lightning.readthedocs.io/en/stable/extensions/logging.html#automatic-logging Or you can use this if on one device: def training_step(self, batch, batch_idx): ... loss = nn.functional.mse_loss(x_hat, x) return loss def training_epoch_end(self, outputs) -&gt; None: loss = sum(output['loss'] for output in outputs) / len(outputs) print(loss) Multiple GPUs: def training_epoch_end(self, outputs) -&gt; None: gathered = self.all_gather(outputs) if self.global_rank == 0: # print(gathered) loss = sum(output['loss'].mean() for output in gathered) / len(outputs) print(loss.item())
https://stackoverflow.com/questions/71236391/
Export tensorboard (with pytorch) data into csv with python
I have Tensorboard data and want it to download all of the csv files behind the data, but I could not find anything from the official documentation. From StackOverflow, I found only this question which is 7 years old and also it's about TensorFlow while I am using PyTorch. We can do this manually, as we can see in the screenshot, manually there is an option. I wonder if we can do that via code or it is not possible? As I have a lot of data to process.
With the help of this script Below is the shortest working code it gets all of the data in dataframe then you can play further. import traceback import pandas as pd from tensorboard.backend.event_processing.event_accumulator import EventAccumulator # Extraction function def tflog2pandas(path): runlog_data = pd.DataFrame({&quot;metric&quot;: [], &quot;value&quot;: [], &quot;step&quot;: []}) try: event_acc = EventAccumulator(path) event_acc.Reload() tags = event_acc.Tags()[&quot;scalars&quot;] for tag in tags: event_list = event_acc.Scalars(tag) values = list(map(lambda x: x.value, event_list)) step = list(map(lambda x: x.step, event_list)) r = {&quot;metric&quot;: [tag] * len(step), &quot;value&quot;: values, &quot;step&quot;: step} r = pd.DataFrame(r) runlog_data = pd.concat([runlog_data, r]) # Dirty catch of DataLossError except Exception: print(&quot;Event file possibly corrupt: {}&quot;.format(path)) traceback.print_exc() return runlog_data path=&quot;Run1&quot; #folderpath df=tflog2pandas(path) #df=df[(df.metric != 'params/lr')&amp;(df.metric != 'params/mm')&amp;(df.metric != 'train/loss')] #delete the mentioned rows df.to_csv(&quot;output.csv&quot;)
https://stackoverflow.com/questions/71239557/
How to use indices from torch.min to index multi-dimensional tensor
Using PyTorch I have a multidimensional tensor A of size (b, 2, x, y), and another related tensor B of size (b, 2, x, y, 3). I want to get the index of the minimum value across dim=1 in A (this dimension is size 2), and apply this index tensor to B so that I would end up with a tensor of shape (b, x, y, 3). By using A_mins, indices = torch.min(A, dim=1) I am able to get a tensor indices of shape (b, x, y) where the value is either 0 or 1 depending on which is the minimum value across dim=1 in A. I don't know how to then apply this to B to get the desired output. I am aware that torch.index_select does a similar job but only for 1D index vectors.
I think a more appropriate function would be torch.gather. You should first apply torch.Tensor.argmin (or equally with torch.Tensor.min) with the keepdim option set to True and broadcast the indexer (here reduced A since the indexed tensor B has an extra dimension): &gt;&gt;&gt; indexer = A.argmin(1,True).unsqueeze(-1).expand(*(-1,)*A.ndim, 3) &gt;&gt;&gt; out = torch.gather(B, 1, indexer)[:, 0] In terms of shapes: indexer tensor will have a shape of (b, 1, x, y, 3) where the last dimension is essentially a view to the values (we expanded from singleton to three-channel with torch.expand). the resulting tensor out will have a shape of (b, x, y, 3) after having squeeze the singleton on dim=1 with squeeze(1) or in an equivalent fashion with the [:, 0] indexing...
https://stackoverflow.com/questions/71241551/
What's the proper way to update a leaf tensor's values (e.g. during the update step of gradient descent)
Toy Example Consider this very simple implementation of gradient descent, whereby I attempt to fit a linear regression (mx + b) to some toy data. import torch # Make some data torch.manual_seed(0) X = torch.rand(35) * 5 Y = 3 * X + torch.rand(35) # Initialize m and b m = torch.rand(size=(1,), requires_grad=True) b = torch.rand(size=(1,), requires_grad=True) # Pass 1 yhat = X * m + b # Calculate yhat loss = torch.sqrt(torch.mean((yhat - Y)**2)) # Calculate the loss loss.backward() # Reverse mode differentiation m = m - 0.1*m.grad # update m b = b - 0.1*b.grad # update b m.grad = None # zero out m gradient b.grad = None # zero out b gradient # Pass 2 yhat = X * m + b # Calculate yhat loss = torch.sqrt(torch.mean((yhat - Y)**2)) # Calculate the loss loss.backward() # Reverse mode differentiation m = m - 0.1*m.grad # ERROR The first pass works fine, but the second pass errors on the last line, m = m - 0.1*m.grad. Error /usr/local/lib/python3.7/dist-packages/torch/_tensor.py:1013: UserWarning: The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad attribute won't be populated during autograd.backward(). If you indeed want the .grad field to be populated for a non-leaf Tensor, use .retain_grad() on the non-leaf Tensor. If you access the non-leaf Tensor by mistake, make sure you access the leaf Tensor instead. See github.com/pytorch/pytorch/pull/30531 for more informations. (Triggered internally at aten/src/ATen/core/TensorBody.h:417.) return self._grad My understanding of why this happens is that, during Pass 1, this line m = m - 0.1*m.grad copies m into a brand new tensor (i.e. a totally separate block of memory). So, it goes from being a leaf tensor to a non-leaf tensor. # Pass 1 ... print(f&quot;{m.is_leaf}&quot;) # True m = m - 0.1*m.grad print(f&quot;{m.is_leaf}&quot;) # False So, how does one perform an update? I've seen it mentioned that one could use something along the lines of m.data = m - 0.1*m.grad, but I haven't seen much discussion about this technique.
You're observation is correct, in order to perform the update you should: Apply the modification with in-place operators. Wrap the calls with torch.no_grad context manager. For instance: with torch.no_grad(): m -= 0.1*m.grad # update m b -= 0.1*b.grad # update b
https://stackoverflow.com/questions/71241940/
How to modify a 2d tensor to 3d in libtorch?
I have a 2d array vector&lt;vector&gt;, I have coverted it to tensor, but how to modify the dimension of the tensor, I want to modify the dimension from 2d to 3d? std::vector&lt;std::vector&lt;float&gt;&gt; voice(434, std::vector&lt;float&gt;(80)) ifstream fp(&quot;data.txt&quot;); if (! fp) { cout &lt;&lt; &quot;Error, file couldn't be opened&quot; &lt;&lt; endl; return 1; } for(int i=0;i&lt;80;i++) { for(int j=0;j&lt;434;j++) { if ( ! fp ) { std::cout &lt;&lt; &quot;read error&quot; &lt;&lt; std::endl; break; } fp &gt;&gt; voice[i][j] } } auto options = torch::TensorOptions().dtype(at::kDouble); auto tensor = torch::zeros({80,434}, options); for (int i = 0; i &lt; 80; i++) tensor.slice(0, i,i+1) = torch::from_blob(vect[i].data(), {434}, options); Now the tensor is 80 * 434, how can I add one dimension in this tensor to 3d, I want 1 * 80 * 434
auto tensor = torch::zeros({80,434}, options); followed by this line auto tensor = tensor.view({1, 80, 434}); I would recommend to create another variable instead of tensor in the second line, like: auto transformed_tensor = tensor.view({1, 80, 434});
https://stackoverflow.com/questions/71246089/
Print Bert model summary using Pytorch
Hi I would like to print the model summary of my BERT model for text classification. I am using command print(summary(model, inputsize=(channels, height, width)). I would like to know what would be the dimensions of input_size in case of text classification? I have use print(model) as well but the output is confusing and I want to see the output in the layered form. Below is my model summary. BertClassifier( (bert): BertModel( (embeddings): BertEmbeddings( (word_embeddings): Embedding(28996, 768, padding_idx=0) (position_embeddings): Embedding(512, 768) (token_type_embeddings): Embedding(2, 768) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) (encoder): BertEncoder( (layer): ModuleList( (0): BertLayer( (attention): BertAttention( (self): BertSelfAttention( (query): Linear(in_features=768, out_features=768, bias=True) (key): Linear(in_features=768, out_features=768, bias=True) (value): Linear(in_features=768, out_features=768, bias=True) (dropout): Dropout(p=0.1, inplace=False) ) (output): BertSelfOutput( (dense): Linear(in_features=768, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (intermediate): BertIntermediate( (dense): Linear(in_features=768, out_features=3072, bias=True) ) (output): BertOutput( (dense): Linear(in_features=3072, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (1): BertLayer( (attention): BertAttention( (self): BertSelfAttention( (query): Linear(in_features=768, out_features=768, bias=True) (key): Linear(in_features=768, out_features=768, bias=True) (value): Linear(in_features=768, out_features=768, bias=True) (dropout): Dropout(p=0.1, inplace=False) ) (output): BertSelfOutput( (dense): Linear(in_features=768, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (intermediate): BertIntermediate( (dense): Linear(in_features=768, out_features=3072, bias=True) ) (output): BertOutput( (dense): Linear(in_features=3072, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (2): BertLayer( (attention): BertAttention( (self): BertSelfAttention( (query): Linear(in_features=768, out_features=768, bias=True) (key): Linear(in_features=768, out_features=768, bias=True) (value): Linear(in_features=768, out_features=768, bias=True) (dropout): Dropout(p=0.1, inplace=False) ) (output): BertSelfOutput( (dense): Linear(in_features=768, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (intermediate): BertIntermediate( (dense): Linear(in_features=768, out_features=3072, bias=True) ) (output): BertOutput( (dense): Linear(in_features=3072, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (3): BertLayer( (attention): BertAttention( (self): BertSelfAttention( (query): Linear(in_features=768, out_features=768, bias=True) (key): Linear(in_features=768, out_features=768, bias=True) (value): Linear(in_features=768, out_features=768, bias=True) (dropout): Dropout(p=0.1, inplace=False) ) (output): BertSelfOutput( (dense): Linear(in_features=768, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (intermediate): BertIntermediate( (dense): Linear(in_features=768, out_features=3072, bias=True) ) (output): BertOutput( (dense): Linear(in_features=3072, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (4): BertLayer( (attention): BertAttention( (self): BertSelfAttention( (query): Linear(in_features=768, out_features=768, bias=True) (key): Linear(in_features=768, out_features=768, bias=True) (value): Linear(in_features=768, out_features=768, bias=True) (dropout): Dropout(p=0.1, inplace=False) ) (output): BertSelfOutput( (dense): Linear(in_features=768, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (intermediate): BertIntermediate( (dense): Linear(in_features=768, out_features=3072, bias=True) ) (output): BertOutput( (dense): Linear(in_features=3072, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (5): BertLayer( (attention): BertAttention( (self): BertSelfAttention( (query): Linear(in_features=768, out_features=768, bias=True) (key): Linear(in_features=768, out_features=768, bias=True) (value): Linear(in_features=768, out_features=768, bias=True) (dropout): Dropout(p=0.1, inplace=False) ) (output): BertSelfOutput( (dense): Linear(in_features=768, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (intermediate): BertIntermediate( (dense): Linear(in_features=768, out_features=3072, bias=True) ) (output): BertOutput( (dense): Linear(in_features=3072, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (6): BertLayer( (attention): BertAttention( (self): BertSelfAttention( (query): Linear(in_features=768, out_features=768, bias=True) (key): Linear(in_features=768, out_features=768, bias=True) (value): Linear(in_features=768, out_features=768, bias=True) (dropout): Dropout(p=0.1, inplace=False) ) (output): BertSelfOutput( (dense): Linear(in_features=768, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (intermediate): BertIntermediate( (dense): Linear(in_features=768, out_features=3072, bias=True) ) (output): BertOutput( (dense): Linear(in_features=3072, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (7): BertLayer( (attention): BertAttention( (self): BertSelfAttention( (query): Linear(in_features=768, out_features=768, bias=True) (key): Linear(in_features=768, out_features=768, bias=True) (value): Linear(in_features=768, out_features=768, bias=True) (dropout): Dropout(p=0.1, inplace=False) ) (output): BertSelfOutput( (dense): Linear(in_features=768, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (intermediate): BertIntermediate( (dense): Linear(in_features=768, out_features=3072, bias=True) ) (output): BertOutput( (dense): Linear(in_features=3072, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (8): BertLayer( (attention): BertAttention( (self): BertSelfAttention( (query): Linear(in_features=768, out_features=768, bias=True) (key): Linear(in_features=768, out_features=768, bias=True) (value): Linear(in_features=768, out_features=768, bias=True) (dropout): Dropout(p=0.1, inplace=False) ) (output): BertSelfOutput( (dense): Linear(in_features=768, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (intermediate): BertIntermediate( (dense): Linear(in_features=768, out_features=3072, bias=True) ) (output): BertOutput( (dense): Linear(in_features=3072, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (9): BertLayer( (attention): BertAttention( (self): BertSelfAttention( (query): Linear(in_features=768, out_features=768, bias=True) (key): Linear(in_features=768, out_features=768, bias=True) (value): Linear(in_features=768, out_features=768, bias=True) (dropout): Dropout(p=0.1, inplace=False) ) (output): BertSelfOutput( (dense): Linear(in_features=768, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (intermediate): BertIntermediate( (dense): Linear(in_features=768, out_features=3072, bias=True) ) (output): BertOutput( (dense): Linear(in_features=3072, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (10): BertLayer( (attention): BertAttention( (self): BertSelfAttention( (query): Linear(in_features=768, out_features=768, bias=True) (key): Linear(in_features=768, out_features=768, bias=True) (value): Linear(in_features=768, out_features=768, bias=True) (dropout): Dropout(p=0.1, inplace=False) ) (output): BertSelfOutput( (dense): Linear(in_features=768, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (intermediate): BertIntermediate( (dense): Linear(in_features=768, out_features=3072, bias=True) ) (output): BertOutput( (dense): Linear(in_features=3072, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (11): BertLayer( (attention): BertAttention( (self): BertSelfAttention( (query): Linear(in_features=768, out_features=768, bias=True) (key): Linear(in_features=768, out_features=768, bias=True) (value): Linear(in_features=768, out_features=768, bias=True) (dropout): Dropout(p=0.1, inplace=False) ) (output): BertSelfOutput( (dense): Linear(in_features=768, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) (intermediate): BertIntermediate( (dense): Linear(in_features=768, out_features=3072, bias=True) ) (output): BertOutput( (dense): Linear(in_features=3072, out_features=768, bias=True) (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True) (dropout): Dropout(p=0.1, inplace=False) ) ) ) ) (pooler): BertPooler( (dense): Linear(in_features=768, out_features=768, bias=True) (activation): Tanh() ) ) (dropout): Dropout(p=0.5, inplace=False) (linear1): Linear(in_features=768, out_features=256, bias=True) (linear2): Linear(in_features=256, out_features=141, bias=True) (relu): ReLU() )
I used torch-summary module- pip install torch-summary summary(model,input_size=(768,),depth=1,batch_dim=1, dtypes=[‘torch.IntTensor’])
https://stackoverflow.com/questions/71248696/
Mask to bounding box for narrow features (cracks)
I am trying to adapt the code detailed here https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html for crack detection using the Kanha dataset (https://github.com/khanhha/crack_segmentation). My problem is that when converting masks to bounding boxes, some are empty - and thus invalid. ValueError: All bounding boxes should have positive height and width. Found invalid box Should I add a minimum area clause before appending boxes[], boxes.append([xmin, ymin, xmax, ymax])? Or does anyone have another idea how to make progress? import os import numpy as np import torch from PIL import Image import torchvision from torchvision.models.detection.faster_rcnn import FastRCNNPredictor from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor from engine import train_one_epoch, evaluate import utils import transforms as T class CracksDataset(object): def __init__(self, root, transforms): self.root = root self.transforms = transforms # load all image files, sorting them to # ensure that they are aligned self.imgs = list(sorted(os.listdir(os.path.join(root, &quot;images&quot;)))) self.masks = list(sorted(os.listdir(os.path.join(root, &quot;masks&quot;)))) def __getitem__(self, idx): # load images and masks img_path = os.path.join(self.root, &quot;images&quot;, self.imgs[idx]) mask_path = os.path.join(self.root, &quot;masks&quot;, self.masks[idx]) img = Image.open(img_path).convert(&quot;RGB&quot;) # note that we haven't converted the mask to RGB, # because each color corresponds to a different instance # with 0 being background mask = Image.open(mask_path) mask = np.array(mask) # instances are encoded as different colors obj_ids = np.unique(mask) # first id is the background, so remove it obj_ids = obj_ids[1:] # split the color-encoded mask into a set # of binary masks masks = mask == obj_ids[:, None, None] # get bounding box coordinates for each mask num_objs = len(obj_ids) boxes = [] for i in range(num_objs): pos = np.where(masks[i]) xmin = np.min(pos[1]) xmax = np.max(pos[1]) ymin = np.min(pos[0]) ymax = np.max(pos[0]) boxes.append([xmin, ymin, xmax, ymax]) boxes = torch.as_tensor(boxes, dtype=torch.float32) # there is only one class labels = torch.ones((num_objs,), dtype=torch.int64) masks = torch.as_tensor(masks, dtype=torch.uint8) image_id = torch.tensor([idx]) area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0]) # suppose all instances are not crowd iscrowd = torch.zeros((num_objs,), dtype=torch.int64) target = {} target[&quot;boxes&quot;] = boxes target[&quot;labels&quot;] = labels target[&quot;masks&quot;] = masks target[&quot;image_id&quot;] = image_id target[&quot;area&quot;] = area target[&quot;iscrowd&quot;] = iscrowd if self.transforms is not None: img, target = self.transforms(img, target) return img, target def __len__(self): return len(self.imgs) def get_model_instance_segmentation(num_classes): # load an instance segmentation model pre-trained pre-trained on COCO model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True) # get number of input features for the classifier in_features = model.roi_heads.box_predictor.cls_score.in_features # replace the pre-trained head with a new one model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes) # now get the number of input features for the mask classifier in_features_mask = model.roi_heads.mask_predictor.conv5_mask.in_channels hidden_layer = 256 # and replace the mask predictor with a new one model.roi_heads.mask_predictor = MaskRCNNPredictor(in_features_mask, hidden_layer, num_classes) return model def get_transform(train): transforms = [] transforms.append(T.ToTensor()) if train: transforms.append(T.RandomHorizontalFlip(0.5)) return T.Compose(transforms) def main(): # train on the CPU device = torch.device('cpu') #device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') # our dataset has two classes only - background and person num_classes = 2 # use our dataset and defined transformations dataset = CracksDataset('datasets', get_transform(train=True)) dataset_test = CracksDataset('datasets', get_transform(train=False)) # split the dataset in train and test set indices = torch.randperm(len(dataset)).tolist() dataset = torch.utils.data.Subset(dataset, indices[:-50]) dataset_test = torch.utils.data.Subset(dataset_test, indices[-50:]) # define training and validation data loaders data_loader = torch.utils.data.DataLoader( dataset, batch_size=2, shuffle=True, num_workers=1, collate_fn=utils.collate_fn) data_loader_test = torch.utils.data.DataLoader( dataset_test, batch_size=2, shuffle=False, num_workers=1, collate_fn=utils.collate_fn) # get the model using our helper function model = get_model_instance_segmentation(num_classes) # move model to the right device model.to(device) # construct an optimizer params = [p for p in model.parameters() if p.requires_grad] optimizer = torch.optim.SGD(params, lr=0.005, momentum=0.9, weight_decay=0.0005) # and a learning rate scheduler lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.1) # let's train it for 10 epochs num_epochs = 10 for epoch in range(num_epochs): # train for one epoch, printing every 10 iterations train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq=10) # update the learning rate lr_scheduler.step() # evaluate on the test dataset evaluate(model, data_loader_test, device=device) print(&quot;That's it!&quot;) if __name__ == &quot;__main__&quot;: main()
I have done exactly the same for a project and I believe the issue comes from detection that will have a width or a height of 1 pixel only. In this case, xmin = xmax or ymin = ymax which creates the issue. I just added 1 to my xmax and ymax to ensure boxes are never empty. boxes.append([xmin, ymin, xmax+1, ymax+1])
https://stackoverflow.com/questions/71249434/
How to use yolov5 api with flask offline?
I was able to run the Flask app with yolov5 on a PC with an internet connection. I followed the steps mentioned in yolov5 docs and used this file: yolov5/utils/flask_rest_api/restapi.py, But I need to achieve the same offline(On a particular PC). Now the issue is, when I am using the following: model = torch.hub.load(&quot;ultralytics/yolov5&quot;, &quot;yolov5&quot;, force_reload=True) It tries to download model from internet. And throws an error. Urllib.error.URLError: &lt;urlopen error [Errno - 2] name or service not known&gt; How to get the same results offline. Thanks in advance.
If you want to run detection offline, you need to have the model already downloaded. So, download the model (for example yolov5s.pt) from https://github.com/ultralytics/yolov5/releases and store it for example to the yolov5/models. After that, replace # model = torch.hub.load(&quot;ultralytics/yolov5&quot;, &quot;yolov5s&quot;, force_reload=True) # force_reload to recache with model = torch.hub.load(r'C:\Users\Milan\Projects\yolov5', 'custom', path=r'C:\Users\Milan\Projects\yolov5\models\yolov5s.pt', source='local') With this line, you can run detection also offline. Note: When you start the app for the first time with the updated torch.hub.load, it will download the model if not present (so you do not need to download it from https://github.com/ultralytics/yolov5/releases).
https://stackoverflow.com/questions/71251177/
How can I get the gradients of two losses in pytorch
I am trying to get the gradients of two losses in the following code snippet but all I get is None (AttributeError: ‘NoneType’ object has no attribute ‘data’) img = img.to(device) #img.requires_grad = True input = model(img) input_prediction = input.max(1, keepdim=True)[1] btarget = torch.tensor(2).unsqueeze(0).to(device) x_prime.requires_grad = True x_prime_output = model(x_prime) x_prime_pred = x_prime_output.max(1, keepdim=True)[1] l_target_loss = F.nll_loss(x_prime_output, btarget) # model.zero_grad() l_target_loss.retain_grad() l_target_loss.backward(retain_graph = True) target_grad = l_target_loss.grad.data l_argmax_loss = F.nll_loss(x_prime_output, input_prediction.squeeze(0)) l_argmax_loss.retain_grad() l_argmax_loss.backward() l_argmax_grad = l_argmax_loss.grad.data when I tried getting target_grad and l_argmax_grad, I get None. Edit: I am actually trying to get the gradient of the l_target_loss w.r.t to the input x and the gradient of the l_argmax_loss w.r.t to the input x as well
You need to retain the gradient on that tensor with retain_grad, by default it is not cached in memory: &gt;&gt;&gt; l_target_loss.retain_grad() &gt;&gt;&gt; l_target_loss.backward(retain_graph=True)
https://stackoverflow.com/questions/71252125/
EarlyStopping callback in PyTorch Lightning problem
I try to train Neural Network model in PyTorch Lightning and training fails on validation step where it executes EarlyStopping callback. The relevant part of the model is below. See, in particular, validation_step which must log the metrics necessary for Early stopping. class DialogActsLightningModel(pl.LightningModule): def __init__(self, config): super().__init__() self.config = config self.model = ContextAwareDAC( model_name=self.config['model_name'], hidden_size=self.config['hidden_size'], num_classes=self.config['num_classes'], device=self.config['device'] ) self.tokenizer = AutoTokenizer.from_pretrained(config['model_name']) def forward(self, batch): logits = self.model(batch) return logits def validation_step(self, batch, batch_idx): input_ids, attention_mask, targets = batch['input_ids'], batch['attention_mask'], batch['label'].squeeze() logits = self(batch) loss = F.cross_entropy(logits, targets) acc = accuracy_score(targets.cpu(), logits.argmax(dim=1).cpu()) f1 = f1_score(targets.cpu(), logits.argmax(dim=1).cpu(), average=self.config['average']) precision = precision_score(targets.cpu(), logits.argmax(dim=1).cpu(), average=self.config['average']) recall = recall_score(targets.cpu(), logits.argmax(dim=1).cpu(), average=self.config['average']) return {&quot;val_loss&quot;: loss, &quot;val_accuracy&quot;: torch.tensor([acc]), &quot;val_f1&quot;: torch.tensor([f1]), &quot;val_precision&quot;: torch.tensor([precision]), &quot;val_recall&quot;: torch.tensor([recall])} def validation_epoch_end(self, outputs): avg_loss = torch.stack([x['val_loss'] for x in outputs]).mean() avg_acc = torch.stack([x['val_accuracy'] for x in outputs]).mean() avg_f1 = torch.stack([x['val_f1'] for x in outputs]).mean() avg_precision = torch.stack([x['val_precision'] for x in outputs]).mean() avg_recall = torch.stack([x['val_recall'] for x in outputs]).mean() wandb.log({&quot;val_loss&quot;: avg_loss, &quot;val_accuracy&quot;: avg_acc, &quot;val_f1&quot;: avg_f1, &quot;val_precision&quot;: avg_precision, &quot;val_recall&quot;: avg_recall}) return {&quot;val_loss&quot;: avg_loss, &quot;val_accuracy&quot;: avg_acc, &quot;val_f1&quot;: avg_f1, &quot;val_precision&quot;: avg_precision, &quot;val_recall&quot;: avg_recall} When I run training in the following way: from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.loggers import WandbLogger import pytorch_lightning as pl import os from trainer import DialogActsLightningModel import wandb wandb.init() logger = WandbLogger( name=&quot;model_name&quot;, entity='myname', save_dir=config[&quot;save_dir&quot;], project=config[&quot;project&quot;], log_model=True, ) early_stopping = EarlyStopping( monitor=&quot;val_accuracy&quot;, min_delta=0.001, patience=5, ) model = DialogActsLightningModel(config=config) trainer = pl.Trainer( logger=logger, gpus=[0], checkpoint_callback=True, callbacks=[early_stopping], default_root_dir=MODELS_DIRECTORY, max_epochs=config[&quot;epochs&quot;], precision=config[&quot;precision&quot;], limit_train_batches=10, # run for only 10 batches, debug mode limit_test_batches=10, limit_val_batches=10 ) trainer.fit(model) I've got an error, but the model should have calculated and logged the metric &quot;val_accuracy&quot; during validation step. Epoch 0: 100% 20/20 [00:28&lt;00:00, 1.41s/it, loss=1.95] /opt/conda/lib/python3.9/site-packages/pytorch_lightning/callbacks/early_stopping.py in _validate_condition_metric(self, logs) 149 if monitor_val is None: 150 if self.strict: --&gt; 151 raise RuntimeError(error_msg) 152 if self.verbose &gt; 0: 153 rank_zero_warn(error_msg, RuntimeWarning) RuntimeError: Early stopping conditioned on metric `val_accuracy` which is not available. Pass in or modify your `EarlyStopping` callback to use any of the following: `` What I am doing wrong? How to fix it?
if you use pytorch-lightning latest version you should want to log the val_accuracy or val_loss while you calling early stopping or similar functions. for more please check out the code below.i think this will definitely helpful for you... def validation_step(self, batch, batch_idx): input_ids, attention_mask, targets = batch['input_ids'], batch['attention_mask'], batch['label'].squeeze() logits = self(batch) loss = F.cross_entropy(logits, targets) acc = accuracy_score(targets.cpu(), logits.argmax(dim=1).cpu()) f1 = f1_score(targets.cpu(), logits.argmax(dim=1).cpu(), average=self.config['average']) precision = precision_score(targets.cpu(), logits.argmax(dim=1).cpu(), average=self.config['average']) recall = recall_score(targets.cpu(), logits.argmax(dim=1).cpu(), average=self.config['average']) ########################################################################## ########################################################################## self.log(&quot;val_accuracy&quot;, torch.tensor([acc]) # try this line ########################################################################## ########################################################################## return {&quot;val_loss&quot;: loss, &quot;val_accuracy&quot;: torch.tensor([acc]), &quot;val_f1&quot;: torch.tensor([f1]), &quot;val_precision&quot;: torch.tensor([precision]), &quot;val_recall&quot;: torch.tensor([recall])} If This Post is Useful Please Up vote
https://stackoverflow.com/questions/71252296/
Applying a 2D function to a 4D tensor PyTorch
I got a 2D function that takes a matrix - 2D tensor with shape (28, 28) and I got a tensor, lets say (64, 10, 28, 28) - it's a tensor that contains a batch of 64 images that passed through a (10 kernels) conv2d layer. Now, I want to activate on the last two dimentions of the tensor, the (28,28) bit, a 2D function. Now I did that in a very inefficient way: def activation_func(input): for batch_idx in range(input.shape[0]): for channel_inx in range(input.shape[1]): input[batch_idx][channel_inx] = 2D_function(input[batch_idx][channel_inx]) return input which is highly inefficient as I noticed. is there any way of doing this efficiently? I can write the entire code If necessary EDIT: def 2D_function(input): global indices # yes I know, I will remove this global stuff later # indices = [(i, j) for i in range(1, 28, 4) for j in range(1, 28, 4)] for x, y in indices: relu_decision = relu(input[x, y]) # standard relu - relu(x)=(x&gt;1)*x if not relu_decision: # zero out the patch input[x - 1: x + 3, y - 1: y + 3] = 0 return input
In such cases, I use a Kronecker product trick: import torch torch.set_printoptions(linewidth=200) # you can better see how the mask is shaped # simulating an input input = torch.rand(1, 1, 28, 28) - 0.5 ids = torch.meshgrid((torch.arange(1, 28, 4), torch.arange(1, 28, 4))) # note that relu(x) = (x &gt; 0.) * x, so adjust it to your needs relus = torch.nn.functional.relu(input[(slice(None), slice(None), *ids)]).to(bool) A = torch.ones(4, 4) # generate a block matrix with ones in positions where blocks are set to 0 in correspondence of relus = 0 mask = torch.kron(relus, A) print(mask.shape) output = input * mask print(mask[0, 0]) print(output[0, 0])
https://stackoverflow.com/questions/71253711/
Pytorch error - RuntimeError: "nll_loss_forward_reduce_cuda_kernel_2d_index" not implemented for 'Float'
I am getting an error very similar to this. My error as below: ----------------------------------------------------------------------- RuntimeError Traceback (most recent call last) &lt;ipython-input-85-5a223a19e3f5&gt; in &lt;module&gt; 8 save_run = 'Yes', 9 return_progress_dict = 'Yes', ---&gt; 10 hide_text = 'No') &lt;ipython-input-84-023bc49b2138&gt; in train_CNN(model, optimizer, train_dataloader, epochs, run_number, val_dataloader, save_run, return_progress_dict, hide_text) 63 print(labels[0].dtype) 64 print(&quot;------------&quot;) ---&gt; 65 loss = F.cross_entropy(probs, labels) 66 67 total_loss += loss.item() /usr/local/anaconda/lib/python3.6/site-packages/torch/nn/functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction, label_smoothing) 2844 if size_average is not None or reduce is not None: 2845 reduction = _Reduction.legacy_get_string(size_average, reduce) -&gt; 2846 return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing) 2847 2848 RuntimeError: &quot;nll_loss_forward_reduce_cuda_kernel_2d_index&quot; not implemented for 'Float' I am making sure that both my labels and probs have same datatype - float probs[0].dtype: torch.float32 probs[0]: tensor([-0.8244, -0.5771], device='cuda:0', grad_fn=&lt;SelectBackward0&gt;) probs[0].dtype: torch.float32 ------------ labels: tensor([0., 0., 0., 0., 0., 1., 0., 1., 0., 1., 1., 0., 0., 1., 1., 1., 1., 1., 0., 0., 1., 1., 0., 1., 0., 0., 0., 1., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 1., 1., 0., 1., 1., 1., 1., 1., 1., 0., 1., 0., 1., 1., 1., 0., 0., 1., 0., 1., 1., 1., 1., 0., 0., 1., 0., 1., 0., 1., 0., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 0., 1., 0., 1., 0., 0., 1., 0., 1., 1., 1., 0., 0., 1., 1., 0., 0., 0., 0., 0., 1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 0., 0., 0., 0., 0., 1., 0., 1., 1., 1., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 1., 1., 1., 1., 1., 1., 0., 1., 1., 0., 0., 1., 0., 0., 0., 1., 1.], device='cuda:0') labels.dtype: torch.float32 labels[0].dtype: torch.float32 ------------ My function is as below def train_CNN(model, optimizer, train_dataloader, epochs, run_number, val_dataloader=None, save_run=None, return_progress_dict = None, hide_text = None): # Tracking lowest validation loss lowest_val_loss = float('inf') if return_progress_dict == 'Yes': progress_dict = {run_number: {'Epoch':[], 'Avg_Training_Loss':[], 'Validation_Loss':[], 'Validation_Accuracy':[]} } # Start training loop if hide_text != &quot;Yes&quot;: print(&quot;Start training...\n&quot;) print(f&quot;{'Epoch':^7} | {'Train Loss':^12} | {'Val Loss':^10} | {'Val Acc':^9} | {'Elapsed':^9}&quot;) print(&quot;-&quot;*60) for epoch_i in range(epochs): # ======================================= # Training # ======================================= # Tracking time and loss t0_epoch = time.time() total_loss = 0 # Put the model into the training mode model.train() for step, batch in enumerate(train_dataloader): # Load batch to CPU data, labels = tuple(t.to(device) for t in batch) #labels = labels.type(torch.LongTensor) #23Feb2022 casting to long as per https://stackoverflow.com/questions/69742930/runtimeerror-nll-loss-forward-reduce-cuda-kernel-2d-index-not-implemented-for #labels.to(device) # Zero out any previously calculated gradients optimizer.zero_grad() # Perform a forward pass. This will return logits. probs = model(data) # Compute loss and accumulate the loss values print(&quot;------------&quot;) print (&quot;probs[0].dtype:&quot;) print(probs[0].dtype) print (&quot;probs[0]:&quot;) print (probs[0]) #print (probs) probs=probs.type(torch.cuda.FloatTensor) #probs=probs.type(torch.cuda.LongTensor) print (&quot;probs[0].dtype:&quot;) print(probs[0].dtype) print(&quot;------------&quot;) labels = labels.type(torch.cuda.FloatTensor) #labels=labels.type(torch.cuda.LongTensor) #labels = labels.type(torch.cuda.DoubleTensor) #x_cuda = Variable(x, requires_grad=True).cuda() print(&quot;labels:&quot;) print (labels) print(&quot;labels.dtype:&quot;) print (labels.dtype) print(&quot;labels[0].dtype:&quot;) print(labels[0].dtype) print(&quot;------------&quot;) loss = F.cross_entropy(probs, labels) total_loss += loss.item() # Perform a backward pass to calculate gradients loss.backward() # Update parameters optimizer.step() any suggestions? I will try to give a reproducible example soon ##########################update 1-------------------- I tried labels=labels.type(torch.cuda.LongTensor). Probs are still float32 and still getting the error RuntimeError: &quot;nll_loss_forward_reduce_cuda_kernel_2d_index&quot; not implemented for 'Int'
labels should be of type torch.long and not torch.float32. I think you just commented out the line that does this casting in your code.
https://stackoverflow.com/questions/71254428/
Anaconda Xgboost unable to find GPU
It seems that Anaconda is unable recognise my GPU, GPU is RTX2070 (Driver version 510.47.03), system Ubuntu 20.04, cudatoolkit 11.3.1, cudnn 8.2.1, XGboost 1.5.2 via pip install. When I run XGboost with GPU enable it shows: XGBoostError: [01:24:12] ../src/gbm/gbtree.cc:531: Check failed: common::AllVisibleGPUs() &gt;= 1 (0 vs. 1) : No visible GPU is found for XGBoost. I also used GPUtil to check the visible GPU, it is showing 0 GPU. Below is the output from nvidia-smi Can anyone help? how come the GPU in the system is no visible to any package in anaconda? (Pytorch, XGBoost etc.)
Appeared to be a driver issue, tried the same code in another computer with two RTX 3090 and got no issue
https://stackoverflow.com/questions/71254462/
writing a custom dataset to pytorch
I am having data of numpy arrays with shape (400, 46, 55, 46) here 400 are the samples and 46,55,46 is the image.350 samples for training and remaining 50 for validation np.max(data[1]), np.min(data[1]), len(data[1]) Output: (2941.0, -43.0, 46) Now i want to load the data into pytorch model for that i need to write a custom dataloader as i am new to pytorch i am finding hard to wrie can someone help
You can use a combination of torch.utils.data.TensorData and torch.utils.data.random_split to construct the two datasets and wrap them with torch.utils.data.DataLoader: &gt;&gt;&gt; data = np.random.rand(400, 46, 55, 46) # Datasets initialization &gt;&gt;&gt; ds = TensorDataset(torch.from_numpy(data)) &gt;&gt;&gt; train_ds, valid_ds = random_split(ds, (350, 50)) # Dataloader wrappers &gt;&gt;&gt; train_dl, valid_dl = DataLoader(train_ds), DataLoader(valid_ds)
https://stackoverflow.com/questions/71258858/
AttributeError: 'list' object has no attribute 'view' while training network
I have a pytorch which i am trying to train but i am getting this error AttributeError: 'list' object has no attribute 'view'. Dont know why i am getting this. sample data data = np.random.rand(400, 46, 55, 46) ds = TensorDataset(torch.from_numpy(data)) train_ds, valid_ds = random_split(ds, (350, 50)) train_dl, valid_dl = DataLoader(train_ds), DataLoader(valid_ds) model class AutoEncoder(pl.LightningModule): def __init__(self): super(AutoEncoder, self).__init__() self.encoder = nn.Sequential( nn.Linear(46*55*46, 400), nn.Tanh()) self.decoder = nn.Sequential( nn.Linear(400, 46*55*46), nn.Sigmoid()) def forward(self, x): x = self.encoder(x) x = self.decoder(x) return x def configure_optimizers(self): optimizer = torch.optim.Adam(self.parameters(), lr=1e-3) return optimizer def training_step(self, train_batch, batch_idx): x = train_batch x = x.view(x.size(0), -1) z = self.encoder(x) x_hat = self.decoder(z) loss = F.mse_loss(x_hat, x) self.log('train_loss', loss) return loss def validation_step(self, val_batch, batch_idx): x = val_batch x = x.view(x.size(0), -1) z = self.encoder(x) x_hat = self.decoder(z) loss = F.mse_loss(x_hat, x) self.log('val_loss', loss) model = AutoEncoder() Error AttributeError Traceback (most recent call last) &lt;ipython-input-18-11e725b78922&gt; in &lt;module&gt;() 1 trainer = pl.Trainer() ----&gt; 2 trainer.fit(model, train_dl, valid_dl) 16 frames /usr/local/lib/python3.7/dist-packages/pytorch_lightning/trainer/trainer.py in fit(self, model, train_dataloaders, val_dataloaders, datamodule, train_dataloader, ckpt_path) 739 train_dataloaders = train_dataloader 740 self._call_and_handle_interrupt( --&gt; 741 self._fit_impl, model, train_dataloaders, val_dataloaders, datamodule, ckpt_path 742 ) 743 /usr/local/lib/python3.7/dist-packages/pytorch_lightning/trainer/trainer.py in _call_and_handle_interrupt(self, trainer_fn, *args, **kwargs) 683 &quot;&quot;&quot; 684 try: --&gt; 685 return trainer_fn(*args, **kwargs) 686 # TODO: treat KeyboardInterrupt as BaseException (delete the code below) in v1.7 687 except KeyboardInterrupt as exception: /usr/local/lib/python3.7/dist-packages/pytorch_lightning/trainer/trainer.py in _fit_impl(self, model, train_dataloaders, val_dataloaders, datamodule, ckpt_path) 775 # TODO: ckpt_path only in v1.7 776 ckpt_path = ckpt_path or self.resume_from_checkpoint --&gt; 777 self._run(model, ckpt_path=ckpt_path) 778 779 assert self.state.stopped /usr/local/lib/python3.7/dist-packages/pytorch_lightning/trainer/trainer.py in _run(self, model, ckpt_path) 1197 1198 # dispatch `start_training` or `start_evaluating` or `start_predicting` -&gt; 1199 self._dispatch() 1200 1201 # plugin will finalized fitting (e.g. ddp_spawn will load trained model) /usr/local/lib/python3.7/dist-packages/pytorch_lightning/trainer/trainer.py in _dispatch(self) 1277 self.training_type_plugin.start_predicting(self) 1278 else: -&gt; 1279 self.training_type_plugin.start_training(self) 1280 1281 def run_stage(self): /usr/local/lib/python3.7/dist-packages/pytorch_lightning/plugins/training_type/training_type_plugin.py in start_training(self, trainer) 200 def start_training(self, trainer: &quot;pl.Trainer&quot;) -&gt; None: 201 # double dispatch to initiate the training loop --&gt; 202 self._results = trainer.run_stage() 203 204 def start_evaluating(self, trainer: &quot;pl.Trainer&quot;) -&gt; None: /usr/local/lib/python3.7/dist-packages/pytorch_lightning/trainer/trainer.py in run_stage(self) 1287 if self.predicting: 1288 return self._run_predict() -&gt; 1289 return self._run_train() 1290 1291 def _pre_training_routine(self): /usr/local/lib/python3.7/dist-packages/pytorch_lightning/trainer/trainer.py in _run_train(self) 1309 self.progress_bar_callback.disable() 1310 -&gt; 1311 self._run_sanity_check(self.lightning_module) 1312 1313 # enable train mode /usr/local/lib/python3.7/dist-packages/pytorch_lightning/trainer/trainer.py in _run_sanity_check(self, ref_model) 1373 # run eval step 1374 with torch.no_grad(): -&gt; 1375 self._evaluation_loop.run() 1376 1377 self.call_hook(&quot;on_sanity_check_end&quot;) /usr/local/lib/python3.7/dist-packages/pytorch_lightning/loops/base.py in run(self, *args, **kwargs) 143 try: 144 self.on_advance_start(*args, **kwargs) --&gt; 145 self.advance(*args, **kwargs) 146 self.on_advance_end() 147 self.restarting = False /usr/local/lib/python3.7/dist-packages/pytorch_lightning/loops/dataloader/evaluation_loop.py in advance(self, *args, **kwargs) 108 dl_max_batches = self._max_batches[dataloader_idx] 109 --&gt; 110 dl_outputs = self.epoch_loop.run(dataloader, dataloader_idx, dl_max_batches, self.num_dataloaders) 111 112 # store batch level output per dataloader /usr/local/lib/python3.7/dist-packages/pytorch_lightning/loops/base.py in run(self, *args, **kwargs) 143 try: 144 self.on_advance_start(*args, **kwargs) --&gt; 145 self.advance(*args, **kwargs) 146 self.on_advance_end() 147 self.restarting = False /usr/local/lib/python3.7/dist-packages/pytorch_lightning/loops/epoch/evaluation_epoch_loop.py in advance(self, data_fetcher, dataloader_idx, dl_max_batches, num_dataloaders) 120 # lightning module methods 121 with self.trainer.profiler.profile(&quot;evaluation_step_and_end&quot;): --&gt; 122 output = self._evaluation_step(batch, batch_idx, dataloader_idx) 123 output = self._evaluation_step_end(output) 124 /usr/local/lib/python3.7/dist-packages/pytorch_lightning/loops/epoch/evaluation_epoch_loop.py in _evaluation_step(self, batch, batch_idx, dataloader_idx) 215 self.trainer.lightning_module._current_fx_name = &quot;validation_step&quot; 216 with self.trainer.profiler.profile(&quot;validation_step&quot;): --&gt; 217 output = self.trainer.accelerator.validation_step(step_kwargs) 218 219 return output /usr/local/lib/python3.7/dist-packages/pytorch_lightning/accelerators/accelerator.py in validation_step(self, step_kwargs) 237 &quot;&quot;&quot; 238 with self.precision_plugin.val_step_context(): --&gt; 239 return self.training_type_plugin.validation_step(*step_kwargs.values()) 240 241 def test_step(self, step_kwargs: Dict[str, Union[Any, int]]) -&gt; Optional[STEP_OUTPUT]: /usr/local/lib/python3.7/dist-packages/pytorch_lightning/plugins/training_type/training_type_plugin.py in validation_step(self, *args, **kwargs) 217 218 def validation_step(self, *args, **kwargs): --&gt; 219 return self.model.validation_step(*args, **kwargs) 220 221 def test_step(self, *args, **kwargs): &lt;ipython-input-12-16d602e3e66b&gt; in validation_step(self, val_batch, batch_idx) 29 def validation_step(self, val_batch, batch_idx): 30 x = val_batch ---&gt; 31 x = x.view(x.size(0), -1) 32 z = self.encoder(x) 33 x_hat = self.decoder(z) AttributeError: 'list' object has no attribute 'view'
As indicated by the error log, it is in this line: 29 def validation_step(self, val_batch, batch_idx): 30 x = val_batch 31 x = x.view(x.size(0), -1) # here is your problem x or vali_batch is a list object, and a list does not have an attribute view() since it is not a tensor. If you want to convert a list to a tensor, you can simply use: x = torch.tensor(val_batch) Or you can convert val_batch to a tensor earlier in your code during loading and processing the data.
https://stackoverflow.com/questions/71260127/
RuntimeError: DataLoader worker exited unexpectedly
I am new to PyTorch and Machine Learning so I try to follow the tutorial from here: https://medium.com/@nutanbhogendrasharma/pytorch-convolutional-neural-network-with-mnist-dataset-4e8a4265e118 By copying the code step by step I got the following error for no reason. I tried the program on another computer and it gives syntax error. However, my IDE didn't warn my anything about syntax. I am really confused how I can fix the issue. Any help is appreciated. RuntimeError: DataLoader worker exited unexpectedly Here is the code. import torch from torchvision import datasets from torchvision.transforms import ToTensor import torch.nn as nn import matplotlib.pyplot as plt from torch.utils.data import DataLoader from torch import optim from torch.autograd import Variable train_data = datasets.MNIST( root='data', train=True, transform=ToTensor(), download=True, ) test_data = datasets.MNIST( root='data', train=False, transform=ToTensor() ) print(train_data) print(test_data) print(train_data.data.size()) print(train_data.targets.size()) plt.imshow(train_data.data[0], cmap='gray') plt.title('%i' % train_data.targets[0]) plt.show() figure = plt.figure(figsize=(10, 8)) cols, rows = 5, 5 for i in range(1, cols * rows + 1): sample_idx = torch.randint(len(train_data), size=(1,)).item() img, label = train_data[sample_idx] figure.add_subplot(rows, cols, i) plt.title(label) plt.axis(&quot;off&quot;) plt.imshow(img.squeeze(), cmap=&quot;gray&quot;) plt.show() loaders = { 'train': DataLoader(train_data, batch_size=100, shuffle=True, num_workers=1), 'test': DataLoader(test_data, batch_size=100, shuffle=True, num_workers=1), } class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Sequential( nn.Conv2d( in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=2, ), nn.ReLU(), nn.MaxPool2d(kernel_size=2), ) self.conv2 = nn.Sequential( nn.Conv2d(16, 32, 5, 1, 2), nn.ReLU(), nn.MaxPool2d(2), ) # fully connected layer, output 10 classes self.out = nn.Linear(32 * 7 * 7, 10) def forward(self, x): x = self.conv1(x) x = self.conv2(x) # flatten the output of conv2 to (batch_size, 32 * 7 * 7) x = x.view(x.size(0), -1) output = self.out(x) return output, x # return x for visualization cnn = CNN() print(cnn) loss_func = nn.CrossEntropyLoss() print(loss_func) optimizer = optim.Adam(cnn.parameters(), lr=0.01) print(optimizer) num_epochs = 10 def train(num_epochs, cnn, loaders): cnn.train() # Train the model total_step = len(loaders['train']) for epoch in range(num_epochs): for i, (images, labels) in enumerate(loaders['train']): # gives batch data, normalize x when iterate train_loader b_x = Variable(images) # batch x b_y = Variable(labels) # batch y output = cnn(b_x)[0] loss = loss_func(output, b_y) # clear gradients for this training step optimizer.zero_grad() # backpropagation, compute gradients loss.backward() # apply gradients optimizer.step() if (i + 1) % 100 == 0: print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' .format(epoch + 1, num_epochs, i + 1, total_step, loss.item())) pass pass pass train(num_epochs, cnn, loaders) def evalFunc(): # Test the model cnn.eval() with torch.no_grad(): correct = 0 total = 0 for images, labels in loaders['test']: test_output, last_layer = cnn(images) pred_y = torch.max(test_output, 1)[1].data.squeeze() accuracy = (pred_y == labels).sum().item() / float(labels.size(0)) pass print('Test Accuracy of the model on the 10000 test images: %.2f' % accuracy) pass evalFunc() sample = next(iter(loaders['test'])) imgs, lbls = sample actual_number = lbls[:10].numpy() test_output, last_layer = cnn(imgs[:10]) pred_y = torch.max(test_output, 1)[1].data.numpy().squeeze() print(f'Prediction number: {pred_y}') print(f'Actual number: {actual_number}')
If you are working on jupyter notebook. The problem is more likely to be num_worker. You should set num_worker=0. You can find here some solutions to follow. Because unfortunately, jupyter notebook has some issues with running multiprocessing.
https://stackoverflow.com/questions/71261347/
SSLCertVerificationError when downloading pytorch datasets via torchvision
I am having trouble downloading the CIFAR-10 dataset from pytorch. Mostly it seems like some SSL error which I don't really know how to interpret. I have also tried changing the root to various other folders but none of them works. I was wondering whether it is a permission type setting on my end but I am inexperienced. Would appreciate some help to fix this! The code executed is here: trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=1) The error is reproduced here: --------------------------------------------------------------------------- SSLCertVerificationError Traceback (most recent call last) File C:\ProgramData\Miniconda3\envs\pDL\lib\urllib\request.py:1354, in AbstractHTTPHandler.do_open(self, http_class, req, **http_conn_args) 1353 try: -&gt; 1354 h.request(req.get_method(), req.selector, req.data, headers, 1355 encode_chunked=req.has_header('Transfer-encoding')) 1356 except OSError as err: # timeout error File C:\ProgramData\Miniconda3\envs\pDL\lib\http\client.py:1256, in HTTPConnection.request(self, method, url, body, headers, encode_chunked) 1255 &quot;&quot;&quot;Send a complete request to the server.&quot;&quot;&quot; -&gt; 1256 self._send_request(method, url, body, headers, encode_chunked) File C:\ProgramData\Miniconda3\envs\pDL\lib\http\client.py:1302, in HTTPConnection._send_request(self, method, url, body, headers, encode_chunked) 1301 body = _encode(body, 'body') -&gt; 1302 self.endheaders(body, encode_chunked=encode_chunked) File C:\ProgramData\Miniconda3\envs\pDL\lib\http\client.py:1251, in HTTPConnection.endheaders(self, message_body, encode_chunked) 1250 raise CannotSendHeader() -&gt; 1251 self._send_output(message_body, encode_chunked=encode_chunked) File C:\ProgramData\Miniconda3\envs\pDL\lib\http\client.py:1011, in HTTPConnection._send_output(self, message_body, encode_chunked) 1010 del self._buffer[:] -&gt; 1011 self.send(msg) 1013 if message_body is not None: 1014 1015 # create a consistent interface to message_body File C:\ProgramData\Miniconda3\envs\pDL\lib\http\client.py:951, in HTTPConnection.send(self, data) 950 if self.auto_open: --&gt; 951 self.connect() 952 else: File C:\ProgramData\Miniconda3\envs\pDL\lib\http\client.py:1425, in HTTPSConnection.connect(self) 1423 server_hostname = self.host -&gt; 1425 self.sock = self._context.wrap_socket(self.sock, 1426 server_hostname=server_hostname) File C:\ProgramData\Miniconda3\envs\pDL\lib\ssl.py:500, in SSLContext.wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, session) 494 def wrap_socket(self, sock, server_side=False, 495 do_handshake_on_connect=True, 496 suppress_ragged_eofs=True, 497 server_hostname=None, session=None): 498 # SSLSocket class handles server_hostname encoding before it calls 499 # ctx._wrap_socket() --&gt; 500 return self.sslsocket_class._create( 501 sock=sock, 502 server_side=server_side, 503 do_handshake_on_connect=do_handshake_on_connect, 504 suppress_ragged_eofs=suppress_ragged_eofs, 505 server_hostname=server_hostname, 506 context=self, 507 session=session 508 ) File C:\ProgramData\Miniconda3\envs\pDL\lib\ssl.py:1040, in SSLSocket._create(cls, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, context, session) 1039 raise ValueError(&quot;do_handshake_on_connect should not be specified for non-blocking sockets&quot;) -&gt; 1040 self.do_handshake() 1041 except (OSError, ValueError): File C:\ProgramData\Miniconda3\envs\pDL\lib\ssl.py:1309, in SSLSocket.do_handshake(self, block) 1308 self.settimeout(None) -&gt; 1309 self._sslobj.do_handshake() 1310 finally: SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1131) During handling of the above exception, another exception occurred: URLError Traceback (most recent call last) Input In [8], in &lt;module&gt; ----&gt; 1 trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) 2 trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=1) File C:\ProgramData\Miniconda3\envs\pDL\lib\site-packages\torchvision\datasets\cifar.py:66, in CIFAR10.__init__(self, root, train, transform, target_transform, download) 63 self.train = train # training set or test set 65 if download: ---&gt; 66 self.download() 68 if not self._check_integrity(): 69 raise RuntimeError('Dataset not found or corrupted.' + 70 ' You can use download=True to download it') File C:\ProgramData\Miniconda3\envs\pDL\lib\site-packages\torchvision\datasets\cifar.py:144, in CIFAR10.download(self) 142 print('Files already downloaded and verified') 143 return --&gt; 144 download_and_extract_archive(self.url, self.root, filename=self.filename, md5=self.tgz_md5) File C:\ProgramData\Miniconda3\envs\pDL\lib\site-packages\torchvision\datasets\utils.py:427, in download_and_extract_archive(url, download_root, extract_root, filename, md5, remove_finished) 424 if not filename: 425 filename = os.path.basename(url) --&gt; 427 download_url(url, download_root, filename, md5) 429 archive = os.path.join(download_root, filename) 430 print(&quot;Extracting {} to {}&quot;.format(archive, extract_root)) File C:\ProgramData\Miniconda3\envs\pDL\lib\site-packages\torchvision\datasets\utils.py:130, in download_url(url, root, filename, md5, max_redirect_hops) 127 _download_file_from_remote_location(fpath, url) 128 else: 129 # expand redirect chain if needed --&gt; 130 url = _get_redirect_url(url, max_hops=max_redirect_hops) 132 # check if file is located on Google Drive 133 file_id = _get_google_drive_file_id(url) File C:\ProgramData\Miniconda3\envs\pDL\lib\site-packages\torchvision\datasets\utils.py:78, in _get_redirect_url(url, max_hops) 75 headers = {&quot;Method&quot;: &quot;HEAD&quot;, &quot;User-Agent&quot;: USER_AGENT} 77 for _ in range(max_hops + 1): ---&gt; 78 with urllib.request.urlopen(urllib.request.Request(url, headers=headers)) as response: 79 if response.url == url or response.url is None: 80 return url File C:\ProgramData\Miniconda3\envs\pDL\lib\urllib\request.py:222, in urlopen(url, data, timeout, cafile, capath, cadefault, context) 220 else: 221 opener = _opener --&gt; 222 return opener.open(url, data, timeout) File C:\ProgramData\Miniconda3\envs\pDL\lib\urllib\request.py:525, in OpenerDirector.open(self, fullurl, data, timeout) 522 req = meth(req) 524 sys.audit('urllib.Request', req.full_url, req.data, req.headers, req.get_method()) --&gt; 525 response = self._open(req, data) 527 # post-process response 528 meth_name = protocol+&quot;_response&quot; File C:\ProgramData\Miniconda3\envs\pDL\lib\urllib\request.py:542, in OpenerDirector._open(self, req, data) 539 return result 541 protocol = req.type --&gt; 542 result = self._call_chain(self.handle_open, protocol, protocol + 543 '_open', req) 544 if result: 545 return result File C:\ProgramData\Miniconda3\envs\pDL\lib\urllib\request.py:502, in OpenerDirector._call_chain(self, chain, kind, meth_name, *args) 500 for handler in handlers: 501 func = getattr(handler, meth_name) --&gt; 502 result = func(*args) 503 if result is not None: 504 return result File C:\ProgramData\Miniconda3\envs\pDL\lib\urllib\request.py:1397, in HTTPSHandler.https_open(self, req) 1396 def https_open(self, req): -&gt; 1397 return self.do_open(http.client.HTTPSConnection, req, 1398 context=self._context, check_hostname=self._check_hostname) File C:\ProgramData\Miniconda3\envs\pDL\lib\urllib\request.py:1357, in AbstractHTTPHandler.do_open(self, http_class, req, **http_conn_args) 1354 h.request(req.get_method(), req.selector, req.data, headers, 1355 encode_chunked=req.has_header('Transfer-encoding')) 1356 except OSError as err: # timeout error -&gt; 1357 raise URLError(err) 1358 r = h.getresponse() 1359 except: URLError: &lt;urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1131)&gt;
Turn off the ssl verification. import ssl ssl._create_default_https_context = ssl._create_unverified_context
https://stackoverflow.com/questions/71263622/
Split torch tensor dimension on two
If I have a torch tensor of shape [2, 12] is it possible to make from it a tensor of shape [3, 2, 4] in such a way that data will be split on chunks along the last dimension? View function does not change the order of data, but here I need change the order, that the new dimension will be the first, and the second dimension would not be changed Here is example image of how data must be split [2, 12] ............ ............ [3, 2, 4] ....|....|.... ....|....|.... torch.split function does exactly what I need in sense of shape, but it outputs not a tensor, but a tuple
I'm assuming you want to split the 12 sized dimension into the leading 3 and trailing 4 dimensions. You simply need to view and permute dimensions: X = torch.permute(X.view(2, 3, 4), (1, 0, 2))
https://stackoverflow.com/questions/71264858/
What is the difference between "modules" and "functionals" in PyTorch?
In PyTorch, we have torch.nn.funtional and torch.nn, and the classes/functions within the former are typically referred to as &quot;functions&quot; while the latter as &quot;modules&quot;. There seems to be a lot of overlap between the two, so I'm wondering what are each used for and what their differences are?
Here are the differences: torch.nn.functional is the base functional interface (in terms of programming paradigm) to apply PyTorch operators on torch.Tensor. torch.nn contains the wrapper nn.Module that provide a object-oriented interface to those operators. So indeed there is a complete overlap, modules are a different way of accessing the operators provided by those functions. Every single tensor operator in PyTorch is available in the form of a function and its wrapper class. For instance F.conv2d, F.relu, F.dropout, F.batch_norm etc... have corresponding modules nn.Conv2d, nn.ReLU, nn.Dropout, nn.BatchNorm2d, 2d, 3d.
https://stackoverflow.com/questions/71266858/
Getting image path through a torchvision dataloader using local images
I want to use a dataloader in my script. normaly the default function call would be like this. dataset = ImageFolderWithPaths( data_dir, transforms.Compose([ transforms.ColorJitter(0.1, 0.1, 0.1, 0.1), transforms.Resize((img_size_XY, img_size_XY)), transforms.ToTensor(), transforms.Normalize(_mean , _std) ]) ) dataloader = torch.utils.data.DataLoader( dataset, batch_size=batch_size, shuffle=False, num_workers=2 ) and to iterate through this dataloader i use for inputs, labels , paths in _dataloader: break now i need to collect the path for each image. i found in github this code: (https://gist.github.com/andrewjong/6b02ff237533b3b2c554701fb53d5c4d) class ImageFolderWithPaths(datasets.ImageFolder): &quot;&quot;&quot;Custom dataset that includes image file paths. Extends torchvision.datasets.ImageFolder &quot;&quot;&quot; # override the __getitem__ method. this is the method that dataloader calls def __getitem__(self, index): # this is what ImageFolder normally returns original_tuple = super(ImageFolderWithPaths, self).__getitem__(index) # the image file path path = self.imgs[index][0] # make a new tuple that includes original and the path tuple_with_path = (original_tuple + (path,)) return tuple_with_path # EXAMPLE USAGE: # instantiate the dataset and dataloader data_dir = &quot;your/data_dir/here&quot; dataset = ImageFolderWithPaths(data_dir) # our custom dataset dataloader = torch.utils.DataLoader(dataset) # iterate over data for inputs, labels, paths in dataloader: # use the above variables freely print(inputs, labels, paths) But this code does not take transforms into account, like in my original code. Can anybody help in how I should go about making it work with that?
Since ImageFolderWithPaths inherits from datasets.ImageFolder as shown in the code from GitHub and datasets.ImageFolder has the following arguments including transform: (see here for more info) torchvision.datasets.ImageFolder(root: str, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None, loader: Callable[[str], Any] = , is_valid_file: Optional[Callable[[str], bool]] = None) Solution: you can use your transformations directly when you instantiate ImageFolderWithPaths. import torch from torchvision import datasets from torch.utils.data import DataLoader class ImageFolderWithPaths(datasets.ImageFolder): def __getitem__(self, index): img, label = super(ImageFolderWithPaths, self).__getitem__(index) path = self.imgs[index][0] return (img, label ,path) # put here your root directory not subfolders directory # subfolders should be names of classes or encodings root_dir = &quot;training&quot; transform = transforms.Compose([transforms.Resize((32, 32)), transforms.ToTensor()]) # my transformations. dataset = ImageFolderWithPaths(root_dir,transform=transform) # add transformation directly dataloader = DataLoader(dataset) for inputs, labels, paths in dataloader: print(inputs.shape, labels, paths) # output torch.Size([1, 3, 32, 32]) tensor([0]) ('training\\0\\1.jpg',) torch.Size([1, 3, 32, 32]) tensor([0]) ('training\\0\\1000.jpg',) torch.Size([1, 3, 32, 32]) tensor([0]) ('training\\0\\10005.jpg',) torch.Size([1, 3, 32, 32]) tensor([0]) ('training\\0\\10010.jpg',) I also edited the code from github because there is no torch.utils.DataLoader but torch.utils.data.DataLoader.
https://stackoverflow.com/questions/71267824/
DataLoaders - wrapping an iterable over the Dataset means?
I am reading the official documentation of Dataloaders: https://pytorch.org/tutorials/beginner/basics/data_tutorial.html And there is this sentence &quot;DataLoader wraps an iterable around the Dataset..&quot; I know that dataloaders are used to iterate over the dataset but what I don't get is that what does wrapping an iterable over the dataset means? I want an insight of the theoretical point of view.
The sentence means that a DataLoader can be used to iterate the contents of a Dataset. For example, if you've got a Dataset of 1000 images, you can iterate certain attributes in the order that they've been stored in the Dataset and nothing else by itself. In the other hand, a DataLoader that wraps that Dataset allows you to iterate the data in batches, shuffle the data, apply functions, sample data, etc. Just checkout the Pytorch docs on torch.utils.data.DataLoader and you'll see all of the options included.
https://stackoverflow.com/questions/71269516/
Saving tensors to a .pt file in order to create a dataset
I was tasked with the creation of a dataset to test the functionality of the code we're working on. The dataset must have a group of tensors that will be used later on in a generative model. I'm trying to save the tensors to a .pt file, but I'm overwriting the tensors thus creating a file with only one. I've read about torch.utils.data.dataset but I'm not able to figure out by my own how to use it. Here is my code: import torch import numpy as np from torch.utils.data import Dataset #variables that will be used to create the size of the tensors: num_jets, num_particles, num_features = 1, 30, 3 for i in range(100): #tensor from a gaussian dist with mean=5,std=1 and shape=size: tensor = torch.normal(5,1,size=(num_jets, num_particles, num_features)) #We will need the tensors to be of the cpu type tensor = tensor.cpu() #save the tensor to 'tensor_dataset.pt' torch.save(tensor,'tensor_dataset.pt') #open the recently created .pt file inside a list tensor_list = torch.load('tensor_dataset.pt') #prints the list. Just one tensor inside .pt file print(tensor_list)
Reason: You overwrote tensor x each time in a loop, therefore you did not get your list, and you only had x at the end. Solution: you have the size of the tensor, you can initialize a tensor first and iterate through lst_tensors: import torch import numpy as np from torch.utils.data import Dataset num_jets, num_particles, num_features = 1, 30, 3 lst_tensors = torch.empty(size=(100,num_jets, num_particles, num_features)) for i in range(100): lst_tensors[i] = torch.normal(5,1,size=(num_jets, num_particles, num_features)) lst_tensors[i] = lst_tensors[i].cpu() torch.save(lst_tensors,'tensor_dataset.pt') tensor_list = torch.load('tensor_dataset.pt') print(tensor_list.shape) # [100,1,30,3]
https://stackoverflow.com/questions/71271752/
Pytorch: How to get the first N item from dataloader
There are 3000 pictures in my list, but I only want the first N of them, like 1000, for training. I wonder how can I achieve this by changing the loop code: for (image, label) in enumerate(train_loader):
for (image, label) in list(enumerate(train_loader))[:1000]: This is not a good way to partition training and validation data though. First, the dataloader class supports lazy loading (examples are not loaded into memory until needed) whereas casting as a list will require all data to be loaded into memory, likely triggering an out-of-memory error. Second, this may not always return the same 1000 elements if the dataloader has shuffling. In general, the dataloader class does not support indexing so is not really suitable for selecting a specific subset of our dataset. Casting as a list works around this but at the expense of the useful attributes of the dataloader class. Best practice is to use a separate data.dataset object for the training and validation partitions, or at least to partition the data in the dataset rather than relying on stopping the training after the first 1000 examples. Then, create a separate dataloader for the training partition and validation partition.
https://stackoverflow.com/questions/71277693/
Difference between pooling and global pooling in torch_geometric.nn
I realised that torch_geometric library offers both global pooling layers and pooling layers, but I don't really understand what is the difference between these 2 when applied to Graph Neural Networks?
The difference is how the pooling is performed. Global pooling gives you one supernode that contains the aggregated features from the whole graph. Local pooling operation on the other hand create clusters and aggregates nodes in them. Among local pooling you can find for instance Top-K pooling algorithm, SAGPool etc. They both have parameter called &quot;ratio&quot; that lets you specify how many nodes should be removed. Local pooling can give you a bit of hierarchical approach.
https://stackoverflow.com/questions/71277741/
How to sort a one hot tensor according to a tensor of indices
Given the below tensor: tensor = torch.Tensor([[1., 0., 0., 0., 0.], [0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 0., 1.], [1., 0., 0., 0., 0.], [1., 0., 0., 0., 0.], [0., 0., 0., 1., 0.], [0., 0., 0., 0., 1.]]) and below is the tensor containing the indices: indices = torch.tensor([2, 6, 7, 5, 4, 0, 3, 1]) How can I sort tensor using the values inside of indices? Trying with sorted gives the error: TypeError: 'Tensor' object is not callable`. While numpy.sort gives: ValueError: Cannot specify order when the array has no fields.`
You can use the indices like this: tensor = torch.Tensor([[1., 0., 0., 0., 0.], [0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 0., 1.], [1., 0., 0., 0., 0.], [1., 0., 0., 0., 0.], [0., 0., 0., 1., 0.], [0., 0., 0., 0., 1.]]) indices = torch.tensor([2, 6, 7, 5, 4, 0, 3, 1]) sorted_tensor = tensor[indices] print(sorted_tensor) # output tensor([[0., 0., 1., 0., 0.], [0., 0., 0., 1., 0.], [0., 0., 0., 0., 1.], [1., 0., 0., 0., 0.], [1., 0., 0., 0., 0.], [1., 0., 0., 0., 0.], [0., 0., 0., 0., 1.], [0., 1., 0., 0., 0.]])
https://stackoverflow.com/questions/71278145/
Pytorch : Expected all tensors on same device
I have my model and inputs moved on the same device but I still get the runtime error : RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument mat1 in method wrapper_addmm) Here is my code, First my model implementation : import torch import torch.nn.functional as F class Net(torch.nn.Module): def __init__(self, n_hiddens, n_feature= 2, n_output= 1): super().__init__() self.hiddens = [] n_hidden_in = n_feature for n_hidden in n_hiddens : self.hiddens.append( torch.nn.Linear(n_hidden_in, n_hidden) ) # hidden layer n_hidden_in = n_hidden self.predict = torch.nn.Linear(n_hidden, n_output) # output layer def forward(self, x): for hidden in self.hiddens : x = F.relu(hidden(x)) # activation function for hidden layer x = self.predict(x) # linear output return x Then I define my dataloaders. Here, X and y are numpy arrays from torch.utils.data import TensorDataset, DataLoader # Split training/test from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state= 42) X_train_tensor = torch.from_numpy(X_train) y_train_tensor = torch.from_numpy(y_train) X_test_tensor = torch.from_numpy(X_test) y_test_tensor = torch.from_numpy(y_test) train_dataset = TensorDataset(X_train_tensor, y_train_tensor) # create your datset train_dataloader = DataLoader(train_dataset, batch_size= 1000) # create your dataloader test_dataset = TensorDataset(X_test_tensor, y_test_tensor) # create your datset test_dataloader = DataLoader(test_dataset, batch_size= 1000) # create your dataloader Here I train my model. The error occurs during the line &quot;outputs = regressor(inputs)&quot; NUM_EPOCHS = 2000 BATCH_SIZE = 1000 device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print(f&quot;Device used : {device}&quot;) # 1 hidden layer total_num_nodes = 256 regressor = Net(n_hiddens= [total_num_nodes]).to(device) optimizer = torch.optim.SGD(regressor.parameters(), lr=0.2, momentum= 0.1, nesterov= True) loss_func = torch.nn.MSELoss() # this is for regression mean squared loss for epoch in range(NUM_EPOCHS): running_loss = 0.0 for i, data in enumerate(train_dataloader, 0): inputs, values = data inputs = inputs.float().to(device) values = values.float().to(device) optimizer.zero_grad() # clear gradients for next train print(f&quot;Input device is : cuda:{inputs.get_device()}&quot;) print(f&quot;Target value device is : cuda:{values.get_device()}&quot;) print(f&quot;Is model on cuda ? : {next(regressor.parameters()).is_cuda}&quot;) outputs = regressor(inputs) # &lt;-- This is where I have the error loss = loss_func(outputs, values) loss.backward() # backpropagation, compute gradients optimizer.step() # apply gradients Here are the outputs of my print statements : Device used : cuda:0 Input device is : cuda:0 Target value device is : cuda:0 Is model on cuda ? :True This should mean that my model and my tensors are all on the same device so why do I still have this error ? The error log is : --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) &lt;ipython-input-6-5234b830bebc&gt; in &lt;module&gt;() 24 print(f&quot;Target value device is : cuda:{values.get_device()}&quot;) 25 print(f&quot;Is model on cuda ? : {next(regressor.parameters()).is_cuda}&quot;) ---&gt; 26 outputs = regressor(inputs) 27 loss = loss_func(outputs, values) 28 loss.backward() # backpropagation, compute gradients 4 frames /usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs) 1100 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks 1101 or _global_forward_hooks or _global_forward_pre_hooks): -&gt; 1102 return forward_call(*input, **kwargs) 1103 # Do not call functions when jit is used 1104 full_backward_hooks, non_full_backward_hooks = [], [] &lt;ipython-input-4-56c54b30b771&gt; in forward(self, x) 16 def forward(self, x): 17 for hidden in self.hiddens : ---&gt; 18 x = F.relu(hidden(x)) # activation function for hidden layer 19 x = self.predict(x) # linear output 20 return x /usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs) 1100 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks 1101 or _global_forward_hooks or _global_forward_pre_hooks): -&gt; 1102 return forward_call(*input, **kwargs) 1103 # Do not call functions when jit is used 1104 full_backward_hooks, non_full_backward_hooks = [], [] /usr/local/lib/python3.7/dist-packages/torch/nn/modules/linear.py in forward(self, input) 101 102 def forward(self, input: Tensor) -&gt; Tensor: --&gt; 103 return F.linear(input, self.weight, self.bias) 104 105 def extra_repr(self) -&gt; str: /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py in linear(input, weight, bias) 1846 if has_torch_function_variadic(input, weight, bias): 1847 return handle_torch_function(linear, (input, weight, bias), input, weight, bias=bias) -&gt; 1848 return torch._C._nn.linear(input, weight, bias) 1849 1850 RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument mat1 in method wrapper_addmm) Thank you very much
TL;DR use nn.ModuleList instead of a pythonic one to store the hidden layers in Net. All your hidden layers are stored in a simple pythonic list self.hidden in Net. When you move your model to GPU, using .to(device), pytorch has no way to tell that all the elements of this pythonic list should also be moved to the same device. however, if you make self.hidden = nn.ModuleLis(), pytorch now knows to treat all elements of this special list as nn.Modules and recursively move them to the same device as Net. See these answers 1, 2, 3 for more details.
https://stackoverflow.com/questions/71278607/
How to interpret the output format of a model?
Noob here, hard to elaborate my question without an example, so I use a model on the MNIST data that classifies digits based on number images. # Load data trainset = datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True) model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10), nn.LogSoftmax(dim=1)) Why does model end up with 64 (row) x 10 (column) matrix? I thought nn.Linear(64, 10) means a layer that has 64 input neurons to 10 neurons. Shouldn't it be an array of 10 probabilities? and Why output activation function has dim=1 not dim=0? Isn't each row of 10 columns for an epoch? Shouldn't LogSoftmax being used to calculate the possibility of each digit? I'm ...lost. I have spent 2 hr on this, still can't find the answer, sorry for the noob question!
We usually have our data in the form of (BATCH SIZE, INPUT SIZE) which here in your case would be (64, 784). What this means is that in every batch you have 64 images and each image has 784 features. Regarding your model this is what it outputs : model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10), nn.LogSoftmax(dim=1)) print(model) # Sequential( # (0): Linear(in_features=784, out_features=128, bias=True) # (1): ReLU() # (2): Linear(in_features=128, out_features=64, bias=True) # (3): ReLU() # (4): Linear(in_features=64, out_features=10, bias=True) # (5): LogSoftmax(dim=1) # ) Let's go through how the data will flow through this model. You have input of shape (64, 784) It passes through first Linear layer, where each image of 784 features is converted to have 128 features so output is of shape (64, 128) ReLU does not change the shape just the values so shape is again (64, 128) Next Linear layer converts 128 features to 64 so now output shape is (64, 64). Again ReLU layer just changes values so shape is still (64, 64) This last Linear layer maps 64 input features to 10 output ones so shape is now (64, 10). Lastly we have the LogSoftmax layer. Here we provided dim=1 because we want to calculate output possibility for each of the possible 10 digits for each of the 64 images in out batch. The dim=0 is the batch and dim=1 is the outputs for digits that is we we provide dim=1. After this your output will have shape (64, 10). Therefore at the end, each image in the batch will have possibility for each of the 10 digits. I thought nn.Linear(64, 10) means a layer that has 64 input neurons to 10 neurons. That is correct. Another point to remember is that batch dimension is not specified in the layers of the models. We define layers to operate on each image. Your second last Linear layer output 64 values for an image so last Linear layer converts it to 10 values and then applies LogSoftmax to it. This operation is simply repeated for all 64 images in a batch efficiently using matrix operations. You might be confusing your batch_size=64 with the input_features=64 of Linear layer which is entirely unrelated.
https://stackoverflow.com/questions/71282058/
GCP Vertex AI Training: Auto-packaged Custom Training Job Yields Huge Docker Image
I am trying to run a Custom Training Job in Google Cloud Platform's Vertex AI Training service. The job is based on a tutorial from Google that fine-tunes a pre-trained BERT model (from HuggingFace). When I use the gcloud CLI tool to auto-package my training code into a Docker image and deploy it to the Vertex AI Training service like so: $BASE_GPU_IMAGE=&quot;us-docker.pkg.dev/vertex-ai/training/pytorch-gpu.1-7:latest&quot; $BUCKET_NAME = &quot;my-bucket&quot; gcloud ai custom-jobs create ` --region=us-central1 ` --display-name=fine_tune_bert ` --args=&quot;--job_dir=$BUCKET_NAME,--num-epochs=2,--model-name=finetuned-bert-classifier&quot; ` --worker-pool-spec=&quot;machine-type=n1-standard-4,replica-count=1,accelerator-type=NVIDIA_TESLA_V100,executor-image-uri=$BASE_GPU_IMAGE,local-package-path=.,python-module=trainer.task&quot; ... I end up with a Docker image that is roughly 18GB (!) and takes a very long time to upload to the GCP registry. Granted the base image is around 6.5GB but where do the additional &gt;10GB come from and is there a way for me to avoid this &quot;image bloat&quot;? Please note that my job loads the training data using the datasets Python package at run time and AFAIK does not include it in the auto-packaged docker image.
The image size shown in the UI is the virtual size of the image. It is the compressed total image size that will be downloaded over the network. Once the image is pulled, it will be extracted and the resulting size will be bigger. In this case, the PyTorch image's virtual size is 6.8 GB while the actual size is 17.9 GB. Also, when a docker push command is executed, the progress bars show the uncompressed size. The actual amount of data that’s pushed will be compressed before sending, so the uploaded size will not be reflected by the progress bar. To cut down the size of the docker image, custom containers can be used. Here, only the necessary components can be configured which would result in a smaller docker image. More information on custom containers here.
https://stackoverflow.com/questions/71284125/
How can I determine validation loss for faster RCNN (PyTorch)?
I followed this tutorial for object detection: https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html and their GitHub repository that contains the following train_one_epoch and evaluate functions: https://github.com/pytorch/vision/blob/main/references/detection/engine.py However, I want to calculate losses during validation. I implemented this for the evaluation loss, where essentially to obtain losses, model.train() needs to be on: @torch.no_grad() def evaluate_loss(model, data_loader, device): val_loss = 0 model.train() for images, targets in data_loader: images = list(image.to(device) for image in images) targets = [{k: v.to(device) for k, v in t.items()} for t in targets] loss_dict = model(images, targets) losses = sum(loss for loss in loss_dict.values()) # reduce losses over all GPUs for logging purposes loss_dict_reduced = utils.reduce_dict(loss_dict) losses_reduced = sum(loss for loss in loss_dict_reduced.values()) val_loss += losses_reduced validation_loss = val_loss/ len(data_loader) return validation_loss I then place it after the learning rate scheduler step in my for loop: for epoch in range(args.num_epochs): # train for one epoch, printing every 10 iterations train_one_epoch(model, optimizer, train_data_loader, device, epoch, print_freq=10) # update the learning rate lr_scheduler.step() validation_loss = evaluate_loss(model, valid_data_loader, device=device) # evaluate on the test dataset evaluate(model, valid_data_loader, device=device) Does this look correct or can it interfere with training or produce inaccurate validation losses? If ok, by using this, is there is a simple way in applying early stopping for validation loss? I'm considering just adding something like this after the evaluate model function shown above: torch.save({ 'epoch': epoch, 'model_state_dict': net.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'validation loss': valid_loss, }, PATH) where I also aim to save the model at every epoch for checkpointing purposes. However I need to determine the validation &quot;loss&quot; for saving the &quot;best&quot; model.
So it turns out no stages of the pytorch fasterrcnn return losses when model.eval() is set. However, you can just manually use the forward code to generate the losses in evaluation mode: from typing import Tuple, List, Dict, Optional import torch from torch import Tensor from collections import OrderedDict from torchvision.models.detection.roi_heads import fastrcnn_loss from torchvision.models.detection.rpn import concat_box_prediction_layers def eval_forward(model, images, targets): # type: (List[Tensor], Optional[List[Dict[str, Tensor]]]) -&gt; Tuple[Dict[str, Tensor], List[Dict[str, Tensor]]] &quot;&quot;&quot; Args: images (list[Tensor]): images to be processed targets (list[Dict[str, Tensor]]): ground-truth boxes present in the image (optional) Returns: result (list[BoxList] or dict[Tensor]): the output from the model. It returns list[BoxList] contains additional fields like `scores`, `labels` and `mask` (for Mask R-CNN models). &quot;&quot;&quot; model.eval() original_image_sizes: List[Tuple[int, int]] = [] for img in images: val = img.shape[-2:] assert len(val) == 2 original_image_sizes.append((val[0], val[1])) images, targets = model.transform(images, targets) # Check for degenerate boxes # TODO: Move this to a function if targets is not None: for target_idx, target in enumerate(targets): boxes = target[&quot;boxes&quot;] degenerate_boxes = boxes[:, 2:] &lt;= boxes[:, :2] if degenerate_boxes.any(): # print the first degenerate box bb_idx = torch.where(degenerate_boxes.any(dim=1))[0][0] degen_bb: List[float] = boxes[bb_idx].tolist() raise ValueError( &quot;All bounding boxes should have positive height and width.&quot; f&quot; Found invalid box {degen_bb} for target at index {target_idx}.&quot; ) features = model.backbone(images.tensors) if isinstance(features, torch.Tensor): features = OrderedDict([(&quot;0&quot;, features)]) model.rpn.training=True #model.roi_heads.training=True #####proposals, proposal_losses = model.rpn(images, features, targets) features_rpn = list(features.values()) objectness, pred_bbox_deltas = model.rpn.head(features_rpn) anchors = model.rpn.anchor_generator(images, features_rpn) num_images = len(anchors) num_anchors_per_level_shape_tensors = [o[0].shape for o in objectness] num_anchors_per_level = [s[0] * s[1] * s[2] for s in num_anchors_per_level_shape_tensors] objectness, pred_bbox_deltas = concat_box_prediction_layers(objectness, pred_bbox_deltas) # apply pred_bbox_deltas to anchors to obtain the decoded proposals # note that we detach the deltas because Faster R-CNN do not backprop through # the proposals proposals = model.rpn.box_coder.decode(pred_bbox_deltas.detach(), anchors) proposals = proposals.view(num_images, -1, 4) proposals, scores = model.rpn.filter_proposals(proposals, objectness, images.image_sizes, num_anchors_per_level) proposal_losses = {} assert targets is not None labels, matched_gt_boxes = model.rpn.assign_targets_to_anchors(anchors, targets) regression_targets = model.rpn.box_coder.encode(matched_gt_boxes, anchors) loss_objectness, loss_rpn_box_reg = model.rpn.compute_loss( objectness, pred_bbox_deltas, labels, regression_targets ) proposal_losses = { &quot;loss_objectness&quot;: loss_objectness, &quot;loss_rpn_box_reg&quot;: loss_rpn_box_reg, } #####detections, detector_losses = model.roi_heads(features, proposals, images.image_sizes, targets) image_shapes = images.image_sizes proposals, matched_idxs, labels, regression_targets = model.roi_heads.select_training_samples(proposals, targets) box_features = model.roi_heads.box_roi_pool(features, proposals, image_shapes) box_features = model.roi_heads.box_head(box_features) class_logits, box_regression = model.roi_heads.box_predictor(box_features) result: List[Dict[str, torch.Tensor]] = [] detector_losses = {} loss_classifier, loss_box_reg = fastrcnn_loss(class_logits, box_regression, labels, regression_targets) detector_losses = {&quot;loss_classifier&quot;: loss_classifier, &quot;loss_box_reg&quot;: loss_box_reg} boxes, scores, labels = model.roi_heads.postprocess_detections(class_logits, box_regression, proposals, image_shapes) num_images = len(boxes) for i in range(num_images): result.append( { &quot;boxes&quot;: boxes[i], &quot;labels&quot;: labels[i], &quot;scores&quot;: scores[i], } ) detections = result detections = model.transform.postprocess(detections, images.image_sizes, original_image_sizes) # type: ignore[operator] model.rpn.training=False model.roi_heads.training=False losses = {} losses.update(detector_losses) losses.update(proposal_losses) return losses, detections Testing this code gives me: import torchvision from torchvision.models.detection.faster_rcnn import FastRCNNPredictor # load a model pre-trained on COCO model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True) # replace the classifier with a new one, that has # num_classes which is user-defined num_classes = 2 # 1 class (person) + background # get number of input features for the classifier in_features = model.roi_heads.box_predictor.cls_score.in_features # replace the pre-trained head with a new one model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes) losses, detections = eval_forward(model,torch.randn([1,3,300,300]),[{'boxes':torch.tensor([[100,100,200,200]]),'labels':torch.tensor([0])}]) {'loss_classifier': tensor(0.6594, grad_fn=&lt;NllLossBackward0&gt;), 'loss_box_reg': tensor(0., grad_fn=&lt;DivBackward0&gt;), 'loss_objectness': tensor(0.5108, grad_fn=&lt;BinaryCrossEntropyWithLogitsBackward0&gt;), 'loss_rpn_box_reg': tensor(0.0160, grad_fn=&lt;DivBackward0&gt;)}
https://stackoverflow.com/questions/71288513/
Only Tensors of floating point and complex dtype can require gradients
I am receiving the following error when I run a convolution operation inside a torch.no_grad() context: RuntimeError: Only Tensors of floating-point and complex dtype can require gradients. import torch.nn as nn import torch with torch.no_grad(): ker_t = torch.tensor([[1, -1] ,[-1, 1]]) in_t = torch.tensor([ [14, 7, 6, 2,] , [4 ,8 ,11 ,1], [3, 5, 9 ,10], [12, 15, 16, 13] ]) print(in_t.shape) in_t = torch.unsqueeze(in_t,0) in_t = torch.unsqueeze(in_t,0) print(in_t.shape) conv = nn.Conv2d(1, 1, kernel_size=2,stride=2,dtype=torch.long) conv.weight[:] = ker_t conv(in_t) Now I am sure if I turn my input into floats this message will go away, but I want to work in integers. But I was under the impression that if I am in a with torch.no_grad() context it should turn off the need for gradients.
The need for gradients comes from nn.Conv2d when it registers the weights of the convolution layer. However, if you are only after the forward pass, you do not need to use a convolution layer: you can use the underlying convolution function: import torch.nn.functional as nnf ker_t = torch.tensor([[1, -1] ,[-1, 1]])[None, None, ...] in_t = torch.tensor([ [14, 7, 6, 2,] , [4 ,8 ,11 ,1], [3, 5, 9 ,10], [12, 15, 16, 13] ])[None, None, ...] out = nnf.conv2d(in_t, ker_t, stride=2) Will give you this output: tensor([[[[11, -6], [ 1, -4]]]])
https://stackoverflow.com/questions/71290915/
Is there a way to train a neural network with untrainable params in torch?
So, I am trying to learn the transfer learning and trying to implement it in an autoencoder while I have frozen some of my initial layers and then i added new layers in it as well now i am trying to train it but for some reasons i cannot train them. Any concept on how to training really works with the untrainable params? This is the code for my training the error occurs in backward propagation and it thinks due to some modification in neural network it cannot work. nb_epoch = 10 for epoch in range(1, nb_epoch+1): train_loss = 0 s = 0. #Compute RMSE for id_user in range(nb_users): input = Variable(training_set_torch[id_user]).unsqueeze(0)#Batch of 1 input vector or else wont work target = input.clone() if torch.sum(target.data &gt; 0) &gt; 0: #Target.data is rating output = net(input) #Now we create optimize the memory target.require_grad = False output[target == 0] = 0 #calculating loss loss = criterion(output, target) #Average of movie considered like non zero ratings mean_corrector = nb_users/float(torch.sum(target.data &gt; 0)+ 1e-10)# 1e-10 is to avoid 0/0 #Now calling backward method loss.backward()* train_loss += np.sqrt(loss.data*mean_corrector) s += 1. #Using the Optimzer optimizer.step() #Printing what happens at every epoch print('Epoch: ' +str(epoch)+ 'Loss: '+str(train_loss/s)) *Error occured ERROR: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [1, 1000]], which is output 0 of SigmoidBackward, is at version 1; expected version 0 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True). and when I set that to True it shows another error ERROR: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [1, 1000]], which is output 0 of SigmoidBackward, is at version 1; expected version 0 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck!
I suspect this line is causing you the issue: output[target == 0] = 0 Try removing it and see if you get an error. Update: You can remove these entries, and still avoid the &quot;in-place&quot; error by replacing the assignment with a multiplication by a mask: output = output * (target != 0)
https://stackoverflow.com/questions/71291918/
PyTorch loss function that depends on gradient of network with respect to input
I'm trying to implement a loss function that depends on the gradient of the network with respect to its inputs. That is, the loss function has a term like sum(u - grad_x(network(x))) where u is computed by forward propagating x through the network. I'm able to compute the gradient by calling funcApprox = funcNetwork.forward(X) funcGrad = grad(funcApprox, X, grad_outputs=torch.ones_like(funcApprox)) Here, funcNetwork is my NN and X is the input. These computations are done in the loss function. However, now if I attempt to do the following opt.zero_grad() loss = self.loss(X) # My custom loss function that calculates funcGrad, etc., from above opt.zero_grad() loss.backward() opt.step() I see the following error: RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward. on the loss.backward() line from above. I've tried playing around with create_graph, retain_graph, etc. but to no avail. Any help is appreciated!
As per comment by @aretor, setting retain_graph=True, create_graph=False in the grad call in the loss function, and retain_graph=True in backward solves the issue.
https://stackoverflow.com/questions/71294401/
Training loss is increasing in CNN?
I am in the process of training my first CNN to solve a multi-class classification problem. I am feeding in images of animals corresponding to one of 182 classes, however I have ran into some issues. Firstly my code appears to get stuck on optimiser.step(), it has been calculating this for roughly 30 minutes. Secondly my training loss is increasing: EPOCH: 0 BATCH: 1999 LOSS: 1.5790680234357715 EPOCH: 0 BATCH: 3999 LOSS: 2.9340945997834207 If any one would be able to provide some guidance that would be greatly appreciated. Below is my code #loading data train_data = dataset.get_subset( &quot;train&quot;, transform=transforms.Compose( [transforms.Resize((448, 448)), transforms.ToTensor()] ), ) train_loader = get_train_loader(&quot;standard&quot;, train_data, batch_size=16) #definind model class ConvNet(nn.Module): def __init__(self): super(ConvNet, self).__init__() self.conv1 = nn.Conv2d(3, 6, 3, 1) self.conv2 = nn.Conv2d(6, 16, 3, 3) self.fc1 = nn.Linear(37*37*16, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 182) def forward(self, X): X = F.relu(self.conv1(X)) X = F.max_pool2d(X, 2, 2) X = F.relu(self.conv2(X)) X = F.max_pool2d(X, 2, 2) X = torch.flatten(X, 1) X = F.relu(self.fc1((X))) X = F.relu(self.fc2((X))) X = self.fc3(X) return F.log_softmax(X, dim=1) criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(modell.parameters(), lr=0.001) import time start_time = time.time() #VARIABLES (TRACKER) epochs = 2 train_losses = [] test_losses = [] train_correct = [] test_correct = [] # FOR LOOP EPOCH for i in range(epochs): trn_corr = 0 tst_corr = 0 running_loss = 0.0 #TRAIN for b, (X_train, Y_train, meta) in enumerate(train_loader): b+=1 #batch starts at 1 #zero parameter gradients optimizer.zero_grad() # pass training to model as float (later compute loss) output = modell(X_train.float()) #Calculate the loss of outputs with respect to ground truth values loss = criterion(output, Y_train) #Backpropagate the loss through the network loss.backward() #perform parameter update based on the current gradient optimizer.step() predicted = torch.max(output.data, 1)[1] batch_corr = (predicted == Y_train).sum() # True (1) or False (0) trn_corr += batch_corr running_loss += loss.item() if b%2000 == 1999: print(f&quot;EPOCH: {i} BATCH: {b} LOSS: {running_loss/2000}&quot;) running_loss = 0.0 train_losses.append(loss) train_correct.append(trn_corr)
As for the loss, it may be due to the model. The model has some rooms for improvement. Only 2 convolution layers is not sufficient for your data, as well as only expanding to 16 channels. Use more convolution layers with more channels. For example, 5 conv layers with channels of 16, 32, 32, 64, 64. Experiment with different numbers of layers and channels to see which one is best. Also, a good learning rate for Adam is 3e-4.To more easily track the models progress, I’d recommend decreasing the interval at which it prints the loss so you can more easily track progress. About the data, are there enough instances of each class? Is it normalized between 0 and 1?
https://stackoverflow.com/questions/71299249/
Pytorch error: TypeError: adaptive_avg_pool3d(): argument 'output_size' (position 2) must be tuple of ints, not list
I got this error when trying to use the AdaptiveAvgPool3D in Pytorch. Below is the error trace Traceback (most recent call last): File &quot;/scratch/a.bip5/BraTS 2021/./sisa.py&quot;, line 395, in outputs = model(inputs) File &quot;/home/a.bip5/.conda/envs/pix2pix/lib/python3.9/site-packages/torch/nn/modules/module.py&quot;, line 1051, in _call_impl return forward_call(*input, **kwargs) File &quot;/home/a.bip5/.conda/envs/pix2pix/lib/python3.9/site-packages/torch/nn/parallel/data_parallel.py&quot;, line 166, in forward return self.module(*inputs[0], **kwargs[0]) File &quot;/home/a.bip5/.conda/envs/pix2pix/lib/python3.9/site-packages/torch/nn/modules/module.py&quot;, line 1051, in _call_impl return forward_call(*input, **kwargs) File &quot;/scratch/a.bip5/BraTS 2021/./sisa.py&quot;, line 96, in forward x1 = self.pool1(x) File &quot;/home/a.bip5/.conda/envs/pix2pix/lib/python3.9/site-packages/torch/nn/modules/module.py&quot;, line 1051, in _call_impl return forward_call(*input, **kwargs) File &quot;/scratch/a.bip5/BraTS 2021/./sisa.py&quot;, line 135, in forward x1=aa(x) File &quot;/home/a.bip5/.conda/envs/pix2pix/lib/python3.9/site-packages/torch/nn/modules/module.py&quot;, line 1051, in _call_impl return forward_call(*input, **kwargs) File &quot;/home/a.bip5/.conda/envs/pix2pix/lib/python3.9/site-packages/torch/nn/modules/pooling.py&quot;, line 1166, in forward return F.adaptive_avg_pool3d(input, self.output_size) File &quot;/home/a.bip5/.conda/envs/pix2pix/lib/python3.9/site-packages/torch/nn/functional.py&quot;, line 1148, in adaptive_avg_pool3d return torch._C._nn.adaptive_avg_pool3d(input, _output_size) TypeError: adaptive_avg_pool3d(): argument 'output_size' (position 2) must be tuple of ints, not list When looking into the error stack I found this piece of code in ../functional.py: if has_torch_function_unary(input): return handle_torch_function( adaptive_max_pool3d_with_indices, (input,), input, output_size, return_indices=return_indices ) _output_size = _list_with_default(output_size, input.size()) return torch._C._nn.adaptive_max_pool3d(input, _output_size) Printing out types for output_size and _output_size shows one's a tuple(as it is supposed to be) and the other is turned into a list before being passed through in the lib function itself. What I don't understand is why this conversion to list is taking place if the function using this list doesn't like it? If the purpose of this is to give out an error, what are the conditions that satisfy the has_torch_function_unary condition? Any help would be appreciated. Edit: I tried to side-step the problem by using output_size in the final return statement instead of _output_size. That led to an even more cryptic error- TypeError: adaptive_avg_pool3d(): argument 'output_size' (position 2) must be tuple of ints, not tuple How does pytorch differentiate between tuple of ints and a tuple?
The reason behind the error turned out to be a type error. When passing the size to AdaptiveAvgPool3d I was getting the values for the size through division. Although the remainder was 0, division by default saves values as float in python. This meant the tuple being passed as the output_size was in fact a tuple of float which the _list_with_default turns into a list but likely doesn't if the tuple was made of int. Simply using int(..) for each dimension passed to AdaptiveAvgPool3d was the solution.
https://stackoverflow.com/questions/71300227/
TypeError: 'module' object is not callable error?
I studying on a model training. when i called the training function i got this error &quot;TypeError: 'module' object is not callable&quot; and i can't see where i missed it. here is my calling function: train( model, optimizer, loss, train_loader, hyperparams[&quot;epoch&quot;], scheduler=hyperparams[&quot;scheduler&quot;], device=hyperparams[&quot;device&quot;], val_loader=val_loader, ) the error i got
You are calling tqdm module, instead of tqdm method from tqdm module. Replace: import tqdm with: from tqdm import tqdm
https://stackoverflow.com/questions/71300827/
output from bert into cnn model
i am trying to concatenate bert model with Cnn 1d using pytorch . I used this code but I do not understand what is meaning of in_channels and out_channels in function conv1d if input shape into cnn model is torch(256,64,768) class MixModel(nn.Module): def __init__(self,pre_trained='distilbert-base-uncased'): super().__init__() self.bert = AutoModel.from_pretrained('distilbert-base-uncased') self.hidden_size = self.bert.config.hidden_size self.conv = nn.Conv1d(in_channels=1, out_channels=256, kernel_size=5, padding='valid', stride=1) self.relu = nn.ReLU() self.pool = nn.MaxPool1d(kernel_size= 256- 5 + 1) self.dropout = nn.Dropout(0.3) self.clf = nn.Linear(self.hidden_size*2,6) def forward(self,inputs, mask , labels): cls_hs = self.bert(input_ids=inputs,attention_mask=mask, return_dict= False) x=cls_hs # x = torch.cat(cls_hs[0]) # x= [416, 64, 768] x = self.conv(x) x = self.relu(x) x = self.pool(x) x = self.dropout(x) x = self.clf(x) return x Edit I use recommended answer and change the parameters but i got error class MixModel(nn.Module): def __init__(self,pre_trained='bert-base-uncased'): super().__init__() self.bert = AutoModel.from_pretrained('distilbert-base-uncased') self.hidden_size = self.bert.config.hidden_size self.conv = nn.Conv1d(in_channels=768, out_channels=256, kernel_size=5, padding='valid', stride=1) self.relu = nn.ReLU() self.pool = nn.MaxPool1d(kernel_size= 64- 5 + 1) print(11) self.dropout = nn.Dropout(0.3) print(12) self.clf = nn.Linear(self.hidden_size*2,6) print(13) def forward(self,inputs, mask , labels): cls_hs = self.bert(input_ids=inputs,attention_mask=mask, return_dict= False) x=cls_hs[0] print(cls_hs[0]) print(len(cls_hs[0])) print(cls_hs[0].size()) #x = torch.cat(cls_hs,0) # x= [416, 64, 768] x = x.permute(0, 2, 1) x = self.conv(x) x = self.relu(x) x = self.pool(x) x = self.dropout(x) x = self.clf(x) return x the error is 5 frames /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py in linear(input, weight, bias) 1846 if has_torch_function_variadic(input, weight, bias): 1847 return handle_torch_function(linear, (input, weight, bias), input, weight, bias=bias) -&gt; 1848 return torch._C._nn.linear(input, weight, bias) 1849 1850 RuntimeError: mat1 and mat2 shapes cannot be multiplied (65536x1 and 1536x6)
The dimension of the output prediction of BERT (and many other transformer-based models) is of shape batchxseq-lenxfeature-dim: That is, your input is a batch of 256 sequences of length (probably with padding) of 64 tokens, each token is represented by a feature vector of dimension 768. In order to apply 1-d convolution along the sequence-len dimension, you will need first to permute x to be of shape batchxdimxlen: x = x.permute(0, 2, 1) Now you can apply nn.Conv1d, where the in_channels is the dimension of x = 768. the out_channels is up to you - what is going to be the hidden dimension of your model.
https://stackoverflow.com/questions/71301279/
Numpy to pyTorch: are there different data types?
Question: Can somebody help me to align this two approaches of data generation so that both of them can be used by the nn-model below ? When using appraoch (2) with numpy and torch.from_numpy(x) a run time error occurs (&quot;expected scalar type Float but found Double&quot;) For data generation I have these two approaches: import torch import torch.nn as nn import numpy as np def get_training_data_1(): x = torch.randn(batch_size, n_in) y = torch.tensor([[1.0], [0.0], [0.0], [1.0], [1.0], [1.0], [0.0], [0.0], [1.0], [1.0]]) return x,y def get_training_data_2(): x = np.random.rand(batch_size, n_in) y = np.array([[1.0], [0.0], [0.0], [1.0], [1.0], [1.0], [0.0], [0.0], [1.0], [1.0]]) x = torch.from_numpy(x) y = torch.from_numpy(y) return x,y n_in, n_h, n_out, batch_size = 2, 5, 1, 10 x, y = get_training_data_2() With this model I run into problems when using appraoch (2) with numpy and torch.from_numpy(x), while it is OK when using approach (1) #---- Create a NN-model model = nn.Sequential( nn.Linear(n_in, n_h), # hidden layer nn.ReLU(), # activation layer nn.Linear(n_h, n_out), # output layer nn.Sigmoid() ) # final 0, 1 rounding #---- Construct the loss function criterion = torch.nn.MSELoss() #---- Construct the optimizer (Stochastic Gradient Descent in this case) optimizer = torch.optim.SGD(model.parameters(), lr = 0.1) #---- Gradient Descent for epoch in range(1501): y_pred = model(x) # Forward pass: Compute predicted y by passing x to the model loss = criterion(y_pred, y) # Compute and print loss if epoch%50 == 0: print(epoch, loss.item()) optimizer.zero_grad() # Zero gradients, perform a backward pass, and update the weights. loss.backward() # perform a backward pass (backpropagation) optimizer.step() # Update the parameters
The default floating point type in torch is float32 (i.e. single precision). In NumPy the default is float64 (double precision). Try changing get_training_data_2 so that it explicitly sets the data type of the numpy arrays numpy.float32 before converting them to torch tensors: def get_training_data_2(): x = np.random.rand(batch_size, n_in).astype(np.float32) y = np.array([[1.0], [0.0], [0.0], [1.0], [1.0], [1.0], [0.0], [0.0], [1.0], [1.0]], dtype=np.float32) x = torch.from_numpy(x) y = torch.from_numpy(y) return x,y Note. With the newer NumPy random API, you can generate float32 samples directly instead of casting float64 values to float32. def get_training_data_2(rng): x = rng.random(size=(batch_size, n_in), dtype=np.float32) y = np.array([[1.0], [0.0], [0.0], [1.0], [1.0], [1.0], [0.0], [0.0], [1.0], [1.0]], dtype=np.float32) x = torch.from_numpy(x) y = torch.from_numpy(y) return x,y rng = np.random.default_rng() x, y = get_training_data_2(rng)
https://stackoverflow.com/questions/71302059/
conda env broken after installing pytorch on M1 - Intel MKL FATAL ERROR
I installed pytorch on my M1 mac book, following some instructions on-line (via conda command). Then my whole environment got corrupted. Whenever I try to import some library (pandas, numpy, whatever) I get this: Intel MKL FATAL ERROR: This system does not meet the minimum requirements for use of the Intel(R) Math Kernel Library. The processor must support the Intel(R) Supplemental Streaming SIMD Extensions 3 (Intel(R) SSSE3) instructions. The processor must support the Intel(R) Streaming SIMD Extensions 4.2 (Intel(R) SSE4.2) instructions. The processor must support the Intel(R) Advanced Vector Extensions (Intel(R) AVX) instructions. How can I fix it? How can I install pytorch successully?
Here is what worked for me a few weeks ago: Create a new conda environment and activate it. conda install ipykernel jupyter numpy pandas matplotlib nomkl (the key part being to include nomkl and don't include PyTorch). pip install torch torchvision I could not get step 3 to work using conda (possibly related issue). This doesn't feel like a robust solution (mixing conda and pip), but the environment has worked for me the past few weeks.
https://stackoverflow.com/questions/71306262/
How to get input size for a operator in pytorch script model?
I use this code to transfer the model to script model: scripted_model = torch.jit.trace(detector.model, images).eval() Then I print the scripted_model. A part of the output is as follows: (base): DLA( original_name=DLA (base_layer): Sequential( original_name=Sequential (0): Conv2d(original_name=Conv2d) (1): BatchNorm2d(original_name=BatchNorm2d) (2): ReLU(original_name=ReLU) ) (level0): Sequential( original_name=Sequential (0): Conv2d(original_name=Conv2d) (1): BatchNorm2d(original_name=BatchNorm2d) (2): ReLU(original_name=ReLU) ) (level1): Sequential( original_name=Sequential (0): Conv2d(original_name=Conv2d) (1): BatchNorm2d(original_name=BatchNorm2d) (2): ReLU(original_name=ReLU) ) (level2): Tree( original_name=Tree (tree1): BasicBlock( original_name=BasicBlock (conv1): Conv2d(original_name=Conv2d) (bn1): BatchNorm2d(original_name=BatchNorm2d) (relu): ReLU(original_name=ReLU) (conv2): Conv2d(original_name=Conv2d) (bn2): BatchNorm2d(original_name=BatchNorm2d) ) (tree2): BasicBlock( original_name=BasicBlock (conv1): Conv2d(original_name=Conv2d) (bn1): BatchNorm2d(original_name=BatchNorm2d) (relu): ReLU(original_name=ReLU) (conv2): Conv2d(original_name=Conv2d) (bn2): BatchNorm2d(original_name=BatchNorm2d ) (root): Root( original_name=Root (conv): Conv2d(original_name=Conv2d) (bn): BatchNorm2d(original_name=BatchNorm2d) (relu): ReLU(original_name=ReLU) ) (downsample): MaxPool2d(original_name=MaxPool2d) (project): Sequential( original_name=Sequential (0): Conv2d(original_name=Conv2d) (1): BatchNorm2d(original_name=BatchNorm2d) ) ) ... I just want to get the input size for the operator, such as how many inputs for the operator (0): Conv2d(original_name=Conv2d). I print the graph of this script model, the output is as follows: %4770 : __torch__.torch.nn.modules.module.___torch_mangle_11.Module = prim::GetAttr[name=&quot;wh&quot;](%self.1) %4762 : __torch__.torch.nn.modules.module.___torch_mangle_15.Module = prim::GetAttr[name=&quot;tracking&quot;](%self.1) %4754 : __torch__.torch.nn.modules.module.___torch_mangle_23.Module = prim::GetAttr[name=&quot;rot&quot;](%self.1) %4746 : __torch__.torch.nn.modules.module.___torch_mangle_7.Module = prim::GetAttr[name=&quot;reg&quot;](%self.1) %4738 : __torch__.torch.nn.modules.module.___torch_mangle_3.Module = prim::GetAttr[name=&quot;hm&quot;](%self.1) %4730 : __torch__.torch.nn.modules.module.___torch_mangle_27.Module = prim::GetAttr[name=&quot;dim&quot;](%self.1) %4722 : __torch__.torch.nn.modules.module.___torch_mangle_19.Module = prim::GetAttr[name=&quot;dep&quot;](%self.1) %4714 : __torch__.torch.nn.modules.module.___torch_mangle_31.Module = prim::GetAttr[name=&quot;amodel_offset&quot;](%self.1) %4706 : __torch__.torch.nn.modules.module.___torch_mangle_289.Module = prim::GetAttr[name=&quot;ida_up&quot;](%self.1) %4645 : __torch__.torch.nn.modules.module.___torch_mangle_262.Module = prim::GetAttr[name=&quot;dla_up&quot;](%self.1) %4461 : __torch__.torch.nn.modules.module.___torch_mangle_180.Module = prim::GetAttr[name=&quot;base&quot;](%self.1) %5100 : (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor) = prim::CallMethod[name=&quot;forward&quot;](%4461, %input.1) %5082 : Tensor, %5083 : Tensor, %5084 : Tensor, %5085 : Tensor, %5086 : Tensor, %5087 : Tensor, %5088 : Tensor, %5089 : Tensor = prim::TupleUnpack(%5100) %5101 : (Tensor, Tensor, Tensor) = prim::CallMethod[name=&quot;forward&quot;](%4645, %5082, %5083, %5084, %5085, %5086, %5087, %5088, %5089) %5097 : Tensor, %5098 : Tensor, %5099 : Tensor = prim::TupleUnpack(%5101) %3158 : None = prim::Constant() I even can find the operator name. How can I get input size for a specific operator in the script model?
One solution is to try summary from torchinfo and the output shape of the first layer is the input shape for the next one and so on: !pip install torchinfo from torchinfo import summary summary(model, input_size=(batch_size, 3, 224, 224)) # input size to your NN #output =============================================================================================== Layer (type:depth-idx) Output Shape Param # =============================================================================================== ResNet50 -- -- ├─ResNet: 1-1 [64, 10] -- │ └─Conv2d: 2-1 [64, 64, 112, 112] 9,408 │ └─BatchNorm2d: 2-2 [64, 64, 112, 112] 128 │ └─ReLU: 2-3 [64, 64, 112, 112] -- │ └─MaxPool2d: 2-4 [64, 64, 56, 56] -- │ └─Sequential: 2-5 [64, 64, 56, 56] -- │ │ └─BasicBlock: 3-1 [64, 64, 56, 56] 73,984 │ │ └─BasicBlock: 3-2 [64, 64, 56, 56] 73,984 │ └─Sequential: 2-6 [64, 128, 28, 28] -- │ │ └─BasicBlock: 3-3 [64, 128, 28, 28] 230,144 │ │ └─BasicBlock: 3-4 [64, 128, 28, 28] 295,424 │ └─Sequential: 2-7 [64, 256, 14, 14] -- │ │ └─BasicBlock: 3-5 [64, 256, 14, 14] 919,040 │ │ └─BasicBlock: 3-6 [64, 256, 14, 14] 1,180,672 │ └─Sequential: 2-8 [64, 512, 7, 7] -- │ │ └─BasicBlock: 3-7 [64, 512, 7, 7] 3,673,088 │ │ └─BasicBlock: 3-8 [64, 512, 7, 7] 4,720,640 │ └─AdaptiveAvgPool2d: 2-9 [64, 512, 1, 1] -- │ └─Linear: 2-10 [64, 10] 5,130 =============================================================================================== Total params: 11,181,642 Trainable params: 11,181,642 Non-trainable params: 0 Total mult-adds (G): 116.07 =============================================================================================== Input size (MB): 38.54 Forward/backward pass size (MB): 2543.33 Params size (MB): 44.73 Estimated Total Size (MB): 2626.59 ===============================================================================================
https://stackoverflow.com/questions/71307639/
Loaded PyTorch model has a different result compared to saved model
I have a python script that trains and then tests a CNN model. The model weights/parameters are saved after testing through the use of: checkpoint = {'state_dict': model.state_dict(),'optimizer' :optimizer.state_dict()} torch.save(checkpoint, path + filename) After saving I immediately load the model through the use of a function: model_load = create_model(cnn_type=&quot;vgg&quot;, numberofclasses=len(cases)) And then, I load the model weights/parameters through: model_load.load_state_dict(torch.load(filePath+filename), strict = False) model_load.eval() Finally, I feed this model the same testing data I used before the model was saved. The problem is that the testing results are not the same when I compare the testing results of the model before saving and after loading. My hunch is that due to strict = False, some of the parameters are not being passed through to the model. However, when I make strict = True. I receive errors. Is there a work around this? The error message is: RuntimeError: Error(s) in loading state_dict for CNN: Missing key(s) in state_dict: &quot;linear.weight&quot;, &quot;linear.bias&quot;, &quot;linear 2.weight&quot;, &quot;linea r2.bias&quot;, &quot;linear 3.weight&quot;, &quot;linear3.bias&quot;. Unexpected key(s) in state_dict: &quot;state_dict&quot;, &quot;optimizer&quot;.
You are loading a dictionary containing the state of your model as well as the optimizer's state. According to your error stack trace, the following should solve the issue: &gt;&gt;&gt; model_state = torch.load(filePath+filename)['state_dict'] &gt;&gt;&gt; model_load.load_state_dict(model_state, strict=True)
https://stackoverflow.com/questions/71308399/
Plotting contour of pytorch functions
I have a function like the one below: x0 = torch.tensor([1.5, .1]) Q = torch.tensor([[10.0, 6.0], [9.0, 8.0]]) def f1(x): z = x - x0 Qz = z @ Q return 0.5 * Qz@z How do I get a contour plot for this? x is a 2D tensor. I am messing up somewhere while using meshgrid.
First, let's make your code work with a batch of 2d points, that is, x of shape nx2: def f1(x): z = x - x0 # z of shape n-2 Qz = z @ Q # Qz of shape n-2 return 0.5 * (Qz * z).sum(dim=-1) # we want output of size n and not n-n Now we can create a grid over which we want to plot f1(x): grid = torch.stack(torch.meshgrid(torch.linspace(-20., 20., 100), torch.linspace(-20., 20., 100), indexing='xy')) # convert the grid to a batch of 2d points: grid = grid.reshape(2, -1).T # get the output on all points in the grid out = f1(grid) # plot plt.matshow(out.detach().numpy().reshape(100,100)) You'll get:
https://stackoverflow.com/questions/71311100/
torchmetric calculate accuracy with threshold
How does torchmetrics.Accuracy threshold keyword work? I have the following setup: import torch, torchmetrics preds = torch.tensor([[0.3600, 0.3200, 0.3200]]) target = torch.tensor([0]) torchmetrics.functional.accuracy(preds, target, threshold=0.5, num_classes=3) output: tensor(1.) None of the values in preds have a probability higher than 0.5, why is it giving 100% accuracy?
threshold=0.5 sets each probability under 0.5 to 0. It is used only in case you are dealing with binary (which is not your case, since num_classes=3) or multilabel classification (which seems not the case because multiclass is not set). Therefore threshold is not actually involved. In your case, preds represents a prediction related to one observation. Its largest probability (0.36) is set at position 0, thus argmax(preds) and target are equal to 0, therefore accuracy is set to 1, because the prediction of the (only) observation is correct.
https://stackoverflow.com/questions/71315491/
BERT Classifier ValueError: Target size (torch.Size([4, 1])) must be the same as input size (torch.Size([4, 2]))
I'm training a Classifier Model but it's a few days that I cannot overcame a problem! I have the ValueError: Target size (torch.Size([4, 1])) must be the same as input size (torch.Size([4, 2])) error but actually it seems correct to me ! Indeed I used unsqueeze(1) to put them of the same size. WHat else I can try? Thank you! class SequenceClassifier(nn.Module): def __init__(self, n_classes): super(SequenceClassifier, self).__init__() self.bert = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME,return_dict=False) self.drop = nn.Dropout(p=0.3) self.out = nn.Linear(self.bert.config.hidden_size, n_classes) def forward(self, input_ids, attention_mask): _, pooled_output = self.bert( input_ids=input_ids, attention_mask=attention_mask ) output = self.drop(pooled_output) return self.out(output) model = SequenceClassifier(len(class_names)) model = model.to(device) EPOCHS = 10 optimizer = AdamW(model.parameters(), lr=2e-5, correct_bias=False) total_steps = len(train_data_loader) * EPOCHS scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=0, num_training_steps=total_steps ) weights=[0.5,1] pos_weight=torch.FloatTensor(weights).to(device) loss_fn=nn.BCEWithLogitsLoss(pos_weight=pos_weight) def train_epoch( model, data_loader, loss_fn, optimizer, device, scheduler, n_examples ): model = model.train() losses = [] correct_predictions = 0 for d in data_loader: input_ids = d[&quot;input_ids&quot;].to(device) attention_mask = d[&quot;attention_mask&quot;].to(device) targets = d[&quot;targets&quot;].to(device) outputs = model( input_ids=input_ids, attention_mask=attention_mask ) _, preds = torch.max(outputs, dim=1) targets = targets.unsqueeze(1) loss = loss_fn(outputs, targets) correct_predictions += torch.sum(preds == targets) losses.append(loss.item()) loss.backward() nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) optimizer.step() scheduler.step() optimizer.zero_grad() return correct_predictions.double() / n_examples, np.mean(losses) %%time history = defaultdict(list) best_accuracy = 0 for epoch in range(EPOCHS): print(f'Epoch {epoch + 1}/{EPOCHS}') print('-' * 10) train_acc, train_loss = train_epoch( model, train_data_loader, loss_fn, optimizer, device, scheduler, len(df_train) ) print(f'Train loss {train_loss} accuracy {train_acc}') val_acc, val_loss = eval_model( model, val_data_loader, loss_fn, device, len(df_val) ) print(f'Val loss {val_loss} accuracy {val_acc}') print() history['train_acc'].append(train_acc) history['train_loss'].append(train_loss) history['val_acc'].append(val_acc) history['val_loss'].append(val_loss) if val_acc &gt; best_accuracy: torch.save(model.state_dict(), 'best_model_state.bin') best_accuracy = val_acc ValueError: Target size (torch.Size([4, 1])) must be the same as input size (torch.Size([4, 2])) EDIT I have a binary classifier problem, indeed i have 2 classes encoded 0 (&quot;bad&quot;) and 1 (&quot;good&quot;).
In case anyone stumbles on this like I did, I'll write out an answer since there aren't a lot of google hits for this target size/input size error and the previous answer has some factual inaccuracies. Unlike the previous answer would suggest, the real problem isn't with the loss function but with the output of the model.nn.BCEWithLogitsLoss is completely fine for multi-label and multi-class applications. Chiara updated her post saying that in fact she has a binary classification problem, but even that should not be a problem for this loss function. So why the error? The original code has: outputs = model( input_ids=input_ids, attention_mask=attention_mask ) _, preds = torch.max(outputs, dim=1) This means &quot;Run the model, then create preds with the row indeces of the highest output of the model&quot;. Obviously, there is only a &quot;index of highest&quot; if there are multiple predicted values. Multiple output values usually means multiple input classes, so I can see why Shai though this was multi-class. But why would we get multiple outputs from a binary classifier? As it turns out, BERT (or Huggingface anyway) for binary problems expects that n_classes is set to 2 -- setting classes to 1 puts the model in regression mode. This means that under the hood, binary problems are treated like a two-class problem, outputting predictions with the size [2, batch size] -- one column predicting the chance of it being a 1 and one for the chance of it being 0. The loss fucntion throws an error because it is supplied with only one row of one-hot encoded labels: targets = d[&quot;targets&quot;].to(device) so the labels have dimensions [batch size] or after the unsqueeze, [1, batch size]. Either way, the dimensions don't match up. Some loss functions can deal with this fine, but others require the exact same dimensions. To make things more frustrating, for version 1.10, nn.BCEWithLogitsLoss requires matching dimensions but later versions do not. One solution may therefore be to update your pytorch (version 1.11 would work for example). For me, this was not an option, so I ended up going with a different loss function. nn.CrossEntropyLoss, as suggested by Shai, indeed does the trick as it accepts any input with the same length. In other words, they had a working solution for the wrong reasons.
https://stackoverflow.com/questions/71318599/
Pytorch Custom dataset's __getitem__ calls itself indefinitely when handling exception
I'm writing a script for my customdatset class but I get Index out of range error whenever I access data using for loop like so: cd = CustomDataset(df) for img, target in cd: pass I realized I might have a problem reading a few images (if they are corrupt) so I implemented a random_on_error feature which chooses a random image if something is wrong with the current image. And I'm sure that's where the problem is. As I've noticed that all the 2160 images in the dataset are read without any hiccups(i print the index number for every iteration) but the loop would not stop and reads the 2161st image which results in an Index out of range exception that gets handled by reading a random image. This continues forever. Here is my class: class CustomDataset(Dataset): def __init__(self, data: pd.DataFrame, augmentations=None, exit_on_error=False, random_on_error: bool = True): &quot;&quot;&quot; :param data: Pandas dataframe with paths as first column and target as second column :param augmentations: Image transformations :param exit_on_error: Stop execution once an exception rises. Cannot be used in conjunction with random_on_error :param random_on_error: Upon an exception while reading an image, pick a random image and process it instead. Cannot be used in conjuntion with exit_on_error. &quot;&quot;&quot; if exit_on_error and random_on_error: raise ValueError(&quot;Only one of 'exit_on_error' and 'random_on_error' can be true&quot;) self.image_paths = data.iloc[:, 0].to_numpy() self.targets = data.iloc[:, 1].to_numpy() self.augmentations = augmentations self.exit_on_error = exit_on_error self.random_on_error = random_on_error def __len__(self): return self.image_paths.shape[0] def __getitem__(self, index): image, target = None, None try: image, target = self.read_image_data(index) except: print(f&quot;Exception occurred while reading image, {index}&quot;) if self.exit_on_error: print(self.image_paths[index]) raise if self.random_on_error: random_index = np.random.randint(0, self.__len__()) print(f&quot;Replacing with random image, {random_index}&quot;) image, target = self.read_image_data(random_index) else: # todo implement return logic when self.random_on_error is false return if self.augmentations is not None: aug_image = self.augmentations(image=image) image = aug_image[&quot;image&quot;] image = np.transpose(image, (2, 0, 1)) return ( torch.tensor(image, dtype=torch.float), torch.tensor(target, dtype=torch.long) ) def read_image_data(self, index: int) -&gt; ImagePlusTarget: # reads image, converts to 3 channel ndarray if image is grey scale and converts rgba to rgb (if applicable) target = self.targets[index] image = io.imread(self.image_paths[index]) if image.ndim == 2: image = np.expand_dims(image, 2) if image.shape[2] &gt; 3: image = color.rgba2rgb(image) return image, target I believe the problem is with the except block (line 27) in __getitem__(), as when I remove it the code works fine. But I cannot see what the problem here is. Any help is appreciated, thanks
How do you expect python to know when to stop reading from your CustomDataset? Defining a method __getitem__ in CustomDataset makes it an iterable object in python. That is, python can iterate over CustomDataset's items one by one. However, the iterable object must raise either StopIteration or IndexError for python to know it reached the end of the iterations. You can either change the loop to expicitly use the __len__ of your dataset: for i in range(len(cd)): img, target = cd[i] Alternatively, you should make sure you raise IndexError from your dataset if index is outside the range. This can be done using multiple except clauses. Something like: try: image, target = self.read_image_data(index) except IndexError: raise # do not handle this error except: # treat all other exceptions (corrupt images) here ...
https://stackoverflow.com/questions/71319485/