How to avoid “CUDA out of memory” in PyTorch

Although import torch torch.cuda.empty_cache() provides a good alternative for clearing the occupied cuda memory and we can also manually clear the not in use variables by using, import gc del variables gc.collect() But still after using these commands, the error might appear again because pytorch doesn’t actually clears the memory instead clears the reference to … Read more

How to fix RuntimeError “Expected object of scalar type Float but got scalar type Double for argument”?

Reference is from this github issue. When the error is RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #4 ‘mat1’, you would need to use the .float() function since it says Expected object of scalar type Float. Therefore, the solution is changing y_pred = model(X_trainTensor) to y_pred = model(X_trainTensor.float()). … Read more

Pytorch tensor to numpy array

I believe you also have to use .detach(). I had to convert my Tensor to a numpy array on Colab which uses CUDA and GPU. I did it like the following: # this is just my embedding matrix which is a Torch tensor object embedding = learn.model.u_weight embedding_list = list(range(0, 64382)) input = torch.cuda.LongTensor(embedding_list) tensor_array … Read more

RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same

You get this error because your model is on the GPU, but your data is on the CPU. So, you need to send your input tensors to the GPU. inputs, labels = data # this is what you had inputs, labels = inputs.cuda(), labels.cuda() # add this line Or like this, to stay consistent with … Read more

PyTorch preferred way to copy a tensor

TL;DR Use .clone().detach() (or preferrably .detach().clone()) If you first detach the tensor and then clone it, the computation path is not copied, the other way around it is copied and then abandoned. Thus, .detach().clone() is very slightly more efficient.– pytorch forums as it’s slightly fast and explicit in what it does. Using perflot, I plotted … Read more

pytorch – connection between loss.backward() and optimizer.step()

Without delving too deep into the internals of pytorch, I can offer a simplistic answer: Recall that when initializing optimizer you explicitly tell it what parameters (tensors) of the model it should be updating. The gradients are “stored” by the tensors themselves (they have a grad and a requires_grad attributes) once you call backward() on … Read more