user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
Mario4272 | Could not fetch URLhttps://download.pytorch.org/whl/test/cu118/accelerate/:There was a problem confirming the ssl certificate: HTTPSConnectionPool(host=‘download.pytorch.org’, port=443): Max retries exceeded with url: /whl/test/cu118/accelerate/ (Caused by SSLError(SSLCertVerificationError(1, ‘[SSL: CERTIFICATE_VERIFY_... | ptrblck | These warnings are expected if you provide an invalid URL.
E.g. take a look at this attempt to pip install numpy while also providing an invalid extra-index-url:
pip install --extra-index-url https://invalidurl.where.numpy.is.not.located.org/whl numpy
Looking in indexes: https://pypi.org/simple, h… |
Ameen_Ali | HelloI have saved a pytorch tensor which I have obtained from some optimization procedure, and I save it as a file.I have noticed that i get different values for the same tensor loaded in each time I load it.First try:tensor([[ 0.0423, 0.0015, 0.0025, ..., -0.0053, -0.0032, 0.0013],
[ 0.0048, 0.0129, -0.01... | ptrblck | Looks like a bug assuming the file didn’t change. Could you update PyTorch and check if you still observe this issue? |
phisanti | Hi, this is my first time building a model with Pytorch, so I am translating a unit from TensorFlow. Thus, I was wondering if someone could give me a sanity check that the model looks valid:class UNet(nn.Module):
def __init__(self, in_channels=1, out_channels=1, init_features=64, pooling_steps=2):
super(UNe... | ptrblck | I don’t see anything obviously wrong in the model implementation.
For mixed-precision training checkthis tutorial. |
LinglanZhao | By switchingeval_testset = Falsetoeval_testset = Truein the above codes (i.e., whether iterating over a deterministic dataloader with shuffle=False and fixed transforms), the program with a fixed seed gets different results:import torch
import numpy as np
import random
import torchvision
import torchvision.transforms a... | ptrblck | Creating the base_seed should be responsible for this behavior as seenhere. |
u7122029 | So let’s say I have arrayAand the indexing arrayidxsas followsA = torch.Tensor([[8, 3, 5],
[7, 6, 1],
[2, 4, 9]])
idxs = torch.Tensor([[0, 2],
[1, 2],
[2, 0]]).int()I want to find a fast method of indexing where the first row ofidxsindexes th... | ptrblck | Your code doesn’t work for me and fails with:
A = torch.Tensor([[8, 3, 5],
[7, 6, 1],
[2, 4, 9]])
idxs = torch.Tensor([[0, 2],
[1, 2],
[2, 0]]).int()
A[:, idxs][torch.eye(len(A))]
# IndexError: tensors used as indices mu… |
Verner_Mednis | That’s what it does.ChatGPT suggested to try running:"import torchprint(torch._version_)print(torch.cuda.is_available())print(torch.version.cuda)print(torch.cuda.nccl.version())" before trying the llama chatbot.The only one that didn’t work was “print(torch.cuda.nccl.version())” with the error:“Traceback (most recent c... | ptrblck | Your binary does not ship with NCCL as it’s not supported on Windows.
I don’t know what you are trying to do exactly, but you won’t be able to use NCCL for a multi-GPU run and would need to use e.g. Gloo. |
heth27 | I want to train an autoencoder, where the encoder and decoder get created with some complex rules.I was wondering why I cannot calculate the encoder matrix from stacked parameters in init, but instead need to do it in forward() (see commented lines that don’t work). Are the combined parameters somehow registered, or di... | ptrblck | Yes, you would need to rebuild the tensor in the forward to allow the gradients to properly backpropagate to the registered parameters. |
stevethesteve | I’d like to do data augmentation and feature extraction on the fly. However, this is computationally expensive. Is there a way to pre-compute a minibatch (data augmentation + feature extraction) on the CPU while thepreviousminibatch is being used to train the model on the GPU? | ptrblck | Yes, by setting num_workers>=1 in the DataLoader multiple processes will be spawned which will preload the batches in the background. |
mihai145 | I have defined a small neural net and tried to train it. However, the loss did not have requires_grad set - that was curious. I set a breakpoint in the forward method of my neural net, and none of the intermediate variables created (embs, means, sim, out) had requires_grad set.Here is my code:class Cbow(nn.Module):
... | ptrblck | Did you try to add debug print statements into the forward to check this attribute? |
yaolr | My question is which of these two is faster and why?t.to("cuda")t.pin_memory().to("cuda")I have this question because:ThisCUDA blogis referenced a lot in related discussion and it says:the CUDA driver must first allocate a temporary page-locked, or “pinned”, host array, copy the host data to the pinned array, and then ... | ptrblck | Using pinned memory allows you to asynchronously transfer the data. This might be beneficial if you are running other workloads between the transfer and the actual data usage. However, if the next call would need to consume the data you wouldn’t expect to see any benefits from the async copy.
You c… |
luke1110 | I recently discovered some nondeterministic behaviour when using a jit script which is supposed to make the usage oftorch.sigmoidmore memory efficient, as described inPerformance Tuning Guide — PyTorch Tutorials 2.2.0+cu121 documentation.When executed on CPU bothtorch.tanhandtorch.sigmoidlead to different results for t... | ptrblck | torch.jit.script is able to optimize the computation graph and add e.g. kernel fusions, which might not output bitwise-identical results compared to the eager execution. I don’t know what exactly is used on the CPU, but note that TorchScript is in maintenance mode and the current recommendation is t… |
HfCloud | Hi, I compiled pytorch1.13.1, built with CUDA (CUDA11.6),When I ran this code on the machine where pytorch was compiled, it worked properly, but when I put the compiled pytorch on another machine, (it was confirmed that torch.caua.is_available () is True), and I found wrong results on CUDA, as the following figure:imag... | ptrblck | That’s not the case and you will need to compile PyTorch for sm_80 to be able to run on your Ampere GPU. Minor versions can be compatible, e.g. sm_89 is compatible to sm_86 and sm_80. |
akt42 | In this simplified example, I wantalphato be learnable andpeto be constant. Below is my model:import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super().__init__()
self.alpha = nn.Parameter(torch.ones([10]))
pe = torch.arange(10)
self.regis... | ptrblck | You need to reassign the tensor if you move it to another device:
ip = ip.to("cuda") |
amm90 | I am trying to train a one embedding layer using masking.It takes a masked sentence of 10 tokens and predict the masked tokens.The values are the ids of the tokens in a vocabulary.E.g:. [223, 444, 1, 11, 53, 232, 1, 435, 12, 43]The target is the same sequence with all non-masked tokens are replaced by empty token 0:E.g... | ptrblck | I’m not sure I entirely understand you use case, but given the mentioned output shapes I would say (A) is the expected shape as generally nn.CrossEntropyLoss expects a model output in the shape [batch_size, nb_classes, *additional_dimensions]. |
adrianj | I’m trying to do some manual model pipelining simply by using .to(device) approach. I have a network that is built from some nested nn.Module classes. My initial idea was to do the movement of individual layers in the class constructors, and then everything should automatically be handled (except for input/output data ... | ptrblck | It works for me using:
import torch
import torch.nn as nn
class Encoder(nn.Module):
def __init__(self, device="cpu"):
super().__init__()
self.enc_blocks = nn.ModuleList([nn.Linear(1, 1).to(device) for i in range(3)])
self.device = device
def forward(self, x):
… |
citystrawman | I am trying to debug and watch the values of a code for studying machine learning. Here’s the code snippet:train_data = DataGenerator(lines[:num_train], input_shape, True) # num_train is 1066
......
gen_train = DataLoader(train_data, batch_size=4)
......
epochs = 20
for epoch in range(epochs):
total_train = 0
... | ptrblck | Check if these values represent borders with a static color by visualizing the images via e.g. matplotlib. |
citystrawman | I am a new learner and I am now learning vgg16.From the following image, vgg only calls maxpooling before FC-4096:image640×644 118 KBHowever, from its source code, a average pooling is called:def forward(self, x):
x = self.features(x)
x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.classifier(x)
... | ptrblck | No, it’s unrelated to overfitting and I’m unsure where this impression comes from. If the original shapes are used, the layer is a no-op since the activation shape has the desired output shape already. However, if the input shapes (and thus the intermediate activation shapes) change, you would recei… |
Waoush | On my machine I was able to train a CNN using:PyTorch 1.6.0 and
Cuda compilation tools, release 11.6, V11.6.112
Build cuda_11.6.r11.6/compiler.30978841_0I needed more memory to expand my testing, so I ported my code to Google CoLab using the T4 GPU instance. Every time I run the code, I keep getting an exception when ... | ptrblck | In the past other users saw similar issues and e.g. did not realize that additional folders were created thus increasing the class count. The targets won’t change themselves randomly. |
Manish_Seal | Goal:create a augmented dataset and concatenate it to the original dataset (CIFAR10)Attempt:import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd as autograd
from torch.autograd import Variable
import torch.optim
import augment
from torch.utils.data import ConcatDataset
from torchvisi... | ptrblck | The error is expected, since you need to access the internal dataset first before accessing its attribute:
dataset = datasets.MNIST(
root="./data",
download=False,
transform=transforms.ToTensor()
)
print(dataset.classes)
# ['0 - zero', '1 - one', '2 - two', '3 - three', '4 - four', '5 -… |
Diego_Lovison | I have the following codedevice = "cuda:0"
model.to(device)
for epoch in range(20000):
for data in dataloader:
inputs = data.to(device)
labels = data.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimize... | ptrblck | I’m still unsure if I’m misunderstanding the question, but the variables will be replaced and the previously used memory will be reused via the internal cache if possible:
import torch
data = torch.randn(1024, 1024, device="cpu")
print("allocated {:.3f}, in cache: {:.3f}".format(
torch.cuda.me… |
lynx276 | import numpy as npimport torchimport skfuzzy as fuzzfrom torch import nnimport torch.optim as optimfrom sklearn.metrics import mean_squared_error as msedef generate_random_params_antecedent():return [np.random.rand() , np.random.rand(), np.random.rand()]def generate_random_params_consequent():while True:a, b, c, d = np... | ptrblck | Your code is not executable and fails with:
NameError: name 'trimf' is not defined
Using self.trimf fails with:
TypeError: MamdaniANFIS.trimf() takes 2 positional arguments but 3 were given
The only pow usage I’m seeing is in:
return 1 / (1 + ((x - ci + epsilon) / (di + epsilon))**(2 * bi))
s… |
grid_world | I am trying to implement a Self-Organizing Map where for a given input sample, the best matching unit/winning unit is chosen based on (say) L2-norm distance between the SOM and the input. To implement this, I have:# Input batch: batch-size = 512, input-dim = 84-
z = torch.randn(512, 84)
# SOM shape: (height, width, in... | ptrblck | This should work:
# Input batch: batch-size = 512, input-dim = 84-
z = torch.randn(512, 84)
# SOM shape: (height, width, input-dim)-
som = torch.randn(40, 40, 84)
# Compute L2 distance for a single sample out of 512 samples-
dist_l2 = np.linalg.norm((som.numpy() - z[0].numpy()), ord = 2, axis = 2… |
learner1234 | Hi codersI am new to pytorch as I have just started today, I saw few examples in kaggle and try to adapt my cnn from tensorflow in torch to enable better gpu allocation. However, I am stuck in a shape problemI want to balance the data in train and test dataset so I have used train_test_split, have I applied it in the c... | ptrblck | I don’t fully understand your code since now you are applying torch.argmax twice on the output:
preds = torch.argmax(outputs, dim=1)
return torch.sum(preds.argmax(1) == labels).float().mean()
while you also claim you are using one-hot encoded targets.
My code snippet shows the expected and workin… |
pak_key | 循环训练、测试torch.manual_seed(42)torch.cuda.manual_seed(42)#循环次数epochs = 100将数据发送至设备X_blob_train,X_blob_test = X_blob_train.to(device),X_blob_test.to(device)y_blob_train,y_blob_test = y_blob_train.to(device),y_blob_test.to(device)循环for epoch in range(epochs):# 训练model_4.train()# 概率
y_logits = model_4(X_blob_train)
y_pred = ... | ptrblck | Add a return statement to the forward method of your model. |
mst72 | I use the following code:for k,v in model.named_parameters():
print(k)Only weight returned:base_model.model.model.embed_tokens.weight
base_model.model.model.layers.0.self_attn.q_proj.base_layer.weight
base_model.model.model.layers.0.self_attn.q_proj.lora_A.default.weight
base_model.model.model.layers.0.self_attn.q_... | ptrblck | Could you post the setup of the layer you are using? |
lu_97 | Hi, I’m training a model with a version of the ppo algorithm and get the following error:RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [64, 1]], which is output 0 of AsStridedBackward0, is at version 4; expected version 2 instead. Hint: ... | ptrblck | Based on your code snippet the error disappears when policy_t, value, and value_next_state are detached.
All these tensors are created from the model in a while loop where the inputs also have dependencies on the previous iteration in a recursive manner. After this while loop was performed for 5 ep… |
ddoron9 | hi, I’ve updated my old driver. after that torch cuda is disabled with this error code. Is there any way to know where the issue came from? Please give any tips.below is my current cuda versions.python3
Python 3.11.5 (main, Sep 11 2023, 13:54:46) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" fo... | ptrblck | No, cuDNN and PyTorch are unrelated to your issue as it seems you are not able to initialize your NVIDIA driver, so I would recommend reinstalling it. |
chocolate_fireball | Inhttps://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html, I see there are three scaled dot product attention algorithms.I am facing an interesting scenario where the kernels for flash and memory-efficient attention aren’t installed, but I get different results when I usewith tor... | ptrblck | I don’t fully understand this statement since PyTorch itself ships with the needed kernels. |
como | Hi,I want to get the gradient of attention map.So, I tried to inject the hook function in torch.nn.functional._scaled_dot_product_attention module.However, I cannot find any source code of _scaled_dot_product_attention in pytorch github.Where can I find it?Thank you, and Happy new year | ptrblck | You can find the source code on GitHub by following the link I’ve posted.
To manipulate it, you would need to git clone the repository, manipulate the corresponding files, and build PyTorch from source. |
provebison | Hi everyone,I am currently facing an issue when trying to load a checkpoint after training. The problem arises from a mismatch between the keys in thestate_dict, resulting in the following error message:RuntimeError: Error(s) in loading state_dict for MyLightningModule:
Missing key(s) in state_dict: "model.llm.embeddin... | ptrblck | I haven’t seen such an issue before pointing to missing parts of the keys.
Is this the only key that shows the mismatch? |
JamesDickens | Are the Dataloader and Dataset classes written in pure python or do they use any c++ bindings? | ptrblck | They should use pure Python:dataset.py,dataloader.py. |
mst72 | For example,I’m calculating dice loss right now.My pred shape is [8,2,512,512], representing batch, channel, H, WMy true label shape is [8,512,512], representing batch, H, WCalculating loss requires the same shape, how do I handle it? | ptrblck | If you are dealing with a multi-class segmentation, the shapes will work for nn.CrossEntropyLoss. |
tal123 | I have a fully convolutional network, (like YOLOv3 or SSD).The last layer uses K 1x1 kernels to produce a tensor of K predictions all over the feature map (i.e., a BxKxHxW tensor).I want those kernels to be linearly independent, i.e., that there will be no predictor that can be computed as a linear combination of the o... | ptrblck | You don’t need to manipulate the forward method and can add any auxiliary loss to the already computed loss as seen here:
conv = nn.Conv2d(1, 64, 1)
x = torch.randn(1, 1, 24, 24)
target = torch.randint(0, 64, (1, 24, 24))
criterion = nn.CrossEntropyLoss()
output = conv(x)
loss = criterion(output,… |
wongkenchiang97 | Hello, I’ve encounter Tensor dimension issue when callingforward()on line 80.螢幕擷取畫面 2024-03-01 2152571524×870 101 KBline 78 perform conv2d once, It succeed when I manuallyunsqueeze()the tensor beforeBatchNorm2d.This is the part describe howSequentialwill initialize underDoubleConv’s constructor.螢幕擷取畫面 2024-03-01 221112... | ptrblck | Why do you squeeze() the activation tensor after the relu layer?
By default PyTorch expects 4D inputs for 2D layers as [batch_size, channels, height, width]. Newer PyTorch releases accept also 3D inputs and assuming a batch size of 1. However, I don’t know if the C++ frontend supports if too for al… |
Allaye | so i am trying to implement the VGG network, everything in the paper, but i have when i am using the architecture that has a conv1-255 as part of it network. below is my codedef _make_convo_layers(architecture) -> torch.nn.Sequential:
"""
Create convolutional layers from the vgg architecture type passed... | ptrblck | In your code you are using nn.Conv1d which seems to be a typo:
elif (layer == 'Conv1-256'):
out_channels = 256
layers += [nn.Conv1d(256, out_channels, kernel_size=3, padding=1, stride=1), nn.ReLU()]
Replace it with nn.Conv2d and it should work. |
mlkonopelski | Let me know please if this is expected behaviour.class ModelB(nn.Module):
def __init__(self) -> None:
super().__init__()
self.layer = nn.Linear(1, 1)
def forward(self, x):
self.layer(x)
return x
class ModelA(nn.Module):
def __init__(self) -> ... | ptrblck | This is expected and you would need to usenn.ModuleList. The same limitations apply to parameters, too (where you would need to use nn.ParameterList instead). |
moo3030 | I am trying to train an inceptionV3 model with a batch size of 256. The whole dataset does not exceed 5MB and the size of the model is around 45MB, so i have no problem in loading the model and batches of data.the error i am getting looks like this:Screenshot 2024-02-28 at 5.32.05 PM916×895 133 KBThe code crashes in th... | ptrblck | The OOM might be expected since the forward activations, needed to compute the gradients, could take the majority of the memory as describedhere. |
AccessTommy | Description:Hello everyone,I am encountering an issue while working with PyTorch’s TransformerEncoderLayer, and I’m seeking some assistance from the community to resolve it.Problem:I am attempting to use PyTorch’s TransformerEncoderLayer in my code, specifically in the context of a Transformer-based model. However, whe... | ptrblck | Your datasets depend on unknown data and I assume the error should also be reproducible using random input tensors. Could you post the model initialization as well as the shapes of the tensors to reproduce the issue without the need to download the data? |
sanipanwala | Hello,I have two GPUs and during training, I’m getting below exception./cuda/IndexKernel.cu:92: operator(): block: [98,0,0], thread: [64,0,0] Assertion `-sizes[i] <= index && index < sizes[i] && "index out of bounds"` failed.
/cuda/IndexKernel.cu:92: operator(): block: [98,0,0], thread: [65,0,0] Assertion `-sizes[i] <=... | ptrblck | Rerun your code with blocking launches via CUDA_LAUNCH_BLOCKING=1 as described in your error message (which is missing here) and isolate the failing operation. Once done, check the inputs and the min/max values and make sure they are valid. |
mmabaei | Dear All,I am new to using PyTorch and Pyro with a GPU. I already have my model, but it takes a long time to run on a CPU. That’s why I’m considering shifting to GPU. However, I’m not sure if my system is running on the GPU or not, even thoughtorch.deviceis successfully set to CUDA. I’m wondering if theto.(device)comma... | ptrblck | The Windows Task Manager might be misleading as you would need to enable the compute tab as also describedhere.
Alternatively, use nvidia-smi as it should show the utilization.
However, assuming you’ve moved the data and model to the GPU it seems to work as you don’t see a hang, so I assume the o… |
samuel_beaussant | I am currently playing with the autograd engine to understand its implementation better. I have made up a very simple computation graph as shown in the code below :import torch
import torch.nn.functional as F
A = torch.arange(16, requires_grad = True, dtype=torch.float32)
B = torch.arange(32, requires_grad = True, d... | ptrblck | By creating the assignment:
C_ = C.reshape(4,1)
The previous issue is not caused by G being deleted, but its computation graph including the intermediate activations needed for the gradient computation. |
gholste | I am running mixed-precision training, converting my model’s outputs (float16) to numpy, and storing those outputs for later evaluation. I just noticed that all numpy arrays are rounded to 2 decimal points! Why would this happen?! This is very easily reproducible:import torch
x = torch.tensor([64.6250, 61.7812, 61.8750... | ptrblck | Increase the precision in numpy’s printoptions and it’ll show the same values:
np.set_printoptions(precision=4, floatmode="fixed")
print(x.numpy())
# [64.6250 61.7812 61.8750 64.7500 64.5000] |
TTeuZ | Hi, I’m a begginer in PyTorch and I’m running into a problem with CUDA.I want to finetune a MobileNetV3 to a Binary classification and the script seems to be OK, it shows that the cuda is available and the device is set to ‘cuda’ for all inputs, targets and models, but it seems that the GPU is not being used.Now, it to... | ptrblck | A good post about data loading bottlenecks can be foundhere.
However, you should also try to figure out what exactly might have changed between your previous run and now as it seems the data loading became the bottleneck now. E.g. did you move the data from a local SSD to a network storage, did yo… |
chinmaester | I have a dataset that has 16 channels. I want to use augmentations like crop and resize. Only problem is that torch expects images in PIL format that only supports upto 4 channels. | ptrblck | torchvision.transform accepts tensors, too, and should work on image tensors with 16 channels:
x = torch.randn(16, 224, 224)
transform = transforms.Resize((200, 200))
out = transform(x)
print(out.shape)
# torch.Size([16, 200, 200]) |
Matt_Pitkin | With the recently introducednested tensors, if I create a nested tensor:import torch
a = torch.randn(20, 128)
nt = torch.nested.nested_tensor([a, a], dtype=torch.float32)and check itstype:type(nt)
torch.Tensorit just appears to be a regularTensorobject. If in a code, I wanted to differentiate between a nested tensor a... | ptrblck | You could check the is_nested attribute:
a = torch.randn(20, 128)
nt = torch.nested.nested_tensor([a, a], dtype=torch.float32)
print(a.is_nested)
# False
print(nt.is_nested)
# True |
IcarusWizard | Hi,I am a big fan of Conda and always use it to create virtual environments for my experiments since it can manage different versions of CUDA easily. Normally, I will install PyTorch with the recommended conda way, e.g.conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia. It has been work... | ptrblck | Yes, the pip wheels depend on the CUDA libs hosted on PyPI (e.g. nvidia-cuda-runtime-cu12, nvidia-cudnn-cu12, etc.) while the conda binaries use their corresponding packages from the nvidia conda channel.
I don’t know why the conda binaries do not work inside your container, but outside they seem t… |
Salman_Abbasi | HiI have two networks. The input data goes into network 1(to be trained), and then outputs data which goes to network 2(already trained).The output of network 2 is the loss data, which is compared with the input data to network 1. How can I train network 1 in pytorch, so that the gradients of network 1 are only updated... | ptrblck | You can simply pass the data as explained from network 1 to 2:
# setup
network1 = nn.Linear(10, 5)
network2 = nn.Linear(5, 10)
optimizer = torch.optim.Adam(network1.parameters(), lr=1e-3)
# freeze network2
for param in network2.parameters():
param.requires_grad = False
# input data
x = torch.… |
sabiha_afroz | I want to see the following function calls happening for Tensor.to(device) function and how the moving of a Tensor is working from CPU to GPU or GPU to CPU. I used the following code to get an idea of function calls.import torch
# Enable the profiler
with torch.autograd.profiler.profile() as prof:
# Your code snip... | ptrblck | copy_will call intocopy_impland dispatch to the stub which will eventually call into e.g.copy_device_to_deviceand there into the actual memcpy kernel. |
Abhishek_Varghese | I’m iterating through batches and deleting tensors once processed. But yet torch is not clearing up the memory. The model is Conv1D based feed forward network. Here’s the code and a screenshot of memory snapshot :Untitled717×859 41.2 KBThe memory screenshot clearly shows even after variable is deleted, somehow, the ten... | ptrblck | You are appending the output of the model to a list, which also stores the computation graphs and thus also intermediate tensors needed for the gradient computation. Deleting tensors manually won’t work as the list still stores a reference to the output and computation graph. |
mo.dify | Hi,During inference, I switch the batch norm modules to be training mode (batchnorm.train())And I manually change variance in every inference step by this code.for _, m in enumerate(encoder.modules()):
if isinstance(m, torch.nn.modules.batchnorm._BatchNorm):
print("Running Var", m.running_var)
m.tra... | ptrblck | This is expected since the running stats will only be used to normalize the input during eval(). During train() the running stats will be updated but not used to normalize the input as already explained. Maybe looking atthis manual implementationclarifies the behavior. |
Wencan | I want to test if my code correctly calculates the loss value. I think I first need to get a correct fixed loss value from CrossEntropyLoss.But …Why is the output of the following code not 0?import torch
import torch.nn as nn
inputs = torch.tensor([[1., 0., 0.],
[0., 1., 0.],
... | ptrblck | nn.CrossEntropyLoss expects logits (unbound), not probabilities, so pass large/small values instead of ones and zeros:
inputs = torch.tensor([[100., 0., 0.],
[0., 100., 0.],
[0., 0., 100.]])
labels = torch.tensor([0, 1, 2])
criterion = nn.CrossEntropyLos… |
Goldname | As I accumulate the model outputs by concatenating them, my CUDA memory grows significantly more than the size of my torch tensors: “out” and “lab”.I am accumulating the output because I need gradient accumulation downstream.I’ve simplified my code down to the pytorch classifier example code:import torch
import torchvi... | ptrblck | This is expected since you are storing the entire computation graphs with these tensors including the intermediate activations needed to compute the gradients during the backward pass.
You can call .backward() on each loss and accumulate the gradients directly in the .grad attribute. If you don’t… |
Goldname | For debugging I switched to a simple example based off pytorch training a classifier tutorial.import torch
import torchvision
import torchvision.transforms as transforms
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
batch_size = 4
trainset = ... | ptrblck | That’s not a fix and will just raise the other mentioned error.
You are running into:
RuntimeError: Trying to backward through the graph a second time ...
since you are accumulating the computation graphs between epochs.
Reset inp and lab after backward was called and it should work. |
Karls | I know that my issue may feel similar to others regarding repeatability of results, but I will try to def the statement that it is different. Why? Let me explain:I useOptunato optimize hyperparameters. Let’s consider this simplified objective function:# For repetability
torch.manual_seed(7)
random.seed(7)
np.random.see... | ptrblck | Setting the seed is one requirement but to get deterministic outputs you would also need to make sure the order of calls into the PRNG is equal in both scripts, which is not always trivial. E.g. take this code snippet demonstrates the effect:
torch.manual_seed(2809)
#nn.Linear(10, 10)
print(torch.r… |
vivekstorm | Hi Community,I would like to know how does dropout2d works? Does the weights are made to zero or output of activation of previous layer is made to zero in dropout? | ptrblck | Dropout layers masks the activations, not the weights or a layer:
drop = nn.Dropout2d()
x = torch.randn(1, 3, 4, 4)
out = drop(x)
print(out)
# tensor([[[[-1.2433, -2.1234, -1.8535, 0.1276],
# [ 5.8782, -2.1130, 1.8116, 1.3773],
# [-2.0260, -1.5322, 1.3397, 0.8360],
# … |
Adex | I am currently working on a timm model where I want to access some specific layers of the model.import torch
import timm
model=timm.create_model('timm/vit_base_patch16_224', pretrained=True)
for i in range(6):
strn='blocks.'+str([i])+'.mlp'
container=model.strnThis code is showing error. Although coddes like ... | ptrblck | Try setattr after accessing the layer via getattr. |
Caleb_Hill | Thanks in advance for any help. I’m using Ubuntu 22.04 for this.The error I’m getting is Couldn’t load custom C++ ops. This can happen if your PyTorch and torchvision versions are incompatible, or if you had errors while compiling torchvision from source. For further information on the compatible versions, checkGitHub ... | ptrblck | You don’t need to install a CUDA toolkit unless you want to build a custom CUDA extension or PyTorch from source.
However, it’s still unclear if that’s the case.
If you want to install matching torch and torchvision versions, use the install commands fromhere. |
sm226 | Traceback (most recent call last):File “/usr/local/lib/python3.10/dist-packages/gradio/queueing.py”, line 495, in call_predictionoutput = await route_utils.call_process_api(File “/usr/local/lib/python3.10/dist-packages/gradio/route_utils.py”, line 230, in call_process_apioutput = await app.get_blocks().process_api(File... | ptrblck | You are passing a floating point tensor to an nn.Embedding layer while an integer type is expected. |
jodunkel | Hello everyone,I would like to create a real-time anomaly checker for a sensor. To do this, I initialise aself.h_0&self.c_0in__init__and with eachforwardstep I save the state in it (very similar to that:https://discuss.pytorch.org/t/how-to-export-real-time-capable-lstm-to-onnx). But now I have the problem that at the b... | ptrblck | torch.jit.trace does not support data-dependent control flow or any other conditions, while torch.jit.script did. However, note that TorchScript in general is in maintenance mode and the current recommendation is to use torch.compile instead. |
BobMcDear | Hello,I would like to implement automatic mixed precision for some custom autograd functions, but decorating them usingcustom_fwd(cast_inputs=torch.float16)disables gradient tracking for the inputs unless they are already of the desired type (that is, when casting does not occur), as demonstrated below.import torch # V... | ptrblck | The reason for the difference is due to a cast and the disabled autograd inside the forward and backward methods unrelated to amp:
class IdentityFunc(torch.autograd.Function):
@staticmethod
def forward(ctx, input):
print(input.dtype, input.requires_grad)
a = input * 2
… |
hoya9802 | Hi,Could you please let me know whether “Geforce RTX 4070ti Super” support Pytorch-gpu.In below linkhttps://developer.nvidia.com/cuda-gpusit is specified that Geforce RTX 4070 ti is capable for CUDA Pytorch-gpu. But it didn’t mentioned anything about “4070ti Super”. “RTX 4070 Ti” and “RTX 4070 Ti Super” have different ... | ptrblck | Yes, the 4070 To Super is supported in all of our current binaries. |
peony | If I have the following tensor:tensor([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])I know I can split it into 5 chunks usingtorch.split(t, 5). However, I’m interested in automatically determining the number of splits based on the number of brackets enclosing the data. In this case, there’s o... | ptrblck | I assume you want to split in dim0 into single slices?
If so,
x = torch.tensor([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
x.split(split_size=1)
will work as it will return 5 slices. |
peony | I am implementingDatasetFolderand only replaced thedef __getitem__(self, index)of the DatasetFolder with the following:def __getitem__(self, index):
frames = []
framespath = []
"""
Args:
index (int): Index
Returns:
tuple: (sample, target) where target is ... | ptrblck | Your class is deriving fromtorch.utils.data.Dataset, which does not accept your input arguments in its __init__.
I guess you want to derive fromtorchvision.datasets.DatasetFolder, which does accept these arguments.
After fixing this you would need to fix the passed arguments as e.g. the required… |
bonen | I’m trying to install PyTorch on Ubuntu 20.04 with pip under Python 3.8.According to the official, PyTorch can work under Python 3.8, however, PyTorch requiresnetworkxpackage and the latest version of it requires Python 3.9+.So, before installing PyTorch, I have to install the older version ofnetworkxmanually bypip ins... | ptrblck | Yes, it should be OK since the CI uses a docker container withnetworkx==2.8.8so even older. |
michaeleisel | I want to deploy a standalone executable, for a variety of Linux execution environments, and use CUDA-enabled libtorch for it. To facilitate this, I want to package everything together in as small a binary as possible. One issue, aside from CUDA libraries, is libtorch_cuda.so. When I usenvpruneto try to make it smaller... | ptrblck | You could build PyTorch from source for the desired architectures only and wouldn’t need to prune them. This should also allow you to statically link other dependencies into PyTorch, but I’m unsure how well tested this approach is. |
Gillian | Can someone explaine what’s going on here ?Is it normal that tensor([71211144.]) is equal to both 71211143 and 71211144 ?t = torch.ones((1))tOut[22]: tensor([1.])t == 1Out[23]: tensor([True])t == 2Out[24]: tensor([False])t == 0Out[25]: tensor([False])t = torch.ones((1))t = t * 71211144tOut[28]: tensor([71211144.])t == ... | ptrblck | Yes, this is expected because of rounding as explained inthis post.
Also,this Wikipedia articlegives you the ranges. |
Matt_R | Possibly a silly question as I’m very much a noob, but I’m trying hard to learn. It’s my understanding that if you manually set a seed number, when printing the seed, it should not change. What am I missing here?import torch
print(f"Version: {torch.__version__}")
generator = torch.Generator(device="cuda").manual_se... | ptrblck | From thedocs:
seed() →intGets a non-deterministic random number from std::random_device or the current time and uses it to seed a Generator.
If you want to access the internal state, use get_state(). |
Srinjoy_Mukherjee | Hello All, I want to know the use of different packages that are installed for pytorch?conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidiaI am currently working on a project which has following installation command for pytorch.conda install pytorch==1.6.0 torchvision==0.7.0 cudatoolkit=1... | ptrblck | The main difference is the used CUDA version and the corresponding packaging.
In the past we relied on the cudatoolkit conda package and switched to pytorch-cuda metapackage defining all dependencies. |
m7md_hka | Hi,I believe there is a mistake in the PyTorch documentation regardingv2.RandomCrop. According to the documentation, thefillparameter can be used as follows:fill(numberortupleordict,optional) – Pixel fill value used when thepadding_modeis constant. The default is 0. If a tuple of length 3, it is used to fill the R, G, ... | ptrblck | Are you sure you are loading RGB images or do these contain an alpha channel? |
kai422 | Hello everyone,I’ve recently encountered a CUDA out of memory issue in my project when an “adding operation” is performed. I have no idea why “adding” will cause so much memory cost.As two tensors only cost ~1MB.IMG_45511263×937 275 KBDo you have any suggestions on how to debug this issue? | ptrblck | Check the shapes of both tensors as they might be broadcasted as seen here:
x = torch.randn(1024**3//4, 1, device="cuda")
y = torch.randn(1, 1024**3//4, device="cuda")
print(torch.cuda.memory_allocated()/1024**3)
# 2.0
z = x + y
# OutOfMemoryError: CUDA out of memory. Tried to allocate 268435456.0… |
smiling_happy_robot | I’ve been trying to run this code that is currently on github.GitHubGitHub - HomeroRR/rmm: This repository contains code for the paper RMM: A...This repository contains code for the paper RMM: A Recursive Mental Model for Dialog Navigation - GitHub - HomeroRR/rmm: This repository contains code for the paper RMM: A Recu... | ptrblck | I assume you are using nn.DataParallel? If so, note that it’s in maintenance mode and we generally recommend using DistributedDataParallel mainly for performance reasons but also functionality.
In this case nn.DataParallel will split the inputs along dim0 as it assumes this to be the batch dimensi… |
rynczakd | While installing PyTorch with GPU support on Ubuntu (22.04 LTS), I ran into a few unknowns.First of all, I checked that I have installed NVIDIA drivers using nvidia-smi command.What I got as a result was a table in which I found: NVIDIA-SMI 535.154.05 / Driver Version: 535.154.05 / CUDA Version 12.2.It shows that I hav... | ptrblck | This won’t matter as PyTorch ships with its own CUDA runtime dependencies and your locally installed CUDA toolkit will be used if you are building PyTorch from source or a custom CUDA extension.
I would recommend the latest CUDA toolkit (currently 12.1) as long as it’s compatible with your NVIDIA… |
CodingInProgress | I am using Jupyter in VSCode on Windows and this doesn’t seem to work for me. Here is a simple reproduction for it.import torch
class SomeIterableDataset(torch.utils.data.IterableDataset):
def __init__(self):
super(SomeIterableDataset).__init__()
def generate(self):
while True:
result = torch.rand... | ptrblck | This might be related tothis issue.
I think this issue is beyond the scope of Pytorch.
It should be an issue ofGitHub - ipython/ipython: Official repository for IPython itself. Other repos in the IPython organization contain things like the website, documentation builds, etc.Python multiproce… |
rohitdat | Hi, I am currently working on a project that involves designing a Reinforcement Learning framework aimed at generating high-quality radiofrequency (RF) pulses for Magnetic Resonance Imaging (MRI).My network architecture consists of aGated Recurrent Unit (GRU) cell followed by several dense layers. The final layer produ... | ptrblck | I don’t fully understand your use case and code.
E.g. in SharedNetwork you are using:
def forward(self, x, state_in):
gru_out, _ = self.gru(x, state_in)
dense_out = self.mlp(gru_out[:, -1, :])
return dense_out, gru_out
which is assigned as:
output, state_out = self.mo… |
dbalaban | Running on Ubuntu 20.04, with python version 3.10.6, I wrote the following test script to reproduce my error:import torch
import torch.nn as nn
from torch.optim import SGD
import faulthandler
faulthandler.enable()
print(f"torch version: {torch.__version__}")
x = torch.ones([1,3,10,10]).to("cuda:0")
conv1 = nn.Conv2d... | ptrblck | It seems your locally installed CUDA toolkit (including cuDNN) might be conflicting with the binaries.
Could you remove cuDNN (and other CUDA libs) from the LD_LIBRARY_PATH allowing PyTorch to use its own CUDA dependencies? |
hitbuyi | I have only one RTX3060, but I want to write my training code as form of DDP, hoping that DDP can compatible with one card condiction, is it possible? | ptrblck | DDP is compatible with single GPUs in a sense as it will fallback to a plain model and won’t use any distributed calls. |
tlkahn | Can anyone kindly take a look at my jupyter notebook and kindly let me know what part I did is erroneous? Thanks so much… Here is the unlearning model I spent a whole day working on:https://github.com/tlkahn/my-notebooks/blob/master/GAN-pytorch.ipynb | ptrblck | Just by skimming through your code, it seems you are freeing the discriminator:
class GAN(nn.Module):
"""GAN model"""
def __init__(self, generator, discriminator):
super().__init__()
self.generator = generator
self.discriminator = discriminator
for param in… |
LewsTherin | I’m trying to figure out what’s the best way to save a model trained with Pytorch and load it for inference, and I was wondering about the different possible approaches.Let’s say I successfully train a model, as far as I understand I can use:Complete Model Saving:# save the model
torch.save(model, saved_model_path)
# l... | ptrblck | Yes, you would need to recreate the model instance when saving the state_dict only, but note that saving the entire model requires you to exactly recreate the same file structure (including the source code of the model) on the target system, which is quite brittle and you will this see a lot of top… |
Yangmin | Hi, I was trying to debug about the"RuntimeError: cuda runtime error (710) : device-side assert triggered "by using Cuda_Launch_Blocking=1.It seems like setting the above environment variable to 1 slows down the training speed of whole code.Should I use this blocking=1 only in debugging and not in training?Does it red... | ptrblck | Yes, CUDA_LAUNCH_BLOCKING=1 is a debug env variable used to block kernel launches and to report the proper stacktrace once an assert is triggered. You should not use it in production, but only during debugging. |
SammyCui | Hello,I’m saving my model outputs as tensors by torch.save() under the no_grad() context manager. However, I noticed that from one job, tensors with shape (524, 720) and float32 consume ~200 MB disk usage, whereas from another set of tensors I created from a separate job with the same shape and dtype, they only take ~4... | ptrblck | This is a known issue observable when tensors are e.g. sliced:
x = torch.randn(524, 720)
torch.save(x, "1.pt")
stats = os.stat("1.pt")
print("{}MB".format(stats.st_size / 1024**2))
# 1.4401836395263672MB
x = torch.randn(10000, 10000)
y = x[:524, :720]
torch.save(y, "2.pt")
stats = os.stat("2.pt")
… |
Sai_Kishore | I want to calculate the gradient of the penultimate layer in a classifier wrt one of the hidden layers. Is there a provision for that | ptrblck | Something like this might work:
model = models.vgg16()
activation = {}
def get_activation(name):
def hook(model, args, output):
activation[name] = output
return hook
model.classifier[3].register_forward_hook(get_activation("fc"))
x = torch.randn(1, 3, 224, 224)
out = model(x)
gr… |
David_Gomez | Trying to implement data augmentation into a semantic segmentation training, I tried to apply some transformations to the same image and mask. If I rotate the image, I need to rotate the mask as well. The thing is RandomRotation, RandomHorizontalFlip, etc. use random seeds.I read somewhere this seeds are generated at t... | ptrblck | You can either use the functional API as describedhereor torchvision.transforms.v2 which allows to pass multiple objects as describedhere. |
paganpasta | I see almost all responses (tutorial,discussion) on training part of a network to include these 2 stepsSettargetnetwork parameters torequires_grad=FalsePass onlynon-targetparameters to the optimiserDoing any one of the above two can achieve the effect of not updating thetargetlayersMy take on the comparison is as follo... | ptrblck | Yes and this can be verified using this small code snippet:
import torch
import torch.nn as nn
model = nn.Sequential(
nn.Conv2d(3, 3, 3),
nn.Conv2d(3, 3, 3),
nn.Conv2d(3, 3, 3)
).cuda()
#model[1].weight.requires_grad = False
#model[1].bias.requires_brad = False
x = torc… |
theory_buff | I have a custom data generation pipeline which randomly samples 2 torch tensors (usingtorch.rand()), multiplies them and the productXis used as input to a PyTorch model. I setX.requires_grad_(False)before input to the model, to avoid any unnecessary gradient accumulation or backprop through the data sampling process.Qu... | ptrblck | No, this does not change the answer as long as U and V are created via torch.rand without setting requires_grad=True:
U = torch.rand((3, 3))
V = torch.rand((3, 3))
X = U @ V
print(X.grad_fn)
# None
print(X.requires_grad)
# False
This would change if U or V are created by a differentiable operation… |
Minennick | Hi all!I am currently training different diffusion models by using the [Imagen-pytorch] repository from Phil Wang, which works super fine when trained on a Nvidia A6000 GPU of a colleague. When trained on my Quadro RTX 8000 I do get nan Losses caused by nan gradients.Setups I experimented with:GPU: A6000Nvidia Driver V... | ptrblck | All used PyTorch binaries are old by now, so update to the latest stable or nightly release and rerun the tests. |
Pakpoom_Singkorapoom | HelloI am trying this exercise from pytorch tutorial.https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html#creating-the-networkI have a question aboutself.softmax = nn.LogSoftmax(dim=1).Could someone explain to me why dim=1???Thanks | ptrblck | PyTorch layers accept batched inputs where often the dimensions represent [batch_size, features, ...]. dim1 is therefore used to represent the number of classes in a classification use case. Applying a log_softmax on this dimension transforms logits to log probabilities and normalizes them over the … |
amperie | Hi there,I’m using forward hooks to look at the intermediate activations of a net as it goes through, works great.I’d like to be able to correlate/separate these activations by the input, so I can see just the activations for a particulr input, even if multiple inputs are being processed at the same time or while the h... | ptrblck | The activations will have a batch dimension containing containing the activation for each corresponding input. I.e. the activation at batch index i corresponds to input at index i. |
seer_mer | When setting a seed for multi-GPU training (DDP), should I set the same seed (e.g. seed=42) for all ranks? or should I set different seeds for different ranks? Or it doesn’t matter?I saw some people settingseed = args.seed + rankand also some people settingseed = args.seed. Would either of these cause any problem with ... | ptrblck | In a DDP setup the DistributedSampler is used to split the dataset and the local seed won’t break it. |
snowcat | envs:NVIDIA GeForce RTX 4090
torch==1.10.0 torchvision==0.11.0
cuda 11.3
(kornia==0.7.1)error:/opt/conda/conda-bld/pytorch_1634272168290/work/aten/src/ATen/native/cuda/ScatterGatherKernel.cu:111: operator(): block: [92,0,0], thread: [32,0,0] Assertion `idx_dim >= 0 && idx_dim < index_size && "index out of bounds"` fail... | ptrblck | The posted code snippet does not contain the failed scatter/gather operation.
Rerun the script with blocking launches as suggested in the error message, isolate the failing operation, and fix its indices as they are out of bounds:
Assertion `idx_dim >= 0 && idx_dim < index_size && "index out of bo… |
Salman_Abbasi | HiI have a network(dnn_Linear) output(v3). I first like to estimate a variables ss, which is Jacobian of this network w.r.t. to its parameters. Then I would like to backpropagate the loss, and later mutate gradients by multiplying with ss.Now i get the error:Trying to backward through the graph a second time"The part o... | ptrblck | Use retain_graph=True in the torch.autograd.grad call and remove it from the backward call assuming you don’t want to backpropagate another time. |
Salman_Abbasi | HiI have a model dnn_Linear. I would like to take derivative output(v2)of this model(dnn_Linear) w.r.t to its parameters.ss = torch.autograd.grad(v2,dnn_Linear.parameters(), grad_outputs=None, retain_graph=None, create_graph=False, only_inputs=True, allow_unused=False)I get the following error: grad can be implicitly c... | ptrblck | You would have to reduce the output or pass a gradient in the same shape as the output to solve the issue:
# setup
model = nn.Linear(10, 10)
x = torch.randn(1, 10)
out = model(x)
# fails
torch.autograd.grad(out, model.parameters())
# RuntimeError: grad can be implicitly created only for scalar ou… |
bash | i am trying to create a GAN this is my code architecturegenerator = Generator(in_channels=3, out_channels=1).to(device)The following is the Generator architecture# Pass the in and out (generator in_channels=3, out_channels=1)channels as argument to the Generator class constructor's parameter
generator = Generator(in_ch... | ptrblck | Yes, indeed:
concatenated = torch.cat((out1, out2, out3), dim=1)
creates the activation with 9 channels, as all outX tensors have 3 channels based on the out_channel setting in the corresponding layers creating them.
You might thus want to use self.concat_block = nn.Conv2d(out_channels * 3, out_… |
yrh | faced NCCL error while trying to run python training script:GitHubGitHub - xg-chu/CrowdDetContribute to xg-chu/CrowdDet development by creating an account on GitHub.Init multi-processing training...
d13186ffee3a:57:57 [0] NCCL INFO Bootstrap : Using [0]eth0:172.17.0.2<0>
d13186ffee3a:57:57 [0] NCCL INFO NET/Plugin : No... | ptrblck | NCCL 2.4.8 was released in 2019 (as well as the rest of the used libs), so update PyTorch to the latest stable or nightly release, which ships with newer and supported CUDA and NCCL versions. |
S_M | Hi all, how can I change a tensor [512,512,3,3] to [1024,512,3,3] using torch.nn?any help would be really appreciated. | ptrblck | You could e.g. repeat or interpolate the tensor, but more importantly you should still check what this dimension represents and if you really want to manipulate this dimension as it’s usually the batch dimension. |
zfan | Hi, I created a custom loss function in which the loss is calculated based on silhouette score. Here is my loss function:class ClusteringLoss(torch.nn.Module):
def __init__(self):
super(ClusteringLoss,self).__init__()
def forward(self, embeddingData, origData, k):
repData = embeddingData.deta... | ptrblck | You are explicitly detaching the output of your model, which will cut the computation graph and will thus explain why your model does not learn anything.
Besides that you are also using 3rd party libraries (in this case numpy and scikit-learn), which Autograd also won’t be able to understand. You w… |
SpikeCurtis | I’m training a DETR network with a Resnet101 backbone, usinghttps://github.com/facebookresearch/detrmodel & loss, but my own data loader and training code.During training in a batch of just 2 images, I end up allocating and then freeing a gigantic 8.7 GB block, which then gets cached by Pytorch and quickly becomes frag... | ptrblck | Thanks for the update!
It’s defined by the available algorithm and depends on the memory layout, data type, memory alignment etc.
No, I don’t know how much performance will be lost, as benchmarking is not even working.
I think the right approach would be to limit the cudnn workspace size requir… |
Ali_Youssef | Hello!I had a question regarding retaining the gradients of tensors when converting to numpy arrays to do computations, for example in the code below,kpts0andkpts1are tensors which require gradients, unfortunately, the poselib library only accepts numpy arrays as inputs, so I detach the tenors, convert to numpy then co... | ptrblck | Yes, operations on R and t will be tracked again and gradients thus also computed up to their creation. |
Mr.Panda | I am using pytorch on a jetson device. Here are the versions:torch: 2.1.0a0+41361538.nv23.06torchvision: 0.16.1I am using this piece of code to resize my images.transform = v2.Compose([
v2.Resize((224, 224), interpolation=v2.InterpolationMode.BILINEAR)
])I am getting the following error:AttributeError: module ‘torc... | ptrblck | Your torchvision release might be too new so build an older and compatible one. |
Ashish_Verma | Issue => AttributeError: module ‘optuna.trial’ has no attribute ‘suggest_int’Code:-- coding: utf-8 --“”"Created on Mon May 15 20:22:07 2023@author: Ashish“”"import torchimport numpy as npfrom optuna.trial import TrialStateimport pandas as pdfrom torch.utils.data import Dataset,DataLoaderimport optunafrom sklearn.model... | ptrblck | optuna.trial.Trial.suggest_int is a valid method as seenhereso you might need to update optuna in case it’s not available in your release. |
MahdiNazemi | When calculating the dot product of two half-precision vectors, it appears that PyTorch uses float32 for accumulation, and finally converts the output back to float16. Is it possible to carry out all operations in float16?import numpy as np
import torch
row = np.load("row.npy") # (1, 4096)
col = np.load("col.npy") #... | ptrblck | No, pure float16 accumulations are not provided as they were causing convergence issues in the past if I’m not mistaken. If you need them for some reason you might want to write a custom extension. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.