Datasets:
Download sft/validation.jsonl from samadpls/torchlight-threads: direct link, hf CLI and curl.
- Browser
- Download file 493 kB
-
https://huggingface.co/datasets/samadpls/torchlight-threads/resolve/main/sft/validation.jsonl
- Command line
-
hf download hf://datasets/samadpls/torchlight-threads/sft/validation.jsonl
-
curl -L -o validation.jsonl https://huggingface.co/datasets/samadpls/torchlight-threads/resolve/main/sft/validation.jsonl
493 kB
| {"messages":[{"role":"user","content":"ModuleNotFoundError: No module named 'torch._prims_common'\n\nHello. I am new to using Pytorch. I am setting up yolo nas for deepstream as per marcoslucianops deepstream yolo repo for yolo nas.\nWhile generating the onnx model (python3 export_yolonas.py -m yolo_nas_s -w yolo_nas_s_coco.pth --dynamic), I get the following error.\n\n$python3 export_yolonas.py -m yolo_nas_s -w yolo_nas_s_coco.pth --dynamic\nTraceback (most recent call last):\n File \"export_yolonas.py\", line 7, in <module>\n import torch.nn as nn\n File \"/opt/nvidia/deepstream/deepstream-6.2/.venv/lib/python3.8/site-packages/torch/nn/__init__.py\", line 1, in <module>\n from .modules import * # noqa: F403\n File \"/opt/nvidia/deepstream/deepstream-6.2/.venv/lib/python3.8/site-packages/torch/nn/modules/__init__.py\", line 1, in <module>\n from .module import Module\n File \"/opt/nvidia/deepstream/deepstream-6.2/.venv/lib/python3.8/site-packages/torch/nn/modules/module.py\", line 8, in <module>\n from torch._prims_common import DeviceLikeType\nModuleNotFoundError: No module named 'torch._prims_common'\n\nThe torch details are as below\nName: torch\nVersion: 2.3.1\nSummary: Tensors and Dynamic neural networks in Python with strong GPU acceleration\nHome-page: https://pytorch.org/\nAuthor: PyTorch Team\nAuthor-email: [email]\nLicense: BSD-3\nLocation: /opt/nvidia/deepstream/deepstream-6.2/.venv/lib/python3.8/site-packages\nRequires: filelock, fsspec, jinja2, networkx, nvidia-cublas-cu12, nvidia-cuda-cupti-cu12, nvidia-cuda-nvrtc-cu12, nvidia-cuda-runtime-cu12, nvidia-cudnn-cu12, nvidia-cufft-cu12, nvidia-curand-cu12, nvidia-cusolver-cu12, nvidia-cusparse-cu12, nvidia-nccl-cu12, nvidia-nvtx-cu12, sympy, triton, typing-extensions\nRequired-by: data-gradients, imagededup, super-gradients, torchaudio, torchmetrics, torchvision"},{"role":"assistant","content":"Hello Amulya!\n\nHere I propose a possible cause of your problem and its solution:\n\nThis error could have been caused by an incomplete install or uninstall of your torch package. To check, see if there is any directory called \"~orch\" in your python path (/opt/nvidia/deepstream/deepstream-6.2/.venv/lib/python3.8/site-packages). If there it is, simply delete the directory and uninstall and reinstall your torch package and the missing modules should be there in the new installation.\n\nThis worked for me."}],"kind":"answer","thread_id":205607,"url":"https://discuss.pytorch.org/t/modulenotfounderror-no-module-named-torch-prims-common/205607","created_at":"2024-07-02T09:04:26.213000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["GU_ZHONGXIANG"]} | |
| {"messages":[{"role":"user","content":"PyTorch Gradient Computation Fails When Not Using Entire Input Tensor\n\nI have a model that takes an input tensor , along with other inputs k and D. The model outputs several tensors, including cs_hat. When I compute gradients of cs_hat with respect to the first slice of inputs (inputs[:,:,0]), the gradient computation only succeeds if I compute it with respect to the entire tensor inputs instead of just the slice.\n\nHere is a simplified version of my code that illustrates the problem:\n\n```\nimport torch\nfrom torch import nn\n\nclass MyModel(torch.nn.Module):\n\n def __init__(self, input_size = 3 , ffn_size = 15, ffn_layers = 2, res_block_size = 15, res_block_layers = 2):\n super(MyModel, self).__init__()\n\n self.input_size = input_size\n self.activation = nn.LeakyReLU()\n\n self.ffn_size = ffn_size\n self.ffn_layers = ffn_layers\n self.res_block_size = res_block_size\n self.res_block_layers = res_block_layers\n\n self.linear_block_0 = self._make_linear_block(self.ffn_size, self.ffn_layers, input_size=self.input_size)\n\n self.final_layer_a = nn.Linear(self.res_block_size, 1, bias=False)\n self.final_layer_b = nn.Linear(self.res_block_size, 1, bias=False)\n self.final_layer_c = nn.Linear(self.res_block_size, 1, bias=False)\n self.final_layer_d = nn.Linear(self.res_block_size, 1, bias=False)\n\n def _make_linear_block(self, width, depth, input_size = None):\n\n if input_size is None:\n linear_block = nn.ModuleList([nn.Linear(width , width), self.activation])\n else:\n linear_block = nn.ModuleList([nn.Linear(input_size , width), self.activation])\n\n for _ in range(depth - 1):\n linear_block.append(nn.Linear(width, width))\n linear_block.append(self.activation)\n\n linear_block_ = nn.Sequential(*linear_block)\n\n return linear_block_\n\n def forward(self, inputs,k,D):\n\n t = inputs[:,:,0]\n x = inputs[:,:,1]\n\n input_t = torch.cat([t,k.view(-1,1),D.view(-1,1)],dim = -1)\n\n z0 = self.linear_block_0(input_t)\n\n a = self.final_layer_a(z0)\n b = self.final_layer_b(z0)\n c = self.final_layer_c(z0)\n d = self.final_layer_d(z0)\n\n return a,b,c,d\n\n#Main\n\nmodel = MyModel()\n\ninputs = torch.tensor([[[0.4521, 0.5205]], [[0.3066, 0.6816]], [[0.0547, 0.9297]], [[0.3936, 0.9229]]], requires_grad=True) #supposed to be of size (batch_size,1 ,1)\n\nbatch_size = 4\n\nk = torch.randn(batch_size, requires_grad=True)\nD = torch.randn(batch_size, requires_grad=True)\n\n# Forward pass\noutputs = model(inputs, k, D)\ncs_hat = outputs[2] # Assuming cs_hat is the third output\n\n# Gradient computation that works\ncs_dt = torch.autograd.grad(cs_hat, inputs, grad_outputs=torch.ones_like(cs_hat), create_graph=True)[0]\n# Gradient computation that fails\ncs_dt = torch.autograd.grad(cs_hat, inputs[:,:,0], grad_outputs=torch.ones_like(cs_hat), create_graph=True)[0]\n```\n\nMy error message:\n```\nRuntimeError: One of the differentiated Tensors appears to not have been used in the graph. Set allow_unused=True if this is the desired behavior.\n```\n\nHow can I fix this without using the whole having to use the whole input sequence to compute gradients?"},{"role":"assistant","content":"This is expected since slicing a tensor is a differentiable operation creating a computation graph.\nIn your case the output of `inputs[:,:,0]` was indeed never used to create `cs_hat`.\nYou could explicitly create the slice and recreate a stacked tensor passed to the model as seen here:\n```python\na = inputs[:,:,0]\nb = inputs[:,:,1]\n\nc = torch.stack((a, b), dim=2)\n\n# Forward pass\noutputs = model(c, k, D)\ncs_hat = outputs[2] # Assuming cs_hat is the third output\n\ncs_dt = torch.autograd.grad(cs_hat, c, grad_outputs=torch.ones_like(cs_hat), create_graph=True)[0]\ncs_dt = torch.autograd.grad(cs_hat, a, grad_outputs=torch.ones_like(cs_hat), create_graph=True)[0]\n```\nThis allows you to compute the gradients w.r.t. `a`."}],"kind":"answer","thread_id":205613,"url":"https://discuss.pytorch.org/t/pytorch-gradient-computation-fails-when-not-using-entire-input-tensor/205613","created_at":"2024-07-02T09:56:36.911000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"RuntimeError: Trying to backward through the graph a second time [...]\n\nHi, I am trying to build an LSTM model. I am encountering this error:\n\n> File \"spam_detection_LSTM_01.py\", line 131, in <module>\n loss.backward()\n File \"/gpfs/software/Anaconda/envs/pytorch-latest/lib/python3.8/site-packages/torch/_tensor.py\", line 487, in backward\n torch.autograd.backward(\n File \"/gpfs/software/Anaconda/envs/pytorch-latest/lib/python3.8/site-packages/torch/autograd/__init__.py\", line 197, in backward\n Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass\nRuntimeError: 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.\n\nI have read several threads here with possible fixes and I have tried all of them arleady (hopefully correctly). However, the error still persists. My model class currently looks like this:\n```\nclass Network(nn.Module):\n def __init__(self, input_size=40, hidden_size=10, num_layers=1, batch_first=True):\n super(Network, self).__init__()\n self.hidden_size = hidden_size\n # our LSTM model\n self.LSTM = LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=batch_first)\n # final fully connected layers\n self.fc1 = Linear(10, 5)\n self.fc2 = Linear(5, 1)\n \n def forward(self, x):\n h0 = torch.zeros(1, x.size(0), self.hidden_size)\n c0 = torch.zeros(1, x.size(0), self.hidden_size)\n output, hidden = self.LSTM(x, (h0.detach(), c0.detach()))\n x = F.relu(self.fc1(output[:,-1,:].view(x.size(0), -1)))\n x = torch.sigmoid(self.fc2(x))\n return x.flatten(), hidden\n```\nI have tried many variations (for instance not including the \".detach()\" methods. I still get the same error. My training loop looks like this:\n```\nstart = time.time()\n# training\nfor epoch in range(epochs):\n running_loss = 0.0\n # hidden = model.init_hidden(batch_size)\n for i, data in enumerate(train_loader, 0):\n current = time.time()\n print(i, (current-start)/60)\n inputs, labels = data\n\n outputs, hidden = model(inputs)\n loss = criterion(outputs, labels.float())\n # running_loss += loss.item()\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n print('Finished Training')\n```\nDoes anyone know what's wrong with my code? Where am I \"trying to backward through the graph a second time\"? Thanks in advance!"},{"role":"assistant","content":"Your code works fine for me after adding the missing pieces:\n```python\nclass Network(nn.Module):\n def __init__(self, input_size=40, hidden_size=10, num_layers=1, batch_first=True):\n super(Network, self).__init__()\n self.hidden_size = hidden_size\n # our LSTM model\n self.LSTM = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=batch_first)\n # final fully connected layers\n self.fc1 = nn.Linear(10, 5)\n self.fc2 = nn.Linear(5, 1)\n \n def forward(self, x):\n h0 = torch.zeros(1, x.size(0), self.hidden_size)\n c0 = torch.zeros(1, x.size(0), self.hidden_size)\n output, hidden = self.LSTM(x, (h0.detach(), c0.detach()))\n x = F.relu(self.fc1(output[:,-1,:].view(x.size(0), -1)))\n x = torch.sigmoid(self.fc2(x))\n return x, hidden\n\nmodel = Network()\nN = 160\nx = torch.randn(N, 20, 40)\ndataset = TensorDataset(x, torch.randint(0, 2, (N, 1)))\ntrain_loader = DataLoader(dataset, batch_size=8)\n\ncriterion = nn.BCELoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\n\nfor epoch in range(100):\n for i, data in enumerate(train_loader, 0):\n inputs, labels = data\n \n outputs, hidden = model(inputs)\n loss = criterion(outputs, labels.float())\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n print(\"epoch {}, loss: {}\".format(epoch, loss.item()))\n\nprint('Finished Training')\n\n# epoch 0, loss: 0.708498477935791\n# epoch 1, loss: 0.7076647877693176\n# epoch 2, loss: 0.7070136070251465\n# ...\n# epoch 97, loss: 0.0009400603594258428\n# epoch 98, loss: 0.0009146835654973984\n# epoch 99, loss: 0.000890372262801975\n# Finished Training\n```"}],"kind":"answer","thread_id":205644,"url":"https://discuss.pytorch.org/t/runtimeerror-trying-to-backward-through-the-graph-a-second-time/205644","created_at":"2024-07-02T18:20:43.885000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"GH200 System RAM and VRAM\n\nWhen attempting to run a training run for a 7 billion parameter model, I receive this error:\n```\nOutOfMemoryError: CUDA out of memory. Tried to allocate 344.00 MiB. GPU 0 has a total capacity of 95.00 GiB of which 238.12 MiB is free. Including non-PyTorch memory, this process has 0 bytes memory in use. Of the allocated memory 92.96 GiB is allocated by PyTorch, and 667.94 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting max_split_size_mb to avoid fragmentation. See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF\n```\n\nWhen running ```torch.cuda.get_device_properties(0)```, torch returns ```CudaDeviceProperties(name='GH200 480GB', major=9, minor=0, total* memory=97280MB, multi_processor_count=132)```. Is the LPDDR5 memory not fully coherent with system memory? If so, is there anyway to expose it to pytorch without a custom allocator?"},{"role":"assistant","content":"No, you would need to use a custom allocator or custom memory pool as described in [this WIP PR](https://github.com/pytorch/pytorch/pull/125722)."}],"kind":"answer","thread_id":205666,"url":"https://discuss.pytorch.org/t/gh200-system-ram-and-vram/205666","created_at":"2024-07-03T02:54:57.390000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"RuntimeError: stack expects each tensor to be equal size, but got [1, 1024, 1024] at entry 0 and [4, 1024, 1024] at entry 1 Collate error on the key 'fixed_image' of dictionary data. MONAI hint: if your transforms intentionally create images of different\n\nI am doing a project about image registration. received this error:\n\nEpoch 0/99: 33%|████████████████████████████████████████████████████████████████████████▎ | 5/15 [00:04<00:05, 1.74batch/s]> collate dict key \"fixed_image\" out of 2 keys\n>> collate/stack a list of tensors\n>> E: stack expects each tensor to be equal size, but got [1, 1024, 1024] at entry 0 and [4, 1024, 1024] at entry 1, shape [torch.Size([1, 1024, 1024]), torch.Size([4, 1024, 1024])] in collate([metatensor([[[1.8903e-02, 1.6555e-02, 1.4817e-02, ..., 1.8006e-01,\n 1.8057e-01, 1.8318e-01],\n [1.7500e-02, 1.5912e-02, 1.5085e-02, ..., 1.7924e-01,\n 1.7876e-01, 1.8112e-01],\n [1.7203e-02, 1.4965e-02, 1.5309e-02, ..., 1.7940e-01,\n 1.7656e-01, 1.7810e-01],\n ...,\n [5.5115e-04, 1.3683e-04, 0.0000e+00, ..., 1.6299e-01,\n 1.6520e-01, 1.6168e-01],\n [1.5516e-03, 7.7386e-04, 2.7677e-05, ..., 1.6049e-01,\n 1.6329e-01, 1.6351e-01],\n [2.6995e-03, 1.3090e-03, 2.9158e-04, ..., 1.6152e-01,\n 1.6472e-01, 1.6307e-01]]]), metatensor([[[0.1033, 0.1383, 0.1528, ..., 0.1248, 0.1120, 0.0833],\n [0.1207, 0.1617, 0.1792, ..., 0.1439, 0.1293, 0.0963],\n [0.1208, 0.1617, 0.1793, ..., 0.1421, 0.1276, 0.0951],\n ...,\n [0.0073, 0.0099, 0.0111, ..., 0.1347, 0.1210, 0.0900],\n [0.0074, 0.0100, 0.0112, ..., 0.1343, 0.1206, 0.0898],\n [0.0064, 0.0085, 0.0095, ..., 0.1145, 0.1028, 0.0765]],\n\n [[0.1033, 0.1383, 0.1528, ..., 0.1248, 0.1120, 0.0833],\n [0.1207, 0.1617, 0.1792, ..., 0.1439, 0.1293, 0.0963],\n [0.1208, 0.1617, 0.1793, ..., 0.1421, 0.1276, 0.0951],\n ...,\n [0.0073, 0.0099, 0.0111, ..., 0.1347, 0.1210, 0.0900],\n [0.0074, 0.0100, 0.0112, ..., 0.1343, 0.1206, 0.0898],\n [0.0064, 0.0085, 0.0095, ..., 0.1145, 0.1028, 0.0765]],\n\n [[0.1033, 0.1383, 0.1528, ..., 0.1248, 0.1120, 0.0833],\n [0.1207, 0.1617, 0.1792, ..., 0.1439, 0.1293, 0.0963],\n [0.1208, 0.1617, 0.1793, ..., 0.1421, 0.1276, 0.0951],\n ...,\n [0.0073, 0.0099, 0.0111, ..., 0.1347, 0.1210, 0.0900],\n [0.0074, 0.0100, 0.0112, ..., 0.1343, 0.1206, 0.0898],\n [0.0064, 0.0085, 0.0095, ..., 0.1145, 0.1028, 0.0765]],\n\n [[0.1412, 0.1900, 0.2119, ..., 0.2119, 0.1900, 0.1412],\n [0.1645, 0.2213, 0.2469, ..., 0.2469, 0.2213, 0.1645],\n [0.1646, 0.2215, 0.2471, ..., 0.2471, 0.2215, 0.1646],\n ...,\n [0.1646, 0.2215, 0.2471, ..., 0.2471, 0.2215, 0.1646],\n [0.1645, 0.2213, 0.2469, ..., 0.2469, 0.2213, 0.1645],\n [0.1412, 0.1900, 0.2119, ..., 0.2119, 0.1900, 0.1412]]])])\n> collate dict key \"moving_image\" out of 2 keys\n>> collate/stack a list of tensors\nEpoch 0/99: 80%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 12/15 [00:06<00:01, 1.77batch/s]\nTraceback (most recent call last):\n File \"/project/med/Hassan_Ghavidel/transformer_target_localization/code/main_train_unsup_TransMorph.py\", line 269, in <module>\n train_val_test.train_val_model_unsupervised(model, train_loader, optimizer, config.loss_name, config.loss_weights,\n File \"/project/med/Hassan_Ghavidel/transformer_target_localization/code/auxiliary/train_val_test.py\", line 49, in train_val_model_unsupervised\n for train_batch_data in tepoch:\n File \"/project/med/Hassan_Ghavidel/TransMorph_Transformer_for_Medical_Image_Registration/myenv/lib/python3.8/site-packages/tqdm/std.py\", line 1181, in __iter__\n for obj in iterable:\n File \"/project/med/Hassan_Ghavidel/TransMorph_Transformer_for_Medical_Image_Registration/myenv/lib/python3.8/site-packages/torch/utils/data/dataloader.py\", line 628, in __next__\n data = self._next_data()\n File \"/project/med/Hassan_Ghavidel/TransMorph_Transformer_for_Medical_Image_Registration/myenv/lib/python3.8/site-packages/torch/utils/data/dataloader.py\", line 1333, in _next_data\n return self._process_data(data)\n File \"/project/med/Hassan_Ghavidel/TransMorph_Transformer_for_Medical_Image_Registration/myenv/lib/python3.8/site-packages/torch/utils/data/dataloader.py\", line 1359, in _process_data\n data.reraise()\n File \"/project/med/Hassan_Ghavidel/TransMorph_Transformer_for_Medical_Image_Registration/myenv/lib/python3.8/site-packages/torch/_utils.py\", line 543, in reraise\n raise exception\nRuntimeError: Caught RuntimeError in DataLoader worker process 0.\nOriginal Traceback (most recent call last):\n File \"/project/med/Hassan_Ghavidel/TransMorph_Transformer_for_Medical_Image_Registration/myenv/lib/python3.8/site-packages/monai/data/utils.py\", line 514, in list_data_collate\n ret[key] = collate_fn(data_for_batch)\n File \"/project/med/Hassan_Ghavidel/TransMorph_Transformer_for_Medical_Image_Registration/myenv/lib/python3.8/site-packages/torch/utils/data/_utils/collate.py\", line 265, in default_collate\n return collate(batch, collate_fn_map=default_collate_fn_map)\n File \"/project/med/Hassan_Ghavidel/TransMorph_Transformer_for_Medical_Image_Registration/myenv/lib/python3.8/site-packages/torch/utils/data/_utils/collate.py\", line 120, in collate\n return collate_fn_map[elem_type](batch, collate_fn_map=collate_fn_map)\n File \"/project/med/Hassan_Ghavidel/TransMorph_Transformer_for_Medical_Image_Registration/myenv/lib/python3.8/site-packages/monai/data/utils.py\", line 458, in collate_meta_tensor_fn\n collated = collate_fn(batch) # type: ignore\n File \"/project/med/Hassan_Ghavidel/TransMorph_Transformer_for_Medical_Image_Registration/myenv/lib/python3.8/site-packages/torch/utils/data/_utils/collate.py\", line 163, in collate_tensor_fn\n return torch.stack(batch, 0, out=out)\n File \"/project/med/Hassan_Ghavidel/TransMorph_Transformer_for_Medical_Image_Registration/myenv/lib/python3.8/site-packages/monai/data/meta_tensor.py\", line 282, in __torch_function__\n ret = super().__torch_function__(func, types, args, kwargs)\n File \"/project/med/Hassan_Ghavidel/TransMorph_Transformer_for_Medical_Image_Registration/myenv/lib/python3.8/site-packages/torch/_tensor.py\", line 1279, in __torch_function__\n ret = func(*args, **kwargs)\nRuntimeError: stack expects each tensor to be equal size, but got [1, 1024, 1024] at entry 0 and [4, 1024, 1024] at entry 1\n\nThe above exception was the direct cause of the following exception:\n\nTraceback (most recent call last):\n File \"/project/med/Hassan_Ghavidel/TransMorph_Transformer_for_Medical_Image_Registration/myenv/lib/python3.8/site-packages/torch/utils/data/_utils/worker.py\", line 302, in _worker_loop\n data = fetcher.fetch(index)\n File \"/project/med/Hassan_Ghavidel/TransMorph_Transformer_for_Medical_Image_Registration/myenv/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py\", line 61, in fetch\n return self.collate_fn(data)\n File \"/project/med/Hassan_Ghavidel/TransMorph_Transformer_for_Medical_Image_Registration/myenv/lib/python3.8/site-packages/monai/data/utils.py\", line 529, in list_data_collate\n raise RuntimeError(re_str) from re\nRuntimeError: stack expects each tensor to be equal size, but got [1, 1024, 1024] at entry 0 and [4, 1024, 1024] at entry 1\nCollate error on the key 'fixed_image' of dictionary data.\n\nMONAI hint: if your transforms intentionally create images of different shapes, creating your `DataLoader` with `collate_fn=pad_list_data_collate` might solve this problem (check its documentation).\n\nthe line that the code is complaining is (for train_batch_data in tepoch:) \nin train_val_test.py script located in auxiliary folder:\n\n # loop over all batches of data\n with tqdm.tqdm(train_loader, unit=\"batch\", initial=0) as tepoch:\n for train_batch_data in tepoch:\n tepoch.set_description(f\"Epoch {epoch}/{epoch_start + epoch_nr - 1}\")\n if wandb_usage:\n wandb.log({\"lr\": optimizer.param_groups[0]['lr']}) \n # clear stored gradients\n optimizer.zero_grad()\n \n # get batch of data\n train_inputs, train_targets = train_batch_data[\"moving_image\"].to(device), train_batch_data[\"fixed_image\"].to(device)\n\nand dataloader in main_train_unsup_TransMorph.py script are as follows:\n\ntrain_loader = DataLoader(train_ds, batch_size=config.batch_size, shuffle=False, num_workers=4)\nif config.unsupervised_validation:\n val_loader = DataLoader(val_ds, batch_size=config.batch_size, shuffle=False, num_workers=4)\nelse:\n val_loader = None\nif config.supervised_validation:\n val_loader_supervised = DataLoader(val_ds_supervised, batch_size=200, shuffle=False, num_workers=2)\nelse:\n val_loader_supervised = None\n \ncheck_data = monai.utils.first(train_loader)\n# print(f\"Shape of check data: {check_data[\"fixed_image\"].shape}\") # (h,w)\nfixed_image = check_data[\"fixed_image\"][0][0] # eg (2,1,224,224)\nmoving_image = check_data[\"moving_image\"][0][0]\n\ni dont have any clue how can i fix this issue. please help me.\nthis is the github link of the code:\nhttps://github.com/hasan-ghavidel/transformer_target_localization\ni am trying to use this datasets of chests:\nhttps://www.kaggle.com/datasets/nih-chest-xrays/data"},{"role":"assistant","content":"You can simply call `repeat` on the tensor inside the `__getitem__` method of your `Dataset`:\n```python\nx = torch.randn(1, 224, 224)\n\nif x.size(0) == 1:\n x = x.repeat(4, 1, 1)\n```\nThis code assumes that the transformed grayscale image has a single channel (the channel dimension could also be missing, so you might want to make sure it was created) and that you want to keep all 4 channels (and do not want to drop the alpha channel)."}],"kind":"answer","thread_id":205706,"url":"https://discuss.pytorch.org/t/runtimeerror-stack-expects-each-tensor-to-be-equal-size-but-got-1-1024-1024-at-entry-0-and-4-1024-1024-at-entry-1-collate-error-on-the-key-fixed-image-of-dictionary-data-monai-hint-if-your-transforms-intentionally-create-images-of-different/205706","created_at":"2024-07-03T16:02:58.907000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Torch.sum does not benefit from parallelism?\n\nThis is my time-taken (seconds) vs batch size for 1000 summation operations on a `NVIDIA A100-SXM4-80GB`\n\n[image]\n\nActual times: \n\n0.07381916046142578\n0.11852669715881348\n0.23033857345581055\n0.4577453136444092\n1.3883068561553955\n3.253286123275757\n6.985889911651611\n\nthis is my code\n\n```python\nimport torch\nimport time\n\nfor bs in [4, 8, 16, 32, 64, 128, 256]:\n tensor = torch.randn(bs, 512, 25000).to('cuda')\n\n start = time.time()\n for i in range(1000):\n torch.sum(tensor)\n\n print(time.time() - start)\n```\n\nnvidia-smi\n\n```\n+---------------------------------------------------------------------------------------+\n| NVIDIA-SMI 535.129.03 Driver Version: 535.129.03 CUDA Version: 12.2 |\n|-----------------------------------------+----------------------+----------------------+\n| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |\n| | | MIG M. |\n|=========================================+======================+======================|\n| 0 NVIDIA A100-SXM4-80GB On | 00000000:01:00.0 Off | 0 |\n| N/A 46C P0 302W / 500W | 12816MiB / 81920MiB | 100% Default |\n| | | Disabled |\n+-----------------------------------------+----------------------+----------------------+\n \n+---------------------------------------------------------------------------------------+\n| Processes: |\n| GPU GI CI PID Type Process name GPU Memory |\n| ID ID Usage |\n|=======================================================================================|\n+---------------------------------------------------------------------------------------+\n```\n\nAm I using too much memory and this is causing things to run slowly or something?"},{"role":"assistant","content":"Imagine you had a person you go to who does your sums for you. You pass them a box full of numbers and you ask them to sum them up. This person has to sum them one number at a time. If you were to have two people, you can roughly half the time by dumping the numbers from the box equally among the two people, the two people come together at the end and sum their own results. If you have three people, it becomes roughly one third of the work. But no matter how many people you have, if you double the quantity of numbers in the box then the time taken to complete the summation will double. Each person is a CUDA core, and the job of summing the numbers can be called a CUDA kernel."}],"kind":"answer","thread_id":205774,"url":"https://discuss.pytorch.org/t/torch-sum-does-not-benefit-from-parallelism/205774","created_at":"2024-07-05T01:05:12.594000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["Brock_Brown"]} | |
| {"messages":[{"role":"user","content":"Does the order of with torch.no_grad(): and model.eval() matter?\n\nDoes the order of with torch.no_grad(): and model.eval() matter?\nLet models be saved in a list model_list.\n```\nfor m in model_list:\n m.eval()\n with torch.no_grad():\n netout = m(x)\n print(netout)\n```\nOR\n```\nwith torch.no_grad():\n for m in model_list:\n m.eval()\n netout = m(x)\n print(netout)\n```\nIn the latter example we avoid multiple calls of `with torch.no_grad()`."},{"role":"assistant","content":"No, the order would not matter here and both codes should yield the same results.\nPersonally, I would move the `no_grad()` to the top to indicate that the following code won't track any gradients."}],"kind":"answer","thread_id":205937,"url":"https://discuss.pytorch.org/t/does-the-order-of-with-torch-no-grad-and-model-eval-matter/205937","created_at":"2024-07-08T13:36:37.454000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Added extra layers to ResNet18 model, getting unexpected results when using forward hook\n\nI want to use contrastive loss for image classification. Untill now, I was training a ResNet18 (torchvision.models.resnet18()), and it was doing ok. I want to use the contrastive triplet loss method to fine-tune so I created a network class like so:\n```\nclass Triplet_Net(nn.Module):\n def __init__(self, model: nn.Module):\n super().__init__()\n self.Feature_Extractor = model\n num_filters = self.Feature_Extractor.fc.in_features\n num_classes = 7\n self.Feature_Extractor.fc = nn.Linear(num_filters,num_classes) # the output I'm gonna need\n self.Triplet_Loss = nn.Sequential(nn.Linear(num_classes,2))\n def forward(self,x):\n features = self.Feature_Extractor(x)\n triplets = self.Triplet_Loss(features)\n return triplets\n```\nThen I loaded the weights of a previously trained pytorch ResNet18 model I had saved, and created a \"Triplet_Net\" with the same weights (I have confirmed that the loaded_model and triplet_model have the same weights after these lines of code).\n```\nloaded_model = torchvision.models.resnet18()\nloaded_model .load_state_dict(torch.load(model_path));\ntriplet_model = Triplet_Net(loaded_model )\ntriplet_model\n\n=====\n\nOutput:\nTriplet_Net(\n (Feature_Extractor): ResNet(\n (conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)\n (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (maxpool): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)\n (layer1): Sequential(\n (0): BasicBlock(\n (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n (1): BasicBlock(\n (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (layer2): Sequential(\n (0): BasicBlock(\n (conv1): Conv2d(64, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (downsample): Sequential(\n (0): Conv2d(64, 128, kernel_size=(1, 1), stride=(2, 2), bias=False)\n (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (1): BasicBlock(\n (conv1): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (layer3): Sequential(\n (0): BasicBlock(\n (conv1): Conv2d(128, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (downsample): Sequential(\n (0): Conv2d(128, 256, kernel_size=(1, 1), stride=(2, 2), bias=False)\n (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (1): BasicBlock(\n (conv1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (layer4): Sequential(\n (0): BasicBlock(\n (conv1): Conv2d(256, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (downsample): Sequential(\n (0): Conv2d(256, 512, kernel_size=(1, 1), stride=(2, 2), bias=False)\n (1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (1): BasicBlock(\n (conv1): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (avgpool): AdaptiveAvgPool2d(output_size=(1, 1))\n (fc): Linear(in_features=512, out_features=7, bias=True)\n )\n (Triplet_Loss): Sequential(\n (0): Linear(in_features=7, out_features=2, bias=True)\n )\n)\n```\nThe problem is, when using a forward hook to get the activations of the last fc layer of the ResNet part of the Triplet_Net I get different values than the ones I get when using the same exact hook on the original ResNet. I have no idea why this is happening. No additional training was done to the triplet_model so it should behave the same as loaded_model.\n\nBellow is part of the code I use to get the fc layer output either with the resnet (classic==True) or with the custom (classic==False) network.\n\n```\nif classic==True:\n hook = model.fc.register_forward_hook(get_activation('fc'))\nelse:\n hook = model.Feature_Extractor.fc.register_forward_hook(get_activation('fc'))\n \nwith torch.inference_mode():\n for batch, (X, y) in enumerate(dataloader):\n X, y = X.to(device), y.to(device)\n \n y_pred = model(X)\n fc_output = activation['fc']\n\nhook.remove()\n```"},{"role":"assistant","content":"Yeah that was it, thanks a lot!\n\nI was basically reinitializing the fc layer weights. The problem was solved when this line\n```\nself.Feature_Extractor.fc = nn.Linear(num_filters,num_classes)\n```\nwas removed."}],"kind":"answer","thread_id":205951,"url":"https://discuss.pytorch.org/t/added-extra-layers-to-resnet18-model-getting-unexpected-results-when-using-forward-hook/205951","created_at":"2024-07-08T15:30:53.519000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["bri"]} | |
| {"messages":[{"role":"user","content":"Added extra layers to ResNet18 model, getting unexpected results when using forward hook\n\nI want to use contrastive loss for image classification. Untill now, I was training a ResNet18 (torchvision.models.resnet18()), and it was doing ok. I want to use the contrastive triplet loss method to fine-tune so I created a network class like so:\n```\nclass Triplet_Net(nn.Module):\n def __init__(self, model: nn.Module):\n super().__init__()\n self.Feature_Extractor = model\n num_filters = self.Feature_Extractor.fc.in_features\n num_classes = 7\n self.Feature_Extractor.fc = nn.Linear(num_filters,num_classes) # the output I'm gonna need\n self.Triplet_Loss = nn.Sequential(nn.Linear(num_classes,2))\n def forward(self,x):\n features = self.Feature_Extractor(x)\n triplets = self.Triplet_Loss(features)\n return triplets\n```\nThen I loaded the weights of a previously trained pytorch ResNet18 model I had saved, and created a \"Triplet_Net\" with the same weights (I have confirmed that the loaded_model and triplet_model have the same weights after these lines of code).\n```\nloaded_model = torchvision.models.resnet18()\nloaded_model .load_state_dict(torch.load(model_path));\ntriplet_model = Triplet_Net(loaded_model )\ntriplet_model\n\n=====\n\nOutput:\nTriplet_Net(\n (Feature_Extractor): ResNet(\n (conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)\n (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (maxpool): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)\n (layer1): Sequential(\n (0): BasicBlock(\n (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n (1): BasicBlock(\n (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (layer2): Sequential(\n (0): BasicBlock(\n (conv1): Conv2d(64, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (downsample): Sequential(\n (0): Conv2d(64, 128, kernel_size=(1, 1), stride=(2, 2), bias=False)\n (1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (1): BasicBlock(\n (conv1): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (layer3): Sequential(\n (0): BasicBlock(\n (conv1): Conv2d(128, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (downsample): Sequential(\n (0): Conv2d(128, 256, kernel_size=(1, 1), stride=(2, 2), bias=False)\n (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (1): BasicBlock(\n (conv1): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (layer4): Sequential(\n (0): BasicBlock(\n (conv1): Conv2d(256, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (downsample): Sequential(\n (0): Conv2d(256, 512, kernel_size=(1, 1), stride=(2, 2), bias=False)\n (1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (1): BasicBlock(\n (conv1): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n (relu): ReLU(inplace=True)\n (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n )\n )\n (avgpool): AdaptiveAvgPool2d(output_size=(1, 1))\n (fc): Linear(in_features=512, out_features=7, bias=True)\n )\n (Triplet_Loss): Sequential(\n (0): Linear(in_features=7, out_features=2, bias=True)\n )\n)\n```\nThe problem is, when using a forward hook to get the activations of the last fc layer of the ResNet part of the Triplet_Net I get different values than the ones I get when using the same exact hook on the original ResNet. I have no idea why this is happening. No additional training was done to the triplet_model so it should behave the same as loaded_model.\n\nBellow is part of the code I use to get the fc layer output either with the resnet (classic==True) or with the custom (classic==False) network.\n\n```\nif classic==True:\n hook = model.fc.register_forward_hook(get_activation('fc'))\nelse:\n hook = model.Feature_Extractor.fc.register_forward_hook(get_activation('fc'))\n \nwith torch.inference_mode():\n for batch, (X, y) in enumerate(dataloader):\n X, y = X.to(device), y.to(device)\n \n y_pred = model(X)\n fc_output = activation['fc']\n\nhook.remove()\n```"},{"role":"assistant","content":"How large is the discrepancy? If it's not large, could be rounding errors. Some code where we can reproduce your error would be valuable."}],"kind":"clarification","thread_id":205951,"url":"https://discuss.pytorch.org/t/added-extra-layers-to-resnet18-model-getting-unexpected-results-when-using-forward-hook/205951","created_at":"2024-07-08T15:30:53.519000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["Brock_Brown"]} | |
| {"messages":[{"role":"user","content":"Correct way of aggregating scalar tensors into a single tensor without losing gradients?\n\nHey all! Let's suppose I have a non-jagged array of scalar tensors each with gradient information (e.g. the losses of a couple of different models). Is there an intended way of aggregating these together into a single tensor without losing gradient information?\n\nHere's a minimal example to demonstrate:\n\n```\nimport torch\nx1, x2, x3, x4 = torch.tensor([1., 2., 3., 4.])\nw = torch.nn.Parameter(torch.tensor(5.), requires_grad = True)\n\nl1, l2, l3, l4 = (x * w for x in [x1, x2, x3, x4])\nl = [\n [l1, l2],\n [l3, l4]\n]\nassert torch.tensor(l).grad_fn is None\n```\n\nCurrently to get around this I'm doing a double `torch.stack`, but I wonder if there's a cleaner solution? Could get especially nasty if you're working with an arbitrarily shaped `l`.\n\nThanks!"},{"role":"assistant","content":"Using `torch.stack` or `torch.cat` to create a single tensor in a differentiable way is the right approach."}],"kind":"answer","thread_id":206037,"url":"https://discuss.pytorch.org/t/correct-way-of-aggregating-scalar-tensors-into-a-single-tensor-without-losing-gradients/206037","created_at":"2024-07-10T00:59:27.480000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"What is commit hash of [PyTorch](https://github.com/pytorch/pytorch) repository for a particular nightly?\n\nSuppose I have a PyTorch Nightly installed on my system:\n```\n>>> import torch\n>>> torch.__version__\n'2.4.0.dev20240530+cu121'\n```\n\nWhich is the nightly released on 30th of June, 2024.\nI was wondering what is the corresponding commit hash in the [main PyTorch Github repository](https://github.com/pytorch/pytorch) based on which this particular nightly was built?\n\nI tried looking into the last commit id of 30th of June, 2024 on the main github page:\n[image]\n\nIf we take the lastest commit of 30th June, 2024, and view the PyTorch repository corresponding to that commit:\n[image]\n\nI see that files in `~/pytorch-venv/lib/python3.10/site-packages/torch` on my local machine (i.e. the 30th June, 2024 nightly), is different from the files under:\nhttps://github.com/pytorch/pytorch/tree/5f642579d6996ef2b4892d0f8d1ebf698d99be54/torch\n\nAny documentation on how nightlies are released?"},{"role":"assistant","content":"@Abhishek_Ghosh some additional information around this is available here\nhttps://discuss.pytorch.org/t/install-particular-pytorch-nightly/186853/6\n\nFor your nightly release , the matching commit is this one\nhttps://hud.pytorch.org/pytorch/pytorch/commit/0bbe39cc0e93abcde8ca1efa435c13bbe484b36b"}],"kind":"answer","thread_id":206060,"url":"https://discuss.pytorch.org/t/what-is-commit-hash-of-pytorch-https-github-com-pytorch-pytorch-repository-for-a-particular-nightly/206060","created_at":"2024-07-10T09:06:04.923000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["anantguptadbl"]} | |
| {"messages":[{"role":"user","content":"Autograd yielding None in a correct computational graph\n\nHi everyone! I'm trying to implement LISTA network (deepunfolded Iterative Soft Thresholding): in order to do so I implemented a custom layer and a network as follows: \n\nCustom layer:\n```\nclass LISTA_LAYER(nn.Module):\n def __init__(self, A):\n super().__init__()\n\n # Initialization of the learnable parameters\n\n self.W1 = nn.Linear(A.shape[0], A.shape[1], bias=False)\n self.W2 = nn.Linear(A.shape[1], A.shape[1], bias=False)\n\n self.beta = nn.Parameter(torch.ones(1, 1, 1), requires_grad=True) \n self.mu = nn.Parameter(torch.ones(1, 1, 1), requires_grad=True) \n \n # Apply Xavier uniform initialization\n nn.init.xavier_uniform_(self.W1.weight)\n nn.init.xavier_uniform_(self.W2.weight)\n\n def _shrink(self, x, beta):\n return beta * F.softshrink(x / beta, lambd=1)\n \n def forward(self, y, x): \n if x is None:\n x = torch.zeros(y.shape[0], A.shape[1], requires_grad=True)\n\n return self._shrink(x - self.mu*(self.W1(y) + self.W2(x)), \n self.beta)\n```\nCustom network:\n\n```\nclass LISTA_Net(nn.Module):\n def __init__(self, A, K = 5):\n super(LISTA_Net, self).__init__()\n\n # Number of layers <-> iterations\n self.K = K\n\n # Layers\n self.LISTA_layers = nn.ModuleList([LISTA_LAYER(A) for _ in range(self.K + 1)])\n\n def forward(self, y): \n x = self.LISTA_layers[0].forward(y,None)\n\n for i in range(1, self.K + 1):\n x = self.LISTA_layers[i].forward(y,x)\n\n return x\n```\n\nThe idea of LISTA is embodied in the following computational graph: \n[image]\n\nWhen I work out the main train loop I have None gradients everywhere, could you please help me figure out why? I mean, I checked that all the variables are seen as leaves of the computational graph looking at\n\n`list([p for p in model.parameters() if p.is_leaf])`\n\nat seing that all network parameters are in this list. \n\nThis is the main train loop once I instantiated the model:\n\n```\noptimizer = torch.optim.SGD(\n model.parameters(),\n lr=5e-05,\n momentum=0.9,\n weight_decay=0,\n )\n scheduler = torch.optim.lr_scheduler.StepLR(\n optimizer, step_size=50, gamma=0.1\n )\n loss_train = np.zeros((num_epochs,))\n loss_test = np.zeros((num_epochs,))\n # Main loop\n for epoch in range(num_epochs):\n model.train()\n train_loss = 0\n for _, (b_x, b_s) in enumerate(train_loader):\n s_hat = model.forward(b_x)\n loss = F.mse_loss(s_hat, b_s, reduction=\"sum\")\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n model.zero_grad()\n train_loss += loss.data.item()\n loss_train[epoch] = train_loss / len(train_loader.dataset)\n scheduler.step()\n```\n\nThanks in advance :)"},{"role":"assistant","content":"I cannot reproduce the issue using your model definition and this minimal code snippet:\n```python\nA = torch.randn(1, 1)\nmodel = LISTA_Net(A)\nx = torch.randn(1, 1)\nout = model(x)\nout.mean().backward()\n\nfor name, param in model.named_parameters():\n print(name, param.grad.abs().sum())\n\n# LISTA_layers.0.beta tensor(0.3581)\n# LISTA_layers.0.mu tensor(0.7568)\n# LISTA_layers.0.W1.weight tensor(0.5244)\n# LISTA_layers.0.W2.weight tensor(0.)\n# LISTA_layers.1.beta tensor(0.2156)\n# LISTA_layers.1.mu tensor(0.3776)\n# LISTA_layers.1.W1.weight tensor(0.3157)\n# LISTA_layers.1.W2.weight tensor(0.2401)\n# LISTA_layers.2.beta tensor(0.0812)\n# LISTA_layers.2.mu tensor(0.1312)\n# LISTA_layers.2.W1.weight tensor(0.1190)\n# LISTA_layers.2.W2.weight tensor(0.1515)\n# LISTA_layers.3.beta tensor(0.0349)\n# LISTA_layers.3.mu tensor(0.1621)\n# LISTA_layers.3.W1.weight tensor(0.0512)\n# LISTA_layers.3.W2.weight tensor(0.0867)\n# LISTA_layers.4.beta tensor(0.1457)\n# LISTA_layers.4.mu tensor(0.7042)\n# LISTA_layers.4.W1.weight tensor(0.2134)\n# LISTA_layers.4.W2.weight tensor(0.8921)\n# LISTA_layers.5.beta tensor(1.)\n# LISTA_layers.5.mu tensor(1.8967)\n# LISTA_layers.5.W1.weight tensor(1.4645)\n# LISTA_layers.5.W2.weight tensor(0.2895)\n```\nCould you post a minimal and executable code snippet reproducing the issue, please?"}],"kind":"answer","thread_id":206069,"url":"https://discuss.pytorch.org/t/autograd-yielding-none-in-a-correct-computational-graph/206069","created_at":"2024-07-10T12:59:53.863000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"DDP and Gradient Sync\n\nI am training a model with DDP and found that my gradients were not being synced after loss.backward() call. After debugging, I found that the reason was because I was manually turning off the gradients of parameters I did not want updated. This somehow prevents the synchronization of the param.grad fields of parameters that I care about. **I wonder if this is the intended behavior and if a warning should be thrown because otherwise the training proceeded with no errors.**\n\nInterestingly, when I turned on NCCL logs, I saw allreduce operations being logged. I'm hypothesizing that those are related to the allreduce operations for each bucket which precedes the final allreduce that writes to param.grad.\n\nA small toy example to showcase the issue is provided below.\n\n```\nimport torch\nimport torch.nn as nn\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nimport torch.distributed as dist\n\nimport os\ndef ddp_setup():\n dist.init_process_group(backend=\"nccl\")\n rank = os.environ[\"LOCAL_RANK\"]\n torch.cuda.set_device(int(rank))\n\nclass SimpleModel(nn.Module):\n def __init__(self, n_layers):\n super().__init__()\n self.layers = nn.ModuleList([nn.Linear(2, 2) for _ in range(n_layers)])\n def forward(self, x):\n output = []\n for layer in self.layers:\n x = layer(x)\n output.append(x)\n\n output = torch.stack(output, dim = 0)\n return output\n\ndef main():\n ddp_setup()\n rank = dist.get_rank()\n\n torch.manual_seed(420)\n\n # Create two layer linear model and wrap with DDP\n model = SimpleModel(2)\n model = DDP(model.to(rank), device_ids=[rank], output_device=rank)\n\n # Turn off gradients for later layers because I only need output from first\n for name, param in model.named_parameters():\n if \"1\" in name:\n param.requires_grad = False\n\n # Pass dummy data through and compute loss from first layer\n inp = torch.rand(2) + rank\n out = model(inp)\n loss = out[0].sum()\n loss.backward()\n\n # Log unsynced gradients\n for name, param in model.named_parameters():\n if \"bias\" not in name:\n print(f\"RANK: {rank}, Param: {name}, Grad: {param.grad}\")\n```\n\nwhich I run by \n\n` torchrun --standalone --nproc-per-node 2 script.py`\n\nwith output\n\n```\nRANK: 1, Param: module.layers.0.weight, Grad: tensor([[1.2448, 1.8644],[1.2448, 1.8644]], device='cuda:1')\nRANK: 1, Param: module.layers.1.weight, Grad: None\nRANK: 0, Param: module.layers.0.weight, Grad: tensor([[0.2448, 0.8644], [0.2448, 0.8644]], device='cuda:0') \nRANK: 0, Param: module.layers.1.weight, Grad: None\n```\n\nIf I do not turn the param.grad to False, the gradients are synced as expected."},{"role":"assistant","content":"Run a second iteration and the code will properly fail:\n```python\n[rank1]: RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one. This error indicates that your module has parameters that were not used in producing loss. You can enable unused parameter detection by passing the keyword argument `find_unused_parameters=True` to `torch.nn.parallel.DistributedDataParallel`, and by \n[rank1]: making sure all `forward` function outputs participate in calculating loss. \n[rank1]: If you already have done the above, then the distributed data parallel module wasn't able to locate the output tensors in the return value of your module's `forward` function. Please include the loss function and the structure of the return value of `forward` of your module when reporting this issue (e.g. list, dict, iterable).\n[rank1]: Parameter indices which did not receive grad for rank 1: 2 3\n[rank1]: In addition, you can set the environment variable TORCH_DISTRIBUTED_DEBUG to either INFO or DETAIL to print out information about which particular parameters did not receive gradient on this rank as part of this error\n```"}],"kind":"answer","thread_id":206096,"url":"https://discuss.pytorch.org/t/ddp-and-gradient-sync/206096","created_at":"2024-07-10T21:16:09.682000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Difference between target and input size\n\nI'm new to pytorch. I tried to run this code:\n\n```\nimport torchvision.transforms\nfrom torch.utils.data import DataLoader\nimport torch.utils.data.dataloader\nfrom torch import nn\nfrom torchsummary import summary\n\ndef train(\n mdl,\n train_dataloader,\n valid_dataloader,\n n_epoch,\n opt,\n loss,\n valid_step,\n save_path):\n min_valid_loss = float('inf')\n mdl = mdl.cpu()\n\n for e in range(0, n_epoch):\n mdl.train()\n train_loss = 0.0\n for i, (inp, out) in enumerate(train_dataloader):\n opt.zero_grad()\n pred = mdl(inp)\n ls = loss(pred, out) **# error raises here**\n ls.backward()\n opt.step()\n train_loss += ls.item()\n\n if e % valid_step != 0:\n continue\n\n mdl.eval()\n valid_loss = 0.0\n with torch.no_grad():\n for i, (inp, out) in enumerate(valid_dataloader):\n pred = mdl(inp)\n ls = loss(pred, out)\n valid_loss += ls.item()\n\n if valid_loss < min_valid_loss:\n p = save_path.format(\n en=n_epoch,\n vl=valid_loss,\n tl=train_loss)\n torch.save(mdl, p)\n\n best_state = mdl.state_dict()\n\n print('epoch: ' + str(e + 1))\n print('train loss: ' + str(train_loss / len(train_dataloader)))\n print('valid loss: ' + str(valid_loss / len(valid_dataloader)))\n print('\\n')\n\n return best_state\n\ntns = torchvision.transforms.Compose([\n torchvision.transforms.ToTensor()\n])\nds = torchvision.datasets.MNIST(root='data/dataset', train=True, download=True, transform=tns)\ndt = DataLoader(dataset=ds, batch_size=32, shuffle=True)\n\nmodel = nn.Sequential(\n nn.Conv2d(in_channels=1, out_channels=16, kernel_size=(3, 3)),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=(2, 2), stride=2),\n nn.Conv2d(in_channels=16, out_channels=32, kernel_size=(3, 3)),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=(2, 2), stride=2),\n nn.Flatten(start_dim=1, end_dim=-1),\n nn.Linear(800, 10),\n nn.LogSoftmax())\n\nsummary(model)\n\ntrain(\n mdl=model,\n train_dataloader=dt,\n valid_dataloader=dt,\n n_epoch=10,\n opt=torch.optim.Adam(params=model.parameters(), lr=0.1),\n loss=nn.BCELoss(),\n valid_step=10,\n save_path='')\n```\nbut I got this error:\n\n> ValueError: Using a target size (torch.Size([32])) that is different to the input size (torch.Size([32, 10])) is deprecated. Please ensure they have the same size.\n\nI know this is because of mismatch size between input size for loss function and out of predicted values. How can I fix this problem?"},{"role":"assistant","content":"`MNIST` is a multi-class classification dataset where each sample belongs to 1 of 10 targets.\nYour model looks alright and you should use `nn.NLLLoss` as the criterion instead of `nn.BCELoss` (which is used for a binary classification or a multi-label classification where each target belongs to 0, 1, or multiple classes)."}],"kind":"answer","thread_id":206129,"url":"https://discuss.pytorch.org/t/difference-between-target-and-input-size/206129","created_at":"2024-07-11T08:43:49.600000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"RuntimeError: Expected all tensors to be on the same device\n\nHello, I know it's because the tensors are on the different device, but I don't know why. Here is my code:\n\n```\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.distributions as dist\n\n# Xavier initializer\ndef xavier(shape):\n return torch.normal(mean=0.0, std=torch.sqrt(torch.tensor(2.0 / sum(shape))), size=shape)\n\nclass BayesianDenseLayer(nn.Module):\n \"\"\"A fully-connected Bayesian neural network layer\n\n Parameters\n ----------\n d_in : int\n Dimensionality of the input (# input features)\n d_out : int\n Output dimensionality (# units in the layer)\n name : str\n Name for the layer\n\n Attributes\n ----------\n losses : torch.Tensor\n Sum of the Kullback–Leibler divergences between\n the posterior distributions and their priors\n\n Methods\n -------\n forward : torch.Tensor\n Perform the forward pass of the data through\n the layer\n \"\"\"\n\n def __init__(self, d_in, d_out, name):\n\n super(BayesianDenseLayer, self).__init__()\n self.d_in = d_in\n self.d_out = d_out\n\n self.w_loc = nn.Parameter(xavier([d_in, d_out]))\n self.w_std = nn.Parameter(xavier([d_in, d_out]) - 6.0)\n self.b_loc = nn.Parameter(xavier([1, d_out]))\n self.b_std = nn.Parameter(xavier([1, d_out]) - 6.0)\n\n def forward(self, x, sampling=True):\n \"\"\"Perform the forward pass\"\"\"\n\n if sampling:\n # Flipout-estimated weight samples\n s = torch.bernoulli(torch.full(x.shape, 0.5)) * 2 - 1\n r = torch.bernoulli(torch.full((x.shape[0], self.d_out), 0.5)) * 2 - 1\n w_samples = F.softplus(self.w_std) * torch.randn(self.d_in, self.d_out)\n w_perturbations = r * torch.matmul(x * s, w_samples)\n w_outputs = torch.matmul(x, self.w_loc) + w_perturbations\n\n # Flipout-estimated bias samples\n r = torch.bernoulli(torch.full((x.shape[0], self.d_out), 0.5)) * 2 - 1\n b_samples = F.softplus(self.b_std) * torch.randn(self.d_out)\n b_outputs = self.b_loc + r * b_samples\n\n return w_outputs + b_outputs\n\n else:\n return torch.matmul(x, self.w_loc) + self.b_loc\n\n @property\n def losses(self):\n \"\"\"Sum of the KL divergences between priors + posteriors\"\"\"\n weight = dist.Normal(self.w_loc, F.softplus(self.w_std))\n bias = dist.Normal(self.b_loc, F.softplus(self.b_std))\n prior = dist.Normal(0, 1)\n return (dist.kl_divergence(weight, prior).sum() +\n dist.kl_divergence(bias, prior).sum())\n\nclass BayesianDenseNetwork(nn.Module):\n \"\"\"A multilayer fully-connected Bayesian neural network\n\n Parameters\n ----------\n dims : List[int]\n List of units in each layer\n name : str\n Name for the network\n\n Attributes\n ----------\n losses : torch.Tensor\n Sum of the Kullback–Leibler divergences between\n the posterior distributions and their priors,\n over all layers in the network\n\n Methods\n -------\n forward : torch.Tensor\n Perform the forward pass of the data through\n the network\n \"\"\"\n\n def __init__(self, dims, name):\n\n super(BayesianDenseNetwork, self).__init__()\n self.steps = nn.ModuleList()\n self.acts = []\n\n for i in range(len(dims) - 1):\n layer_name = name + '_Layer_' + str(i)\n self.steps.append(BayesianDenseLayer(dims[i], dims[i + 1], name=layer_name))\n self.acts.append(F.relu)\n\n self.acts[-1] = lambda x: x\n\n def forward(self, x, sampling=True):\n \"\"\"Perform the forward pass\"\"\"\n\n for i in range(len(self.steps)):\n x = self.steps[i](x, sampling=sampling)\n x = self.acts[i](x)\n\n return x\n\n @property\n def losses(self):\n \"\"\"Sum of the KL divergences between priors + posteriors\"\"\"\n return torch.sum(torch.stack([s.losses for s in self.steps]))\n\ndims = [10, 20, 30, 40]\nnetwork = BayesianDenseNetwork(dims=dims, name=\"network\")\nx = torch.randn(5, 10)\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nnetwork.to(device)\nx = x.to(device)\noutput = network(x)\nprint(f'output: {output.shape}')\nprint(network.losses)\n```\n\nthe problem is from:\n```\nfor i in range(len(self.steps)):\n x = self.steps[i](x, sampling=sampling)\n x = self.acts[i](x)\n\n return x\n```\nthis for loop. But I can't figure out why it causes different devices. Could you please help me figure out?\n\nthe error output is:\n```\nFile \"/var/lib/condor/execute/slot1/dir_1700200/Process/bnn.py\", line 217, in <module>\n output = network(x)\n File \"/var/lib/condor/execute/slot1/dir_1700200/miniconda3/envs/studio/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1051, in _call_impl\n return forward_call(*input, **kwargs)\n File \"/var/lib/condor/execute/slot1/dir_1700200/Process/bnn.py\", line 120, in forward\n x = self.steps[i](x, sampling=sampling)\n File \"/var/lib/condor/execute/slot1/dir_1700200/miniconda3/envs/studio/lib/python3.9/site-packages/torch/nn/modules/module.py\", line 1051, in _call_impl\n return forward_call(*input, **kwargs)\n File \"/var/lib/condor/execute/slot1/dir_1700200/Process/bnn.py\", line 54, in forward\n w_samples = F.softplus(self.w_std) * torch.randn(self.d_in, self.d_out)\nRuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!\n```"},{"role":"assistant","content":"You are creating new tensors in the `forward` which will be created on the CPU by default.\nUse the `.device` attribute of any parameter and move the newly created tensors to this device:\n```python\n def forward(self, x, sampling=True):\n \"\"\"Perform the forward pass\"\"\"\n\n if sampling:\n device = next(self.parameters()).device\n # Flipout-estimated weight samples\n s = torch.bernoulli(torch.full(x.shape, 0.5, device=device)) * 2 - 1\n r = torch.bernoulli(torch.full((x.shape[0], self.d_out), 0.5, device=device)) * 2 - 1\n w_samples = F.softplus(self.w_std) * torch.randn(self.d_in, self.d_out, device=device)\n w_perturbations = r * torch.matmul(x * s, w_samples)\n w_outputs = torch.matmul(x, self.w_loc) + w_perturbations\n\n # Flipout-estimated bias samples\n r = torch.bernoulli(torch.full((x.shape[0], self.d_out), 0.5, device=device)) * 2 - 1\n b_samples = F.softplus(self.b_std) * torch.randn(self.d_out, device=device)\n b_outputs = self.b_loc + r * b_samples\n\n return w_outputs + b_outputs\n\n else:\n return torch.matmul(x, self.w_loc) + self.b_loc\n```"}],"kind":"answer","thread_id":206165,"url":"https://discuss.pytorch.org/t/runtimeerror-expected-all-tensors-to-be-on-the-same-device/206165","created_at":"2024-07-11T21:47:29.910000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Numpy and pytorch backpropagation\n\nHello everyone,\n\n I have a question regarding backpropagation. If I have a tensor `X` that I'm using for backpropagation, and there's a constant `c`, if during an operation I compute `np.sqrt (c) × X` , will this cause any issue with the backpropagation process? \n\nThanks in advance,"},{"role":"assistant","content":"I assume you are wrapping this `numpy * torch` operation into `torch.compile` which will translate it to pure PyTorch ops? If so, multiplying with a constant won't cause any issues during the backpropagation."}],"kind":"answer","thread_id":206193,"url":"https://discuss.pytorch.org/t/numpy-and-pytorch-backpropagation/206193","created_at":"2024-07-12T11:36:53.751000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"How to know which triton version to build for a given pytorch version\n\nI am trying to make the inductor backend of torchdynamo work on Jetson AGX Orin (aarch64 iGPU system). I have to use torch version 2.3, and I compiled triton v2.1 and also the main branch from the source and installed it. However, both have compatibility issues, resulting in errors like no such package found triton.common etc. How can I know which branch or commit of triton I should compile to make it work with torch 2.3 (or any other version)?"},{"role":"assistant","content":"The Triton commit for a PyTorch release is listed in `.ci/docker/ci_commit_pins/triton.txt`, for example at https://github.com/pytorch/pytorch/blob/v2.3.0/.ci/docker/ci_commit_pins/triton.txt. If that commit isn't in your clone, fetch it by hash and check it out:\n\n```\ngit fetch origin 79c6c9b209a5692b9a895398f4f3a033f8f80415\ngit checkout 79c6c9b209a5692b9a895398f4f3a033f8f80415\n```"}],"kind":"answer","thread_id":206201,"url":"https://discuss.pytorch.org/t/how-to-know-which-triton-version-to-build-for-a-given-pytorch-version/206201","created_at":"2024-07-12T13:59:23.050000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["ahmedius2","ptrblck"]} | |
| {"messages":[{"role":"user","content":"Layer output inconsistent on CUDA\n\nI encountered inconsistent Conv2d layer outputs on CUDA, although on CPUs the outputs are consistent. The differences are bigger than the floating point precision, and switching to double precision did not help. Below is an example script. When I ran it for the second time, I also received an error about illegal memory access.\n\n```\n# example.py\n\nimport torch\nfrom torch.nn import Conv2d\n\ntorch.manual_seed(0)\n\nshape = (30, 3, 256, 256)\nx = torch.linspace(0, 1, shape[0] * shape[1] * shape[2] * shape[3]).view(shape)\nlayer = Conv2d(3, 1024, kernel_size=(16, 16), stride=(16, 16))\n\nprint('cpu:')\nprint(layer(x[:1]).mean((1, 2, 3)).item())\nprint(layer(x[:1]).mean((1, 2, 3)).item())\nprint(layer(x[:2]).mean((1, 2, 3))[:1].item())\nprint(layer(x[:2]).mean((1, 2, 3))[:1].item())\n\nx = x.to('cuda')\nlayer = layer.to('cuda')\n\nprint('cuda:')\nprint(layer(x[:1]).mean((1, 2, 3)).item())\nprint(layer(x[:1]).mean((1, 2, 3)).item())\nprint(layer(x[:2]).mean((1, 2, 3))[:1].item())\nprint(layer(x[:2]).mean((1, 2, 3))[:1].item())\n\nprint('cuda again:')\nprint(layer(x[:1]).mean((1, 2, 3)).item())\nprint(layer(x[:1]).mean((1, 2, 3)).item())\nprint(layer(x[:2]).mean((1, 2, 3))[:1].item())\nprint(layer(x[:2]).mean((1, 2, 3))[:1].item())\n\nlayer = layer.double()\nx = x.double()\n\nprint('cuda double precision:')\nprint(layer(x[:1]).mean((1, 2, 3)).item())\nprint(layer(x[:1]).mean((1, 2, 3)).item())\nprint(layer(x[:2]).mean((1, 2, 3))[:1].item())\nprint(layer(x[:2]).mean((1, 2, 3))[:1].item())\n```\n\nThe outputs I received are:\n\n```\n$ python example.py # first run\ncpu:\n0.0011005939450114965\n0.0011005939450114965\n0.0011005939450114965\n0.0011005939450114965\ncuda:\n0.0011005939450114965\n0.0005542933358810842\n0.0005991645157337189\n0.0011005939450114965\ncuda again:\n0.003864584257826209\n0.0011005939450114965\n0.0011006519198417664\n0.0011010946473106742\ncuda double precision:\n0.0011005939325371148\n0.0016997585289742778\n0.0004818475426274861\n0.0004950613530068367\n\n$ python example.py # second run\ncpu:\n0.0011005939450114965\n0.0011005939450114965\n0.0011005939450114965\n0.0011005939450114965\ncuda:\n0.0011005939450114965\n0.0011032642796635628\n0.0005991645157337189\n0.0011005939450114965\ncuda again:\n0.003864584257826209\n0.0011005939450114965\n0.0004513512831181288\n0.0010505157988518476\ncuda double precision:\n0.0011005939325371148\nTraceback (most recent call last):\n File \"/home/my_username/conv2d_cuda.py\", line 36, in <module>\n print(layer(x[:1]).mean((1, 2, 3)).item())\nRuntimeError: CUDA error: an illegal memory access was encountered\nCUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.\nFor debugging consider passing CUDA_LAUNCH_BLOCKING=1.\nCompile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.\n```"},{"role":"assistant","content":"I solved the problem by setting `CUDA_LAUNCH_BLOCKING=1`\n\n```\n$ CUDA_LAUNCH_BLOCKING=1 python example.py\ncpu:\n0.0011005939450114965\n0.0011005939450114965\n0.0011005939450114965\n0.0011005939450114965\ncuda:\n0.0011005939450114965\n0.0011005939450114965\n0.0011005939450114965\n0.0011005939450114965\ncuda again:\n0.0011005939450114965\n0.0011005939450114965\n0.0011005939450114965\n0.0011005939450114965\ncuda double precision:\n0.0011005939325371148\n0.0011005939325371148\n0.0011005939325371148\n0.0011005939325371148\n```\n\nThe error reappears if I set `CUDA_LAUNCH_BLOCKING=0`:\n\n```\n$ CUDA_LAUNCH_BLOCKING=0 python conv2d_cuda.py\ncpu:\n0.0011005939450114965\n0.0011005939450114965\n0.0011005939450114965\n0.0011005939450114965\ncuda:\n0.0011005939450114965\n0.0005014293710701168\n0.0005991645157337189\n0.0011005939450114965\ncuda again:\n0.003864584257826209\n0.0011005939450114965\n0.0011019300436601043\n0.0011007939465343952\ncuda double precision:\n0.0011005939325371148\nTraceback (most recent call last):\n File \"/home/daiweiz/hist-embs/conv2d_cuda.py\", line 36, in <module>\n print(layer(x[:1]).mean((1, 2, 3)).item())\nRuntimeError: CUDA error: an illegal memory access was encountered\nCUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.\nFor debugging consider passing CUDA_LAUNCH_BLOCKING=1.\nCompile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.\n```\n\nI looked it up and found that `CUDA_LAUNCH_BLOCKING=1` makes CUDA API calls blocking and synchronous. This might be the cause of the problem on my server."}],"kind":"answer","thread_id":206224,"url":"https://discuss.pytorch.org/t/layer-output-inconsistent-on-cuda/206224","created_at":"2024-07-12T20:11:47.069000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[6],"answer_authors":["davidz0123"]} | |
| {"messages":[{"role":"user","content":"CPU libtorch fails to find CUDA headers\n\nI am attempting to link to libtorch in my CMake project. I explicitly downloaded a CPU version of libtorch with no CUDA support (https://download.pytorch.org/libtorch/cpu/libtorch-win-shared-with-deps-2.3.1%2Bcpu.zip).\n\nHowever, when trying to build and link/include the library, it fails because it cannot find CUDA headers (which it shouldn't need because this is not a CUDA version).\n```\nC:\\Users\\[redacted]\\libtorch\\include\\c10\\cuda\\CUDAStream.h(3): fatal error C1083: Cannot open include file: 'cuda_runtime_api.h': No such file or directory\n```\n\nThis header file is part of CUDA itself. I have triple-checked that the version of the `\\libtorch\\` is indeed `2.3.1+cpu`, and is from the download."},{"role":"assistant","content":"Alright, I found the issue.\nMy project was explicitly including:\n```#include <c10/cuda/CUDACachingAllocator.h>```\nto allow manual freeing of CUDA cache (following memory clogging issues).\n\nThis header is still present in the CPU libtorch version for some reason, but from my testing, is normally not ever included/compiled. If you do include it from CPU torch without CUDA installed, the actual CUDA header includes from libtorch will unsurprisingly fail.\nSo it definitely is an issue on my part. Sorry for bothering!"}],"kind":"answer","thread_id":206234,"url":"https://discuss.pytorch.org/t/cpu-libtorch-fails-to-find-cuda-headers/206234","created_at":"2024-07-13T02:37:48.486000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["ZealanL"]} | |
| {"messages":[{"role":"user","content":"CPU libtorch fails to find CUDA headers\n\nI am attempting to link to libtorch in my CMake project. I explicitly downloaded a CPU version of libtorch with no CUDA support (https://download.pytorch.org/libtorch/cpu/libtorch-win-shared-with-deps-2.3.1%2Bcpu.zip).\n\nHowever, when trying to build and link/include the library, it fails because it cannot find CUDA headers (which it shouldn't need because this is not a CUDA version).\n```\nC:\\Users\\[redacted]\\libtorch\\include\\c10\\cuda\\CUDAStream.h(3): fatal error C1083: Cannot open include file: 'cuda_runtime_api.h': No such file or directory\n```\n\nThis header file is part of CUDA itself. I have triple-checked that the version of the `\\libtorch\\` is indeed `2.3.1+cpu`, and is from the download."},{"role":"assistant","content":"Are you seeing the same issue using any of the tutorials? If so, could you link to it or post a minimal and executable code to reproduce the build issue?"}],"kind":"clarification","thread_id":206234,"url":"https://discuss.pytorch.org/t/cpu-libtorch-fails-to-find-cuda-headers/206234","created_at":"2024-07-13T02:37:48.486000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"CUDA error when trying to run nomic-embed-text-v1.5\n\nI have a 4070ti super, and I want to embed around 315k+ data locally. When I use my CPU the code below works fine, but when I set it to the GPU, i keep getting this CUDA error message\n> CUDA error: CUBLAS_STATUS_EXECUTION_FAILED when calling cublasSgemm( handle, opa, opb, m, n, k, &alpha, a, lda, b, ldb, &beta, c, ldc)\n\nEven though my GPU's VRAM is not completely used (I checked using task manager). I tried reinstalling everything, downgrading my GPU drivers to the one in cuda 12.4, but still no luck. Lowering the batch size and sentences size just lets it run a few iterations before the error occurs. What am I doing wrong here? Is my VRAM not being released after an iteration or something?\n```\nstart = 0\ninc = 64\niteration = 1\nmatryoshka_dim = 512\nmodel = SentenceTransformer(\"nomic-ai/nomic-embed-text-v1.5\", trust_remote_code=True)\n\n# gpu = 0\ndevice = torch.device(\"cuda:0\"if torch.cuda.is_available() else \"cpu\")\n# torch.cuda.set_device(gpu)\n\n# device = torch.device(\"cpu\")\n\nfor i in tqdm(range(start, len(rows), inc)):\n\tend = min(i + inc, len(rows))\n\t# print(start, end)\n\tsentences = rows[start:end]\n\tembeddings = model.encode(sentences, convert_to_tensor=True, device=device)\n\tembeddings = F.layer_norm(embeddings, normalized_shape=(embeddings.shape[1],))\n\tembeddings = embeddings[:, :matryoshka_dim]\n\tembeddings = F.normalize(embeddings, p=2, dim=1)\n\t# write to file in fk_ro_v\n\twith open(\"./fk_ro_v/ro_\" + str(iteration) + \".pkl\", \"wb\") as f:\n\t\tpickle.dump(embeddings, f)\n\ttorch.cuda.empty_cache()\n\titeration += 1\n\tstart += inc\n```\n\nVRAM Usage\n[image]\n\ntorch 2.5.0.dev20240715+cu124\ntorchaudio 2.4.0.dev20240715+cu124\ntorchvision 0.20.0.dev20240715+cu124"},{"role":"assistant","content":"The GPU was overclocked (+200 MHz on both boost and core clock), which caused the memory errors. Setting both overclocks to +100 MHz made the code run."}],"kind":"answer","thread_id":206384,"url":"https://discuss.pytorch.org/t/cuda-error-when-trying-to-run-nomic-embed-text-v1-5/206384","created_at":"2024-07-16T11:47:00.258000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[7],"answer_authors":["Sanjid_Chowdhury"]} | |
| {"messages":[{"role":"user","content":"CUDA error when trying to run nomic-embed-text-v1.5\n\nI have a 4070ti super, and I want to embed around 315k+ data locally. When I use my CPU the code below works fine, but when I set it to the GPU, i keep getting this CUDA error message\n> CUDA error: CUBLAS_STATUS_EXECUTION_FAILED when calling cublasSgemm( handle, opa, opb, m, n, k, &alpha, a, lda, b, ldb, &beta, c, ldc)\n\nEven though my GPU's VRAM is not completely used (I checked using task manager). I tried reinstalling everything, downgrading my GPU drivers to the one in cuda 12.4, but still no luck. Lowering the batch size and sentences size just lets it run a few iterations before the error occurs. What am I doing wrong here? Is my VRAM not being released after an iteration or something?\n```\nstart = 0\ninc = 64\niteration = 1\nmatryoshka_dim = 512\nmodel = SentenceTransformer(\"nomic-ai/nomic-embed-text-v1.5\", trust_remote_code=True)\n\n# gpu = 0\ndevice = torch.device(\"cuda:0\"if torch.cuda.is_available() else \"cpu\")\n# torch.cuda.set_device(gpu)\n\n# device = torch.device(\"cpu\")\n\nfor i in tqdm(range(start, len(rows), inc)):\n\tend = min(i + inc, len(rows))\n\t# print(start, end)\n\tsentences = rows[start:end]\n\tembeddings = model.encode(sentences, convert_to_tensor=True, device=device)\n\tembeddings = F.layer_norm(embeddings, normalized_shape=(embeddings.shape[1],))\n\tembeddings = embeddings[:, :matryoshka_dim]\n\tembeddings = F.normalize(embeddings, p=2, dim=1)\n\t# write to file in fk_ro_v\n\twith open(\"./fk_ro_v/ro_\" + str(iteration) + \".pkl\", \"wb\") as f:\n\t\tpickle.dump(embeddings, f)\n\ttorch.cuda.empty_cache()\n\titeration += 1\n\tstart += inc\n```\n\nVRAM Usage\n[image]\n\ntorch 2.5.0.dev20240715+cu124\ntorchaudio 2.4.0.dev20240715+cu124\ntorchvision 0.20.0.dev20240715+cu124"},{"role":"assistant","content":"Could you check the memory usage via `nvidia-smi`?"}],"kind":"clarification","thread_id":206384,"url":"https://discuss.pytorch.org/t/cuda-error-when-trying-to-run-nomic-embed-text-v1-5/206384","created_at":"2024-07-16T11:47:00.258000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Decreasing FPS of PyTorch Model Prediction in Inference Time\n\nHi. I am getting an output by using anomaly detection model which is unsupervised learning model. When I control with time.time(), model inference is looking fast, but when I would like to get image score from model output by using torch.max() or something, fps is decreasing suddenly. What is cause of that. I think this state relevant to autograd (or grad_mode.py call) by pytorch or like this but I cannot ensure. I do not have knowledge enough. Help me please."},{"role":"assistant","content":"Assuming your are using your GPU for the model execution, using host timers requires a device synchronization since CUDA operations are executed asynchronously."}],"kind":"answer","thread_id":206388,"url":"https://discuss.pytorch.org/t/decreasing-fps-of-pytorch-model-prediction-in-inference-time/206388","created_at":"2024-07-16T12:22:33.246000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Unreproducible pseudorandomness using CPU\n\nWe have a cluster of GPU nodes at the university, so consequent runs are most probably executed on different nodes, but all have the same software and package versions.\n\nOne of my models started to produce inconsistent results between runs after a recent change.\n\nA fix in one line finally solved the issue, but I have no idea what the issue actually was.\n\nThe line prior to the fix:\n\n```\na = torch.randn(n, m).to(b)\n```\n\nThe line after the fix:\n\n```\na = torch.randn(n, m, dtype=b.dtype, device=b.device)\n```\n\n(b is a float64 tensor on CUDA.)\n\nIn both cases I use a seed for everything, but only the second version guarantees reproducible results.\n\nWhat is going on here? Shouldn't seeded pseudorandomness on different CPUs yield the same results? Or does it have to do with the casting to float64?"},{"role":"assistant","content":"I don't know if there is a guarantee for different CPU architectures to generate the same random numbers (I would guess not, but we would need to wait for colleagues working on CPU backends to confirm). At least for NVIDIA GPUs, we do not guarantee different devices will create the same random values.\nWhich CPUs are you using btw.?"},{"role":"user","content":"I'm not sure how to get this info. I'm guessing all CPUs are x86-64.\n\nHowever, it seems like this change didn't really fix the issue; it was probably a coincidence. What happens is that there are some periods in which reproductions happen and some periods in which reproductions don't happen (even if runs are on the same GPU model but on different nodes), **without any change in code in between**. Thus, it is most likely an environment-related issue.\n\nWhat kinds of environment details should I log in order to debug this issue?\n\nIn the meantime, I'll log [these details](https://gist.github.com/AmosHason/78662524eda9aead7e220ab49e69df9e)."},{"role":"assistant","content":"This points to a script issue where calls into the PRNG are made without you being aware of it. You could try to re-seed the code at various places to see which section of the code might have created random values behind your back."},{"role":"user","content":"Let me rephrase that:\n\nI'm able to reproduce results multiple times. Then, out of nowhere, and without any change in the code, I'm no longer able to reproduce them. Then, after a few hours, I'm able to reproduce them again. In the periods of failed reproductions, the metrics are different from the git-go.\n\nSo now I experienced it again, but I have more information. The environments are similar in all aspects except for the GPU. In one run it is NVIDIA GeForce RTX 2080 Ti, and in the other it is NVIDIA GeForce RTX 3090 (both are using CUDA 12.1).\n\nIs it possible that different GPUs produce different random sequences for the same seed?"},{"role":"assistant","content":"Yes, there is no guarantee to see the same random numbers between different platforms, CPUs, GPUs, etc. as described in the [docs](https://pytorch.org/docs/stable/notes/randomness.html)."}],"kind":"answer","thread_id":206412,"url":"https://discuss.pytorch.org/t/unreproducible-pseudorandomness-using-cpu/206412","created_at":"2024-07-16T21:48:51.870000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[7],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Constraining parameter vector to unit sphere\n\nI am creating a class for my model using nn.Module. It's a simple model with only a set of linear filters as parameters. The parameters are `self.f`, defined by `self.f = nn.Parameter(f_init)` where `self.f` has shape `(n_filters, n_dims)`.\n\nThe issue is that I want to constrain the filters to have unit norm. So far I am doing this with the wonderful `geotorch` [package](https://github.com/lezcano/geotorch), using the call `geotorch.sphere(self, \"f\")`. Then I don't have to think of this constraint when doing back-propagation.\n\nMy question is whether there is a simple way of implementing this constraint without `geotorch`, since it seems simple enough, and to avoid an extra required package that is not in pip. Naively, it occurs to me that I could just divide `self.f` by its norm after every update step. It is not obvious to me though whether this would mess with my gradient and learning somehow, although I don't see why they should.\n\nSo, does it sound right to impose the unit-length constrain by dividing the vectors after each update step?"},{"role":"assistant","content":"A quick check of the code indicates [`torch.nn.utils.parametrize.register_parametrization`](https://pytorch.org/docs/stable/generated/torch.nn.utils.parametrize.register_parametrization.html) is used which is then registering [`Sphere`](https://github.com/lezcano/geotorch/blob/ba38d406c245d609fee4b4dac3f6427bf6d73a8e/geotorch/sphere.py#L109) on the parameter, so you could try to use the same approach."}],"kind":"answer","thread_id":206460,"url":"https://discuss.pytorch.org/t/constraining-parameter-vector-to-unit-sphere/206460","created_at":"2024-07-17T18:16:22.853000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Processing Sequences with Linear layers Behaviour\n\nHi there. \n\nI have implemented a sequential neural network that has an MLP feature extractor prior to the recurrent blocks. Intuitively I found out that the torch.nn.Linear can handle data of shapes (L, B, N)\nwhere L is the time-series length, B is the batch size and N is the feature shape.\nFor instance the following block works:\n```\nrand_tens = torch.randn(12, 4, 16)\nlinear_layer = torch.nn.Linear(16, 8)\noutput = linear_layer(rand_tens)\n```\nand its output is torch.Size([12, 4, 8]). \n\nHowever, normally we would require flattening of the temporal dimension and the batch dimension, allowing for the Linear layer to operate at a shape (L*B, N). My questions are the following:\n\n1. Is this flattening (and unflattening) what torch.nn.Linear does under the hood? \n2. Is my thought process for processing (L, B, N) shaped data at the feature dimension with linear layers correct?\n\nIf you could point me a reference for that or the part of the documentation that describes it I would be greatful.\n\nThank you!"},{"role":"assistant","content":"Yes, this should be the case as seen [here](https://github.com/pytorch/pytorch/blob/6d9f74f0af54751311f0dd71f7e5c01a93260ab3/aten/src/ATen/native/Linear.cpp#L102C14-L108) and [here](https://github.com/pytorch/pytorch/blob/6d9f74f0af54751311f0dd71f7e5c01a93260ab3/aten/src/ATen/native/Linear.cpp#L55-L70)."}],"kind":"answer","thread_id":206515,"url":"https://discuss.pytorch.org/t/processing-sequences-with-linear-layers-behaviour/206515","created_at":"2024-07-18T13:42:23.437000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"OOM error while caching\n\nHi, my team and I were working with a ViT for a project but ran into a OOM issue. We have a couple of variants of ViT:\n1. Normal ViT \n2. ViT with some form of caching \n\nThe OOM error only occurs for ViT with caching but only on model sizes larger than 200M parameters (works fine for ViT of upto 76M parameters, i.e. it works fine for base and small, but not for large). \n\nRight now we have tried the following to prevent memory leakages:\n1. Tried to avert it with detach (as can be seen)\n2. Checking if there was a broadcasting making the tensors bigger than they actually are (we printed out the cache in the forward pass and it had the same shape throughout, so it's not looking like that's the issue)\n3. Also tried to instantiate the cache using self.register_buffer(...) in the hopes that it would automatically fix any accumulated gradient issues but that didn't work in our last run either - we're not crystal clear on how these work in the context of the computational graph and tracking of gradients so this was a hail mary for us\n\nI have attached part of the code where we work with the cache. The update_splits_cache_training is called after a window_size number of iterations have passed. Assume that the self.splits_func is set to get_ratios_diff. \n\nWe want to know whether our handling of cache has implications on back-prop which we have not figured out (for eg. using while loops, converting tensors to lists and tuples etc) which might be contributing to the OOM.\n\nAn interesting note is that after a window_size number of iterations, we also cleared the cache (torch.cuda.empty_cache) which actually allowed the training to go on much longer but eventually another OOM error showed up.\n\nAny help would be really really appreciated! Thanks.\n\n[image]"},{"role":"assistant","content":"Detaching the `curr_cache` is a good idea, but since this does not seem to fix the issue, you could check if other tensors (which are accumulated or stored in any container) have a valid `.grad_fn`. If so, you could also detach these (assuming they are not needed in the `backward` pass).\nIf this does not help, you might need to add debug `print` statements into your training code trying to isolate which part of the code increases the memory usage unexpectedly."}],"kind":"answer","thread_id":206565,"url":"https://discuss.pytorch.org/t/oom-error-while-caching/206565","created_at":"2024-07-19T10:03:40.893000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Compatible versions for installing from source\n\nHi,\nI am running many difficulties while installing from source and most of them are about incompatible libraries.\nThe question is what is the correct version of PyTorch, TorchVision and CUDA 12.2?"},{"role":"assistant","content":"You could check the commits from successfully built nightly binaries as discussed in [this topic](https://discuss.pytorch.org/t/what-is-commit-hash-of-pytorch-https-github-com-pytorch-pytorch-repository-for-a-particular-nightly/206060). Generally, staying close to the same commit dates should also work. I.e. I usually `pull` all repositories after each other and haven't seen a lot of issues in source building due to `torch` being incompatible with `vision`.\nCUDA 12.2 should work for any recent commit."}],"kind":"answer","thread_id":206568,"url":"https://discuss.pytorch.org/t/compatible-versions-for-installing-from-source/206568","created_at":"2024-07-19T12:16:18.152000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Am I permitted to use functions such as `torch._foreach_add`\n\nBefore posting a query, check the [FAQs](https://discuss.pytorch.org/c/faq/30) - it might already be answered!\n\nThis function `torch._foreach_add` is not mentioned anywhere, like on documentation, etc, except a few of foreach functions are mentioned in the Foreach section of this page https://pytorch.org/docs/stable/torch.html, but most like `_foreach_add` are not mentioned there either, so I am unsure whether I am allowed to use them, or if they are subject to change, etc. I do notice that the official optimizer implementations use them, and as I understand, they are a bit faster than doing for loops. So is it okay if I use that?"},{"role":"assistant","content":"These methods are tagged as internal/private indicated by the underscore at the front of the function names, since their interface can easily change and break.\nYou can of course use these, but should not depend on backwards compatibility and might need to change some calls in future versions if their interfaces change."}],"kind":"answer","thread_id":206616,"url":"https://discuss.pytorch.org/t/am-i-permitted-to-use-functions-such-as-torch-foreach-add/206616","created_at":"2024-07-20T14:37:59.589000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"transforms.ToTensor ignores set_default_device(\"cuda\")\n\nIt seems that transforms.ToTensor ignores set_default_device.\n\nHere is an example:\n\n import torch\n import torchvision.transforms as transforms\n import torchvision.datasets as datasets\n\n torch.set_default_device(\"cuda\")\n transform = transforms.ToTensor()\n dataset = datasets.MNIST(\"~/datasets\", train=True, download=False, transform=transform)\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=32)\n batch = next(iter(dataloader))\n print(\"Batch[0] = \", batch[0].device)\n print(\"Batch[1] = \", batch[1].device)\n\nWhen run, I have batch[1] on cuda, but batch[0] is on the CPU. I expected batch[0] to be on cuda.\n\nInterestingly, from examining the transforms code, it seems that it is using torch.from_numpy and this maybe a problem:\n\n import torch\n import numpy as np\n\n torch.set_default_device(\"cuda\")\n t = torch.from_numpy(np.array(5.0))\n print(t)\n\nI get:\ntensor(5., dtype=torch.float64)\n\nI would have expected this to be on the CUDA device, and I believe it may be the source of the above problem."},{"role":"assistant","content":"Yes, this is expected as explained in the [docs](https://pytorch.org/docs/stable/generated/torch.set_default_device.html#torch.set_default_device):\n> This doesn’t affect functions that create tensors that share the same memory as the input, like: torch.from_numpy() and torch.frombuffer()"}],"kind":"answer","thread_id":206707,"url":"https://discuss.pytorch.org/t/transforms-totensor-ignores-set-default-device-cuda/206707","created_at":"2024-07-22T10:07:19.813000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Even = total_real[:, :, :, :, 0]\n\nIn pytorch, \n\neven = total_real[:, :, :, :, 0] # extract even elements\nodd = total_real[:, :, :, :, 1] # extract odd elements\n\ntotal_real.shape \ntorch.Size([1, 1, 1023, 64, 2])\n\neven.shape\ntorch.Size([1, 1, 1023, 64])\n\nodd.shape\ntorch.Size([1, 1, 1023, 64])\n\nIn C++ Torch lib, \nHow to convert it as same ?"},{"role":"assistant","content":"To convert the output to be the same, you can ensure each step in the operation is valid. If you're trying to get the real part of the cosine of freqs, you might need to separately apply the operations and ensure they're compatible. Here's an example:\n\n```\ncos_freqs = freqs.cos() # Apply cosine\nreal_cos_freqs = cos_freqs.real() # Get the real part\n```\nIf `freqs` is a complex tensor, this should work. If not, please provide more details about `freqs` and the desired output."},{"role":"user","content":"I want to extract even elements, in C++ torch lib."},{"role":"assistant","content":"```python\nauto even = total_real.index({\"...\", 0});\nauto odd = total_real.index({\"...\", 1});\n```\nshould work based on the [docs](https://pytorch.org/cppdocs/notes/tensor_indexing.html)."}],"kind":"answer","thread_id":206712,"url":"https://discuss.pytorch.org/t/even-total-real-0/206712","created_at":"2024-07-22T11:03:33.255000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Sin = sin[position_ids].unsqueeze(1)\n\nIn pytorch,\n\nsin = sin[position_ids].unsqueeze(1)\n\nposition_ids.shape is\ntorch.Size([1, 1024])\n\nsin.shape is \ntorch.Size([1024, 64])\n\nIn C++ Torch lib,\nHow to convert it as same ?"},{"role":"assistant","content":"Found another solution \n\n torch::Tensor position_ids_temp = position_ids.reshape(1024);\n sin = sin.index_select(0, position_ids_temp).unsqueeze(0).unsqueeze(0);"}],"kind":"answer","thread_id":206822,"url":"https://discuss.pytorch.org/t/sin-sin-position-ids-unsqueeze-1/206822","created_at":"2024-07-24T05:43:31.999000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["TaeYeon_Lee"]} | |
| {"messages":[{"role":"user","content":"How to use numpy for other general library to rewrite nn.KLDiv?\n\nIn my project, I used nn.KLDiv(A.log(), B) to calculate the KL divergence between A and B.\nBut now I have to rewrite this part as numpy or other general python libraries in order to some model conversion.\n\nI did a lot of search on google, and tried the following implementations:\n\n```\n(1) First method\ndef KL(a, b):\n a = np.asarray(a, dtype=np.float)\n b = np.asarray(b, dtype=np.float)\n return np.sum(np.where(a != 0, a * np.log(a / b), 0))\n\n(2) Second method\nscipy.special.kldiv\nNeither of them show the similar output with the nn.KLDivLoss method in pytorch.\n```\nCould someone provide some guidance how to implement KL divergence with numpy to provide similar output with pytorch? Thanks."},{"role":"assistant","content":"Using the formula from the [docs](https://pytorch.org/docs/stable/generated/torch.nn.KLDivLoss.html), I get the same results (up to floating point precision):\n```python\ndef KL(a, b):\n return b * (np.log(b) - a)\n\nkl_loss = nn.KLDivLoss(reduction=\"batchmean\")\n# input should be a distribution in the log space\ninput = F.log_softmax(torch.randn(3, 5, requires_grad=True), dim=1)\n# Sample a batch of distributions. Usually this would come from the dataset\ntarget = F.softmax(torch.rand(3, 5), dim=1)\nref = kl_loss(input, target)\n\n# numpy reference\nout = KL(input.detach().numpy(), target.numpy())\nout = np.sum(out) / out.shape[0]\n\nprint((ref - out).abs().max())\n# tensor(2.9802e-08, grad_fn=<MaxBackward1>)\n```"}],"kind":"answer","thread_id":206826,"url":"https://discuss.pytorch.org/t/how-to-use-numpy-for-other-general-library-to-rewrite-nn-kldiv/206826","created_at":"2024-07-24T06:02:59.008000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Getting \"torch,amp has no attribute GradScaler\" error, when trying to train YOLO models (yolov10, v9) on kaggle\n\n**Code:**\n`!pip install ultralytics from ultralytics import YOLO model = YOLO('yolov10x.yaml') results = model.train(data='config.yaml', epochs=400, patience=40, device=[0, 1]) `\n**Error:**\n\nAttributeError Traceback (most recent call last)\nCell In[23], line 2\n1 MODEL = YOLO(\"yolov10x.yaml\")\n----> 2 results = MODEL.train(data=\"/kaggle/input/configuration/config.yaml\", epochs=400, patience=35, device=0, cache=True)\n\nFile /opt/conda/lib/python3.10/site-packages/ultralytics/engine/model.py:810, in Model.train(self, trainer, **kwargs)\n807 self.model = self.trainer.model\n809 self.trainer.hub_session = self.session # attach optional HUB session\n--> 810 self.trainer.train()\n811 # Update model and cfg after training\n812 if RANK in {-1, 0}:\n\nFile /opt/conda/lib/python3.10/site-packages/ultralytics/engine/trainer.py:206, in BaseTrainer.train(self)\n203 ddp_cleanup(self, str(file))\n205 else:\n--> 206 self._do_train(world_size)\n\nFile /opt/conda/lib/python3.10/site-packages/ultralytics/engine/trainer.py:329, in BaseTrainer._do_train(self, world_size)\n327 if world_size > 1:\n328 self._setup_ddp(world_size)\n--> 329 self._setup_train(world_size)\n331 nb = len(self.train_loader) # number of batches\n332 nw = max(round(self.args.warmup_epochs * nb), 100) if self.args.warmup_epochs > 0 else -1 # warmup iterations\n\nFile /opt/conda/lib/python3.10/site-packages/ultralytics/engine/trainer.py:270, in BaseTrainer._setup_train(self, world_size)\n267 dist.broadcast(self.amp, src=0) # broadcast the tensor from rank 0 to all other ranks (returns None)\n268 self.amp = bool(self.amp) # as boolean\n269 self.scaler = (\n--> 270 torch.amp.GradScaler(\"cuda\", enabled=self.amp)\n271 if TORCH_1_13\n272 else torch.cuda.amp.GradScaler(enabled=self.amp)\n273 )\n274 if world_size > 1:\n275 self.model = nn.parallel.DistributedDataParallel(self.model, device_ids=[RANK], find_unused_parameters=True)\n\nAttributeError: module 'torch.amp' has no attribute 'GradScaler'\n\nAttem\n\npts:\nTried updating torch, torchvision. Even when I try to import torch.amp.GradScaler, still I get the Attribute error.\nAlso I had to mention, this wasn't happening before, I trained a yolov10 model a few days ago. I also verified on my local linux machine, it also gives the same attribute error when trying to import torch.amp.GradScaler"},{"role":"assistant","content":"I had a simliar error. What fixed it for me was upgrading torch. I see you already tried it but maybe try it again or make sure you really have the latest version"}],"kind":"answer","thread_id":206847,"url":"https://discuss.pytorch.org/t/getting-torch-amp-has-no-attribute-gradscaler-error-when-trying-to-train-yolo-models-yolov10-v9-on-kaggle/206847","created_at":"2024-07-24T09:07:35.800000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["martijn_sikking"]} | |
| {"messages":[{"role":"user","content":"Reading Images from 4D numpy array\n\nI am learning PyTorch and I want to write a custom data loader for my training. My training data is saved in to two numpy arrays. Input_images.npy and Output_images.npy. Each of them has a shape of (N,W,H,C), where N is number of samples, e.g. 2000. I have wrote the following:\n\n```python \nimport torch\nimport numpy as np\n\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\n\nclass CustomNumpyDataset(Dataset):\n def __init__(self, input_list, output_list, transform):\n self.input_list = input_list\n self.output_list = output_list\n self.transform = transform\n\n def __len__(self):\n list_in = np.load(self.input_list)\n return list_in.shape[0]\n def __getitem__(self, idx):\n sample_in = np.load(self.input_list)\n sample_in = sample_in[idx,:,:,:]\n sample_in = torch.from_numpy(sample_in)\n \n\n sample_out = np.load(self.output_list)\n sample_out = sample_out[idx,:,:,:]\n sample_out = torch.from_numpy(sample_out)\n \n return sample_in, sample_out\n\ndataset = CustomNumpyDataset(\"./Input_images.npy\", \"./Output_images.npy\")\n\ndataloader = DataLoader(dataset, batch_size=8, shuffle=True)\n```\nThis works fine, the problem is it is slow. Can you help me understand why it is slower, and what can I do to speed it up? I tried using `num_workers=2` in the DataLoader call and it speeds it up a bit. will there be another solution without increasing the number of workers."},{"role":"assistant","content":"Repeatedly loading arrays in `__getitem__` before indexing it is expensive and you won't have any benefit from it, as you are already loading the entire array.\nMove it to the `__init__` and just index the array in the `__getitem__`.\n\nAlternatively, revisit your approach and check if you can split the data into separate files, index the file list, and load the actual sample only in the `__getitem__`."}],"kind":"answer","thread_id":206860,"url":"https://discuss.pytorch.org/t/reading-images-from-4d-numpy-array/206860","created_at":"2024-07-24T12:55:40.700000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Question about the CrossEntroyLoss and BCELoss?\n\nDuring the process of attempting to extract table lines (which I divided into horizontal and vertical lines), I found that when I used CrossEntropyLoss, the loss value remained at a constant level without changing. However, when I used BCELoss, the loss gradually decreased with each iteration.\nFor example:\nInput: (batch_size, 3, 1024, 1024)\nOutput: (batch_size, 2, 1024, 1024)\nTarget: (batch_size, 2, 1024, 1024)"},{"role":"assistant","content":"`nn.CrossEntropyLoss` can be used for multi-class classification use cases (where each sample belongs to a single class) while `nn.BCEWithLogitsLoss` (don't use `nn.BCELoss` as it has a lower numerical stability compared to `nn.BCEWithLogitsLoss`) can be used for multi-label classification use cases (where each sample belongs to 0, 1, or multiple classes).\nI don't know which use case you are working on."},{"role":"user","content":"For example, in an image, I would first mark the lines of the table (that is, all parts that belong to the table are marked as 1, and those that do not belong to the table are marked as 0). Then I use a model to determine whether each pixel belongs to a line."},{"role":"assistant","content":"In this case it sounds like a multi-class segmentation use case and `nn.CrossEntropyLoss` would be the commonly used criterion. \nThe target would then contain class indices in `[0, 1]` and have the shape `[batch_size, height, width]` (note the missing class dimension) or would contain \"soft\" targets (i.e. floating point values between 0 - 1) in the same shape as the model output."}],"kind":"answer","thread_id":206870,"url":"https://discuss.pytorch.org/t/question-about-the-crossentroyloss-and-bceloss/206870","created_at":"2024-07-24T14:07:09.835000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"RuntimeError: CUDA error: device-side assert triggered CUDA \n\nI am trying to run my project on Google Colab's L4 GPU. However, I get the error: \n```\nRuntimeError: CUDA error: device-side assert triggered\nCUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.\nFor debugging consider passing CUDA_LAUNCH_BLOCKING=1.\nCompile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.\n```\nIts weird because everytime I run the project, this error seems to pop up in different places. \n\nI also checked https://discuss.pytorch.org/t/runtimeerror-cuda-error-device-side-assert-triggered-cuda-kernel-errors-might-be-asynchronously-reported-at-some-other-api-call-so-the-stacktrace-below-might-be-incorrect/139735. I also use ``` nn.CrossEntropyLoss() ```, but the error occurs before that line. \n\nI'm not sure what is the problem. Could someone help me?"},{"role":"assistant","content":"Device-side assert errors are usually caused by invalid indexing. In one case an out-of-bounds index in the code caused the error; fixing that index made it go away."}],"kind":"answer","thread_id":206937,"url":"https://discuss.pytorch.org/t/runtimeerror-cuda-error-device-side-assert-triggered-cuda/206937","created_at":"2024-07-25T09:10:12.751000Z","tier":"silver","answer_origin":"composed","answer_post_numbers":[3,4],"answer_authors":["ptrblck","yusako"]} | |
| {"messages":[{"role":"user","content":"Custom Image Folder\n\nHello!\n\nI want to create a custom `ImageFolder` were instead of the default `(sample, target)`, it will also return an annotated version of each data sample. Therefore `(sample, annotated_sample, target)`.\n\nBelow \n```\nclass AugmentatedImageFolder(ImageFolder):\n \"\"\"Augmentated Images dataset.\"\"\"\n\n def __getitem__(self, index: int):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (sample, augmented_sample, target) where target is class_index of the target class.\n \"\"\"\n path, target = self.samples[index]\n sample = self.loader(path)\n\n if self.transform is not None:\n sample_augmented = self.transform(sample)\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return sample, sample_augmented, target\n```\n\nIs the above approach correct?\n\nI run my experiments in an HPC, and I get the below memory error when I do this customization:\n`slurmstepd: error: Detected 2 oom_kill events in StepId=1819449.batch. Some of the step tasks have been OOM Killed.`\n\nIs there something in the custom class that could be affecting the memory?\n\nThank you! :slight_smile:"},{"role":"assistant","content":"It's unclear what is causing the OOM issues but depending on the sample size and batch size the data loading could be responsible for it. \nYour code looks generally alright, but you should receive an error if the `if` conditions are not met since the returned variables would be undefined."}],"kind":"answer","thread_id":207095,"url":"https://discuss.pytorch.org/t/custom-image-folder/207095","created_at":"2024-07-27T16:15:11.720000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"DataLoader CPU bottleneck with on-the-fly data on GPU\n\nHi everyone!\n\nI'm training a model with synthetic data that i'm generating on-the-fly with an IterableDataset. I made sure the data generation runs entirely on the GPU, since I want to reduce the CPU usage to the bare minimum.\n\nThe issue is that, when I'm training the model, i've noticed with the profiler that there is still a bottleneck on the CPU when loading the data with the DataLoader. I'm confused because I'm sure the tensors that I'm generating are on the GPU (i cannot set pin_memory=True for example cause they already are on GPU), but at the same time if i change the num_workers parameter performance are affected (from what I understand, the workers should be relevant just when using the CPU).\n\nDo you have any suggestion to solve this issue?\n\nThank you in advance"},{"role":"assistant","content":"Increasing the number of workers creates new processes corresponding to each worker which will load and process the data in the background and could thus also yield benefits in your use case."}],"kind":"answer","thread_id":207118,"url":"https://discuss.pytorch.org/t/dataloader-cpu-bottleneck-with-on-the-fly-data-on-gpu/207118","created_at":"2024-07-28T10:58:05.133000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Is it a good idea to use float16/bfloat16 for inference?\n\nHi\n\nI am currently using bfloat16 for inference and the model seems to be performing well (with torch.amp.autocast).\nIs it a common practice to use reduce precision for inference as well as for training? I am not confident enough because most articles about reduced precision are focusing on training."},{"role":"assistant","content":"Yes, lower dtypes can be used for inference, too."}],"kind":"answer","thread_id":207281,"url":"https://discuss.pytorch.org/t/is-it-a-good-idea-to-use-float16-bfloat16-for-inference/207281","created_at":"2024-07-31T06:23:42.842000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Why my model has different weights in each gpu after DDP training\n\nThe code is as follows. I have hidden some irrelevant code. When training with DDP, I printed the network parameters of different ranks in the same iteration. The update results of the model parameters on each GPU were different. Strangely, I only found this problem after upgrading from torch1.13.1 to torch2.0.1. I am not 100% sure if this problem is related to the upgrading, because the models are also different, but my training code framework remains unchanged overall. \n\n IS there are any precautions to be taken in the upgrade of DDP in torch2.0.1 to ensure that the GPUs are updated synchronously? \n\n Or, could another reason be that I called a module like `model.module.unet` instead of using `model.forward`? After the model was decorated by DDP, we can only use `.module` to call the submodules.\n\n \n```\nimport argparse\nimport os\nimport shutil\nimport torch\nimport torch.optim as optim\nimport torchvision\nimport torch.nn.functional as F \nfrom datasets_prep.dataset import create_dataset\n\ndef init_distributed_mode(args):\n if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:\n args.rank = int(os.environ[\"RANK\"])\n args.world_size = int(os.environ['WORLD_SIZE'])\n \n args.gpu = int(os.environ['LOCAL_RANK'])\n \n elif 'SLURM_PROCID' in os.environ:\n args.rank = int(os.environ['SLURM_PROCID'])\n args.gpu = args.rank % torch.cuda.device_count()\n else:\n print('Not using distributed mode')\n args.distributed = False\n args.gpu = 0\n return False\n\n args.distributed = True\n torch.cuda.set_device(args.gpu)\n args.dist_backend = 'nccl' # 通信后端,nvidia GPU推荐使用NCCL try gloo\n print('| distributed init (rank {}): {}'.format(\n args.rank, args.dist_url), flush=True)\n dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,\n world_size=args.world_size, rank=args.rank)\n # local_rank = torch.distributed.get_rank() \n # print('args.rank,local_rank,args.gpu ,args.world_size',args.rank,local_rank,args.gpu,args.world_size)\n return True\n\n \n \n \n\ndef train(args): \n # %% init the distributed training \n is_distributed = init_distributed_mode(args=args)\n if is_distributed: \n rank = args.rank\n device = torch.device(args.device) \n else:\n device = torch.device('cuda:0') \n args.rank=rank = 0 \n if rank==0:\n print('torchversion',torch.__version__)\n\n torch.manual_seed(args.seed + rank)\n torch.cuda.manual_seed(args.seed + rank)\n torch.cuda.manual_seed_all(args.seed + rank)\n if rank==0:\n print(f\"Running DDP on rank {rank} device {device}\")\n \n \n dataset = create_dataset(args) \n train_sampler = torch.utils.data.distributed.DistributedSampler(dataset, num_replicas=args.world_size, rank=rank)\n data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True,\n unet_small = model(args) \n unet_small.to(device) \n\n if is_distributed: \n unet_small = DDP(unet_small, device_ids=[device], find_unused_parameters=False)\n train_param_list= list(unet_small.module.unet.parameters())+list(unet_small.module.vae.parameters())\n else:\n train_param_list= list(unet_small.unet.parameters())+list(unet_small.vae.parameters())\n optimizer = optim.Adam(filter(lambda p: p.requires_grad, train_param_list), \n lr=args.lr_g, \n betas=(args.beta1, args.beta2))\n \n \n \n lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, args.num_epoch, eta_min=args.lr_g/100)\n\n optimizer.zero_grad()\n\n for epoch in range(init_epoch, args.num_epoch + 1):\n if is_distributed: dist.barrier()\n train_sampler.set_epoch(epoch) \n iters_per_epoch = len(data_loader) \n if is_distributed: dist.barrier()\n for iteration, batch in enumerate(data_loader):\n\n \n HQ, LQ, text = Degrator.GetLR(batch) \n hr_img, lr_img =(HQ-0.5)*2 , (LQ-0.5)*2 \n \n if is_distributed: \n \n latent_dnoised =unet_small.module.sample_denoised_latent(lr_img,text)\n else: \n latent_dnoised =unet_small.sample_denoised_latent(lr_img,text)\n \n if is_distributed: \n fake_data = unet_small.module.decode(latent_dnoised)\n else:\n fake_data = unet_small.decode(latent_dnoised)\n \n \n real_data = HQ\n\n \n err_end = torch.nn.functional.mse_loss(fake_data,real_data)\n err_lp = lp_loss(fake_data, real_data)*args.lpips_w \n loss_total = err_end + err_lp \n \n loss_total.backward()\n torch.nn.utils.clip_grad_norm_(unet_small.parameters(), max_norm=20, norm_type=2)\n \n optimizer.step()\n optimizer.zero_grad()\n \n \n if 0 == rank: \n # import pdb;pdb.set_trace()\n print(iteration,unet_small.module.unet.conv_out.state_dict()['lora_A.default_decoder.weight'][0,0,0])\n\n if iteration % 4 == rank: \n print(iteration,unet_small.module.unet.conv_out.state_dict()['lora_A.default_decoder.weight'][0,0,0])\n \n \n \n \n \n# %%\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--seed', type=int, default=1024, help='seed used for initialization') \n \n # parser.add_argument('--master_address', type=str, default='127.0.0.1',\n # help='address for master')\n # parser.add_argument('--master_port', type=str, default='6002',\n # help='port for master')\n parser.add_argument('--num_workers', type=int, default=4, help='num_workers') \n parser.add_argument('--device', default='cuda', help='device id (i.e. 0 or 0,1 or cpu)') \n parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes')\n parser.add_argument('--dist-url', default='env://', help='url used to set up distributed training')\n parser.add_argument('--iters_to_accumulate', type=int, default=1,\n help='iters_to_accumulate') \n\n opt = parser.parse_args()\n # print(opt)\n train(opt)\n\n \n```"},{"role":"assistant","content":"Yes, this is a common reason since calling internal modules will skip the distributed logic. Call the model directly via `output = model(input)` and check the parameters again."}],"kind":"answer","thread_id":207299,"url":"https://discuss.pytorch.org/t/why-my-model-has-different-weights-in-each-gpu-after-ddp-training/207299","created_at":"2024-07-31T10:57:55.974000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Module name updated after saving\n\nI trained a Faster RCNN model and evaluated it with `torchmetrics`. I had saved a dictionary with model weights in `.pt` format along with the `torchmetrics.detection.map` object after training an object detection model. I now upgraded torchmetrics and the module name has changed from `map` to `mean_ap`. Now when I use `torch.load`, I get the error `ModuleNotFoundError: No module named 'torchmetrics.detection.map'`. How do I solve this without having to downgrade `torchmetrics`? Thanks in advance for your help."},{"role":"assistant","content":"I assume you have saved the `torchmetrics` object directly, which might require the same source code during the load process. I don't know if this object contains a `state_dict` but if so you should save and restore it instead, as the actual data will be saved only instead of the object."}],"kind":"answer","thread_id":207399,"url":"https://discuss.pytorch.org/t/module-name-updated-after-saving/207399","created_at":"2024-08-01T13:21:07.620000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Problem with auto_grad()\n\nHi,\nI'm currently trying to implement a simple SGD without using a built in optimizer.\nWhat I'm running into is that after the first mini-batch, my loss loses its requires_grad status, and thus throws an error. \nHere is my code:\n```\nimport numpy as np\nimport torch\n\ndef generate_data():\n data = torch.rand(1000, 2)\n label = ((data[:,0]+0.3*data[:,1]) > 0.5).to(torch.int)\n return data[:,0], label\n\ninput, label = generate_data()\n\n# Make minibatches.\ninputs = torch.split(input, 32)\nlabels = torch.split(label, 32)\n\n# Define the two variables to optimize\nb1 = torch.autograd.Variable(torch.tensor([0.01]), requires_grad=True)\nb2 = torch.autograd.Variable(torch.tensor([0.01]), requires_grad=True)\n\nfor epoch in range(15):\n for x, y in zip(inputs,labels):\n \n b1.grad = None\n b2.grad = None\n\n # Calculate p_x as per formula above\n p_x = 1 / (1 + torch.exp(-(b1 + b2 * x)))\n\n # Calculate the negative loss likelihood\n l = (y * torch.log(p_x) + (1 - y) * torch.log(1 - p_x)).sum()\n\n l.backward()\n # Calculate the gradient of the loss w.r.t. the inputs\n delta_b1 = b1.grad\n delta_b2 = b2.grad\n # Update the parameters b according to SGD formula\n\n with torch.no_grad():\n b1 = b1 - 0.01 * delta_b1\n b2 = b2 - 0.01 * delta_b2\n\n```\n\nP.S. I am aware Variable is deprecated, but I am working around given code. \nAny help would be greatly appreciated."},{"role":"assistant","content":"You are replacing the trainable and deprecated `Variable`s inside the `no_grad` block with constant tensors. You could try to update these variables via inplace methods instead."},{"role":"user","content":"I see. Is it acceptable to change to tensor.data directly? Like so:\n```\nb1.data -= 0.1 * delta_b1\n b2.data -= 0.1 * delta_b2\n```\n\nOtherwise I get:\nRuntimeError: a leaf Variable that requires grad is being used in an in-place operation."},{"role":"assistant","content":"Since you are already using deprecated `Variable` objects you could also use the internal `.data` attribute, but note that I would strongly recommend updating your code and to use supported approaches."}],"kind":"answer","thread_id":207428,"url":"https://discuss.pytorch.org/t/problem-with-auto-grad/207428","created_at":"2024-08-02T03:38:38.350000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Loss.backward() throws error because output tensor has no gradient\n\nI created model to do custom edge detection and the forward pass works fine and produces the right result. \n\nHowever training does not work because the gradients of the parameters can not be computed. I made a minimal reproducer below, which throws the error. I think the issue here is that my output tensor has no gradients, but setting it to require_grad=True does not solve the issue, instead no error is thrown, but the gradients do not change even if the loss is super high.\n\nThis might be due to masks I use. Maybe you have an idea how to solve this issue since I want to use the model in downstream tasks and train it in combination with a classificator.\n\nHere is the code:\n\n```\n\nfrom torch import nn\nimport torch\nfrom torchvision.transforms import v2\n\nclass NeuralNetwork(nn.Module):\n def __init__(self):\n super().__init__()\n self.x_sob = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=(3, 3), stride=(1, 1), padding=\"same\")\n self.y_sob = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=(3, 3), stride=(1, 1), padding=\"same\")\n self.x_sob.weight = nn.Parameter(torch.Tensor([[[[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]]]))\n self.y_sob.weight = nn.Parameter(torch.Tensor([[[[1, 2, 1], [0, 0, 0], [-1, -2, -1]]]]))\n #self.apply_thresh = MaxPool2dStaticSamePadding(kernel_size=(3, 3), stride=1)\n self.low_threshold = nn.Parameter(torch.Tensor([0.05]))\n self.high_threshold = nn.Parameter(torch.Tensor([0.15]))\n self.blur = v2.GaussianBlur(kernel_size=5, sigma=1.4)\n\n def forward(self, x):\n # Gaussian blur & sobel filter\n x = self.blur(x)\n gX = self.x_sob(x)\n gY = self.y_sob(x)\n\n # Calculate Magnitude and angle theta\n mag = torch.sqrt(torch.pow(gX, 2) + torch.pow(gY, 2))\n mag = ((mag / torch.max(mag)) * 255)\n theta = torch.arctan2(gY, gX)\n\n # Create nms representation of img\n #img = self.non_max_suppression(mag, theta)\n img = mag\n\n # calculate low and high threshold\n batch_size = img.size(0)\n h_t = img.reshape(batch_size, -1).max(dim=1).values.reshape(batch_size, 1, 1, 1) * self.high_threshold\n l_t = h_t * self.low_threshold\n\n # accept pixels values higher than h_t, reject pixel value lower l_t, create mask\n accept_mask = (img > h_t).bool()\n reject_mask = (img < l_t).bool()\n\n # get values between high and low threshold\n bet_mask = ((img > l_t) & (img < h_t)).bool()\n\n # set all value in \"img\" to zero which are not True in the accept mask\n img_acc = img.masked_fill(~accept_mask, 0)\n\n # apply hysteresis by using max_pooling -> all pixels with neighbouring \"strong\" pixels get also \"strong\"\n #img_th = self.apply_thresh(img_acc)\n img_th = img_acc\n\n # create a mask where all fields are true which fall between the thresholds\n img_b_mask = img.masked_fill(~bet_mask, 0).bool()\n\n # Replace all values < 0 in img_acc with the strong neighbours which are in bet_mask, else 0\n out = torch.where(img_acc > 0, img_acc, img_th.masked_fill(~img_b_mask, 0))\n out = torch.where(reject_mask, 0, out) # Apply reject mask directly\n out = torch.where(out > 0, 255.0, 0.0).to(torch.float32)\n # out.requires_grad = True\n\n #THIS WORKS BETTER: return img_th[0, 0, :200, :200]\n return out[0,0,:200,:200]\n\n# Init\nnet = NeuralNetwork()\nnet.train()\noptimizer = torch.optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\nloss_fn = torch.nn.CrossEntropyLoss()\n\n# Print parameters before backward to see if there is a change\nprint(list(net.parameters()))\n\n# Dummy input and labels\nlbl = torch.randn(3,1,224,224)\ninp = torch.randn(3,1,224,224)\n\noptimizer.zero_grad()\n\nres = net(inp)\nl = loss_fn(res, lbl[0,0,:200,:200])\nprint(\"LOSS:\", l)\nl.backward()\noptimizer.step()\n\n# Print parameters again\nprint(list(net.parameters()))\n```"},{"role":"assistant","content":"Could you check if `img_acc` shows a valid `.grad_fn` inside the `forward` method? If so, your masking might not select any of its values which are attached to a computation graph."},{"role":"user","content":"`img_acc` shows a valid *.grad_fn* : `<MaskedFillBackward0 object at 0x7f8c01f2aad0>`\n\nHowever I figured out that the last line seems to be the culprit here:\n`out = torch.where(out > 0, 255.0, 0.0).to(torch.float32)`\n\nWhen I change it to:\n`out3 = torch.where(out > 0, out-out+255.0, 0.0)`\n\nIt works (Maybe because `out` has to be written instead of constants?) with this, however now the gradient does not change. When I use the second line from the bottom ` out = torch.where(reject_mask, 0, out)` instead the gradient calculation works.\n\nThis seems rather odd, why does the gradient not change when I set all positive values in my tensor to 255.0 and all other to 0.0 ?\n\nAlso I noticed, the gradient of `self.low_threshold` and `self.high_threshold` never changes no matter what I do. Is it because they are only used in a boolean mask? And how would I change that?\n\nBest regards, sorry I know this is a bit complex and confusing :("},{"role":"assistant","content":"Good catch! Indeed, replacing the tensor with constants won't work. The threshold is not usefully differentiable since its gradient would be zeros everywhere and undefined or Inf at the rounding points. [This post](https://discuss.pytorch.org/t/training-with-threshold-in-pytorch/145962/3?u=ptrblck) might be useful."}],"kind":"answer","thread_id":207434,"url":"https://discuss.pytorch.org/t/loss-backward-throws-error-because-output-tensor-has-no-gradient/207434","created_at":"2024-08-02T07:21:44.339000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Loss.backward() throws error because output tensor has no gradient\n\nI created model to do custom edge detection and the forward pass works fine and produces the right result. \n\nHowever training does not work because the gradients of the parameters can not be computed. I made a minimal reproducer below, which throws the error. I think the issue here is that my output tensor has no gradients, but setting it to require_grad=True does not solve the issue, instead no error is thrown, but the gradients do not change even if the loss is super high.\n\nThis might be due to masks I use. Maybe you have an idea how to solve this issue since I want to use the model in downstream tasks and train it in combination with a classificator.\n\nHere is the code:\n\n```\n\nfrom torch import nn\nimport torch\nfrom torchvision.transforms import v2\n\nclass NeuralNetwork(nn.Module):\n def __init__(self):\n super().__init__()\n self.x_sob = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=(3, 3), stride=(1, 1), padding=\"same\")\n self.y_sob = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=(3, 3), stride=(1, 1), padding=\"same\")\n self.x_sob.weight = nn.Parameter(torch.Tensor([[[[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]]]))\n self.y_sob.weight = nn.Parameter(torch.Tensor([[[[1, 2, 1], [0, 0, 0], [-1, -2, -1]]]]))\n #self.apply_thresh = MaxPool2dStaticSamePadding(kernel_size=(3, 3), stride=1)\n self.low_threshold = nn.Parameter(torch.Tensor([0.05]))\n self.high_threshold = nn.Parameter(torch.Tensor([0.15]))\n self.blur = v2.GaussianBlur(kernel_size=5, sigma=1.4)\n\n def forward(self, x):\n # Gaussian blur & sobel filter\n x = self.blur(x)\n gX = self.x_sob(x)\n gY = self.y_sob(x)\n\n # Calculate Magnitude and angle theta\n mag = torch.sqrt(torch.pow(gX, 2) + torch.pow(gY, 2))\n mag = ((mag / torch.max(mag)) * 255)\n theta = torch.arctan2(gY, gX)\n\n # Create nms representation of img\n #img = self.non_max_suppression(mag, theta)\n img = mag\n\n # calculate low and high threshold\n batch_size = img.size(0)\n h_t = img.reshape(batch_size, -1).max(dim=1).values.reshape(batch_size, 1, 1, 1) * self.high_threshold\n l_t = h_t * self.low_threshold\n\n # accept pixels values higher than h_t, reject pixel value lower l_t, create mask\n accept_mask = (img > h_t).bool()\n reject_mask = (img < l_t).bool()\n\n # get values between high and low threshold\n bet_mask = ((img > l_t) & (img < h_t)).bool()\n\n # set all value in \"img\" to zero which are not True in the accept mask\n img_acc = img.masked_fill(~accept_mask, 0)\n\n # apply hysteresis by using max_pooling -> all pixels with neighbouring \"strong\" pixels get also \"strong\"\n #img_th = self.apply_thresh(img_acc)\n img_th = img_acc\n\n # create a mask where all fields are true which fall between the thresholds\n img_b_mask = img.masked_fill(~bet_mask, 0).bool()\n\n # Replace all values < 0 in img_acc with the strong neighbours which are in bet_mask, else 0\n out = torch.where(img_acc > 0, img_acc, img_th.masked_fill(~img_b_mask, 0))\n out = torch.where(reject_mask, 0, out) # Apply reject mask directly\n out = torch.where(out > 0, 255.0, 0.0).to(torch.float32)\n # out.requires_grad = True\n\n #THIS WORKS BETTER: return img_th[0, 0, :200, :200]\n return out[0,0,:200,:200]\n\n# Init\nnet = NeuralNetwork()\nnet.train()\noptimizer = torch.optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\nloss_fn = torch.nn.CrossEntropyLoss()\n\n# Print parameters before backward to see if there is a change\nprint(list(net.parameters()))\n\n# Dummy input and labels\nlbl = torch.randn(3,1,224,224)\ninp = torch.randn(3,1,224,224)\n\noptimizer.zero_grad()\n\nres = net(inp)\nl = loss_fn(res, lbl[0,0,:200,:200])\nprint(\"LOSS:\", l)\nl.backward()\noptimizer.step()\n\n# Print parameters again\nprint(list(net.parameters()))\n```"},{"role":"assistant","content":"Could you check if `img_acc` shows a valid `.grad_fn` inside the `forward` method? If so, your masking might not select any of its values which are attached to a computation graph."}],"kind":"clarification","thread_id":207434,"url":"https://discuss.pytorch.org/t/loss-backward-throws-error-because-output-tensor-has-no-gradient/207434","created_at":"2024-08-02T07:21:44.339000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Problem with Unet multiclass image segmentation and overlapping classes\n\nHi,\nI'm working on a personal project, and I'm trying to use UNet to mask the lead and the big boxes from the ECG paper into two different classes. I created my dataset containing 200 images of ECG paper, lead masks, and big boxes masks. However, my problem is that the model always predicts both classes the same way, with both classes being visible in the other class's prediction. for example:\n[image]\nmy image shape is [N, C, H, W] (batch, class, height, width) and the class dims are:\n[0, 0] if the pixel is not in any classes, example: [N, [0, 0], H, W]\n[1, 0] if the pixel is in the class lead, example: [N, [1, 0], H, W]\n[0, 1] if the pixel is in the class boxes, example: [N, [0, 1], H, W]\n[1, 1] if the pixel is in both classes, example: [N, [1, 1], H, W]\nI'm using Dice Loss and the Adam Optimizer. The model outputs in the shape of [N, 2, H, W] (2 for the two classes), and I squeeze then split them using numpy: [0, :, :] for the lead class and [1, :, :] for the boxes class into their respective variables.\nI don't understand why the model predicts both classes in both classes. Could it be that my way of dividing them into two different arrays?\n(there are some minor differences between both class predictions, so I know they are not exact copy of each other.)"},{"role":"assistant","content":"Could you check how your criterion processes the model outputs and if multi-label targets are supported? For the sake of debugging you could also pass the model output to `nn.BCEWithLogitsLoss` and compare it to your current approach."}],"kind":"answer","thread_id":207472,"url":"https://discuss.pytorch.org/t/problem-with-unet-multiclass-image-segmentation-and-overlapping-classes/207472","created_at":"2024-08-03T05:29:16.950000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Cuda not working on NVIDIA Jetson\n\nI'm trying to get cuda working on Nvidia Jetson AGX Xavier with PyTorch but torch.cuda.is_available() keeps returning false. I have installed Cuda 11.4 along with the standard Jetpack (v5.1.3-b29) installation. I have also installed Python 3.9, PyTorch 2.0.1 compiled with Cuda 11.8 and TorchVision 0.15. \n\nI would appreciate any help I can get in solving this issue. Thanks in advance."},{"role":"assistant","content":"Install the PyTorch binaries from https://forums.developer.nvidia.com/t/pytorch-for-jetson/72048, or run an L4T container."}],"kind":"answer","thread_id":207571,"url":"https://discuss.pytorch.org/t/cuda-not-working-on-nvidia-jetson/207571","created_at":"2024-08-05T12:37:13.041000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Forward Hooks Not Working When `model.eval()` and `torch.no_grad()`\n\nFor `TransformerEncoder` network, when I created a forward hook, it does not get called if there are `model.eval()` and `with torch.no_grad():`\n\nHere is a code to reproduce:\n```\nimport torch\nmodel = torch.nn.TransformerEncoder(encoder_layer=torch.nn.TransformerEncoderLayer(100, 4, 200, batch_first=True), num_layers=3).to('cuda')\ninput = torch.randn(2, 10, 100).to('cuda')\n\ndef createHook(name):\n print(f\"Hook for {name} is set\")\n \n def hook(model, input, output):\n print(f\"Hook working\")\n\n return hook\n\nfor i in range(len(model.layers)):\n model.layers[i].self_attn.register_forward_hook(createHook(f\"t_layer_{i}\"))\n\nmodel.eval()\nwith torch.no_grad():\n pred = model(input) \n pred = pred.cpu().detach().numpy()\n```\nIt gives \"Hook for * is set\" as output, but it does not print \"Hook working\", (and it does not actually call the hook).\n\nI observed that when there is only `model.eval()`, it works. Also, when there is only `with torch.no_grad()`, it also works. Somehow using both of them make it not working. And also, I only observed this with `TransformerEncoder`\n\nIs this some kind of a bug? Or, am I missing something?"},{"role":"assistant","content":"As one user suggested in the github issue, this problem can be overcomed by simply using `torch.backends.mha.set_fastpath_enabled(False)`. Apparently fastpath disables the hooks"}],"kind":"answer","thread_id":207596,"url":"https://discuss.pytorch.org/t/forward-hooks-not-working-when-model-eval-and-torch-no-grad/207596","created_at":"2024-08-05T18:18:53.129000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["enerd"]} | |
| {"messages":[{"role":"user","content":"Create a view using subsampling\n\nFor example with a tensor\n```\n[ [0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]]\n```\ncreate a view exposing\n```\n[ [0,2],[4,6],[8,10],[12,14]]\n```\nObviously this is not a reshaping with AFAIK is all you can do with view. However, it doesn't seem like it would be impossible so I though I would ask."},{"role":"assistant","content":"Direct indexing should work:\n```python\nx = torch.tensor([[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]])\ny = x[:, ::2]\nprint(y)\n# tensor([[ 0, 2],\n# [ 4, 6],\n# [ 8, 10],\n# [12, 14]])\n\ny[0, 0].fill_(100)\nprint(x)\n# tensor([[100, 1, 2, 3],\n# [ 4, 5, 6, 7],\n# [ 8, 9, 10, 11],\n# [ 12, 13, 14, 15]])\n```"}],"kind":"answer","thread_id":207714,"url":"https://discuss.pytorch.org/t/create-a-view-using-subsampling/207714","created_at":"2024-08-07T20:43:32.504000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Why is LibTorch from pip not build with CXX11 ABI\n\nThe opencv and torch problem continues to persist with the libtorch that comes torch installed via pip. I use conan as my package manager for most packages, so naturally i install opencv via conan. But when i try to link both torch installed via pip (cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH=`python3 -c 'import torch;print(torch.utils.cmake_prefix_path)'` ..) and opencv from conan i get the usual error that everyone faces. I need to specify in my conan profile the cxx flag CXXFLAGS=-D_GLIBCXX_USE_CXX11_ABI=0 which builds opencv without the cxx11 abi and then everything compiles as expected. I have seen many threads that suggest to use the libtorch cpp package from the site with abi **libtorch-cxx11-abi-shared-with-deps** (see https://discuss.pytorch.org/t/library-conflict-between-libtorch-and-opencv/64489/8), but i like the idea of using the libtorch that comes with pip, it would reduce duplicates of the package. I was wondering why the libtorch that comes torch pip is not compile with -D_GLIBCXX_USE_CXX11_ABI=1 ? I use opencv/4.8.1 (conan) and torch==2.4.0 (pip). My conan profile for the curious:\n```\n[settings]\nos=Linux\narch=x86_64\ncompiler=gcc\ncompiler.version=11\ncompiler.libcxx=libstdc++11\ncompiler.cppstd=17\nbuild_type=Release\n\n[options]\n\n[tool_requires]\n\n[buildenv]\nCC=/usr/bin/gcc-11\nCXX=/usr/bin/g++-11\nCXXFLAGS=-D_GLIBCXX_USE_CXX11_ABI=0 # I need it for the moment to tell conan to install opencv withouth cxx abi\n```\n\nAs you can see i am pretty up to date with gcc version and all. So just curious, is it a miss that the libtorch packaged with torch pip is not the one installed with abi, or is it because it would break something?"},{"role":"assistant","content":"The wheels support `manylinux` based on CentOS7 as described [here](https://github.com/pytorch/pytorch/issues/51039) and thus are build without the CXX11 ABI. Since CentOS7 is EOL already, future releases could relax the requirement and use the CXX11 ABI."}],"kind":"answer","thread_id":207765,"url":"https://discuss.pytorch.org/t/why-is-libtorch-from-pip-not-build-with-cxx11-abi/207765","created_at":"2024-08-08T18:07:11.017000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Correctlly assign weights BinaryClassification BCEWithLogitsLoss\n\nHey\n\nCan I ask if this is the correct way to assigned weights for unbalanced dataset?\n\nmy class weights are \n{0: 1.94, 1: 0.67}\n\ncriterion = torch.nn.BCEWithLogitsLoss(pos_weight = torch.FloatTensor([1.94 / 0.67]).to(device)) \n\nabove is correct?"},{"role":"assistant","content":"[This post](https://discuss.pytorch.org/t/bceloss-with-class-weights/196991/4?u=ptrblck) might be helpful."},{"role":"user","content":"num_negative / num positives\n\nPatric question:\n\naccording to your post it is:\n\nnum_neg / num_positive\n\nso if:\n\n0: 10000 1:20000\n\nit will be \n\n10000/20000\n\nbut if\n\n0: 20000 1:10000\n\n20000/10000?\n\nis this correct? my understanding"},{"role":"assistant","content":"Yes, the [docs](https://pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.html) are also giving the example:\n> For example, if a dataset contains 100 positive and 300 negative examples of a single class, then `pos_weight` for the class should be equal to `300/100=3`. The loss would act as if the dataset contains `3×100=300` positive examples."}],"kind":"answer","thread_id":207883,"url":"https://discuss.pytorch.org/t/correctlly-assign-weights-binaryclassification-bcewithlogitsloss/207883","created_at":"2024-08-10T23:58:23.037000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"NLP indexing question\n\nhi guys.\ni want to train LSTM network for filling a form using a given text.\nnow when i turn my inputs and labels to tokens, i have something like: \n```\ntensor([[ 0, 15, 14, ..., 0, 0, 0],\n [ 0, 15, 14, ..., 0, 0, 0],\n [ 0, 15, 14, ..., 0, 0, 0],\n ...,\n [ 0, 15, 14, ..., 0, 0, 0],\n [ 0, 15, 14, ..., 43, 0, 0],\n [ 0, 15, 14, ..., 0, 0, 0]])\n```\nfor input text, and :\n```\ntensor([[ 175, 153, 202, 242, 482],\n [ 186, 26, 627, 363, 393],\n [ 171, 26, 190, 835, 246],\n [ 160, 149, 313, 449, 337],\n [ 157, 152, 1001, 1024, 408],\n [ 186, 149, 551, 1020, 288],\n [ 158, 154, 445, 1051, 259],\n [ 159, 149, 791, 1104, 432],\n [ 166, 155, 553, 780, 259],\n [ 159, 153, 767, 462, 246],\n [ 168, 149, 188, 378, 302],\n [ 179, 149, 237, 461, 291],\n [ 163, 152, 1000, 690, 235],\n [ 165, 153, 223, 968, 289],\n [ 164, 154, 445, 236, 215],\n [ 159, 153, 442, 390, 807],\n [ 183, 154, 765, 1036, 488],\n [ 181, 154, 221, 970, 480],\n [ 157, 153, 905, 473, 249],\n [ 161, 154, 369, 242, 479],\n [ 169, 153, 271, 196, 253],\n [ 178, 149, 476, 1110, 488],\n [ 159, 26, 241, 222, 342],\n [ 163, 152, 534, 467, 232],\n [ 179, 152, 818, 200, 302],\n [ 173, 26, 1169, 602, 267],\n [ 158, 149, 306, 581, 329],\n [ 179, 153, 191, 304, 492],\n [ 174, 149, 788, 311, 301],\n [ 173, 149, 545, 883, 302],\n [ 163, 152, 910, 543, 411],\n [ 183, 26, 446, 319, 505]])\n\n```\nfor my labels.\nnow i am confused how to put them inside the loss function.\nalso my network class is :\n```\nclass FormFillingModel(nn.Module):\n def __init__(self, vocab_size, embed_size, hidden_size, num_tags):\n super(FormFillingModel, self).__init__()\n self.embedding = nn.Embedding(vocab_size, embed_size)\n self.lstm = nn.LSTM(embed_size, hidden_size, batch_first=True)\n self.fc1 = nn.Linear(hidden_size, num_tags) # For age\n self.fc2 = nn.Linear(hidden_size, num_tags) # For action\n self.fc3 = nn.Linear(hidden_size, num_tags) # For first_name\n self.fc4 = nn.Linear(hidden_size, num_tags) # For last_name\n self.fc5 = nn.Linear(hidden_size, num_tags) # For date\n\n def forward(self, x):\n x = self.embedding(x)\n x, _ = self.lstm(x)\n x = x[:, -1, :] \n return self.fc1(x), self.fc2(x), self.fc3(x), self.fc4(x), self.fc5(x)\n```"},{"role":"assistant","content":"Assuming you want to classify each token in a sentence, the model outputs should have the shape `[batch_size, nb_classes, seq_len]`."}],"kind":"answer","thread_id":207942,"url":"https://discuss.pytorch.org/t/nlp-indexing-question/207942","created_at":"2024-08-12T11:30:25.952000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Torch uses wrong GPU\n\nI am using a laptop with two GPUs. The first one is a Intel(R) UHD Graphics and the second one is a NVIDIA GeForce RTX 4090 Laptop GPU. I want to run a RAG application using a llama3 model using the second GPU. When I run it, the model is loaded into memory. Afterwards the second GPU is used only until the streaming of the output starts. When streaming only the first GPU is used. This can be seen by running the application and watching the performance with the task manager.\n\nThe problem can be reproduced with the following code:\n\n```\nimport torch\nimport os\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer\nfrom pathlib import Path\n\ntorch.set_default_device(\"cuda\")\n\ndir_ = Path(__file__).parent\n\nmodel_path = \"my_path\"\n\ntokenizer = AutoTokenizer.from_pretrained(model_path, device_map=\"cuda\")\nmodel = AutoModelForCausalLM.from_pretrained(\n model_path,\n torch_dtype=torch.bfloat16,\n device_map=\"cuda\",\n load_in_8bit=True\n)\nmodel.generation_config.pad_token_id = tokenizer.pad_token_id\n\nterminators = [\n tokenizer.eos_token_id,\n tokenizer.convert_tokens_to_ids(\"<|eot_id|>\")\n]\n\ndef respond(message):\n\n messages = []\n user_message = {\"role\": \"user\", \"content\":\n \"\"\"\n Frage: '{query}'\n \"\"\".format(query=message)}\n messages.extend([{\"role\": \"system\", \"content\": 'Du bist ein Assistent, der Fragen beantwortet.'},\n ]\n )\n messages.append(user_message)\n\n text = tokenizer.apply_chat_template(\n messages,\n tokenize=False,\n add_generation_prompt=True\n )\n\n model_inputs = tokenizer([text], return_tensors=\"pt\").to('cuda:0')\n\n generated_ids = model.generate(\n model_inputs.input_ids,\n do_sample=True,\n temperature=0.01,\n top_p=0.9\n )\n \n answer = tokenizer.decode(generated_ids[0], skip_special_tokens=True)\n answer = answer.split('assistant')[-1]\n return answer\n \nprint(respond('Welche Sehenswürdigkeiten gibt es in Berlin?'))\n```\n\nI checked that Cuda is using the right device by typing `python -m torch.utils.collect_env` in the console. This resulted in:\n\n```\n<frozen runpy>:128: RuntimeWarning: 'torch.utils.collect_env' found in sys.modules after import of package 'torch.utils', but prior to execution of 'torch.utils.collect_env'; this may result in unpredictable behaviour\nCollecting environment information...\nPyTorch version: 2.4.0+cu124\nIs debug build: False\nCUDA used to build PyTorch: 12.4\nROCM used to build PyTorch: N/A\n\nOS: Microsoft Windows 11 Pro\nGCC version: Could not collect\nClang version: Could not collect\nCMake version: Could not collect\nLibc version: N/A\n\nPython version: 3.11.7 (tags/v3.11.7:fa7a6f2, Dec 4 2023, 19:24:49) [MSC v.1937 64 bit (AMD64)] (64-bit runtime)\nPython platform: Windows-10-10.0.22631-SP0\nIs CUDA available: True\nCUDA runtime version: 12.4.131\nCUDA_MODULE_LOADING set to: LAZY\nGPU models and configuration: GPU 0: NVIDIA GeForce RTX 4090 Laptop GPU\nNvidia driver version: 551.78\ncuDNN version: Could not collect\nHIP runtime version: N/A\nMIOpen runtime version: N/A\nIs XNNPACK available: True\n\nCPU:\nArchitecture=9\nCurrentClockSpeed=2200\nDeviceID=CPU0\nFamily=207\nL2CacheSize=32768\nL2CacheSpeed=\nManufacturer=GenuineIntel\nMaxClockSpeed=2200\nName=13th Gen Intel(R) Core(TM) i9-13900HX\nProcessorType=3\nRevision=\n\nVersions of relevant libraries:\n[pip3] mypy-extensions==1.0.0\n[pip3] numpy==1.26.3\n[pip3] onnxruntime==1.16.3\n[pip3] torch==2.4.0+cu124\n[pip3] torchaudio==2.4.0+cu124\n[pip3] torchvision==0.19.0+cu124\n[conda] Could not collect\n```\n\nI also tried\n\n```\nprint(torch.cuda.is_available())\nprint(torch.cuda.device_count())\nprint(torch.cuda.current_device())\nprint(torch.cuda.get_device_name(0))\n```\n\nand got\n\n```\nTrue\n1\n0\n'NVIDIA GeForce RTX 4090 Laptop GPU'\n```\n\nAs far as I understand, everything runs with cuda and since the NVIDIA GPU is the only cuda device, only this GPU should be used.\n\nDoes somebody know how to use the NVIDIA GPU only when running the application? Why is the Intel GPU used when it is not even detected by cuda?"},{"role":"assistant","content":"I doubt it as your Intel UHD Graphics seems to be an integrated GPU, which does not support CUDA (and I don't know if any other Intel backends are supported on it).\n\nMake sure to check the `compute` tab in your Task Manager or use `nvidia-smi` to see the utilization of your GPU."}],"kind":"answer","thread_id":208011,"url":"https://discuss.pytorch.org/t/torch-uses-wrong-gpu/208011","created_at":"2024-08-13T12:26:14.510000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Can't create tensors as shown in first Captum Titanic tutorial?!\n\nI'm stumped by the simplest part of the most basic \"Titanic Basic\" [captum tutorial](https://captum.ai/tutorials/Titanic_Basic_Interpret): converting the data into tensors?!\n\nAfter getting the data and performing the first preprocessing steps,\nconverting to numpy arrays and separating out train and test sets works fine:\n\n\t\tdata = titanic_data.to_numpy()\n\n\t\ttrain_indices = np.random.choice(len(labels), int(0.7*len(labels)), replace=False)\n\t\ttest_indices = list(set(range(len(labels))) - set(train_indices))\n\t\ttrain_features = data[train_indices]\n\t\ttrain_labels = labels[train_indices]\n\t\ttest_features = data[test_indices]\n\t\ttest_labels = labels[test_indices]\n\nbut converting to tensors doesn't work:\n\n\t\tFile \".../Titanic_Basic_Interpret.py\", line 139, in <module>\n\t\tinput_tensor = torch.as_tensor(train_features,dtype=torch.float32)\n\t\t^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\t\tTypeError: can't convert np.ndarray of type numpy.object_. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.\n\nMaybe the problem is [\"no more magic, convert_objects has been\ndeprecated in pandas 0.17\" ](https://stackoverflow.com/a/21197863)? It seems the tutorial was added back in 2019, but other issues seem to have used it more recently?\n\nI've tried some of the suggestions there (building a separate dictionary of data types and then `data = data.astype(dtype=dtypeDict)`, converting each column separately:\n\n\t\tfor c in titanic_data.columns:\n\t\t titanic_data[c] = pd.to_numeric(titanic_data[c])\n\nbut these don't go thru either. What could the issue be?!"},{"role":"assistant","content":"way simpler than I'd imagined: `data = data.astype(np.float32)` is all that was required!"}],"kind":"answer","thread_id":208024,"url":"https://discuss.pytorch.org/t/cant-create-tensors-as-shown-in-first-captum-titanic-tutorial/208024","created_at":"2024-08-13T16:26:29.307000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["rbelew"]} | |
| {"messages":[{"role":"user","content":"Weird Pytorch profiler output\n\nHello,\n\nI am profiling my training code and I'm struggling to understand the output. The different steps seem to be taking different amount of time and I am not sure why.\n[image]\n\nA simplified version of my code would be:\n```\nwith profiler.profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], ...) as p:\n for x, y in training_dataloader:\n p.step()\n out = model(x)\n loss = loss_fn(out,y)\n loss.backward()\n optim.step()\n optim.zero_grad()\n```\n\nScheduler is set to `skip_first=10, wait=5, warmup=1, active=5, repeat=1`\n\nIf I then add some operation that downloads something to cpu memory such as `l = loss.item()` after the optimizer step, I get something like this:\n\n[image]\nIn both scenarios the average train step is the same even though each profiler step seems to vary in time in the first case.\n\nI am a bit confused by this behaviour. My hypothesis is that my profiler might be measuring the async python function calls and not the actual cuda kernels. But isn't the point of the profiler to measure the cuda kernel time? I am interested in analysing how long does my CPU and GPU take in each part of the code, and I guess here I am just seeing the CPU? \n\nIf I go down below in the GPU thread part of the profiler, I get this, which I don't understand or is giving me too little information about how long is spent in each kernel by the gpu. \n\n[image]\n\nNote that this screenshot is taken for the first example where i do NOT add l = loss.item() and all the different steps are taking different time in cpu time. Yet in the GPU thread they seem to be taking the same amount of time.\n\nI would appreciate any insights on why this is happening or if my intuitions are correct and what is the best way to measure how long is my GPU spending in each kernel.\n\nI am using a 4090 GPU and the model is a simple UNet with 128x128 image input.\n\nThanks,\nBenet"},{"role":"assistant","content":"This is expected since the `item()` call is synchronizing the GPU.\n\nYes, this seems to be the case and I would expect to see different time lines: one for the host and another one for the device.\n\nI'm not familiar with the native PyTorch profiler visualization as I am using Nsight Systems for profiling. You could check [this post](https://dev-discuss.pytorch.org/t/using-nsight-systems-to-profile-gpu-workload/59) for instructions on how to use `nsys`."}],"kind":"answer","thread_id":208078,"url":"https://discuss.pytorch.org/t/weird-pytorch-profiler-output/208078","created_at":"2024-08-14T16:07:31.597000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Reproducing results across different machines (CPU) - Dropout layers\n\nI was trying to reproduce the results for a CNN in two different machines (both running on CPU) but I ended up with different results (setting the same python and torch seed in advance). After checking the CNN layers individually, I noticed that the difference is caused in the Dropout layer specifically. I couldn't find the exact implementation for Dropout, so I was wondering if there's any idea on what may be behind this?\n\nSome additional details:\n```\nimport random\nimport torch\nrandom.seed(2)\ntorch.manual_seed(3)\na = torch.randn(4, 4)\ndp1 = torch.nn.Dropout(p=0.3)\ndp1(data)\n# Result in one of the machines:\n# tensor([[-1.0361, -3.5810, -0.0000, 1.8477],\n# [-2.0117, -0.0000, -0.0785, 1.7217],\n# [-0.0000, -2.3690, -0.0955, -0.7392],\n# [-0.0000, 1.5011, 1.8367, 2.3154]])\n# Result for the other machine:\n# tensor([[-1.0361, -0.0000, -1.1379, 1.8477],\n# [-2.0117, -1.2687, -0.0000, 1.7217],\n# [-1.4952, -2.3690, -0.0000, -0.7392],\n# [-0.4844, 1.5011, 1.8367, 2.3154]])\n```\n\n- I also tried the tips from the reproducibility page - using deterministic algorithms, ... However, the results are still different.\n- I used a docker image, so library versions are exactly the same (Python 3.9/torchvision 0.11.1/torch 1.10.0)\n\nAny tips/ideas are welcome, thanks."},{"role":"assistant","content":"As described in the [reproducibility docs](https://pytorch.org/docs/stable/notes/randomness.html) there is no guarantee to receive exactly the same random values between different platforms, CPUs, GPUs etc."}],"kind":"answer","thread_id":208180,"url":"https://discuss.pytorch.org/t/reproducing-results-across-different-machines-cpu-dropout-layers/208180","created_at":"2024-08-16T17:58:36.127000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Need to run torch 1.9.0 >= 1.60 on RTX4090\n\nNeed to run torch 1.9.0 >= 1.6.0 on RTX4090 because these are the requirements for Unity mlagents\nWhat I need to figure out is what version of Cuda to install to satisfy these requirements on Ubuntu 20.04\nI've tried Cuda Version 12.7 and 11.6 with torch 1.6.0 but I still see the same error:\n\n```\nNVIDIA GeForce RTX 4090 with CUDA capability sm_89 is not compatible with the current PyTorch installation.\nThe current PyTorch install supports CUDA capabilities sm_37 sm_50 sm_60 sm_70 sm_75\n```"},{"role":"assistant","content":"CUDA 12.7 is not a thing and your locally installed CUDA toolkit won't be used (unless you build PyTorch from source or a custom CUDA extension). Based on the error message you have installed a PyTorch binary with CUDA 10.2 runtime dependencies and you can verify it via `print(torch.version.cuda)`. If so, install a PyTorch binary with CUDA 11+ runtime dependencies."}],"kind":"answer","thread_id":208225,"url":"https://discuss.pytorch.org/t/need-to-run-torch-1-9-0-1-60-on-rtx4090/208225","created_at":"2024-08-18T01:03:54.498000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Is there a forum for discussion of GPU hardware for PyTorch?\n\nI am reasonably knowledgeable with Caffe and pretty strong with Python and C++, but a fair newbie to PyTorch. I have questions about performance - and expected performance - of different hardware while training networks like ResNet34 using PyTorch. Is there a forum where the focus is on hardware for PyTorch and tuning for hardware, rather than programming with PyTorch per se?\n\nExample: running [github.com/pytorch/examples/tree/main/imagenet](https://github.com/pytorch/examples/tree/main/imagenet) I get similar performance with an old Radeon Pro VII as an Nvidia L4, and an Nvidia A100 is only about 80% faster than either. But I think this is not the best place to be asking?"},{"role":"assistant","content":"You can just ask here. \n\nTo your question about performance of different devices: profile your workload to isolate where the bottleneck if your code is. E.g. if all use cases are CPU-limited, a better GPU will hardly improve the end2end performance."}],"kind":"answer","thread_id":208314,"url":"https://discuss.pytorch.org/t/is-there-a-forum-for-discussion-of-gpu-hardware-for-pytorch/208314","created_at":"2024-08-19T22:10:29.221000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Torch's to()'s D2D Bandwidth is way lower than just call cudaMemcpyAsync()\n\nHello Community. :slight_smile:\n\nI've got a way different NVLink bandwidth on [NVIDIA's p2pBandwidthLatencyTest](https://github.com/NVIDIA/cuda-samples/tree/master/Samples/5_Domain_Specific/p2pBandwidthLatencyTest) and just simple pytorch Tensor.to() microbenchmark.\n\n```\nimport torch\n\nn_test = 50\n\nsize = 1 * 1024**3\n\nsrc_stream = torch.cuda.Stream(0)\ndst_stream = torch.cuda.Stream(1)\n\nbegin = [torch.cuda.Event(enable_timing=True) for _ in range(n_test)]\nend = [torch.cuda.Event(enable_timing=True) for _ in range(n_test)]\n\nprint(\n torch.cuda.can_device_access_peer(\"cuda:0\", \"cuda:1\"),\n torch.cuda.can_device_access_peer(\"cuda:1\", \"cuda:0\"),\n)\n\nfor idx in range(n_test):\n with torch.cuda.stream(src_stream), torch.cuda.stream(dst_stream):\n src_tensor = torch.zeros(size, dtype=torch.int8, device=\"cuda:0\")\n\n begin[idx].record(src_stream)\n dst_tensor = src_tensor.to(\"cuda:1\", non_blocking=True)\n end[idx].record(src_stream)\n\n src_stream.synchronize()\n dst_stream.synchronize()\n\nfor idx in range(n_test):\n print(\n idx,\n (size / 1 * 1024**3) / (begin[idx].elapsed_time(end[idx]) / 1000),\n \"GiB/s\",\n )\n\n```\n\nWith Nvidia's p2pBandwidthLatencyTest ~260 GiB/s\nWith PyTorch: ~180 GiB/s\n\nAnd, also when I profile them with nsight system. It shows that there is a difference in utilization of NVLink Bandwidth like the below screenshots. \n\n**With PyTorch**\n[image]\n\n**With Nvidia's p2pBandwidthLatencyTest**\n[image]\n\nI've tested transferring various sizes of tensors, it doesn't seem to change.\nI've tested this with CUDA-12.1, 12.4, PyTorch 2.1.0, 2.4.0, and even with libtorch.\n\nMy test setup is like Ubuntu 22.04, A100-PCIE-40GB * 2ea with NVLink\n\nDoes anyone know how to increase this NVLink Bandwidth? and why NVLink Bandwidths are slowed down with Torch?"},{"role":"assistant","content":"I don't believe your code is measuring what you are expecting since just executing it on my system shows:\n```python\nTrue True\n0 1.8611069056223566e+20 GiB/s\n1 2.858158028990284e+20 GiB/s\n2 2.8896318645194097e+20 GiB/s\n3 2.879378253393044e+20 GiB/s\n4 2.88518891328474e+20 GiB/s\n5 2.885281356930677e+20 GiB/s\n6 2.856911514236231e+20 GiB/s\n7 2.870820626852414e+20 GiB/s\n8 2.860109177266271e+20 GiB/s\n9 2.8837802682572302e+20 GiB/s\n10 2.8664580582636336e+20 GiB/s\n11 2.892717548554107e+20 GiB/s\n...\n```\nUsing a synchronized host timer shows the expected throughput and comes close to the `p2pbandwidth` output:\n```python\nTrue True\n120.0287539103961\n172.00936547064114\n243.15145801687785\n246.97742448140528\n245.87622759793612\n246.23833937204734\n245.2449410922305\n245.96833192313278\n245.55683371862324\n245.98291216146774\n245.2250435656027\n245.91504775655062\n246.70707711492975\n246.7607121895865\n246.61070882572474\n246.08115898634074\n245.74239032439328\n247.3937729274789\n...\n```\n```python\n./p2pBandwidthLatencyTest\n...\nUnidirectional P2P=Enabled Bandwidth (P2P Writes) Matrix (GB/s)\n D\\D 0 1 2 3 4 5 6 7 \n 0 1275.51 262.12 262.87 273.39 274.27 273.18 272.84 273.50 \n 1 262.01 1286.01 263.14 273.80 273.30 273.74 273.65 273.77 \n 2 261.31 263.34 1282.84 272.24 273.98 273.20 274.26 273.93 \n 3 263.15 265.36 263.82 1301.00 274.83 273.43 275.73 275.37 \n 4 263.06 264.02 263.27 275.80 1303.17 273.29 274.73 274.76 \n 5 263.67 264.33 263.92 274.93 273.94 1301.00 274.82 273.04 \n 6 262.78 263.84 263.52 264.28 275.18 275.69 1298.84 273.23 \n 7 265.20 264.37 264.31 265.14 274.91 275.44 274.76 1302.08 \n```"}],"kind":"answer","thread_id":208340,"url":"https://discuss.pytorch.org/t/torchs-to-s-d2d-bandwidth-is-way-lower-than-just-call-cudamemcpyasync/208340","created_at":"2024-08-20T09:42:01.649000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Conv2d output is NaN on GPU, but not on CPU\n\nI've been working on this project with a collaborator lately and we've been trying to train a large Unet model (~800k params). I noticed that when I tried to train the model on my GPU I got a nan loss. After sifting through possible issues, I came across that my activations started off as well distributed normalized numbers and eventually an upsampling followed by a 2D convolution caused some of the activations to become nan. These eventually cascaded down the rest of the model and turned the entire output, gradients, and loss into nan. This didn't occur on my CPU however.\n\nI managed to distill the error to just this:\n```\n>>>x = torch.rand((32,64,16,16)).to(torch.float32).to(\"cpu\")\n>>>\n>>>conv = nn.Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)).to(torch.float32).to(\"cpu\")\n>>>\n>>>with torch.no_grad():\n>>> output = conv(x)\n>>>print(output.isnan().any())\ntensor(False, device='cuda:0')\n```\n```\n>>>x = torch.rand((32,64,16,16)).to(torch.float32).to(\"cuda\")\n>>>\n>>>conv = nn.Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)).to(torch.float32).to(\"cuda\")\n>>>\n>>>with torch.no_grad():\n>>> output = conv(x)\n>>>print(output.isnan().any())\ntensor(True, device='cuda:0')\n```\nWhere the output tensor from the GPU has a shape of torch.Size([32, 64, 16, 16]) looks like this:\n```\ntensor([[[[ nan, nan, 0.0310, ..., nan, 0.0310, 0.0310],\n [ nan, 0.0310, nan, ..., 0.0310, nan, 0.0310],\n [ nan, 0.0310, 0.0310, ..., 0.0310, nan, 0.0310],\n ...,\n [ nan, 0.0310, nan, ..., nan, nan, 0.0310],\n [ nan, 0.0310, 0.0310, ..., 0.0310, nan, 0.0310],\n [ 0.0310, nan, 0.0310, ..., nan, 0.0310, 0.0310]],\n\n [[-0.0250, -0.0250, -0.0250, ..., -0.0250, -0.0250, -0.0250],\n [-0.0250, -0.0250, -0.0250, ..., -0.0250, -0.0250, -0.0250],\n [-0.0250, -0.0250, -0.0250, ..., -0.0250, -0.0250, -0.0250],\n ...,\n [-0.0250, -0.0250, -0.0250, ..., -0.0250, -0.0250, -0.0250],\n [-0.0250, -0.0250, -0.0250, ..., -0.0250, -0.0250, -0.0250],\n [-0.0250, -0.0250, -0.0250, ..., -0.0250, -0.0250, -0.0250]],\n\n [[ nan, nan, 0.0058, ..., 0.0058, nan, nan],\n [ nan, nan, nan, ..., nan, nan, nan],\n [ nan, nan, nan, ..., nan, nan, nan],\n ...,\n [ 0.0058, 0.0058, 0.0058, ..., nan, 0.0058, nan],\n [ nan, nan, 0.0058, ..., 0.0058, nan, nan],\n [ nan, nan, nan, ..., nan, nan, nan]],\n\n ...,\n...\n ...,\n [ 0.0051, 0.0051, 0.0051, ..., 0.0051, 0.0051, 0.0051],\n [ 0.0051, 0.0051, 0.0051, ..., 0.0051, 0.0051, 0.0051],\n [ 0.0051, 0.0051, 0.0051, ..., 0.0051, 0.0051, 0.0051]]]],\n device='cuda:0', dtype=torch.float16)\n```\nTo me it seems there are a surprising amount of repeated numbers and nan.\n\nMy GPU is an NVIDIA GeForce GTX 1660 Ti and I'm running this through WSL2. I'm using pytorch 11.7 and CUDA 11.5. \n\nIf anyone has any ideas what might be causing this issue and how to resolve it, I'd love to hear whatever ideas you guys have to say. I'm still relatively new deep learning so this is turning out to be quite the challenge for me."},{"role":"assistant","content":"Check which PyTorch version you have installed. If it is an old one, update to the latest release and rerun the code. In this thread, moving to torch 2.4.0 removed the NaN values from the convolution."}],"kind":"answer","thread_id":208441,"url":"https://discuss.pytorch.org/t/conv2d-output-is-nan-on-gpu-but-not-on-cpu/208441","created_at":"2024-08-21T23:11:40.912000Z","tier":"silver","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["GalvanizedHeart","ptrblck"]} | |
| {"messages":[{"role":"user","content":"Conv2d output is NaN on GPU, but not on CPU\n\nI've been working on this project with a collaborator lately and we've been trying to train a large Unet model (~800k params). I noticed that when I tried to train the model on my GPU I got a nan loss. After sifting through possible issues, I came across that my activations started off as well distributed normalized numbers and eventually an upsampling followed by a 2D convolution caused some of the activations to become nan. These eventually cascaded down the rest of the model and turned the entire output, gradients, and loss into nan. This didn't occur on my CPU however.\n\nI managed to distill the error to just this:\n```\n>>>x = torch.rand((32,64,16,16)).to(torch.float32).to(\"cpu\")\n>>>\n>>>conv = nn.Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)).to(torch.float32).to(\"cpu\")\n>>>\n>>>with torch.no_grad():\n>>> output = conv(x)\n>>>print(output.isnan().any())\ntensor(False, device='cuda:0')\n```\n```\n>>>x = torch.rand((32,64,16,16)).to(torch.float32).to(\"cuda\")\n>>>\n>>>conv = nn.Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)).to(torch.float32).to(\"cuda\")\n>>>\n>>>with torch.no_grad():\n>>> output = conv(x)\n>>>print(output.isnan().any())\ntensor(True, device='cuda:0')\n```\nWhere the output tensor from the GPU has a shape of torch.Size([32, 64, 16, 16]) looks like this:\n```\ntensor([[[[ nan, nan, 0.0310, ..., nan, 0.0310, 0.0310],\n [ nan, 0.0310, nan, ..., 0.0310, nan, 0.0310],\n [ nan, 0.0310, 0.0310, ..., 0.0310, nan, 0.0310],\n ...,\n [ nan, 0.0310, nan, ..., nan, nan, 0.0310],\n [ nan, 0.0310, 0.0310, ..., 0.0310, nan, 0.0310],\n [ 0.0310, nan, 0.0310, ..., nan, 0.0310, 0.0310]],\n\n [[-0.0250, -0.0250, -0.0250, ..., -0.0250, -0.0250, -0.0250],\n [-0.0250, -0.0250, -0.0250, ..., -0.0250, -0.0250, -0.0250],\n [-0.0250, -0.0250, -0.0250, ..., -0.0250, -0.0250, -0.0250],\n ...,\n [-0.0250, -0.0250, -0.0250, ..., -0.0250, -0.0250, -0.0250],\n [-0.0250, -0.0250, -0.0250, ..., -0.0250, -0.0250, -0.0250],\n [-0.0250, -0.0250, -0.0250, ..., -0.0250, -0.0250, -0.0250]],\n\n [[ nan, nan, 0.0058, ..., 0.0058, nan, nan],\n [ nan, nan, nan, ..., nan, nan, nan],\n [ nan, nan, nan, ..., nan, nan, nan],\n ...,\n [ 0.0058, 0.0058, 0.0058, ..., nan, 0.0058, nan],\n [ nan, nan, 0.0058, ..., 0.0058, nan, nan],\n [ nan, nan, nan, ..., nan, nan, nan]],\n\n ...,\n...\n ...,\n [ 0.0051, 0.0051, 0.0051, ..., 0.0051, 0.0051, 0.0051],\n [ 0.0051, 0.0051, 0.0051, ..., 0.0051, 0.0051, 0.0051],\n [ 0.0051, 0.0051, 0.0051, ..., 0.0051, 0.0051, 0.0051]]]],\n device='cuda:0', dtype=torch.float16)\n```\nTo me it seems there are a surprising amount of repeated numbers and nan.\n\nMy GPU is an NVIDIA GeForce GTX 1660 Ti and I'm running this through WSL2. I'm using pytorch 11.7 and CUDA 11.5. \n\nIf anyone has any ideas what might be causing this issue and how to resolve it, I'd love to hear whatever ideas you guys have to say. I'm still relatively new deep learning so this is turning out to be quite the challenge for me."},{"role":"assistant","content":"PyTorch 11.7 is not a thing so could you check which version you have installed? In case it's an older one, please update to the latest release and rerun your code."}],"kind":"clarification","thread_id":208441,"url":"https://discuss.pytorch.org/t/conv2d-output-is-nan-on-gpu-but-not-on-cpu/208441","created_at":"2024-08-21T23:11:40.912000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"RuntimeError: Cannot find callable deit_tiny_patch16_224 in hubconf\n\nHi,\n\nCould you someone help me understand why I got this error \"RuntimeError: Cannot find callable deit_tiny_patch16_224 in hubconf\", when running the following code: \n\n```\n model = torch.hub.load('facebookresearch/deit:main',\n 'deit_tiny_patch16_224', pretrained=True)\n```"},{"role":"assistant","content":"I cannot reproduce the issue using a recent nightly build:\n```python\nmodel = torch.hub.load('facebookresearch/deit:main',\n 'deit_tiny_patch16_224', pretrained=True)\n\nmodel\n# VisionTransformer(\n# (patch_embed): PatchEmbed(\n# (proj): Conv2d(3, 192, kernel_size=(16, 16), stride=(16, 16))\n# (norm): Identity()\n# )\n# (pos_drop): Dropout(p=0.0, inplace=False)\n# (patch_drop): Identity()\n# (norm_pre): Identity()\n# (blocks): Sequential(\n# (0): Block(\n# ...\n```"}],"kind":"answer","thread_id":208455,"url":"https://discuss.pytorch.org/t/runtimeerror-cannot-find-callable-deit-tiny-patch16-224-in-hubconf/208455","created_at":"2024-08-22T06:54:28.850000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Torchvision.transforms.v2 does nothing / fails silently?\n\nI want to transform a PIL image or np.ndarray, but it in both cases, the transform does nothing to the image. \n\n**Minimal reproducable example:** As you can see, the mean does not change\n```python\nimport torch\nimport numpy as np\nimport torchvision.transforms.v2 as v2\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\n## np.array (does nothing / fails silently)\nimg_np = np.ones((100,100,3))\nimg_np_transformed = v2.Pad(50)(img_np)\nprint(np.mean(img_np_transformed)) # still 1.0\nplt.imshow(img_np_transformed)\n\n## PIL image (does nothing / fails silently)\nimg_pil = Image.fromarray((img_np * 255).astype('uint8'))\nimg_pil_transformed = v2.Pad(50)(img_np) # still 1.0\nprint(np.mean(img_pil_transformed))\n\n## Tensor (works)\ntensor_img = torch.tensor(np.ones((1,3,100,100)))\ntensor_img_transformed = v2.Pad(50)(tensor_img)\nprint(float(tensor_img_transformed.mean())) # correct 0.25\nplt.figure()\nplt.imshow(np.transpose(tensor_img_transformed.squeeze(), (2, 1, 0)))\n```\n\nWhat do I do wrong or is this a bug? According to the [docs](https://pytorch.org/vision/stable/transforms.html#supported-input-types-and-conventions), PIL Images should work. And at least, I would expect an Exception if the input is invalid."},{"role":"assistant","content":"Apparently this not a bug but a feature for passing arbitrary data structures. However, this is (at this time) not very well described in the documents and is only described here https://pytorch.org/vision/stable/auto_examples/transforms/plot_transforms_getting_started.html#what-do-i-pass-as-input but e.g. not [here](https://pytorch.org/vision/stable/transforms.html)\n\nSee also [#8662](https://github.com/pytorch/vision/issues/8662)"}],"kind":"answer","thread_id":208500,"url":"https://discuss.pytorch.org/t/torchvision-transforms-v2-does-nothing-fails-silently/208500","created_at":"2024-08-22T21:05:48.862000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[9],"answer_authors":["turbotimon"]} | |
| {"messages":[{"role":"user","content":"Pytorch >= 2.1 is no more able to use my GPU :(\n\nWith all versions of PyTorch >= 2.1 I have this error:\n`RuntimeError: Torch is not able to use GPU; add --skip-torch-cuda-test to COMMANDLINE_ARGS variable to disable this check`\nIf I disable the check, it uses the CPU.\n\nOlder PyTorch 2.0.1 works perfectly on my system though, I still use it for the old version of ForgeUI. New versions of ForgeUI however need at least version 2.1 of PyTorch, else it says: `AttributeError: module 'torch' has no attribute 'float8_e4m3fn'`.\n\nCan someone help, please?\n\nWindows 7, Cuda11.4, RTX3060, Python 3.10.14"},{"role":"assistant","content":"It was indeed an incompatibility with Windows 7.\nIf someone ever has the same problem, here is how I fixed it:\n\nDon't replace the embed python with pythonwin7, it's not necessary. Don't replace any dll either.\nIf you copied \"api-ms-win-security-systemfunctions-l1-1-0.dll\" to \"system32\", remove it.\n\nInstall VxKex (the original repo is dead, I don't know which new source is safe to download it from: [i486/VxKex](https://github.com/i486/VxKex) / [Blaukovitch/VxKex](https://github.com/Blaukovitch/VxKex))\nIn VxKex settings, add Forge's \"system/python/python.exe\"\n\nUninstall pytorch and reinstall a compatible version, without torchaudio. \n```\npython -m pip uninstall Torch Torchvision Torchaudio\npython -m pip install torch==2.4.0 torchvision==0.19.0 --index-url https://download.pytorch.org/whl/cu118\n```\n\n\"LIBOMP140.X86_64.DLL\" will be missing, it's a known bug for pytorch 2.4.0. Download it, unzip and copy the dll in system32.\n[https://www.dllme.com/dll/files/libomp140_x86_64/00637fe34a6043031c9ae4c6cf0a891d](https://www.dllme.com/dll/files/libomp140_x86_64/00637fe34a6043031c9ae4c6cf0a891d)\n\nVoila."}],"kind":"answer","thread_id":208672,"url":"https://discuss.pytorch.org/t/pytorch-2-1-is-no-more-able-to-use-my-gpu/208672","created_at":"2024-08-26T16:46:27.252000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[13],"answer_authors":["Dom83"]} | |
| {"messages":[{"role":"user","content":"What does the `use_fast_accum` option do in `torch._scaled_mm`\n\nRecent PyTorch support for FP8 in the `torch._scaled_mm` has a `use_fast_accum` flag that I have found to increase throughput by a noticable amount.\nHowever, even after going through the CUDA code, I was unable to find out what this option does and what potential effects it may have on the matrix multiplication outputs.\nMay I ask for help on where to find detailed documentation on the matter?\nIf such documentation is not available, I would like to request that it be added, maybe in `torch.ao`.\n\nMany thanks in advance!"},{"role":"assistant","content":"This flag enables `CUBLASLT_MATMUL_DESC_FAST_ACCUM` [here](https://github.com/pytorch/pytorch/blob/dde5974b1368d26bc2cade9722b8ef242e46e242/aten/src/ATen/cuda/CUDABlas.cpp#L1432) which is defined as:\n> Flag for managing FP8 fast accumulation mode. When enabled, problem execution might be faster but at the cost of lower accuracy because intermediate results will not periodically be promoted to a higher precision. Default value: 0 - fast accumulation mode is disabled\n\nin the [cuBLAS docs](https://docs.nvidia.com/cuda/cublas/)."}],"kind":"answer","thread_id":208719,"url":"https://discuss.pytorch.org/t/what-does-the-use-fast-accum-option-do-in-torch-scaled-mm/208719","created_at":"2024-08-27T11:40:43.919000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"nn.Conv2d produces NaNs when specific value of out_channels is set\n\nI am trying to implement `fp16` training for a VQ-GAN. The issue is: `NaNs` appear in the first batch when using gradient scaler. I tracked down the issue to a specific `Conv2d` layer. I also saved the input coming to it which can be downloaded here:\n\nhttps://drive.google.com/file/d/1Wv74Bp46au4mWFhVAW9CikDejIkdsiNE/view?usp=drive_link\n\nCode to reproduce `NaNs`:\n```\nfrom torch.nn import GroupNorm, SiLU, Conv2d\n\ninf = torch.load(\"inf.pt\").cuda()\n\ngn1 = GroupNorm(16, 128, eps=1e-05, affine=True).cuda().half()\ns = SiLU()\n# out_channels: 64 -> 73 NaN\nconv1 = Conv2d(128, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)).cuda().half()\n\no_gn1 = gn1(inf)\no_s = s(o_gn1)\nconv1_out = conv1(o_s)\nconv1_out.min(), conv1_out.max()\n\n(tensor(nan, device='cuda:0', dtype=torch.float16, grad_fn=<MinBackward1>),\n tensor(nan, device='cuda:0', dtype=torch.float16, grad_fn=<MaxBackward1>))\n```\n\nThe weird part is that when I set `out_channels` to anything outside the [64, 73] range, `Nans` suddenly disappear. Also when I swich back to `fp32` the problem does not occur. Am I not seeing something important? I would appreciate any help, thanks.\n\nI run experiments on:\nCUDA: cuda_11.7\nTorch: 2.0.1"},{"role":"assistant","content":"Update PyTorch to the latest stable or nightly release. The NaNs didn't appear on a newer version."}],"kind":"answer","thread_id":208988,"url":"https://discuss.pytorch.org/t/nn-conv2d-produces-nans-when-specific-value-of-out-channels-is-set/208988","created_at":"2024-09-02T15:55:56.404000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[4,5],"answer_authors":["Vinc","ptrblck"]} | |
| {"messages":[{"role":"user","content":"How does Pytorch sequence together modules\n\nI am curious how Pytorch sequences together modules.\n\nThe application is, suppose I have a module structure A->B->C->D-E.\n\nThen, I want to inject new modules A->B->G->H->C->D->E in the middle.\n\nIn general, I want to take any existing module and splice new modules into it.\n\nI know I can replace modules by modifying the attribute. For example, resnet.fc = TransformerBlock would insert a transformer block for the fully connected layer of resnet.\n\nSo under the hood, does Pytorch store a sequential list of attributes to parse over, passing the output from one module as the input to the next?"},{"role":"assistant","content":"It depends on the model implementation and while simple models can be created using an `nn.Sequential` container, the majority of the models use custom `nn.Module`s defining the forward pass in their `forward` method as seen [here](https://github.com/pytorch/vision/blob/d0ebeb55573820df89fa24f6418b9e624683932d/torchvision/models/resnet.py#L266-L285) for e.g. ResNet models."}],"kind":"answer","thread_id":209053,"url":"https://discuss.pytorch.org/t/how-does-pytorch-sequence-together-modules/209053","created_at":"2024-09-04T01:53:50.161000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Building cov1d model with residual block + hypermeter tunner\n\nHi, I’m working on a stock forecasting project and trying to build a Conv1D model using residual blocks. I’m using Optuna to find the best hyperparameters and save the best model. However, I’m facing a shape/channel error when running the trial.\n\nSome printout output\nUsing device: cuda\nprocess_conv1d - Input shape after reshaping: (163, 1, 100)\nprocess_conv1d - Training data shape: (130, 1, 100), Validation data shape: (33, 1, 100)\nconv1d_objective - Model initialized with in_channels=1, out_channels=105, kernel_size=4, num_blocks=6\nConv1DModel - Input shape: torch.Size([130, 1, 100])\nResidualBlock - Input shape: torch.Size([130, 1, 100])\nResidualBlock - After conv1: torch.Size([130, 105, 100])\nResidualBlock - After bn1: torch.Size([130, 105, 100])\nResidualBlock - After relu1: torch.Size([130, 105, 100])\nResidualBlock - After conv2: torch.Size([130, 105, 100])\nResidualBlock - After bn2: torch.Size([130, 105, 100])\nResidualBlock - After adding residual: torch.Size([130, 105, 100])\nResidualBlock - After relu2: torch.Size([130, 105, 100])\n\nError Message\nRuntimeError: Given groups=1, weight of size [105, 1, 1], expected input[130, 105, 100] to have 1 channels, but got 105 channels instead\n[W 2024-09-04 12:14:32,605] Trial 0 failed with value None.\n\nSome part of code\n```\nimport os\nimport numpy as np\nimport pandas as pd\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport optuna\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, root_mean_squared_error , mean_squared_error\n\ndef preprocess_data(df):\n if df.isna().sum().sum() > 0 or df.isin([float('inf'), float('-inf')]).sum().sum() > 0:\n df = df.replace([float('inf'), float('-inf')], float('nan')).dropna()\n\n df = df.dropna()\n\n columns_to_drop = [\n 'NEXT_DAY_CLOSEPRICE', 'DAILY_CLOSEPRICE_CHANGE', 'CLOSEPRICE_DIRECTION',\n 'DAILY_MIDPRICE', 'NEXT_DAY_MIDPRICE', 'DAILY_MIDPRICE_CHANGE', 'MIDPRICE_DIRECTION', 'Date'\n ]\n X = df.drop(columns=columns_to_drop)\n y_classifier = (df['DAILY_CLOSEPRICE_CHANGE'] > 0).astype(int)\n y_regressor = df['DAILY_CLOSEPRICE_CHANGE']\n\n return X, y_classifier, y_regressor\n\nclass ResidualBlock(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, l2_lambda=0.01):\n super(ResidualBlock, self).__init__()\n \n self.conv1 = nn.Conv1d(in_channels, out_channels, kernel_size, stride=1, padding='same')\n self.bn1 = nn.BatchNorm1d(out_channels)\n self.conv2 = nn.Conv1d(out_channels, out_channels, kernel_size, stride=1, padding='same')\n self.bn2 = nn.BatchNorm1d(out_channels)\n self.relu = nn.ReLU(inplace=True)\n \n nn.init.kaiming_normal_(self.conv1.weight, nonlinearity='relu')\n nn.init.kaiming_normal_(self.conv2.weight, nonlinearity='relu')\n nn.init.zeros_(self.conv1.bias)\n nn.init.zeros_(self.conv2.bias)\n \n self.l2_lambda = l2_lambda\n\n if in_channels != out_channels:\n self.residual_conv = nn.Conv1d(in_channels, out_channels, kernel_size=1, stride=1)\n else:\n self.residual_conv = nn.Identity()\n\n def forward(self, x):\n residual = self.residual_conv(x)\n print(f'ResidualBlock - Input shape: {x.shape}')\n out = self.conv1(x)\n print(f'ResidualBlock - After conv1: {out.shape}')\n out = self.bn1(out)\n print(f'ResidualBlock - After bn1: {out.shape}')\n out = self.relu(out)\n print(f'ResidualBlock - After relu1: {out.shape}')\n out = self.conv2(out)\n print(f'ResidualBlock - After conv2: {out.shape}')\n out = self.bn2(out)\n print(f'ResidualBlock - After bn2: {out.shape}')\n out += residual\n print(f'ResidualBlock - After adding residual: {out.shape}')\n out = self.relu(out)\n print(f'ResidualBlock - After relu2: {out.shape}')\n \n return out\n\nclass Conv1DModel(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, num_blocks=1, l2_lambda=0.01, classification=True):\n super(Conv1DModel, self).__init__()\n self.blocks = nn.Sequential(\n *[ResidualBlock(in_channels, out_channels, kernel_size, l2_lambda=l2_lambda) for _ in range(num_blocks)]\n )\n self.global_avg_pool = nn.AdaptiveAvgPool1d(1) # Global average pooling for 1D\n self.fc = nn.Linear(out_channels, 2 if classification else 1)\n self.classification = classification\n\n def forward(self, x):\n print(f'Conv1DModel - Input shape: {x.shape}')\n out = self.blocks(x)\n print(f'Conv1DModel - After residual blocks: {out.shape}')\n out = self.global_avg_pool(out)\n print(f'Conv1DModel - After global average pooling: {out.shape}')\n out = out.view(out.size(0), -1) # Flatten the tensor\n print(f'Conv1DModel - After flattening: {out.shape}')\n out = self.fc(out)\n print(f'Conv1DModel - After fully connected layer: {out.shape}')\n if self.classification:\n out = F.log_softmax(out, dim=1)\n print(f'Conv1DModel - After log_softmax: {out.shape}')\n return out\n\nef process_conv1d(X, y, classification, gpu_available, ticker):\n device = torch.device('cuda' if gpu_available and torch.cuda.is_available() else 'cpu')\n print(f'Using device: {device}')\n \n # Convert DataFrame to numpy array\n X = X.to_numpy()\n y = y.to_numpy()\n \n # Reshape X for Conv1D\n NUM_CHANNELS = 1\n X = X.reshape((X.shape[0], NUM_CHANNELS, -1)) # Reshape for Conv1D: (batch_size, num_channels, sequence_length)\n print(f'process_conv1d - Input shape after reshaping: {X.shape}')\n \n # Split data into training and validation sets\n TEST_SIZE = 0.2\n RANDOM_STATE = 42\n X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=TEST_SIZE, random_state=RANDOM_STATE)\n print(f'process_conv1d - Training data shape: {X_train.shape}, Validation data shape: {X_val.shape}')\n \n def conv1d_objective(trial):\n in_channels = X_train.shape[1] # Ensure this matches the reshaped input\n out_channels = trial.suggest_int('out_channels', 16, 128)\n kernel_size = trial.suggest_int('kernel_size', 3, 7)\n num_blocks = trial.suggest_int('num_blocks', 1, 10)\n l2_lambda = trial.suggest_float('l2_lambda', 1e-5, 1e-2)\n \n model = Conv1DModel(in_channels, out_channels, kernel_size, num_blocks, l2_lambda, classification).to(device)\n print(f'conv1d_objective - Model initialized with in_channels={in_channels}, out_channels={out_channels}, kernel_size={kernel_size}, num_blocks={num_blocks}')\n \n optimizer = optim.Adam(model.parameters(), lr=trial.suggest_float('lr', 1e-5, 1e-2), weight_decay=l2_lambda)\n criterion = nn.CrossEntropyLoss() if classification else nn.MSELoss()\n \n input_train = torch.tensor(X_train, dtype=torch.float32).to(device)\n target_train = torch.tensor(y_train, dtype=torch.long if classification else torch.float32).to(device)\n \n model.train()\n EPOCHS = 10\n for epoch in range(EPOCHS):\n optimizer.zero_grad()\n output = model(input_train)\n print(f'conv1d_objective - Epoch {epoch}: Output shape: {output.shape}')\n loss = criterion(output, target_train)\n loss.backward()\n optimizer.step()\n \n # Validation\n model.eval()\n input_val = torch.tensor(X_val, dtype=torch.float32).to(device)\n target_val = torch.tensor(y_val, dtype=torch.long if classification else torch.float32).to(device)\n with torch.no_grad():\n val_output = model(input_val)\n val_loss = criterion(val_output, target_val)\n if classification:\n val_accuracy = (val_output.argmax(dim=1) == target_val).float().mean().item()\n print(f'conv1d_objective - Trial {trial.number}: Validation Accuracy = {val_accuracy:.4f}, Validation Loss = {val_loss.item():.4f}')\n return 1 - val_accuracy\n else:\n val_mse = val_loss.item()\n print(f'conv1d_objective - Trial {trial.number}: Validation MSE = {val_mse:.4f}, Validation Loss = {val_loss.item():.4f}')\n return val_mse\n \n study = optuna.create_study(direction='minimize')\n study.optimize(conv1d_objective, n_trials=100)\n \n best_model = Conv1DModel(X.shape[1], study.best_params['out_channels'], study.best_params['kernel_size'], study.best_params['num_blocks'], study.best_params['l2_lambda'], classification).to(device)\n \n # Save the best model\n model_type = 'classification' if classification else 'regression'\n torch.save(best_model.state_dict(), f'../models/pytorch/conv1d-{model_type}/{ticker}.pth')\n\nfor ticker in ticker_list:\n dataframe = pd.read_csv(f\"../data/{ticker}.csv\")\n X, y_classifier, y_regressor = preprocess_data(dataframe)\n process_conv1d(X, y_classifier, True, gpu_available, ticker)\n\n```"},{"role":"assistant","content":"This definition:\n```python\n self.blocks = nn.Sequential(\n *[ResidualBlock(in_channels, out_channels, kernel_size, l2_lambda=l2_lambda) for _ in range(num_blocks)]\n )\n```\nwon't work for multiple `ResidualBlock`s since each of these will expect an input with `in_channels` channels while the previous one will return an activation with `out_channels`.\nYou could fix it e.g. via:\n```python\n self.blocks = nn.Sequential(\n ResidualBlock(in_channels, out_channels, kernel_size, l2_lambda=l2_lambda),\n *[ResidualBlock(out_channels, out_channels, kernel_size, l2_lambda=l2_lambda) for _ in range(num_blocks-1)]\n )\n```\nbut would need to double check if the \"internal\" `ResidualBlock`s should use `out_channels` for their input and output."}],"kind":"answer","thread_id":209060,"url":"https://discuss.pytorch.org/t/building-cov1d-model-with-residual-block-hypermeter-tunner/209060","created_at":"2024-09-04T05:08:59.297000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Torch.cuda.is_available() returns False with CUDA 12.6\n\nI've combed through a few forum posts on this topic, but none of the solutions I've seen have worked. I installed PyTorch to my environment with the following command: `pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124`.\n\nOutput from 'torch.__version\\__':\n```\n2.4.0+cpu\n```\n\nOutput from 'nvcc --version':\n```\nnvcc: NVIDIA (R) Cuda compiler driver\nCopyright (c) 2005-2024 NVIDIA Corporation\nBuilt on Tue_Feb_27_16:28:36_Pacific_Standard_Time_2024\nCuda compilation tools, release 12.4, V12.4.99\nBuild cuda_12.4.r12.4/compiler.33961263_0\n```\nOutput from 'nvidia-smi':\n```\n+-----------------------------------------------------------------------------------------+\n| NVIDIA-SMI 560.94 Driver Version: 560.94 CUDA Version: 12.6 |\n|-----------------------------------------+------------------------+----------------------+\n| GPU Name Driver-Model | Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |\n| | | MIG M. |\n|=========================================+========================+======================|\n| 0 NVIDIA GeForce RTX 3050 ... WDDM | 00000000:01:00.0 Off | N/A |\n| N/A 45C P0 9W / 40W | 0MiB / 4096MiB | 0% Default |\n| | | N/A |\n+-----------------------------------------+------------------------+----------------------+\n\n+-----------------------------------------------------------------------------------------+\n| Processes: |\n| GPU GI CI PID Type Process name GPU Memory |\n| ID ID Usage |\n|=========================================================================================|\n| No running processes found |\n+-----------------------------------------------------------------------------------------+\n```\nI do not know why one of these shows 12.4 and the other shows 12.6.\n\nI tried a fresh install of both torch and of the CUDA toolkit, neither of which had any effect. I saw in one forum post that rolling torch's supported CUDA version back to 12.1 if you have 12.6 installed, but this did not work either. Am I missing something obvious?"},{"role":"assistant","content":"You have installed the CPU-only binary and should install the PyTorch binary with CUDA support instead. \n\nYour locally CUDA toolkit won't be used unless you build PyTorch from source or a custom CUDA extension."},{"role":"user","content":"This is what I'm confused about, I use the command provided in the 'Start Locally' portion of the PyTorch page, which yields the following on completion:\n\nSuccessfully installed torch-2.4.1+cu124 torchaudio-2.4.1+cu124 torchvision-0.19.1+cu124\nHowever, when I run the program again, I get the same '2.4.0+cpu' for version.\nIs the toolkit interfering with torch in some way?"},{"role":"assistant","content":"You've most likely installed multiple PyTorch binaries and the CPU-only one is being picked. Uninstall all previous PyTorch installations and reinstall the latest release with CUDA only.\n\nNo, since the PyTorch binary itself shows it does not have CUDA support: `2.4.0+cpu`."}],"kind":"answer","thread_id":209168,"url":"https://discuss.pytorch.org/t/torch-cuda-is-available-returns-false-with-cuda-12-6/209168","created_at":"2024-09-05T22:39:04.621000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"How to use torch.exp() with flatten()\n\nHi everyone,\nI've trained a model using CNN like this:\n```\nmodel = nn.Sequential(\n nn.Conv2d(in_channels=3,out_channels=16,kernel_size=5,padding_mode = 'zeros'),\n nn.Flatten(),\n nn.Linear(3701776,256),\n nn.ReLU(),\n nn.Dropout(0.2),\n nn.Linear(256, 128),\n nn.ReLU(),\n nn.Dropout(0.2),\n nn.Linear(128, 64),\n nn.ReLU(),\n nn.Dropout(0.2),\n nn.Linear(64, 5),\n nn.LogSoftmax(dim = 1)\n )\n```\n\nI can train the model just fine calculating loss / accuracy like this:\n\n```\n with torch.no_grad():\n # Set the model to evaluation mode\n model.eval()\n \n # Validation pass\n for images, labels in test_dataloader:\n \n log_ps = model(images)\n \n test_loss += criterion(log_ps, labels)\n \n ps = torch.exp(log_ps)\n top_p, top_class = ps.topk(1, dim = 1)\n equals = top_class == labels.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor))\n```\n\nBut I don't know how to test samples, since when I try to call \n\n```\nps = torch.exp(model(img))\n```\nI get an error:\n\nmat1 and mat2 shapes cannot be multiplied (16x231361 and 3701776x256)\n\nProbably since I'm not passing in batches, but I'm not sure how to fix this. Any help would be greatly appreciated"},{"role":"assistant","content":"The `torch.exp` call should not fail as it's an elementwise operation and thus won't raise a shape mismatch. Check the input shapes to your model and make sure these are valid."}],"kind":"answer","thread_id":209267,"url":"https://discuss.pytorch.org/t/how-to-use-torch-exp-with-flatten/209267","created_at":"2024-09-08T16:34:41.632000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"BCEWithLogitsLoss with weights causes runtimeError\n\nHello,\nfirst of all let me say that I have seen different issues related to this problem however I cannot get it to work for my use case.\n\nI am using a resnet network with a single output and therefore trying to use BCEWithLogitsLoss for binary classification (1 or 0). This is some code snippets:\n\nTHE LOSS FUNCTION\n```\n...\nloss_fn = nn.BCEWithLogitsLoss(weight=weight)\n...\n```\nWEIGHT TENSOR\n```\ntensor([7.2039, 0.5373], dtype=torch.float64)\nweight size torch.Size([2])\n```\nMODEL\n```\nclass Net2(nn.Module):\n\n def __init__(self):\n super().__init__()\n self.network = models.resnet152(pretrained=False)\n num_ftrs = self.network.fc.in_features\n self.network.fc = nn.Linear(num_ftrs, 1)\n def forward(self, xb):\n return self.network(xb)\n```\n\nTRAINING SNIPPET\n```\n prediction_logist = model(input).squeeze()\n predicted_probability = torch.sigmoid(prediction_logist) \n prediction = torch.round(predicted_probability)\n target = target.type_as(prediction_logist) \n loss = loss_fn(prediction_logist, target)\n\n```\n\nERROR\n```\nreturn torch.binary_cross_entropy_with_logits(input, target, weight, pos_weight, reduction_enum)\nRuntimeError: The size of tensor a (3) must match the size of tensor b (2) at non-singleton dimension 0\n```\n\nBATCH SIZE = 3\n\nOUTPUT and TARGET/LABELS SIZE\n```\ntorch.Size([3]) torch.Size([3])\n```\n\nthe issue is obviously related to the the weights being a tensor of size 2 while target a tensor of size 3 = to the batchsize.. things work for batchsize = 2 or no weights. \n\nWhat do I need to do to work with a generic batchsize ?\n\nThanks you.\nGiuseppe."},{"role":"assistant","content":"`unsqueeze` the model output and target to have a shape of `[batch_size, 1]` and rerun your code."},{"role":"user","content":"Hello, thank you for your reply.\nI added \n```\n prediction_logist=prediction_logist.unsqueeze(1)\n target=target.unsqueeze(1)\n```\nbefore the loss function and the Size of output is now torch.Size([3, 1]) torch.Size([3, 1]\n\nhowever now the issue moved to a different dimension and I now get\n\n```\nRuntimeError: output with shape [3, 1] doesn't match the broadcast shape [3, 2]\n``` \nI assume the broadcast share has a 2 because of the weights dimension,\n\nThanks."},{"role":"assistant","content":"You are right and I misread the `weight` argument as `pos_weight`.\nBased on the [docs](https://pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.html#bcewithlogitsloss) the `weight` will rescale the loss of each batch element and should thus have the same shape as the batch size.\nUnsure, but you might want to use `pos_weight` instead which is used to balance e.g. an class imbalance in the dataset and can be defined as `pos_weight = nb_negative_examples/nb_positive_examples`."}],"kind":"answer","thread_id":209328,"url":"https://discuss.pytorch.org/t/bcewithlogitsloss-with-weights-causes-runtimeerror/209328","created_at":"2024-09-09T21:14:21.079000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Torch DataLoader for a custom requirement\n\nHello! I am new to torch coding and can someone advice me on the following requirement.\n\nI have an ordered dataset(shuffle=False) that is categorised into \"bins\". I shall present an example on smaller scale that helps to clarify. Let's say the size of dataset is 60 with bins of sizes 10,20,30. I want to train my model in the order of bins. (first with 10 then 20 and 30). I want my DataLoader to get data in batch_sizes of 8. In this case, after getting the first 8 datapoints, I don't want to get the 2 remaining from bin-1 and get 6 from next one. What I want is to get only 2 and in the next iteration, get the 8 from bin-2. In short, I want to complete training in one bin first before moving to other. Also if batch_size happens to be greater than bin size, I want to get data in solely one bin before moving to next.\n\nCan I please get some advice on how to do this? I could think of two ways: implementing a custom DataLoader(need advice on this too) or just create separate DataLoaders for each bin and while iterating with bins in the outermost loop, grab the corresponding DataLoader and do training. Will the latter method have some serious downsides?"},{"role":"assistant","content":"I found the way! I ended up writing a custom BatchSampler class to feed into Dataloader.\nAssume that bins =[10,30,60] (a cummulative count of bin sizes) and batch_size=8 as in my question.\n```\nclass CustomBatchSampler(Sampler):\n\tdef __init__(self, sampler, batch_size, bins):\n\t\tself.sampler = sampler\n\t\tself.batch_size = batch_size\n\t\tself.bins = bins\n\t\tself.num_batches = sum([((j-i)/batch_size).__ceil__() for i,j in zip([0] + self.bins, self.bins)])\n\t\t\n\tdef __iter__(self):\n\t\tsampler_iter = iter(self.sampler)\n\t\tbatch = [0] * self.batch_size\n\t\tidx_in_batch = 0\n\t\tbin_count = 0\n\t\tfor total, idx in enumerate(self.sampler):\n\t\t\tbatch[idx_in_batch] = idx\n\t\t\tidx_in_batch += 1\n\t\t\tif total+1 == self.bins[bin_count]:\n\t\t\t\tyield batch[:idx_in_batch]\n\t\t\t\tidx_in_batch = 0\n\t\t\t\tbatch = [0] * self.batch_size\n\t\t\t\tbin_count += 1\n\t\t\tif idx_in_batch == self.batch_size:\n\t\t\t\tyield batch\n\t\t\t\tidx_in_batch = 0\n\t\t\t\tbatch = [0] * self.batch_size\n\n\tdef __len__(self):\n\t\treturn self.num_batches\n```\nI used it like this:\n```\ndata = MySet(##Dataset class)\nbatch_sampler = CustomBatchSampler(SequentialSampler(data), batch_size, bins)\nloader = DataLoader(data, batch_sampler=batch_sampler)\nfor each in loader:\n print(len(each[\"label\"]))\n```\nOutput (which was expected):\n```\n8\n2\n8\n8\n4\n8\n8\n8\n6\n```\nIt works in other cases too but I would like to know if this is safe? \nEspecially if I am doing some multiprocessing or distributed computing (iam using accelerate library). \nAre there some expected behaviours in the BatchSampler that I am missing? (perhaps the num_batches? Or some dependency that iter(BatchSampler) gives lists of same length?). \nCan someone please clarify this. I would be very grateful."}],"kind":"answer","thread_id":209336,"url":"https://discuss.pytorch.org/t/torch-dataloader-for-a-custom-requirement/209336","created_at":"2024-09-10T04:45:36.664000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["_Stelk"]} | |
| {"messages":[{"role":"user","content":"Using pytorch with cuda\n\nHello, I am trying to execute Pytorch with Cuda on two machines. In both cases, I didn't get the expected results. I will try to explain both cases to see if I am doing something wrong or if there is any incompatibility I cannot see.\n\nCase 1) \n- Cuda installed (nvcc --version): 11.2\n- torch 1.12.1+cu113\n- torchaudio 0.12.1+cu113\n- torchvision 0.13.1+cu113\n\nI run the following code (some parts of it are omitted for simplifications purposes):\n\n```\nprint(f\"Is CUDA supported by this system? {torch.cuda.is_available()}\")\nprint(f\"CUDA version: {torch.version.cuda}\")\n\n# Storing ID of current CUDA device\ncuda_id = torch.cuda.current_device()\nprint(f\"ID of current CUDA device: {torch.cuda.current_device()}\")\n \nprint(f\"Name of current CUDA device: {torch.cuda.get_device_name(cuda_id)}\")\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\nmodel = model.cuda()\nmodel = model.eval() \n\nwith torch.no_grad():\n for i, (x, y) in enumerate(val_loader):\n x = x.cuda()\n y = y.cuda()\n y_pred = model(x)\n```\nThe result I get is the following:\n\n```\n\nIs CUDA supported by this system? True\nCUDA version: 11.3\nID of current CUDA device: 0\nName of current CUDA device: NVIDIA A100-PCIE-40GB\ninputs torch.Size([1024, 3, 224, 224]) \\ rep 0 \\ labels torch.Size([1024])\nSegmentation fault (core dumped)\n```\nWhen the model does the inference, fails. I don't know why, because when I run the example with gdb, it gets stuck, and does not finish. \n\nIf I run some commands like nvidia-smi -lms to see if there is some program in execution on GPU, it appears, but with a 0% usage of GPU.\n\nIf, for instance, I eliminate x.cuda and y.cuda, the program finishes okay, and with Nvidia-semi, it appears like there is some MiB of the GPU allocated but with 0% usage. I suppose this happens because the model is in GPU, but the inference is not. \n\nI change the code, instead of using model.cuda(), model.to(device) or x.to(device) with the same output.\n\ncase 2) \n- Cuda installed (nvcc --version): 11.8\n- torch 2.4.1+cu118\n- torchaudio 2.4.1+cu118\n- torchvision 0.19.1+cu118\n\nsame code, and this is the output:\n\n```\nIs CUDA supported by this system? True\nCUDA version: 11.8\nID of current CUDA device: 0\nName of current CUDA device: Tesla V100-PCIE-32GB\nSegmentation fault (core dumped)\n```\n\nI get the same output with different Cuda configurations and different GPUs, and I can detect not only the Cuda version but also the GPU in my code with functions like current_device() , get_device() or is_available(). \n\nAgain, if a don't use x.to(device) or y.to(device) works but with 0% usage. Surprisingly, model.to(device) or model.cuda() never fails.\n\n```\n+-----------------------------------------------------------------------------+\n| NVIDIA-SMI 520.61.05 Driver Version: 520.61.05 CUDA Version: 11.8 |\n|-------------------------------+----------------------+----------------------+\n| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\n| | | MIG M. |\n|===============================+======================+======================|\n| 0 Tesla V100-PCIE... Off | 00000000:3D:00.0 Off | 0 |\n| N/A 35C P0 35W / 250W | 1684MiB / 32768MiB | 0% Default |\n| | | N/A |\n+-------------------------------+----------------------+----------------------+\n \n+-----------------------------------------------------------------------------+\n| Processes: |\n| GPU GI CI PID Type Process name GPU Memory |\n| ID ID Usage |\n|=============================================================================|\n+-----------------------------------------------------------------------------+\n```\nThe only possible answer I find is that somehow I am using the wrong code to send the model and the tensors to GPU, or I don't have a compatible torch version.\n\nAny help would be appreciated,\n\nThank you."},{"role":"assistant","content":"Have you tried to run the model on cpu?\nYou are getting segmentation fault, core dump. It's a bit generic but typically means error on the C++ side.\n\nTry to run your workload via:\n```\ngdb--args python script.py\n...\nrun\n...\nbt\n```\nto print the backtrace of the segfault."},{"role":"user","content":"This is the output from gdb: \n```\nThread 66 \"python3.8\" received signal SIGSEGV, Segmentation fault.\n[Switching to Thread 0x7fff5b1aa700 (LWP 25254)]\n__memcpy_ssse3 () at ../sysdeps/x86_64/multiarch/memcpy-ssse3.S:2509\n2509 ../sysdeps/x86_64/multiarch/memcpy-ssse3.S: No such file or directory.\n(gdb) bt\n#0 __memcpy_ssse3 () at ../sysdeps/x86_64/multiarch/memcpy-ssse3.S:2509\n#1 0x00007ffeefdb5754 in void fbgemm::pack_a_with_im2col_opt<2, 512>(fbgemm::conv_param_t<2> const&, fbgemm::block_type_t const&, unsigned char const*, unsigned char*, int, int*, int, int, bool) ()\n from /mnt/beegfs/gap/izcagal/.local/lib/python3.8/site-packages/torch/lib/libtorch_cpu.so\n#2 0x00007ffeefdb60ce in fbgemm::PackAWithIm2Col<unsigned char, int, 2>::pack(fbgemm::block_type_t const&) () from /mnt/beegfs/gap/izcagal/.local/lib/python3.8/site-packages/torch/lib/libtorch_cpu.so\n#3 0x00007ffeefd3d8a4 in void fbgemm::fbgemmPacked<fbgemm::PackAWithIm2Col<unsigned char, int, 2>, fbgemm::PackBMatrix<signed char, int>, unsigned char, fbgemm::ReQuantizeOutput<true, (fbgemm::QuantizationGranularity)2, float, unsigned char, int, fbgemm::DoNothing<unsigned char, unsigned char> > >(fbgemm::PackMatrix<fbgemm::PackAWithIm2Col<unsigned char, int, 2>, fbgemm::PackAWithIm2Col<unsigned char, int, 2>::inpType, fbgemm::PackAWithIm2Col<unsigned char, int, 2>::accType>&, fbgemm::PackMatrix<fbgemm::PackBMatrix<signed char, int>, fbgemm::PackBMatrix<signed char, int>::inpType, fbgemm::PackBMatrix<signed char, int>::accType>&, unsigned char*, int*, unsigned int, fbgemm::ReQuantizeOutput<true, (fbgemm::QuantizationGranularity)2, float, unsigned char, int, fbgemm::DoNothing<unsigned char, unsigned char> > const&, int, int, fbgemm::BlockingFactors const*) ()\n from /mnt/beegfs/gap/izcagal/.local/lib/python3.8/site-packages/torch/lib/libtorch_cpu.so\n#4 0x00007ffeefd7e815 in int fbgemm::fbgemmConv<fbgemm::ReQuantizeOutput<true, (fbgemm::QuantizationGranularity)2, float, unsigned char, int, fbgemm::DoNothing<unsigned char, unsigned char> >, 2, int>(fbgemm::conv_param_t<2> const&, unsigned char const*, fbgemm::PackWeightsForConv<2, signed char, int>&, fbgemm::ReQuantizeOutput<true, (fbgemm::QuantizationGranularity)2, float, unsigned char, int, fbgemm::DoNothing<unsigned char, unsigned char> >::outType*, int*, fbgemm::ReQuantizeOutput<true, (fbgemm::QuantizationGranularity)2, float, unsigned char, int, fbgemm::DoNothing<unsigned char, unsigned char> >&, int, int, fbgemm::BlockingFactors const*) ()\n from /mnt/beegfs/gap/izcagal/.local/lib/python3.8/site-packages/torch/lib/libtorch_cpu.so\n#5 0x00007ffeebd020cb in void at::internal::invoke_parallel<PackedConvWeight<2>::apply_impl<true>(at::Tensor const&, double, long)::{lambda(long, long)#2}>(long, long, long, PackedConvWeight<2>::apply_impl<true>(at::Tensor const&, double, long)::{lambda(long, long)#2} const&) [clone ._omp_fn.0] ()\n from /mnt/beegfs/gap/izcagal/.local/lib/python3.8/site-packages/torch/lib/libtorch_cpu.so\n#6 0x00007fffdc5c0405 in ?? ()\n from /mnt/beegfs/gap/izcagal/.local/lib/python3.8/site-packages/torch/lib/libgomp-a34b3233.so.1\n#7 0x00007ffff7bbb6db in start_thread (arg=0x7fff5b1aa700) at pthread_create.c:463\n--Type <RET> for more, q to quit, c to continue without paging--c\n#8 0x00007ffff713f61f in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95\n```\n\n@ptrblck, could you take a look at the backtrace?"},{"role":"assistant","content":"@ptrblck I think sse3 is a red herring here (note, that it fails with SIGSEGV not SIGILL), i.e. looks like either src or dst pointer is invalid. \nAlso, fbgemm just calls to `memcpy` (for example see https://github.com/pytorch/FBGEMM/blob/49fa9a55ba97a0d655cf2c51bf595caab37638e1/src/PackAWithIm2Col.cc#L260 ) and than glibc decides to make a dispatch to one or another accelerated flavor based on the CPU instruction set support.\n\n@Izan_C_G do you mind running `info registers` and `disasm` commands when exception happens?"}],"kind":"answer","thread_id":209369,"url":"https://discuss.pytorch.org/t/using-pytorch-with-cuda/209369","created_at":"2024-09-10T15:42:34.871000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[8],"answer_authors":["malfet"]} | |
| {"messages":[{"role":"user","content":"Torch.tensor() throws \"RuntimeError: Overflow when unpacking long\" exception?!\n\ni see this exception mentioned in some older and more exotic contexts but this is as straight-forward as it gets:\n\n```\n import torch\n\n for package in [torch]: \n print(package.__name__, package.__version__)\n \n tstList = [10,20,30,40,50]\n tstTensor = torch.tensor(tstList)\n print('tst',type(tstTensor),tstTensor)\n \n tstLongTensor = torch.tensor(tstList,dtype=torch.int64)\n print('long',type(tstLongTensor),tstLongTensor)\n \n tstLng2Tensor = torch.tensor(tstList).type(torch.int64)\n print('long2',type(tstLng2Tensor),tstLng2Tensor) \n\n indexedTst = [10239237003504588839, 9921686513378912864, 11901859001352538922, 4316640507316845735, 7162342725099726394, 17494803046312582752]\n idxTensor = torch.tensor(indexedTst)\n print('idx',type(idxTensor),idxTensor)\n```\nworks fine until it's given long ints:\n\n```\ntorch 2.3.0\ntst <class 'torch.Tensor'> tensor([10, 20, 30, 40, 50])\nlong <class 'torch.Tensor'> tensor([10, 20, 30, 40, 50])\nlong2 <class 'torch.Tensor'> tensor([10, 20, 30, 40, 50])\nTraceback (most recent call last):\n File \".../tstTensor.py\", line 33, in <module>\n main()\n File \".../tstTensor.py\", line 29, in main\n idxTensor = torch.tensor(indexedTst)\n ^^^^^^^^^^^^^^^^^^^^^^^^\nRuntimeError: Overflow when unpacking long\n```\nversion info:\n- Python 3.11.9 (main, Apr 19 2024, 11:43:47) [Clang 14.0.6 ] on darwin\n- same exception using device=`cpu` or `mps`"},{"role":"assistant","content":"This error is expected since `torch.long==torch.int64` corresponds to a max. value of `9223372036854775807` while your values are larger than this:\n```python\ntorch.iinfo(torch.long).max > 10239237003504588839\n# False\n```\nUse `torch.uint64` if you really need such large values:\n```python\nindexedTst = [10239237003504588839, 9921686513378912864, 11901859001352538922, 4316640507316845735, 7162342725099726394, 17494803046312582752]\nidxTensor = torch.tensor(indexedTst, dtype=torch.uint64)\nprint('idx',type(idxTensor),idxTensor)\n# idx <class 'torch.Tensor'> tensor([10239237003504588839, 9921686513378912864, 11901859001352538922,\n# 4316640507316845735, 7162342725099726394, 17494803046312582752],\n# dtype=torch.uint64)\n```\nI would also be interested to learn more about your use case and when these indices are useful."}],"kind":"answer","thread_id":209386,"url":"https://discuss.pytorch.org/t/torch-tensor-throws-runtimeerror-overflow-when-unpacking-long-exception/209386","created_at":"2024-09-10T22:20:06.317000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"ㅇdropout deactivating\n\nI understand that in PyTorch, dropout is automatically disabled when not in training mode. However, I observed that changing the dropout value during inference affects the results. Are the conditions for disabling dropout only being not in training mode, or is it specifically when `eval()` is activated?"},{"role":"assistant","content":"\"Not in training mode\" and calling `.eval()` is the same as internally `.eval()` will set the `self.training` attribute of the module (and all regustered submodules) to `False`.\nDo you have a minimal code snippet showing this behavior?"},{"role":"user","content":"sorry for late reply... \n```\nfrom model_zoo.RCF import RCF\nmodel = RCF(dropout_prob = 0)\n...\nmodel.load_state_dict(torch.load(model_path))\nmodel.to(device)\n...\nimgs = Variable(imgs.cuda())\n outputs = model(imgs)\n``` \nThis is all code using model and when I set dropout different makes varying result. I didn't set anny mode (train, eval) and this case What cause result varying?"},{"role":"assistant","content":"If you don't explicitly call `model.eval()` the default training mode is active, dropout thus also activated, and it's expected to see different outputs."}],"kind":"answer","thread_id":209400,"url":"https://discuss.pytorch.org/t/dropout-deactivating/209400","created_at":"2024-09-11T05:15:08.664000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"ㅇdropout deactivating\n\nI understand that in PyTorch, dropout is automatically disabled when not in training mode. However, I observed that changing the dropout value during inference affects the results. Are the conditions for disabling dropout only being not in training mode, or is it specifically when `eval()` is activated?"},{"role":"assistant","content":"\"Not in training mode\" and calling `.eval()` is the same as internally `.eval()` will set the `self.training` attribute of the module (and all regustered submodules) to `False`.\nDo you have a minimal code snippet showing this behavior?"}],"kind":"clarification","thread_id":209400,"url":"https://discuss.pytorch.org/t/dropout-deactivating/209400","created_at":"2024-09-11T05:15:08.664000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Which activation function should I use in the last layer output while using Resnet50?\n\nHi, I hope you are great.\nI have been creating my own cnn model with pytorch. But I am not sure which activation function should I use in resnet50 for the last layer (output) and what is the difference between them. Do you have any idea about that?"},{"role":"assistant","content":"What is your task? Generally for image classification its softmax.\n\nKeep in mind that commonly used loss functions for classification tasks require logits, i.e. no final activation function, if `nn.CrossEntropyLoss` is used, or log-probabilities, i.e. `F.log_softmax` as the final activation function, if `nn.NLLLoss` is used."},{"role":"user","content":"I got glass images. I want to predict which glass image is good (I mean quality) which image is not good (1 or 0)."},{"role":"assistant","content":"Your problem statement sounds like its a binary classification. Usually Sigmoid is preferred. \nWhile inference any value greater than equal to 0.5 is considered as 1 and lesser than 0.5 considered as 0. \n\nFor loss you can use Binary Cross Entropy \n`loss = F.binary_cross_entropy(torch.sigmoid(input), target)`"}],"kind":"answer","thread_id":209407,"url":"https://discuss.pytorch.org/t/which-activation-function-should-i-use-in-the-last-layer-output-while-using-resnet50/209407","created_at":"2024-09-11T07:43:17.086000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["deepsthecoder"]} | |
| {"messages":[{"role":"user","content":"Summation of a tensor is giving -inf as output even though no element has -inf value in it\n\nThe size of tensor is [4,884736].\n\nI am doing the summation with torch.sum(dim=1)\n\nI have checked whether the tensor has float('-inf') value with :- \n1] torch.where(tensor == float('-inf'), 1, 0) --> count the non_zero --> output is zero\n2] torch.where(tensor < -7, 1, 0) --> count the non_zero --> output is zero. Thus specifying the no element is lesser than -7\n3] tensor[tensor == float('-inf')] == 0. Still the result is -inf.\n\nKindly suggest."},{"role":"assistant","content":"Convert the tensor from float16 to float64 before calling torch.sum(dim=1). This removed the -inf result."}],"kind":"answer","thread_id":209426,"url":"https://discuss.pytorch.org/t/summation-of-a-tensor-is-giving-inf-as-output-even-though-no-element-has-inf-value-in-it/209426","created_at":"2024-09-11T15:54:38.004000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[4],"answer_authors":["Sanjeet_Patil"]} | |
| {"messages":[{"role":"user","content":"Impact of resuming from a checkpoint vs training/finetuning from the start\n\nI had a doubt about the impact resuming fine-tuning/training from checkpoints might have.\n\nIs there anything that resets like the optimizer state, or perhaps some other parameter in the case of resuming training from a checkpoint instead of a model fine-tuning continuously without interruptions? I wanted to figure out the impact of resuming training vs keeping it going from scratch - is it equivalent or does it impact something in the model updates?"},{"role":"assistant","content":"Resuming from a checkpoint should not break the training run and you should see the same model convergence if all states are restored. Besides restoring the `state_dict`s of the model and optimizer you could also check if you need to seed the code carefully to restore the data loading state as well."}],"kind":"answer","thread_id":209499,"url":"https://discuss.pytorch.org/t/impact-of-resuming-from-a-checkpoint-vs-training-finetuning-from-the-start/209499","created_at":"2024-09-13T04:52:27.560000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Half precision training time same as full precision\n\nHi all,\n\nI am training a model (~25M params) which takes ~1day to train on the full dataset. In my attempt to reduce the training time I am testing half precision. In using half precision, it allowed me to double the batch size, yet the overall training time remains the same.\n\nI was under the impression that doubling the batch size would reduce training time in ~half since many operations can be parallelized over the batch dimension. But this does not seem to be the case. Could this be a hardware (GPU architecture) or CUDA version problem? Or is my understanding of the relationship between batch size and speed just plain wrong.\n\nI have tried samples to bfloat16 and weights to float32, and both samples and weights to bfloat16 with same training times as both in float32. I am using a NVIDIA Quadro GV100 with 32Gb of VRAM and CUDA 11.4.\n\nThanks"},{"role":"assistant","content":"Profile your code to narrow down the bottleneck as it seems doubling the batch size is doubling the execution time, which could point to a data loading bottleneck."},{"role":"user","content":"Hi @ptrblck,\n\nThank you for your response, you were quite on the spot. After some digging I found that indeed there was a data loading bottleneck as you pointed out, just running the DataLoader on more workers alleviates the problem. \n\nI however also found that using `bfloat16` is quite slower than `float16`. My guess is that my GPU architecture or CUDA version is the culprit here, but if anyone has any ideas on how to close the speed gap between `bfloat16` and `float16` I welcome them.\n\nI have tried running the same model on a RTX4090 with CUDA 12 and `bfloat16` is now as fast as `float16`. This indicates that indeed the Quadro GV100 did not support the `bfloat16` speed up."},{"role":"assistant","content":"Yes, this is correct as `bfloat16` is supported on Ampere and newer devices. Older devices could emulate it but you should not expect to see a speedup."}],"kind":"answer","thread_id":209503,"url":"https://discuss.pytorch.org/t/half-precision-training-time-same-as-full-precision/209503","created_at":"2024-09-13T07:36:46.233000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Docker Image for PyTorch 2.4.1 CUDA 12.4 with cuDNN8 Missing\n\nI don't see `pytorch/pytorch:2.4.1-cuda12.4-cudnn8-devel` image in docker hub. I'm trying to run my pytorch lightning setup on 4 RTX 4090s.I was told RTX 4090 only supports 8.9 compute capability...is this different from cuDNN9 and cuDNN8? Can I use `pytorch/pytorch:2.4.1-cuda12.4-cudnn9-devel` with RTX 4090?"},{"role":"assistant","content":"That's wrong since compute capability 8.9 is binary compatible with 8.6 and 8.0. \n\nYes, the compute capability of a GPU is not directly related to cuDNN versions (the library itself needs to build their kernels for a compatible GPU architecture but cuDNN8 does not correspond to compute capability 8.x)."}],"kind":"answer","thread_id":209589,"url":"https://discuss.pytorch.org/t/docker-image-for-pytorch-2-4-1-cuda-12-4-with-cudnn8-missing/209589","created_at":"2024-09-15T03:52:59.786000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Faster Alternative to a Loop\n\nHi,\n\nMy model has a bottleneck from this loop\n\n```\na = torch.zeros(B, N, D1, D2)\nfor t in range(N):\n Bt = b[:,:t+1,:] #B,T,D1\n Ct = c[:,:t+1,:] #B,T,D2\n a[:,t,:,:] = Bt.mT @ Ct #B,D1,T @ B,T,D2 -> B,1,D1,D2\n```\n\nIt takes two 3d tensors - `b` & `c` - of shape `(B,N,D)`, does a transpose for rows 0:t, and then outputs - `a` - a 4d tensor of shape `(B, N, D1, D2)`. But the loop gets really slow (especially in back-propagation) as N gets large. Is there a faster alternative? Some way to do this all with matrix multiplication?\n\nThanks in advance for your help!!!\n\nFWIW, I eventually do a reshape of `a` to be `(B,N,D1*D2)` so solutions in that shape work too!"},{"role":"assistant","content":"You could try this:\n\n```\nimport torch\n\nB = 2\nN = 3\nD1 = 4\nD2 = 5\n\na = torch.zeros(B, N, D1, D2)\nb = torch.rand(B, N, D1)\nc = torch.rand(B, N, D2)\n\ndef loop(a, b, c): #old loop definition you provided\n N = a.size(1)\n for t in range(N):\n Bt = b[:,:t+1, :]\n Ct = c[:,:t+1, :]\n a[:,t,:,:]=Bt.mT @ Ct\n return a\n\ndef parallel(b, c): #parallelized version\n N = b.size(1)\n Bt = b.unsqueeze(1).repeat(1,N,1,1).permute(0,3,2,1).triu().permute(0,3,2,1)\n Ct = c.unsqueeze(1).repeat(1,N,1,1).permute(0,3,2,1).triu().permute(0,3,2,1)\n a = Bt.mT @ Ct\n return a\n\noutput_loop = loop(a,b,c)\noutput_parallel = parallel(b,c)\n\nprint(torch.isclose(output_loop, output_parallel))\n```\n\nCheers"}],"kind":"answer","thread_id":209670,"url":"https://discuss.pytorch.org/t/faster-alternative-to-a-loop/209670","created_at":"2024-09-17T06:34:24.714000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["J_Johnson"]} | |
| {"messages":[{"role":"user","content":"RuntimeError: CUDA error: unspecified launch failure // Neural Amp Modeler\n\nHi everyone,\n\nFirst of all, I want to apologize as I’m not a programmer or developer, so I may not have a complete understanding at the same level as many of you here.\n\nI’m using Anaconda + PyTorch to create guitar profiles through Neural Amp Modeler, which performs local training on this infrastructure.\n\nI recently switched from an Intel 14900K to an AMD 9950X, and now I can’t complete the training, something I’ve never had issues with before.\nGPU remained the same: RTX4070.\n\nI’ve already tried uninstalling Anaconda completely, reinstalling it, and reinstalling PyTorch, but no luck.\n\nDoes anyone have any ideas on how to solve this? I really need to get back to work on this project.\n\nI’m linking two text files with the content of the Anaconda Prompt here: https://www.dropbox.com/scl/fo/4cjvob5tchjq23ls2tfy1/AJ0GtvlA2wVv9mCMq5L0nJY?rlkey=pg6tkeoolog6fodl7qm7qjajf&dl=0\n\nThanks so much for your help!"},{"role":"assistant","content":"In your code, allocate a tensor on the GPU via:\n```python\nx = torch.randn(16, 16, device=\"cuda\")\nprint(x)\nprint(torch.matmul(x, x))\n```\nand make sure the output shows a valid tensor without raising any errors.\n\nIf so, run `dmesg -T | grep -i xid` in your terminal next and check if any errors are raised and correlate to failures in your script when checking the timestamp."}],"kind":"answer","thread_id":209706,"url":"https://discuss.pytorch.org/t/runtimeerror-cuda-error-unspecified-launch-failure-neural-amp-modeler/209706","created_at":"2024-09-17T18:00:21.991000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[6],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"RuntimeError: CUDA error: unspecified launch failure // Neural Amp Modeler\n\nHi everyone,\n\nFirst of all, I want to apologize as I’m not a programmer or developer, so I may not have a complete understanding at the same level as many of you here.\n\nI’m using Anaconda + PyTorch to create guitar profiles through Neural Amp Modeler, which performs local training on this infrastructure.\n\nI recently switched from an Intel 14900K to an AMD 9950X, and now I can’t complete the training, something I’ve never had issues with before.\nGPU remained the same: RTX4070.\n\nI’ve already tried uninstalling Anaconda completely, reinstalling it, and reinstalling PyTorch, but no luck.\n\nDoes anyone have any ideas on how to solve this? I really need to get back to work on this project.\n\nI’m linking two text files with the content of the Anaconda Prompt here: https://www.dropbox.com/scl/fo/4cjvob5tchjq23ls2tfy1/AJ0GtvlA2wVv9mCMq5L0nJY?rlkey=pg6tkeoolog6fodl7qm7qjajf&dl=0\n\nThanks so much for your help!\n\n@ptrblck some kind of help might be highly appreciated! Thanks so much!\n\nI also did the verification you have here: https://pytorch.org/get-started/locally/\n\n[image]\n\nThanks to anyone who can help!"},{"role":"assistant","content":"Could you check if `dmesg` is reporting any `Xid` error codes? \nAlso, are you able to move the tensor from your example to the GPU as the verification is incomplete?"}],"kind":"clarification","thread_id":209706,"url":"https://discuss.pytorch.org/t/runtimeerror-cuda-error-unspecified-launch-failure-neural-amp-modeler/209706","created_at":"2024-09-17T18:00:21.991000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Understanding \"mask\" dtype from TransformerEncoder forward\n\nDear all,\n\nI am working with TransformerEncoder module. I understood the \"mask\" parameter from the forward function can be a boolean tensor where **True** indicates that it is forbidden to attend the token and **False** is the inverse.\n\nIn my case, I am working with sequence-to-sequece mask. Initially, I was converting my mask to float with the following code\n\n```\nmask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n```\n\nHowever, I realized it takes lots of time (~0.60 seconds) when length of context is > 50. So I removed the float conversion and kept boolean values and it takes only ~0.06 seconds for equivalent context length.\n\nNote that my masks shape are (batch_size, T, T) because each sample from the batch has have different mask.\n\nMy question is : what is the key difference between a boolean and float mask ? Do they give the same results ?\n\nThanks !"},{"role":"assistant","content":"You might run into [this limitation](https://discuss.pytorch.org/t/floating-point-masks-are-not-supported-for-fast-path/205721) disallowing the fast path if floating point masks are used."}],"kind":"answer","thread_id":209761,"url":"https://discuss.pytorch.org/t/understanding-mask-dtype-from-transformerencoder-forward/209761","created_at":"2024-09-18T14:36:01.931000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Torch Profiler: GPU substantially slower than CPU\n\n**Synopsis:** Training and inference on a GPU is *dramatically* slower than on any CPU.\n\n**Setup:**\n* Training a highly customized Transformer model on an Azure VM (Standard NC6s v3 [6 vcpus, 112 GiB memory]) with a Tesla V100 (Driver Version: 550.54.15 & CUDA Version: 12.4).\n* The dataset is not very large (e.g. 1 GB) with dimensions [12000, 51, 48] using mini-batches of size 256.\n* All data are loaded into tensors and sent to GPU memory (e.g. *to(device)*) before even instantiating the model.\n* model is sent *to(device)* and then compiled via *model = torch.compile(model, mode=“reduce-overhead”)*.\n* Call model training via *torch.autocast(device_type=device, dtype=torch.bfloat16, enabled=False)*.\n\n**Situation:** Using Torch’s built-in Profiler, I am noticing a dramatic slowdown when using GPU/CUDA rather than calculating everything on CPU. I do not believe this has anything to do with data flowing between the CPU and GPU given my comments above, but could be wrong.\n\nThe following two tables are exactly the same datasets and run on the same machine. The only difference between the CPU runtime and the GPU/CUDA runtime is where the data is being stored (e.g. they are both Torch.Tensors sent to(device)) and where compute occurs.\n\n**What's Weird:** *model_inference* is 27.5x slower on GPU than on CPU *and* model_inference is called 3x times in the CUDA version...\n\n _____________\n**CPU Runtime**\n|Name | Self CPU % | Self CPU | CPU total % | CPU total | CPU time avg | # of Calls|\n|--- | --- | --- | --- | --- | --- | ---|\n|model_inference | 1.90% | 496.389ms | 100.00% | **26.178s** | **26.178s** | 1|\n|aten::empty | 0.55% | 144.920ms | 0.55% | 144.920ms | 19.006us | 7625|\n|aten::random_ | 0.00% | 12.914us | 0.00% | 12.914us | 12.914us | 1|\n|aten::item | 0.00% | 3.033us | 0.00% | 4.424us | 4.424us | 1|\n|aten::_local_scalar_dense | 0.00% | 1.391us | 0.00% | 1.391us | 1.391us | 1|\n|enumerate(DataLoader)#_SingleProcessDataLoaderIter._... | 0.64% | 167.173ms | 1.34% | 349.861ms | 9.207ms | 38|\n|aten::randperm | 0.00% | 436.807us | 0.00% | 876.528us | 219.132us | 4|\n|aten::scalar_tensor | 0.00% | 7.450us | 0.00% | 7.450us | 3.725us | 2|\n|aten::resize_ | 0.01% | 1.711ms | 0.01% | 1.711ms | 2.554us | 670|\n|aten::resolve_conj | 0.01% | 2.982ms | 0.01% | 2.982ms | 0.326us | 9141|\n\n*Self CPU time total: 26.178s*\n _____________\n**GPU/CUDA Runtime**\n|Name | Self CPU % | Self CPU | CPU total % | CPU total | CPU time avg | Self CUDA | Self CUDA % | CUDA total | CUDA time avg | # of Calls|\n|--- | --- | --- | --- | --- | --- | --- | --- | --- | --- | ---|\n|model_inference | 0.00% | 0.00us | 0.00% | 0.00us | 0.00us | **1439.411s** | 95.27% | **1439.411s** | **719.705s** | 2|\n|GraphLowering.run (dynamo_timed) | 0.00% | 0.00us | 0.00% | 0.00us | 0.00us | **59.987s** | 3.97% | **59.987s** | 810.641ms | 74|\n|CachingAutotuner.benchmark_all_configs (dynamo_timed... | 0.00% | 0.00us | 0.00% | 0.00us | 0.00us | 5.193s | 0.34% | 5.193s | 144.253ms | 36|\n|aten::fill_ | 0.13% | 950.923ms | 0.17% | 1.249s | 28.885us | 3.996s | 0.26% | 3.996s | 92.384us | 43249|\n|aten::zero_ | 0.13% | 947.515ms | 0.30% | 2.238s | 49.680us | 0.000us | 0.00% | 3.994s | 88.611us | 45049|\n|void at::native::vectorized_elementwise_kernel<4, at... | 0.00% | 0.00us | 0.00% | 0.00us | 0.00us | 3.956s | 0.26% | 3.956s | 287.800us | 13747|\n|CachingAutotuner.benchmark_all_configs (dynamo_timed... | 0.36% | 2.618s | 0.71% | 5.23s | 145.287ms | 0.000us | 0.00% | 3.737s | 103.808ms | 36|\n|model_inference | 0.43% | 3.184s | 99.58% | **731.765s** | **731.765s** | 0.000us | 0.00% | 2.663s | 2.663s | 1|\n|Torch-Compiled Region | 0.00% | 11.368ms | 0.52% | 103.364ms | 3.824s | 0.000us | 0.00% | 2.298s | 62.111ms | 37|\n|CompiledFunction | 0.10% | 768.567ms | 0.52% | 103.032ms | 3.812s | 158.932ms | 0.01% | 2.298s | 62.111ms | 37|\n\nSelf CPU time total: 734.872s\nSelf CUDA time total: 1510.825s\n\nAny insight as to what's causing this would be greatly appreciated."},{"role":"assistant","content":"Use float16 for the data. The inputs were float64 and integer tensors, and converting them to float16 let the V100 match CPU speed. Volta GPUs do not support bfloat16, and autocast alone did not fix it. If torch.compile raises an error for your model, removing the call made the model run:\n\n```\nmodel = torch.compile(model, mode=\"reduce-overhead\", fullgraph=True)\n```"}],"kind":"answer","thread_id":209774,"url":"https://discuss.pytorch.org/t/torch-profiler-gpu-substantially-slower-than-cpu/209774","created_at":"2024-09-18T20:00:43.547000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[3,6],"answer_authors":["mloewen","ptrblck"]} | |
| {"messages":[{"role":"user","content":"`training` property of complied models is always `True`\n\nI noticed that I can't set the `training` property to `False` for modules that I have compiled, regardless of the state of the property when the module was compiled.\n\nIs this expected behaviour?\n\nA demo:\n\n```\nimport torch\nimport torch.nn as nn\n\nprint(torch.__version__)\n\nclass M(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc = nn.Linear(16, 1)\n\n def forward(self, x):\n return self.fc(x)\n\nprint(\"--------standard--------\")\nm = M()\nprint(f\"m.training = {m.training}\\t← default\")\nm.train(False)\nprint(f\"m.training = {m.training}\\t← m.train(False)\")\n\nprint(\"--------compiled--------\")\nm = M()\nm = torch.compile(m)\nprint(f\"m.training = {m.training}\\t← default\")\nm.train(False)\nprint(f\"m.training = {m.training}\\t← m.train(False)\")\n\nprint(\"------compiled (eval)---\")\nm = M()\nm.train(False)\nm = torch.compile(m)\nprint(f\"m.training = {m.training}\\t← default\")\nm.train(False)\nprint(f\"m.training = {m.training}\\t← m.train(False)\")\n```\n\nOutput:\n\n```text\n2.4.1+cu121\n--------standard--------\nm.training = True\t← default\nm.training = False\t← m.train(False)\n--------compiled--------\nm.training = True\t← default\nm.training = True\t← m.train(False)\n------compiled (eval)---\nm.training = True\t← default\nm.training = True\t← m.train(False)\n```"},{"role":"assistant","content":"This is a known issue, tracked at https://github.com/pytorch/pytorch/issues/132986. It appears to be fixed on master, so try a build from master."}],"kind":"answer","thread_id":209992,"url":"https://discuss.pytorch.org/t/training-property-of-complied-models-is-always-true/209992","created_at":"2024-09-24T10:00:22.864000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["Chillee","ptrblck"]} | |
| {"messages":[{"role":"user","content":"How to perform backpropagation with noise\n\nHi, I wonder if it is possible to backpropagate with noise. For example, I may have a network look like this:\n\n```\nclass ThreeLayerNetwork(nn.Module):\n def __init__(self):\n super(ThreeLayerNetwork, self).__init__()\n self.fc1 = nn.Linear(1, 2)\n self.fc2 = nn.Linear(2, 1)\n \n def forward(self, x):\n x = torch.relu(self.fc1(x))\n x = self.fc2(x)\n return x\n```\nI believe the gradient of fc1 is calculated based on that of fc2 during backpropagation. Now I would like to add noise to the gradient of fc2, and let the gradient of fc1 calculated based on the noisy gradient of fc2. I wonder in which way can I achieve it.\n\nThanks a lot!"},{"role":"assistant","content":"You could use [`torch.nn.Module.register_full_backward_hook`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.register_full_backward_hook) to access the gradients and manipulate the `input_grad` before returning it."}],"kind":"answer","thread_id":210014,"url":"https://discuss.pytorch.org/t/how-to-perform-backpropagation-with-noise/210014","created_at":"2024-09-24T17:49:08.596000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Does torch.rot90 support gradient flow?\n\nThank you much ahead.."},{"role":"assistant","content":"Yes, it does:\n```python\nx = torch.randn(2, 2, requires_grad=True)\nout = torch.rot90(x)\nout.grad_fn\n# <Rot90Backward0 at 0x7f21c7f4e110>\n\nout.mean().backward()\nprint(x.grad)\n# tensor([[0.2500, 0.2500],\n# [0.2500, 0.2500]])\n```"}],"kind":"answer","thread_id":210135,"url":"https://discuss.pytorch.org/t/does-torch-rot90-support-gradient-flow/210135","created_at":"2024-09-26T14:43:17.626000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Expected Tensor as element 0 in argument 0, but got JpegImageFile\n\nHello guys\n\nI am using this example,\n\n > ``` import torchvision.transforms as transforms\n> import torch\n> import os\n> from PIL import Image\n> import random\n> \n> list_file='C/.../file_names.txt' #A txt's files path that contains the names of the images Dataset\n> raw_dir='C/.../DirImageA' # the path of the folder where the A type images of the dataset are located\n> expert_dir='C/.../DirImageB' # the path of the folder where the B type images of the dataset are located\n> join = os.path.join\n> \n> \n> file_list = [ ]\n> with open(list_file) as f:\n> for line in f: \n> name = line.strip() \n> if name:\n> p = (join(raw_dir, name), join(expert_dir, name), name)\n> file_list.append(p)\n> \n> transformation= [ ]\n> size=256\n> \n> transformation.append(transforms.Resize((size,size)))\n> transformation.append(transforms.RandomHorizontalFlip(0.5))\n> \n> transformation.append(transforms.ToTensor())\n> transform=transforms.Compose(transformation)\n> \n> index=random.randint(1, 1000) #random sample image for training\n> \n> raw = Image.open(file_list[index][0])\n> expert = Image.open(file_list[index][1])\n> \n> raw_exp = transform(torch.stack([raw, expert])) #The error appears on this line to torch.stack([raw, expert]) ```\n\nand I am getting this error\n\n> expected Tensor as element 0 in argument 0, but got JpegImageFile\n\nAny suggestions?"},{"role":"assistant","content":"Transform the images to tensors first e.g. via:\n```python\nimage = PIL.Image.open(\"image.jpeg\")\n\ntorch.stack([image, image])\n# TypeError: expected Tensor as element 0 in argument 0, but got JpegImageFile\n\nx = transforms.ToTensor()(image)\ny = torch.stack([x, x])\nprint(y.shape)\n# torch.Size([2, 3, 800, 800])\n```"}],"kind":"answer","thread_id":210180,"url":"https://discuss.pytorch.org/t/expected-tensor-as-element-0-in-argument-0-but-got-jpegimagefile/210180","created_at":"2024-09-27T12:53:55.425000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Large performance difference when using torchvision EMNIST dataset vs custom dataset\n\nHi! I am training a classification model on the EMNIST dataset. I noticed big differences in the convergence of the loss when using the EMNIST dataset from torchvision (`torchvision.datasets.EMNIST`), instead of loading from CSV. I tested using the same parameters for the model and with the same random seed.\n\nI constructed a custom dataset class to fetch data from csv files:\n\n```\ndef load_csv_data(csv_path:str):\n #function to load data from csv, used to create img_data & label_data\n data_df = pd.read_csv(csv_path)\n labels = (data_df.iloc[:,0]).values #first column, labels are uppercase & lowecase, e.g \"a\" or \"A\" = 1, shift range from 1-26 to 0-25\n raw_pixels = data_df.iloc[:,1:].values #pixel values , transpose to get correct orientation\n\n imgs = raw_pixels.reshape(-1,28,28) #emnist images are 28*28 pixels - 3d ndarray\n return imgs, labels\n\nclass EMNISTDataset(Dataset):\n def __init__(self, img_data:ndarray, label_data:ndarray, transform, target_transform, subset_indices:slice,):\n super().__init__()\n self.img_subset = img_data[subset_indices]\n self.label_subset = label_data[subset_indices]\n\n if self.img_subset.shape[0] != self.label_subset.shape[0]:\n raise RuntimeError(f\"Img subset len does not match label subset len: \\n Img subset len: {self.img_subset.shape[0]} \\n Label subset len:{self.label_subset.shape[0]}\")\n self.transform = transform\n self.target_transform = target_transform\n \n def __len__(self):\n data_len = self.label_subset.shape[0]\n return data_len\n \n def __getitem__(self, idx):\n X = self.img_subset[idx,:,:]\n y = int(self.label_subset[idx])\n if self.transform:\n X = self.transform(X) #applies torchvision transform\n if self.target_transform:\n y = self.target_transform(y) #applies torchvision transform\n return X, y\n```\n\nI am using these transforms:\n```\nimg_transform = v2.Compose([\n v2.Resize(28),\n v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)]), # to tensor\n v2.RandomHorizontalFlip(p=1),#100% probability\n v2.RandomRotation(degrees=(90,90)), #flip 90 degrees\n ])\ntarget_transform = lambda y:y-1\n```\n\nThis is the Crossentropyloss from multiple runs, the worse ones (around 3.2) are from my custom dataset, while the better ones are from the torchvision dataset:\n[image]"},{"role":"assistant","content":"Compare a batch created by the `torchvision` dataset with one created by your custom dataset w.r.t. its stats (e.g. `mean`, `min`, `max`, `std`) to see if the processing differs."}],"kind":"answer","thread_id":210196,"url":"https://discuss.pytorch.org/t/large-performance-difference-when-using-torchvision-emnist-dataset-vs-custom-dataset/210196","created_at":"2024-09-27T22:07:48.609000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"In-place operations in gradient computation in nested PyTorch loops\n\nI'm working on a PyTorch model that involves a double loop for calculations. The problem is that I'm getting an error related to in-place operations when I try to perform backpropagation.\n\nHere's a simplified example of my code:\n\n```\nimport torch\n\nlength = 1000\ndx = 100\nnum_rows = 5\nnum_cols = int(length / dx) + 1\n\nC = torch.rand(num_rows, requires_grad=True)\nD = torch.rand(num_rows, requires_grad=True)\nqobs = torch.rand(num_rows)\n\nCaux = 1 + C + D\nC0 = (-1 + C + D) / Caux\nC1 = (1 + C - D) / Caux\nC2 = (1 - C + D) / Caux\n\nqprop = torch.zeros((num_rows, num_cols))\nqprop[:, 0] = qobs\n\n# causes the problem\nfor j in range(1, num_cols): \n for n in range(1, num_rows):\n term1 = C2[n] * qprop[n-1, j-1]\n term2 = C1[n] * qprop[n, j-1]\n term3 = C0[n] * qprop[n-1, j]\n qprop[n, j] = term1 + term2 + term3 \n\nloss = qprop.sum()\nloss.backward() # This raises an error\n```"},{"role":"assistant","content":"You could try to work around this issue by cloning the `termX` tensors:\n```python\nfor j in range(1, num_cols): \n for n in range(1, num_rows):\n term1 = C2[n] * qprop[n-1, j-1].clone()\n term2 = C1[n] * qprop[n, j-1].clone()\n term3 = C0[n] * qprop[n-1, j].clone()\n qprop[n, j] = term1 + term2 + term3 \n```"}],"kind":"answer","thread_id":210985,"url":"https://discuss.pytorch.org/t/in-place-operations-in-gradient-computation-in-nested-pytorch-loops/210985","created_at":"2024-09-30T13:33:46.498000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Can I make zero-division in pytorch return torch.inf instead of NaNs?\n\nThe title says it all. Zero-division in pytorch returns NaNs, while mathematically it should return infinity. In certain cases, `torch.inf` would convert to normal values further on (e.g. `exp(-torch.inf)`, `1/torch.inf`, etc.), while NaNs on the other hand propagate endlessly, messing up model gradients. Pytorch functions already yield correct results for infinite values, so all that's left is to return infinities after division. Is there any way to achieve this without resorting to masks or `torch.where`?"},{"role":"assistant","content":"Additionally to @Soumya_Kundu's recommendation I also see that `Inf` is returned:\n```python\nx = torch.tensor(1.)\ny = torch.tensor(0.)\n\nprint(x / y)\n# tensor(inf)\n```"}],"kind":"answer","thread_id":211030,"url":"https://discuss.pytorch.org/t/can-i-make-zero-division-in-pytorch-return-torch-inf-instead-of-nans/211030","created_at":"2024-10-01T12:54:02.071000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"CUDA 12.4 for PyTorch build 1.9\n\nI am trying to run the following repository for text detection: [CRAFT-pytorch text detection](https://github.com/clovaai/CRAFT-pytorch)\n\nThe requirements include PyTorch=1.9 which I am trying to install in a conda environment this is resulting in errors since 1.9 install supports CUDA capabilities sm_37 sm_50 sm_60 sm_70.\n\nMy current GPU is A100-SXM4-40GB with CUDA VERSION 12.4 \nNVIDIA A100-SXM4-40GB with CUDA capability sm_80 is not compatible with the my desired pytorch 1.9.\n\nIs there anyway I can install 1.9 using my current GPU CUDA VERSION on a conda environment?"},{"role":"assistant","content":"I would recommend updating PyTorch to a recent release which ships with CUDA 12.4 runtime dependencies. Did you try updating and if so did you see any issues in your code?"}],"kind":"answer","thread_id":211033,"url":"https://discuss.pytorch.org/t/cuda-12-4-for-pytorch-build-1-9/211033","created_at":"2024-10-01T13:19:51.047000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Replace multiple linear networks with convolutional layers\n\nGiven\n``` \nimport torch\nimport torch.nn as nn\n\nnof_samples = 1\nnof_features = 2\ninput = torch.rand(nof_samples, nof_features)\n```\nI have two feature networks (one for each feature), which look like this:\n```\nfeature_networks = nn.ModuleList()\nfor _ in range(nof_features):\n feature_networks.append(\n nn.Sequential(\n nn.Linear(in_features=1, out_features=3),\n nn.Linear(in_features=3, out_features=3),\n nn.Linear(in_features=3, out_features=1)\n )) \n\noutput = torch.zeros(nof_samples, nof_features)\nfor feature_index in range(nof_features): # Iterate over features\n output[:, feature_index] = feature_networks[feature_index](input[:, feature_index])\n\noutput # shape of [1, 2]\n# nof trainable params: 44\n```\nI would like to replace it with sth like the following to get rid of the (I believe) **time-consuming for-loop**:\n```\nconv1 = nn.Conv1d(in_channels=nof_features, out_channels=nof_features*3, kernel_size=1, groups=nof_features)\nconv2 = nn.Conv1d(in_channels=nof_features, out_channels=nof_features*3, kernel_size=3, groups=nof_features)\nconv3 = nn.Conv1d(in_channels=nof_features, out_channels=nof_features, kernel_size=3, groups=nof_features)\n\noutputv2 = conv3(conv2(conv1(input.unsqueeze(2)).view(nof_samples, nof_features, 3)).view(nof_samples, nof_features, 3)).squeeze(2)\noutputv2\n# shape of [1, 2, 1]\n# nof trainable params: 44\n```\n\n**Are `outputs` and `outputsv2` the same (assuming the weights are)? Or do I have to do it differently?**"},{"role":"assistant","content":"Yes, your approach seems to be valid based on this quick check by loading the trainable parameters:\n```python\nimport torch\nimport torch.nn as nn\n\nnof_samples = 1\nnof_features = 2\ninput = torch.rand(nof_samples, nof_features)\n\nbias = True\n\nfeature_networks = nn.ModuleList()\nfor _ in range(nof_features):\n feature_networks.append(\n nn.Sequential(\n nn.Linear(in_features=1, out_features=3, bias=bias),\n nn.Linear(in_features=3, out_features=3, bias=bias),\n nn.Linear(in_features=3, out_features=1, bias=bias)\n )) \n\noutput = torch.zeros(nof_samples, nof_features)\nfor feature_index in range(nof_features): # Iterate over features\n output[:, feature_index] = feature_networks[feature_index](input[:, feature_index])\n\nconv1 = nn.Conv1d(in_channels=nof_features, out_channels=nof_features*3, kernel_size=1, groups=nof_features, bias=bias)\nconv2 = nn.Conv1d(in_channels=nof_features, out_channels=nof_features*3, kernel_size=3, groups=nof_features, bias=bias)\nconv3 = nn.Conv1d(in_channels=nof_features, out_channels=nof_features, kernel_size=3, groups=nof_features, bias=bias)\n\nwith torch.no_grad():\n print(conv1.weight.shape)\n weight = torch.cat((feature_networks[0][0].weight, feature_networks[1][0].weight))\n print(weight.shape, conv1.weight.shape)\n conv1.weight.copy_(weight.unsqueeze(1))\n \n if hasattr(conv1, \"bias\"):\n bias = torch.cat(((feature_networks[0][0].bias, feature_networks[1][0].bias)))\n print(bias.shape, conv1.bias.shape)\n conv1.bias.copy_(bias)\n \n weight = torch.cat((feature_networks[0][1].weight, feature_networks[1][1].weight))\n print(weight.shape, conv2.weight.shape)\n conv2.weight.copy_(weight.unsqueeze(1))\n \n if hasattr(conv2, \"bias\"):\n bias = torch.cat(((feature_networks[0][1].bias, feature_networks[1][1].bias)))\n print(bias.shape, conv2.bias.shape)\n conv2.bias.copy_(bias)\n \n weight = torch.cat((feature_networks[0][2].weight, feature_networks[1][2].weight))\n print(weight.shape, conv3.weight.shape)\n conv3.weight.copy_(weight.unsqueeze(1))\n \n if hasattr(conv3, \"bias\"):\n bias = torch.cat(((feature_networks[0][2].bias, feature_networks[1][2].bias)))\n print(bias.shape, conv3.bias.shape)\n conv3.bias.copy_(bias)\n\noutputv2 = conv3(conv2(conv1(input.unsqueeze(2)).view(nof_samples, nof_features, 3)).view(nof_samples, nof_features, 3)).squeeze(2)\n\nprint(output - outputv2)\n# tensor([[ 0.0000e+00, -2.9802e-08]], grad_fn=<SubBackward0>)\n```\nI haven't checked the reshape operations in detail but given the numerical mismatch is small, I assume it's valid."}],"kind":"answer","thread_id":211118,"url":"https://discuss.pytorch.org/t/replace-multiple-linear-networks-with-convolutional-layers/211118","created_at":"2024-10-03T19:38:55.883000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Why do we need to detach() the output while doing eval?\n\nHere's the function I have for eval:\n\n```\n@torch.no_grad()\ndef amp_eval(dataloader, loss_fn, model, optimiser, scaler):\n model.eval()\n y_true, y_pred = [], []\n for inputs, labels, filenames, num_tumour_pixels in dataloader:\n with torch.autocast(device_type='cuda', dtype=torch.float16):\n outputs, attention_weights = model(inputs)\n y_pred.append(outputs.cpu().detach().item())\n y_true.append(labels.item())\n # del outputs\n\n print(inputs.requires_grad, f'Memory usage: {get_process_memory()} GB', flush=True)\n print(f\"Objects in memory: {len(gc.get_objects())}\", flush=True)\n\n```\nIf I don't use .item(), the memory blows up giving OOM. Why do I need when I'm using `@torch.no_grad()`?"},{"role":"assistant","content":"You don't need it as no computation graph will be created as seen in this small example:\n```python\ndef fun1(x):\n y = x ** 2\n return y\n\n@torch.no_grad()\ndef fun2(x):\n y = x ** 2\n return y\n\nx = torch.randn(1, requires_grad=True)\n\ny1 = fun1(x)\nprint(y1.grad_fn)\n# <PowBackward0 object at 0x7f514be26f80>\n\ny2 = fun2(x)\nprint(y2.grad_fn)\n# None\n```"}],"kind":"answer","thread_id":211175,"url":"https://discuss.pytorch.org/t/why-do-we-need-to-detach-the-output-while-doing-eval/211175","created_at":"2024-10-05T02:07:03.608000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"StyleGAN2 Demodulation grouped convolution incorrect dimensions\n\nHello,\n\nThe following code:\n\n```\nclass mod_demod(nn.Module):\n def __init__(self, latent_dim, out_channels):\n super().__init__()\n \n self.map_layer = EqualLRLinear(latent_dim, out_channels)\n self.bias = nn.Parameter(torch.zeros(1, out_channels, 1, 1))\n\n self.out_channels = out_channels\n def forward(self, w, conv_weight, batch):\n # conv_weight is the weights of the current convolutional layer\n s = self.map_layer(w)\n s = s.view(w.size(0), -1, 1, 1, 1)\n # Add bias and 1 (as per StyleGAN2)\n s = s + 1 + self.bias.view(1, -1, 1, 1, 1)\n # Modulation\n weight = conv_weight * s\n\n # Demodulation\n demod = torch.rsqrt(weight.pow(2).sum([2,3,4])+ 1e-8)\n weight = weight * demod.unsqueeze(2).unsqueeze(3).unsqueeze(4)\n\n # Return the weight's of the convolution\n return nn.Parameter(weight)\n \n\nclass Conv2d_mod(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, latent_dim, padding=1):\n super().__init__()\n\n # The weights for our conv\n self.weights = nn.Parameter(torch.randn(out_channels, in_channels, kernel_size, kernel_size))\n nn.init.normal_(self.weights)\n\n self.bias = nn.Parameter(torch.zeros(1, out_channels, 1, 1)) # b2 in diagram\n \n self.modulator = mod_demod(latent_dim, out_channels)\n\n self.eq_lr_scale = sqrt(2 / (in_channels * kernel_size ** 2))\n\n self.padding = padding\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n self.latent_dim = latent_dim\n\n def forward(self, x, style_w):\n batch, channels, H, W = x.shape\n\n weights = self.weights * self.eq_lr_scale\n # Need to create the modulated and demodulated weights\n weights = self.modulator(style_w, weights, batch)\n\n print(f'Channels in x: {channels} | self.in_channels: {self.in_channels} | self.out_channels: {self.out_channels}')\n\n print(weights.shape)\n weights = weights.view(batch * self.out_channels, self.in_channels, self.kernel_size, self.kernel_size)\n #weights = weights.view(batch * self.out_channels, channels, self.kernel_size, self.kernel_size)\n\n x = x.view(1, batch*channels, H, W)\n print(f'x.shape: {x.shape} | weights.shape: {weights.shape}')\n out = F.conv2d(x, weights, groups=batch, padding=self.padding)\n out = out.view(batch, self.out_channels, out.shape[-2], out.shape[-1])\n\n out += self.bias\n \n return out\n```\n\nWorks fine for the input: \nconv2d_mod = Conv2d_mod(256, 256, 3, 256)\nx = torch.randn(4, 256, 64, 64)\nw = torch.randn(4, 256)\n\nBut when the input is:\n\nconv2d_mod = Conv2d_mod(256, 256//2, 3, 256)\nx = torch.randn(4, 128, 128, 128)\nw = torch.randn(4, 256)\n\nIt throws the following error:\n\n```\n---------------------------------------------------------------------------\nRuntimeError Traceback (most recent call last)\nCell In[183], line 4\n 2 x = torch.randn(4, 128, 128, 128)\n 3 w = torch.randn(4, 256)\n----> 4 conv2d_mod(x, w).shape\n\nFile ~/anaconda3/envs/gpu_use/lib/python3.11/site-packages/torch/nn/modules/module.py:1553, in Module._wrapped_call_impl(self, *args, **kwargs)\n 1551 return self._compiled_call_impl(*args, **kwargs) # type: ignore[misc]\n 1552 else:\n-> 1553 return self._call_impl(*args, **kwargs)\n\nFile ~/anaconda3/envs/gpu_use/lib/python3.11/site-packages/torch/nn/modules/module.py:1562, in Module._call_impl(self, *args, **kwargs)\n 1557 # If we don't have any hooks, we want to skip the rest of the logic in\n 1558 # this function, and just call forward.\n 1559 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks\n 1560 or _global_backward_pre_hooks or _global_backward_hooks\n 1561 or _global_forward_hooks or _global_forward_pre_hooks):\n-> 1562 return forward_call(*args, **kwargs)\n 1564 try:\n 1565 result = None\n\nCell In[181], line 36, in Conv2d_mod.forward(self, x, style_w)\n 34 x = x.view(1, batch*channels, H, W)\n 35 print(f'x.shape: {x.shape} | weights.shape: {weights.shape}')\n---> 36 out = F.conv2d(x, weights, groups=batch, padding=self.padding)\n 37 out = out.view(batch, self.out_channels, out.shape[-2], out.shape[-1])\n 39 out += self.bias\n\nRuntimeError: Given groups=4, weight of size [512, 256, 3, 3], expected input[1, 512, 128, 128] to have 1024 channels, but got 512 channels instead\n```\n\nI am stumped as to what is causing this error, it appears to be due to the in and out channels being different but this is typical for a StyleGAN so it needs to stay this way.\n\nAny ideas on how to fix?"},{"role":"assistant","content":"I'm not familiar with your code but note that `in_channels=256` in `Conv2d_mod` while the actual input uses only `128` channels. Using:\n```python\nconv2d_mod = Conv2d_mod(256, 256//2, 3, 256)\nx = torch.randn(4, 256, 128, 128)\nw = torch.randn(4, 256)\nout = conv2d_mod(x, w)\n```\nfixes the shape mismatch."}],"kind":"answer","thread_id":211182,"url":"https://discuss.pytorch.org/t/stylegan2-demodulation-grouped-convolution-incorrect-dimensions/211182","created_at":"2024-10-05T10:50:25.570000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"My linear layer's output does not have gradients\n\nI have the following toy code:\ntestx = torch.tensor([[1.0, 2.0, 3.0]], requires_grad=True)\ntestw = torch.tensor([[0.1, 0.2, 0.3]], requires_grad=True)\ntestb = torch.tensor([0.5], requires_grad=True)\ntesty = F.linear(testx, testw, bias=testb)\nprint([a.requires_grad for a in [testx, testw, testb, testy]])\n\nWhen I run it standalone in a new python file it correctly gives me [True, True, True, True] . But when I run exactly these lines in a larger program I get the output [True, True, True, False]\n\nWhat could cause requires_grad to be set to false for testy in this case and how can I debug it? Is there some context that I need to set for this to work correctly? \n\nThanks in advance for your help."},{"role":"assistant","content":"You might have disabled gradient computation globally, e.g. via:\n```python\ntorch.set_grad_enabled(False)\ntestx = torch.tensor([[1.0, 2.0, 3.0]], requires_grad=True)\ntestw = torch.tensor([[0.1, 0.2, 0.3]], requires_grad=True)\ntestb = torch.tensor([0.5], requires_grad=True)\ntesty = F.linear(testx, testw, bias=testb)\nprint([a.requires_grad for a in [testx, testw, testb, testy]])\n# [True, True, True, False]\n```"}],"kind":"answer","thread_id":211246,"url":"https://discuss.pytorch.org/t/my-linear-layers-output-does-not-have-gradients/211246","created_at":"2024-10-07T16:00:06.149000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Optimize training data after training stage\n\nHi, I'm trying to optimize a noise which is used during model training to aim for a specific target when the training is done.\nA sample code can be found here:\n```\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import transforms\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 32, 3, 1)\n self.conv2 = nn.Conv2d(32, 64, 3, 1)\n self.dropout1 = nn.Dropout(0.25)\n self.dropout2 = nn.Dropout(0.5)\n self.fc1 = nn.Linear(9216, 128)\n self.fc2 = nn.Linear(128, 10)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.relu(x)\n x = F.max_pool2d(x, 2)\n x = self.dropout1(x)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.dropout2(x)\n x = self.fc2(x)\n output = F.log_softmax(x, dim=1)\n return output\n\ndef train(model, optimizer, data, label, noise, target):\n\n noise.requires_grad_()\n # model training\n model.train()\n optimizer.zero_grad()\n output = model(data + noise)\n loss = F.cross_entropy(output, label)\n noise.retain_grad()\n loss.backward()\n optimizer.step()\n \n # optimize noise\n model.eval()\n output = model(target['data'])\n loss = -F.cross_entropy(output, target['label'])\n grad = torch.autograd.grad(loss, [noise])[0]\n noise = noise.detach() + 0.001 * torch.sign(grad.detach())\n noise = torch.clamp(noise, 0, 1)\n return noise\n\ndef main():\n model = Net().cuda()\n optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n data = torch.randn((100, 1, 28, 28)).cuda()\n label = torch.randint(0, 10, (100,)).cuda()\n\n noise = torch.randn((100, 1, 28, 28)).cuda()\n target = {'data': torch.randn((1, 1, 28, 28)).cuda(), 'label': torch.tensor([0]).cuda()}\n train(model, optimizer, data, label, noise, target)\n\nif __name__ == '__main__':\n main()\n```\nWhen I run the code it says ```RuntimeError: One of the differentiated Tensors appears to not have been used in the graph. Set allow_unused=True if this is the desired behavior.``` on the line ```grad = torch.autograd.grad(loss, [noise])[0]```.\n\nIf I add allow_unused=True to it, the grad will just be None. It seems that the gradient of the noise wrt the model during training is gone when I optimize the noise.\n\nI wonder if there is any way to retain the gradient of the noise so I can optimize it later.\n\nI also tried ```loss.backward(create_graph=True)```, but it didn't work."},{"role":"assistant","content":"The `noise` tensor wasn't used in the eval loop in the computation of `output` and `loss` so it also won't influence their values resulting in a `None` gradient. You would need to add `noise` to the actual computation so that its value influences the output."}],"kind":"answer","thread_id":211271,"url":"https://discuss.pytorch.org/t/optimize-training-data-after-training-stage/211271","created_at":"2024-10-08T02:33:13.263000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Training resnet on increasing fraction of a dataset\n\nHello there!\n\nFor a ongoing research project, we are utilizing a NF-ResNet 26 model and training it to classify two outcomes (yes/no). We'd like to follow this approach: Take a fraction of the dataset (1%-10%), and train each fraction for a number of 50 epochs. Afterwards the model is tested on the whole validation dataset, the fraction increases and so on. I've never tried an approach like this, so I want to make sure that the code I set up is properly working. It looks like this\n\n```\nresults = {\n 'fraction': [],\n 'epoch': [],\n 'train_loss': [],\n 'train_accuracy':[],\n 'val_loss': [],\n 'val_accuracy': []\n}\n\nnum_epochs = 50\ntotal_samples = len(train_dataset)\n\n # Create a subset of the dataset\nfor fraction in range(1, 11): # 1% to 10%\n # Calculate the number of samples for the current fraction\n num_samples = int(total_samples * (fraction / 100))\n subset_indices = list(range(num_samples))\n\n subset= Subset(train_dataset, subset_indices)\n \n\n # Create a DataLoader for the current subset\n train_loader = DataLoader(subset, batch_size=32, shuffle=True)\n\n print(f\"Training with {fraction}% of the dataset ({num_samples} samples)...\")\n\n for epoch in range(num_epochs):\n\n model.train() # Set model to training mode\n\n running_loss = 0.0\n train_correct = 0\n train_total = 0\n for inputs, labels in train_loader:\n\n inputs, labels = inputs.to(device), labels.to(device)\n\n # Zero the parameter gradients\n optimizer.zero_grad()\n\n # Forward pass\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n\n _, predicted = torch.max(outputs.data, 1)\n train_total += labels.size(0)\n train_correct += (predicted == labels).sum().item()\n\n # Backward pass and optimization\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n\n # Print the average loss for this epoch\n print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {running_loss/len(train_loader):.4f}')\n # Print the average accuracy for this epoch\n print(f'Epoch[{epoch+1}/{num_epochs}],Train_Accuracy: {100 * train_correct / train_total:.2f}%')\n\n # Optionally, evaluate on the validation set\n model.eval() # Set model to evaluation mode\n val_loss = 0.0\n correct = 0\n total = 0\n with torch.no_grad():\n for inputs, labels in test_loader:\n inputs, labels = inputs.to(device), labels.to(device)\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n val_loss += loss.item()\n\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n print(f'Validation Loss: {val_loss/len(test_loader):.4f}, Accuracy: {100 * correct / total:.2f}%')\n\n results['fraction'].append(fraction)\n results['epoch'].append(epoch + 1)\n results['train_loss'].append(running_loss/len(train_loader))\n results['train_accuracy'].append(100 * train_correct / train_total)\n results['val_loss'].append(val_loss/len(test_loader))\n results['val_accuracy'].append(100 * correct / total)\n```\n\nIn particular, Im not sure about the following: Do I understand correctly, that the model is trained on a fraction (lets say 1%) and if the fraction is increased (i.e 2% of the dataset sampled), the model is not \"newly trained\" but utilizes the weights learned with the 1% fraction dataset? And so on?\n\nI would appreciate any feedback a lot, I just want to be crystal clear the I am following the correct path here.\n\nThank you in advance\n\nBest"},{"role":"assistant","content":"Yes, this is the case as long as you don't recreate the `model` or re-initialize its parameters explicitly."}],"kind":"answer","thread_id":211475,"url":"https://discuss.pytorch.org/t/training-resnet-on-increasing-fraction-of-a-dataset/211475","created_at":"2024-10-12T13:38:29.658000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"How to define forward of nn.Embedding\n\nHi,\nI would like to apply the code below to nn.Embedding.\nHowever, the forward function still calls the original nn.Embedding forward, instead of calling the one I created.\nI would appreciate your help. Could you tell me why the model behaves like this?\n\n```\nclass Linear(nn.Linear): \n def __init__(self, in_features, out_features):\n super(Linear, self).__init__(in_features, out_features)\n self.weight.fast = None #Lazy hack to add fast weight link\n self.bias.fast = None\n\n def forward(self, x):\n if self.weight.fast is not None and self.bias.fast is not None:\n out = F.linear(x, self.weight.fast, self.bias.fast)\n else:\n out = super(Linear, self).forward(x)\n return out\n```\n\n```\nclass Embedding(nn.Embedding): \n def __init__(self, num_embeddings, embedding_dim):\n super(Embedding, self).__init__(num_embeddings, embedding_dim)\n self.weight.fast = None\n \n def forward(self, user_id):\n if self.weight.fast is not None:\n user_emb = F.embedding(user_id, self.weight.fast)\n else:\n user_emb = super(Embedding, self).forward(user_id)\n return user_emb\n```"},{"role":"assistant","content":"The code works for me and calls the custom `forward`: \n```python\nclass Embedding(nn.Embedding): \n def __init__(self, num_embeddings, embedding_dim):\n super(Embedding, self).__init__(num_embeddings, embedding_dim)\n self.weight.fast = None\n \n def forward(self, user_id):\n print(\"calling custom forward\")\n if self.weight.fast is not None:\n print(\"calling fast custom\")\n user_emb = F.embedding(user_id, self.weight.fast)\n else:\n print(\"calling default custom\")\n user_emb = super(Embedding, self).forward(user_id)\n return user_emb\n\nemb = Embedding(10, 10)\nx = torch.randint(0, 10, (10,))\n\nout = emb(x)\n# calling custom forward\n# calling default custom\n\nemb.weight.fast = emb.weight.clone()\nout = emb(x)\n# calling custom forward\n# calling fast custom\n```"}],"kind":"answer","thread_id":211541,"url":"https://discuss.pytorch.org/t/how-to-define-forward-of-nn-embedding/211541","created_at":"2024-10-14T10:47:28.805000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"DataParal works for 1 GPU but not for more GPUs\n\nI am working on parallelizing my training using DP, however within a single instance (with 4 GPUs) it it not working when selecting more than 1 GPUs. Following is my code snippet:\n```\ndef main():\n # Set CUDA_VISIBLE_DEVICES to limit the GPUs used\n if args.num_of_gpu > 0:\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \",\".join(str(i) for i in range(args.num_of_gpu))\n\n # Check available GPUs\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n num_available_gpus = torch.cuda.device_count()\n print(f\"Running on {num_available_gpus} GPU(s): {torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'No GPU'}\")\n\n # Check if the GPU is available\n # device = torch.device(args.device) if torch.cuda.is_available() else torch.device(\"cpu\")\n # print(f'Main Selected device: {device}')\n\n # To store the five fold losses\n cv_valid_losses = []\n cv_valid_mse_losses = []\n cv_test_losses = []\n for i in range (5):\n\n # Specify the Model\n if model_name==\"x\":\n model = DNN() ## note this DNN is imported\n elif model_name==\"enc\":\n model = ED(64)\n elif model_name==\"dncnn\":\n model = DnCNN(2,5)\n elif model_name==\"dncnn_mod\":\n model = DnCNNmod(2,5)\n elif model_name ==\"unet\": ## this is imported as a model\n model = UNet(n_channels=2,n_classes=1)\n\n if num_available_gpus > 1:\n model = nn.DataParallel(model)\n model.to(device)\n```\n\nhere is the error I am getting\n```\nRuntimeError: module must have its parameters and buffers on device cuda:0 (device_ids[0]) but found one of them on device: cuda:1```\n\nPlease note, I am calling other models in this main.py. In only main.py I am using the DP. I am not sure whats is the problem or how should I solve. Can anyone please help?"},{"role":"assistant","content":"Could you post the model definition, please?"},{"role":"user","content":"here it is. please have a look\n```\nimport torch\nimport torch.nn as nn\nfrom torchinfo import summary\nimport torch.nn.functional as F\nclass DoubleConv(nn.Module):\n \"\"\"(convolution => [BN] => ReLU) * 2\"\"\"\n\n def __init__(self, in_channels, out_channels, mid_channels=None):\n super().__init__()\n if not mid_channels:\n mid_channels = out_channels\n self.double_conv = nn.Sequential(\n nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(mid_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True)\n )\n\n def forward(self, x):\n return self.double_conv(x)\n\nclass Down(nn.Module):\n \"\"\"Downscaling with maxpool then double conv\"\"\"\n\n def __init__(self, in_channels, out_channels):\n super().__init__()\n self.maxpool_conv = nn.Sequential(\n nn.MaxPool2d(2),\n DoubleConv(in_channels, out_channels)\n )\n\n def forward(self, x):\n return self.maxpool_conv(x)\n\nclass Up(nn.Module):\n \"\"\"Upscaling then double conv\"\"\"\n\n def __init__(self, in_channels, out_channels, bilinear=True, dp = False):\n super().__init__()\n self.dp = dp\n # if bilinear, use the normal convolutions to reduce the number of channels\n self.dropout = nn.Dropout(0.5)\n if bilinear:\n self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n self.conv = DoubleConv(in_channels, out_channels, in_channels // 2)\n else:\n self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)\n self.conv = DoubleConv(in_channels, out_channels)\n\n def forward(self, x1, x2):\n x1 = self.up(x1)\n if self.dp:\n x1 = self.dropout(x1)\n # input is CHW\n diffY = x2.size()[2] - x1.size()[2]\n diffX = x2.size()[3] - x1.size()[3]\n\n x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,\n diffY // 2, diffY - diffY // 2])\n x = torch.cat([x2, x1], dim=1)\n return self.conv(x)\n\nclass OutConv(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(OutConv, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)\n\n def forward(self, x):\n return self.conv(x)\n\nclass UNet(nn.Module):\n def __init__(self, n_channels, n_classes, bilinear=False):\n super(UNet, self).__init__()\n self.n_channels = n_channels\n self.n_classes = n_classes\n self.bilinear = bilinear\n\n self.inc = DoubleConv(n_channels, 64)\n self.down1 = Down(64, 128)\n self.down2 = Down(128, 256)\n self.down3 = Down(256, 512)\n factor = 2 if bilinear else 1\n self.down4 = Down(512, 1024 // factor)\n self.up1 = Up(1024, 512 // factor, bilinear)\n self.up2 = Up(512, 256 // factor, bilinear)\n self.up3 = Up(256, 128 // factor, bilinear,dp=True)\n self.up4 = Up(128, 64, bilinear,dp=True)\n self.outc = OutConv(64, n_classes)\n self.dropout = nn.Dropout2d(0.5)\n\n def forward(self, x):\n x1 = self.inc(x)\n x1 = self.dropout(x1)\n x2 = self.down1(x1)\n x2 = self.dropout(x2)\n x3 = self.down2(x2)\n x3 = self.dropout(x3)\n # x4 = self.down3(x3)\n # x5 = self.down4(x4)\n # x = self.up1(x5, x4)\n # x = self.up2(x, x3)\n x = self.up3(x3, x2)\n\n x = self.up4(x, x1)\n logits = self.outc(x)\n return logits\n\nif __name__==\"__main__\":\n model = UNet(n_channels=3,n_classes=1)\n summary(model, input_size=(128,3, 10, 10))\n print(\"Done!\")\n```"},{"role":"assistant","content":"Thanks for the code! Your code works fine for me:\n```python\nif __name__==\"__main__\":\n model = UNet(n_channels=3,n_classes=1)\n model = nn.DataParallel(model).cuda()\n x = torch.randn(128,3, 10, 10).cuda()\n out = model(x)\n print(out.shape)\n```\nand the proper output shape is shown without any errors being raised."}],"kind":"answer","thread_id":211670,"url":"https://discuss.pytorch.org/t/dataparal-works-for-1-gpu-but-not-for-more-gpus/211670","created_at":"2024-10-16T13:59:41.406000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"DataParal works for 1 GPU but not for more GPUs\n\nI am working on parallelizing my training using DP, however within a single instance (with 4 GPUs) it it not working when selecting more than 1 GPUs. Following is my code snippet:\n```\ndef main():\n # Set CUDA_VISIBLE_DEVICES to limit the GPUs used\n if args.num_of_gpu > 0:\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \",\".join(str(i) for i in range(args.num_of_gpu))\n\n # Check available GPUs\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n num_available_gpus = torch.cuda.device_count()\n print(f\"Running on {num_available_gpus} GPU(s): {torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'No GPU'}\")\n\n # Check if the GPU is available\n # device = torch.device(args.device) if torch.cuda.is_available() else torch.device(\"cpu\")\n # print(f'Main Selected device: {device}')\n\n # To store the five fold losses\n cv_valid_losses = []\n cv_valid_mse_losses = []\n cv_test_losses = []\n for i in range (5):\n\n # Specify the Model\n if model_name==\"x\":\n model = DNN() ## note this DNN is imported\n elif model_name==\"enc\":\n model = ED(64)\n elif model_name==\"dncnn\":\n model = DnCNN(2,5)\n elif model_name==\"dncnn_mod\":\n model = DnCNNmod(2,5)\n elif model_name ==\"unet\": ## this is imported as a model\n model = UNet(n_channels=2,n_classes=1)\n\n if num_available_gpus > 1:\n model = nn.DataParallel(model)\n model.to(device)\n```\n\nhere is the error I am getting\n```\nRuntimeError: module must have its parameters and buffers on device cuda:0 (device_ids[0]) but found one of them on device: cuda:1```\n\nPlease note, I am calling other models in this main.py. In only main.py I am using the DP. I am not sure whats is the problem or how should I solve. Can anyone please help?"},{"role":"assistant","content":"Could you post the model definition, please?"}],"kind":"clarification","thread_id":211670,"url":"https://discuss.pytorch.org/t/dataparal-works-for-1-gpu-but-not-for-more-gpus/211670","created_at":"2024-10-16T13:59:41.406000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Audios wav pytorch\n\ngood day your support this error RuntimeError: mat1 dim 1 must match mat2 dim 0, I am working pytorch to classify wav audios, \nBATCH_SIZE = 32 ###128 para 4conv\nEPOCHS = 10\nLEARNING_RATE = 0.001\n\nANNOTATIONS_FILE = \"../data_aymara/metadata/aymara_sound.csv\"\nAUDIO_DIR = \"../data_aymara/audio\"\nSAMPLE_RATE = 22050\nNUM_SAMPLES = 22050\n\nfrom torch import nn\nfrom torchsummary import summary\nclass CNNNetwork(nn.Module):\n\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Sequential(\n nn.Conv2d(\n in_channels=1,\n out_channels=16,\n kernel_size=3,\n stride=1,\n padding=2\n ),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2)\n )\n self.conv2 = nn.Sequential(\n nn.Conv2d(\n in_channels=16,\n out_channels=32,\n kernel_size=3,\n stride=1,\n padding=2\n ),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2)\n )\n \n self.flatten = nn.Flatten()\n self.linear = nn.Linear(32 * 3 * 4, 3)####2 convoluciones ####3 son las clases de salida, 32 capas ocultas\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, input_data):\n x = self.conv1(input_data)\n x = self.conv2(x)\n x = self.flatten(x)\n logits = self.linear(x)\n predictions = self.softmax(logits)\n return predictions"},{"role":"assistant","content":"solved by printing xshape and setting the value to linear\n print(x.shape)###con esto se sabe que debe ir en la seccion A\n x = self.flatten(x)\n \n x = x.view(x.size(0), -1)"}],"kind":"answer","thread_id":211673,"url":"https://discuss.pytorch.org/t/audios-wav-pytorch/211673","created_at":"2024-10-16T14:33:55.339000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["jsanchez"]} | |
| {"messages":[{"role":"user","content":"Multiple digit classification loss function\n\nAs title suggests I have a modified mnist dataset with multiple digits per image 0-3 and each digit can be 0-9.\nI have modelled it as a multi label classification problem and am using cross entropy on 9*3 labels for each sample.\nIs this the right way to go about?\nMy training accuracy is going down but validation accuracy is monotonically increasing\n\nI think I am supposed to do something like cross entropy among the 10 labels for each digit seperately and average them out or something \nBut I am not able to formulate it."},{"role":"assistant","content":"`nn.CrossEntropyLoss` is used for multi-class classification use cases and I'm unsure how your model output and target looks exactly. For multi-label classification use cases you would commonly use `nn.BCEWithLogitsLoss` adding another \"no-class\" class so that your output and target would have the shape `[batch_size, nb_total_classes=11*3]` or with another dimension as `[batch_size, num_digits, num_classes=11]` where `num_classes = 10 digit classes + 1 \"background/no-class\"` class. Let me know if this works."}],"kind":"answer","thread_id":211836,"url":"https://discuss.pytorch.org/t/multiple-digit-classification-loss-function/211836","created_at":"2024-10-20T21:18:01.869000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"How can I track the nightly version of PyTorch\n\nHi, guys!\n\nI know I can track every official release version of pytorch here (https://github.com/pytorch/pytorch/releases)\n\nBut if I want to know the nightly version is doing (e.g., what new features are added, what bugs are fixed). I mean is there any doc of these things?\n\nThx in advance!"},{"role":"assistant","content":"No, release notes are not created daily, but you can use `torch.version.git_version` to check the commit the nightly is based on and check the commit history on [GitHub](https://github.com/pytorch/pytorch/commits/main/)."}],"kind":"answer","thread_id":211844,"url":"https://discuss.pytorch.org/t/how-can-i-track-the-nightly-version-of-pytorch/211844","created_at":"2024-10-21T03:11:24.010000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"1D convolution for 1D feature input\n\nHello Everyone,\n\nI am using a time-series data for binary class classification. I have a training dataset of 4917 x 244 where 244 are the feature columns and 4917 are the onsets. For example if I am using a sliding window of 2048 then it calculates 1 x 244 feature vector for one window. Therefore we have such 4917 windows and its respective feature columns. \nNow I am using a batch size to divide 4917 onsets into number of batches of size 256 each. Therefore we have feature vector 256 x 244 for one batch. \n\nI want to implement 1D convolution to process this data and classify each window into 0 or 1 class. At my initial efforts I am very much confused in input_channel, output_channel and kernel size. I tried my best but eventually I am getting error of dimension mismatch or out of range during training. \n\nI would appreciate if anyone could clearly explain the steps that I can follow to implement 1D CNN for my dataset."},{"role":"assistant","content":"I don't understand this approach completely. Are you padding the input and are you using the \"feature\" dimension as the channels? Are you then striding over the first dimension of the size `4917`? \n\nI'm also unsure how this operation is performed as it cannot be a `reshape` operation so could you also explain in more detail how the input is processed?"},{"role":"user","content":"Sorry may be I could not explain it better.\n\nFor example: I have a time series acoustic signal of an event of class 0 with a total number of samples let say 204800. Now I am using a window size of 2048 to slide over the total samples with zero overlap length. Then we have such 100 windows to scan all 204800 samples. Now for each window I am calculating 1D 244 features (Temporal, spectral, avg mffcs etc.). It means for each window I have a feature vector of 1 x 244. Now for a total of 100 windows I have 100 x 244 feature vectors. Now read the next .wav file let say for class 1 we have 20480 samples. Then the window size of 2048 with zero overlap length will return 10 x 244 feature vectors. When I append this feature vector to the previous one and now I have a feature size of 110 x 244. Repeating the same for all .wav files of class 0 and 1.\nIn the above query I said that I have such 4917 x 244 feature vectors that is evaluated on the window size of 2048 for all the .wav file of class 0 and 1. In other word I have training set of x_train = 4917 x 244 and y_train = 4917 x 1.\nNow I am using the concept of batch size to divide the training set into number of batches and created a train_dataloader. \n train_dl = DataLoader(CageData(X_train, y_train),\n batch_size = 256,\n shuffle = True,\n num_workers = 2,\n pin_memory = False)\n\nThus for 1 epoch it will iterate 19 times 4917/256 = ~19 to complete training of 4917 examples.\nSimilarly I have a test set of X_test = 626 x 244 and labels y_test = 626 x 1.\n test_dl = DataLoader(CageData(X_test, y_test),\n batch_size = 256,\n shuffle = True,\n num_workers = 2,\n pin_memory = False)\n\nNow I want to know how to process this data to my 1D CNN to train and test. What will be my channel_in , channel_out, kernel_size and what will be the dimension of fully connected layer."},{"role":"assistant","content":"Thanks for the update.\nI assume the preprocessing is already done and your `X_train/test` as well as `y_train/test` datasets are already created.\n\nIf I understand your question correctly you now want to pass this data (from the `DataLoader`) into a 1d-CNN.\n\n`nn.Conv1d` layers expect a 3D input in the shape `[batch_size, channels, seq_len]` where `channels` corresponds to the number of input channels and `seq_len` to the size of the temporal dimension which will be used for the actual convolution. \nYour current input has a shape of `[batch_size, nb_features]` and it's unclear what exactly these features represent. \n`nn.Conv1d` layers can be used for e.g. audio signals and the signal input could be a stereo audio data tensor in the shape `[batch_size, nb_channels=2, seq_len=number_of_timesteps]`. \nI thus don't know if you want to treat the feature dimension in your input as a temporal dimension and thus move the conv filters through it (you would expect a temporal dependency between these data points in this case) or as channels.\n\nBased on:\n\nit seems you are computing a variety of features and since these were created using a sliding window I would expect they are correlated in the temporal dimension.\nIf so, you could `unsqueeze(1)` another additional dimension creating a single channel so that your input would have the shape `[batch_size, nb_channels=1, seq_len=244]`.\nIn this case the `nn.Conv1d` layer would use `in_channels=1` and an arbitrary number of `out_channels`. The same goes for the `kernel_size`, `stride`, etc. as you can define it yourself. \nThe number of `in_features` in the first linear layer used after flattening the intermediate activation would thus also depend on the setup used for all conv layers, which you should pick."}],"kind":"answer","thread_id":211919,"url":"https://discuss.pytorch.org/t/1d-convolution-for-1d-feature-input/211919","created_at":"2024-10-22T11:23:17.700000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Help with Install Torch with Cuda\n\nHello!\n\nI am facing issues while installing and using PyTorch with CUDA support on my computer. Here are some details about my system and the steps I have taken:\n\n### System Information:\n- **Graphics Card:** NVIDIA GeForce GTX 1050 Ti\n- **NVIDIA Driver Version:** 566.03\n- **CUDA Version (from nvidia-smi):** 12.7\n- **CUDA Version (from nvcc):** 11.7\n\n### Steps Taken:\n1. I installed Anaconda and created an environment named `pytorch_env`.\n2. I installed PyTorch, torchvision, and torchaudio using the command:\n ```bash\n conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c nvidia\n ```\n3. I checked the installation by running Python and executing the following commands:\n ```python\n import torch\n print(torch.__version__) # PyTorch Version: 2.4.1\n print(torch.cuda.is_available()) # CUDA Availability: False\n ```\n\n### Problem:\nEven though PyTorch is installed, CUDA availability returns `False`. I have checked the NVIDIA drivers and the installation of the CUDA Toolkit, but the issue persists.\n\n### Questions:\n1. How can I properly configure PyTorch to work with CUDA?\n2. Do I need to install a different version of PyTorch or NVIDIA drivers to resolve this issue?\n3. Are there any additional steps I could take to troubleshoot this problem?\n\nI would appreciate any help or advice!"},{"role":"assistant","content":"What exactly did you check to make sure the driver works?\nYour locally installed CUDA toolkit won't be used as PyTorch binaries ship with their own CUDA runtime dependencies. \n\nYour install command looks also wrong as it does not correspond to any command from our install matrix."},{"role":"user","content":"We checked several key aspects to ensure that the driver works correctly with PyTorch:\n\n1. **Driver Verification**: We used the `nvidia-smi` command to confirm that the NVIDIA driver is installed and functioning. This command shows the driver version and the CUDA version it supports, ensuring compatibility with PyTorch.\n2. **CUDA Toolkit**: We noted that the locally installed CUDA toolkit is not utilized by PyTorch binaries, as they come with their own CUDA runtime dependencies. This means we don’t need to worry about having a separate CUDA installation unless we are building from source.\n3. **Installation Command**: We carefully reviewed the installation command used for PyTorch. It should match the official installation matrix provided on the PyTorch website. For example, we used:\n\nbash\n\n```\npip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118\n```\n\nThis command ensures that we are installing the correct version of PyTorch with CUDA support.\n4. **CUDA Availability Check**: After installation, we ran a simple check in Python:\n\npython\n\n```\nimport torch\nprint(torch.cuda.is_available())\n```\n\nThis confirmed whether PyTorch could access the GPU.\n5. **Environment Setup**: We created a clean virtual environment to avoid conflicts with other packages, ensuring that all dependencies were correctly installed without any remnants from previous installations.\n\nBy following these steps, we ensured that everything was set up properly for using PyTorch with GPU support.\n\nIn your question, there is an implication that you believe you know how to solve the problem. If you have specific recommendations or advice regarding this, please share! It could help us better understand the situation and find an optimal solution.\n\nI'm sharing the process of installing PyTorch with CUDA support on my computer. Below are the steps and verification results that I performed.\n\n## Checking CUDA Version\n\nbash\n\n```\nnvcc: NVIDIA (R) Cuda compiler driver\nCopyright (c) 2005-2022 NVIDIA Corporation\nBuilt on Tue_May__3_19:00:59_Pacific_Daylight_Time_2022\nCuda compilation tools, release 11.7, V11.7.64\nBuild cuda_11.7.r11.7/compiler.31294372_0\n```\n\n## Checking Python Version\n\nbash\n\n```\nPython 3.12.4\n```\n\n## Checking pip Version\n\nbash\n\n```\npip 24.2 from E:\\tyflow\\Tools\\python\\lib\\site-packages\\pip (python 3.10)\n```\n\n## Checking Installed PyTorch Version\n\nbash\n\n```\nPyTorch Version: 2.3.1\n```\n\n## Checking Available CUDA Devices\n\nbash\n\n```\nNumber of available CUDA devices: CUDA is not available.\n```\n\nSince CUDA is not available, I decided to reinstall PyTorch.\n\n## Uninstalling Current Versions of PyTorch\n\nbash\n\n```\nFound existing installation: torch 2.5.0\nUninstalling torch-2.5.0:\n Successfully uninstalled torch-2.5.0\nFound existing installation: torchvision 0.20.0\nUninstalling torchvision-0.20.0:\n Successfully uninstalled torchvision-0.20.0\nFound existing installation: torchaudio 2.5.0\nUninstalling torchaudio-2.5.0:\n Successfully uninstalled torchaudio-2.5.0\n```\n\n## Installing PyTorch with CUDA Support\n\nbash\n\n```\nLooking in indexes: https://pypi.org/simple, https://download.pytorch.org/whl/cu117\nCollecting torch\nUsing cached torch-2.5.0-cp310-cp310-win_amd64.whl.metadata (28 kB)\nCollecting torchvision\nUsing cached torchvision-0.20.0-cp310-cp310-win_amd64.whl.metadata (6.2 kB)\nCollecting torchaudio\nUsing cached torchaudio-2.5.0-cp310-cp310-win_amd64.whl.metadata (6.5 kB)\nRequirement already satisfied: filelock in e:\\tyflow\\tools\\python\\lib\\site-packages (from torch) (3.16.1)\n...\nSuccessfully installed torch-2.5.0 torchaudio-2.5.0 torchvision-0.20.0\n```\n\n## Checking Installation of PyTorch with CUDA\n\nbash\n\n```\nCUDA available: False\n```\n\n## Rechecking PyTorch Version After Reinstallation\n\nbash\n\n```\nPyTorch Version: 2.3.1\n```\n\n## Rechecking Available CUDA Devices After Reinstallation\n\nbash\n\n```\nNumber of available CUDA devices: 0.\n```\n\n[image]"},{"role":"assistant","content":"This is unfortunately not a valid driver test and you should instead verify if any CUDA application is able to run on your GPU.\n\nThis command looks correct, but does not match any of your other outputs.\n\nE.g. here you are claiming to have `torch==2.3.1` installed\n\nwhile you are uninstalling `torch==2.5.0`:\n\nLater you are reinstalling `torch==2.5.0`:\n\nwhile the check again shows `torch==2.3.1`:\n\nI would recommend starting with a clean and new environment, copy/pasting the install command from our website, and install a single version of PyTorch.\nThe installation log should also show if a CUDA-enabled binary is being installed and you can double check it via `torch.cuda.version`."},{"role":"user","content":"Thank you for taking the time to respond; I really appreciate it. I want to clarify about the new environment: should I uninstall Python and reinstall it? Or is it enough to create a virtual environment? As for the environment, I set it up twice—once with pip and once with Anaconda. I installed it using the command from the website, but during testing, I received a message saying that there is no graphics card. \n*Or do I need to uninstall Python?*\n\nTo understand the problem, I will show the test results I obtained using CUDA. \n\nC:\\Users\\ASROCK>nvcc --version\nnvcc: NVIDIA (R) Cuda compiler driver\nCopyright (c) 2005-2022 NVIDIA Corporation\nBuilt on Tue_May__3_19:00:59_Pacific_Daylight_Time_2022\nCuda compilation tools, release 11.7, V11.7.64\nBuild cuda_11.7.r11.7/compiler.31294372_0\n\nC:\\Users\\ASROCK>where nvcc\nC:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.7\\bin\\nvcc.exe\n\nCUDA Device Query (Runtime API) version (CUDART static linking)\n\nDetected 1 CUDA Capable device(s)\n\nDevice 0: \"NVIDIA GeForce GTX 1050 Ti\"\nCUDA Driver Version / Runtime Version 12.7 / 11.7\nCUDA Capability Major/Minor version number: 6.1\nTotal amount of global memory: 4096 MBytes (4294705152 bytes)\n( 6) Multiprocessors, (128) CUDA Cores/MP: 768 CUDA Cores\nGPU Max Clock rate: 1392 MHz (1.39 GHz)\nMemory Clock rate: 3504 Mhz\nMemory Bus Width: 128-bit\nL2 Cache Size: 1048576 bytes\nMaximum Texture Dimension Size (x,y,z) 1D=(131072), 2D=(131072, 65536), 3D=(16384, 16384, 16384)\nMaximum Layered 1D Texture Size, (num) layers 1D=(32768), 2048 layers\nMaximum Layered 2D Texture Size, (num) layers 2D=(32768, 32768), 2048 layers\nTotal amount of constant memory: zu bytes\nTotal amount of shared memory per block: zu bytes\nTotal number of registers available per block: 65536\nWarp size: 32\nMaximum number of threads per multiprocessor: 2048\nMaximum number of threads per block: 1024\nMax dimension size of a thread block (x,y,z): (1024, 1024, 64)\nMax dimension size of a grid size (x,y,z): (2147483647, 65535, 65535)\nMaximum memory pitch: zu bytes\nTexture alignment: zu bytes\nConcurrent copy and kernel execution: Yes with 5 copy engine(s)\nRun time limit on kernels: Yes\nIntegrated GPU sharing Host Memory: No\nSupport host page-locked memory mapping: Yes\nAlignment requirement for Surfaces: Yes\nDevice has ECC support: Disabled\nCUDA Device Driver Mode (TCC or WDDM): WDDM (Windows Display Driver Model)\nDevice supports Unified Addressing (UVA): Yes\nDevice supports Compute Preemption: Yes\nSupports Cooperative Kernel Launch: Yes\nSupports MultiDevice Co-op Kernel Launch: No\nDevice PCI Domain ID / Bus ID / location ID: 0 / 1 / 0\nCompute Mode:\n< Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >\n\ndeviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 12.7, CUDA Runtime Version = 11.7, NumDevs = 1, Device0 = NVIDIA GeForce GTX 1050 Ti\nResult = PASS\n\nC:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.7\\extras\\demo_suite>bandwidthTest.exe > c:\\1\\222.txt\n\n[CUDA Bandwidth Test] - Starting...\nRunning on...\n\n Device 0: NVIDIA GeForce GTX 1050 Ti\n Quick Mode\n\n Host to Device Bandwidth, 1 Device(s)\n PINNED Memory Transfers\n Transfer Size (Bytes)\tBandwidth(MB/s)\n 33554432\t\t\t12643.2\n\n Device to Host Bandwidth, 1 Device(s)\n PINNED Memory Transfers\n Transfer Size (Bytes)\tBandwidth(MB/s)\n 33554432\t\t\t12514.7\n\n Device to Device Bandwidth, 1 Device(s)\n PINNED Memory Transfers\n Transfer Size (Bytes)\tBandwidth(MB/s)\n 33554432\t\t\t96155.2\n\nResult = PASS\n\nNOTE: The CUDA Samples are not meant for performance measurements. Results may vary when GPU Boost is enabled.\n\n System Information:\nGraphics Card: NVIDIA GeForce GTX 1050 Ti\nCUDA Driver Version: 12.7\nCUDA Runtime Version: 11.7\nTotal Memory: 4096 MB\nTesting Results:\nDevice Query:\nConfirmed that the graphics card is functioning correctly and supports CUDA.\nAll information about the graphics card specifications was successfully retrieved.\nBandwidth Test:\nHost to Device: 12,643.2 MB/s\nDevice to Host: 12,514.7 MB/s\nDevice to Device: 96,155.2 MB/s\nThe results show that the data transfer bandwidth between the host and device is within the normal range, indicating good system performance.\nConclusions:\nYour system fully supports CUDA and is functioning correctly.\nThe data transfer bandwidth is at an acceptable level, making your graphics card suitable for computationally intensive tasks.\nYou can use CUDA for developing and running applications optimized for your graphics card.\n\n**I express my deep gratitude for the attention and time you have given.**"},{"role":"assistant","content":"No, don't uninstall Python itself.\nJust make sure no PyTorch installation can be found before trying to install a new version.\nI.e. run these commands a few times in your base environment (i.e. without activating a new virtual environment):\n```python\npip uninstall torch -y\npip uninstall torch -y\npip uninstall torch -y\n...\nconda uninstall pytorch -y\nconda uninstall pytorch -y\nconda uninstall pytorch -y\n...\n```\nThe terminal should then claim no further installations were detected. Once this is done, create a new virtual environment, e.g. via `conda`, and install a single PyTorch binary there using an install command from our website.\nDuring the installation check which packages are installed as the pip wheel as well as the conda binary should pull either directly CUDA runtime libraries or would indicate the CUDA runtime version in the binary name of PyTorch.\n\nAfterwards, check which version was installed via:\n```python\nimport torch\nprint(torch.__version__)\nprint(torch.version.cuda)\n```\nwhich should show the selected CUDA runtime version and perform a quick test to allocate a random tensor on the GPU:\n```python\nprint(torch.randn(1).cuda())\n```"}],"kind":"answer","thread_id":211985,"url":"https://discuss.pytorch.org/t/help-with-install-torch-with-cuda/211985","created_at":"2024-10-23T12:13:38.026000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[9],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Float16 matmul works while bfloat16 throws CUBLAS_STATUS_NOT_SUPPORTED when calling cublasGemmStridedBatchedEx\n\nmwe:\n```py\na = th.randn(16, 8, 1024, 1024, dtype=th.float16, device=\"cuda\") # switch to bfloat fails\nb = th.randn(16, 8, 1024, 256, dtype=th.float16, device=\"cuda\") # switch to bfloat fails\nc = a @ b\nprint(c.shape)\n\nCUDA error: CUBLAS_STATUS_NOT_SUPPORTED when calling `cublasGemmStridedBatchedEx(handle, opa, opb, (int)m, (int)n, (int)k, (void*)&falpha, a, CUDA_R_16BF, (int)lda, stridea, b, CUDA_R_16BF, (int)ldb, strideb, (void*)&fbeta, c, CUDA_R_16BF, (int)ldc, stridec, (int)num_batches, compute_type, CUBLAS_GEMM_DEFAULT_TENSOR_OP)\n```\n```bash\nnvcc --version\nnvcc: NVIDIA (R) Cuda compiler driver\nCopyright (c) 2005-2019 NVIDIA Corporation\nBuilt on Wed_Oct_23_19:24:38_PDT_2019\nCuda compilation tools, release 10.2, V10.2.89\n\n pip show torch\nName: torch\nVersion: 2.5.0+cu121\n\nnvidia-smi \nSat Oct 26 14:11:57 2024 \n+---------------------------------------------------------------------------------------+\n| NVIDIA-SMI 535.161.08 Driver Version: 535.161.08 CUDA Version: 12.2 |\n|-----------------------------------------+----------------------+----------------------+\n| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |\n| | | MIG M. |\n|=========================================+======================+======================|\n| 0 NVIDIA GeForce GTX TITAN X On | 00000000:04:00.0 Off | N/A |\n| 22% 34C P8 16W / 250W | 7450MiB / 12288MiB | 0% Default \n```"},{"role":"assistant","content":"I cannot reproduce the issue in my setup on a 3090 and `bfloat16` support is also not available on your Maxwell GPU."},{"role":"user","content":"Thank you! I should have included this in my first message but the reason I'm confused is that with less dimensions it works just well. I guess the support is partial?\n```py\nIn [5]: a = th.randn(16, 8, dtype=th.bfloat16, device=\"cuda\")\n ...: b = th.randn(8, 8, dtype=th.bfloat16, device=\"cuda\") \n ...: c = a @ b \n ...: print(c.shape) \n ...: \ntorch.Size([16, 8])\n```"},{"role":"assistant","content":"Yes, maybe fallback kernels are used for specific shapes. However, since the support was added for Ampere and later devices, don't depend on it for Maxwell or any other generation before Ampere."}],"kind":"answer","thread_id":212129,"url":"https://discuss.pytorch.org/t/float16-matmul-works-while-bfloat16-throws-cublas-status-not-supported-when-calling-cublasgemmstridedbatchedex/212129","created_at":"2024-10-26T12:14:12.725000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"How to do finetune traning with BatchNorm2d inside?\n\npython3.10 and torch2.0.1+cu118 \nI have a model to finetune, the model has encoder and decoder part. I want only to finetune the decoder part. So I use code follows to freeze layers except the decoder \n\n```\ndecoder_layer_tag = [\"decoder\", \"dec_lstm\"]\nfor name, para in pretrained_base_model.named_parameters():\n name_tag = name.split(\".\")[0]\n if name_tag not in decoer_layer_tag:\n para.require_grad = False\n``` \n\nthe training process is OK, but during the inference, I found that the encoder output from the pretrained_base_model is different from the encoder output of the finetuned model. \nI found that the different output comes from the output of submodule inside encoder like this: \n```\n sequential([torch.nn.Conv2d(), torch.nn.BatchNorm2d(), torch.nn.ReLU(inplace=True)])\n \n``` \nthe output of torch.nn.BatchNorm2d is different. I compared the weight here in these two models, they are the same. So I guess that even I had freeze the weight inside the BatchNorm2d, its self.training still be true and something inside had changed. I am not formilla with this BatchNorm2d inside. so need some help about it here."},{"role":"assistant","content":"It seems that inside the BatchNorm2d in the encoder part , those parameters are changed during finetune: \nconv.1.runing_mean \nconv1.runing_war \nconv1.num_batches_tracked \n...."}],"kind":"answer","thread_id":212196,"url":"https://discuss.pytorch.org/t/how-to-do-finetune-traning-with-batchnorm2d-inside/212196","created_at":"2024-10-28T08:29:41.455000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["JohnHerry"]} | |
| {"messages":[{"role":"user","content":"Convert Conv3d to Conv2d but outputs different\n\nI tried to convert a Conv3d to Conv2d by splitting 3D kernels by the temporal axis, but outputs from the two differ:\n[[image]](https://private-user-images.githubusercontent.com/71132578/380730915-b7d6bc4e-a0c2-40be-b4de-851800ab5f96.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MzAxODQzOTUsIm5iZiI6MTczMDE4NDA5NSwicGF0aCI6Ii83MTEzMjU3OC8zODA3MzA5MTUtYjdkNmJjNGUtYTBjMi00MGJlLWI0ZGUtODUxODAwYWI1Zjk2LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNDEwMjklMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjQxMDI5VDA2NDEzNVomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTEzZWViMjU0NTY1ZDJjZjk1NzEyNWQ3MGNkOWRjMzVjZjliNGJhOWFlZDAwYjIzZmJiNDVkZmEwZjI5MTVlZDkmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.vVyLQNyS6_JRIrKWUQhqi00kQTwK18DP0uRojwCgPlM)\nI expect output1 and output2 should be the same. Any details I've overlooked?\n\ncode:\n\n```\nt = torch.randn(1, 1, 4, 4, dtype=torch.float32)\nconv3d = torch.nn.Conv3d(out_channels=1, in_channels=1, kernel_size=(2,2,2), stride=(2,2,2), bias=False, dtype=torch.float32)\n# conv3d2 = torch.nn.Conv3d(out_channels=1, in_channels=1, kernel_size=(2,2,2), stride=(2,2,2), bias=False, dtype=torch.bfloat16)\n# conv3d.weight.data = torch.ones(1, 1, 2, 2, 2, dtype=torch.bfloat16)\n# conv3d2.weight.data = conv3d.weight.data\nconv2d1 = torch.nn.Conv2d(in_channels=1, out_channels=1, kernel_size=(2,2), stride=(2,2), bias=False, dtype=torch.float32)\nconv2d2 = torch.nn.Conv2d(in_channels=1, out_channels=1, kernel_size=(2,2), stride=(2,2), bias=False, dtype=torch.float32)\n# conv2d3 = torch.nn.Conv2d(in_channels=3, out_channels=12, kernel_size=(14,14), stride=(14,14), bias=False)\n# print(conv3d.weight.shape)\n# conv2d1.weight = torch.nn.parameter.Parameter(conv3d.weight.detach().reshape(12, 6, 14, 14).contiguous())\n# conv2d3.weight = torch.nn.parameter.Parameter(torch.mean(conv3d.weight.detach(), dim=2).squeeze(dim=2))\n\nprint(conv3d.weight.data.dtype)\nconv2d1.weight.data = conv3d.weight.data[:,:, 0, :, :]\nconv2d2.weight.data = conv3d.weight.data[:,:, 1, :, :]\n\ninput = torch.stack([t, t], dim=0).view(-1, 1, 2, 2, 2)\n# print(input.shape)\noutput1 = conv3d(input).view(-1, 1)\noutput2 = (conv2d1(input[:, :, 0, :, :]) + conv2d2(input[:, :, 1, :, :])).view(-1, 1)\n# output3 = conv3d2(input).view(-1, 1)\nprint(output1==output2)\n```\n\n### Versions\n\nPyTorch version: 2.4.1\nIs debug build: False\nCUDA used to build PyTorch: None\nROCM used to build PyTorch: N/A\n\nOS: macOS 15.0.1 (arm64)\nGCC version: Could not collect\nClang version: 16.0.0 (clang-1600.0.26.3)\nCMake version: version 3.28.1\nLibc version: N/A\n\nPython version: 3.10.13 (main, Sep 11 2023, 08:16:02) [Clang 14.0.6 ] (64-bit runtime)\nPython platform: macOS-15.0.1-arm64-arm-64bit\nIs CUDA available: False\nCUDA runtime version: No CUDA\nCUDA_MODULE_LOADING set to: N/A\nGPU models and configuration: No CUDA\nNvidia driver version: No CUDA\ncuDNN version: No CUDA\nHIP runtime version: N/A\nMIOpen runtime version: N/A\nIs XNNPACK available: True\n\nCPU:\nApple M3 Max\n\nVersions of relevant libraries:\n[pip3] numpy==1.26.3\n[pip3] torch==2.4.1\n[pip3] torchaudio==2.4.1\n[pip3] torchvision==0.19.1\n[conda] numpy 1.26.3 pypi_0 pypi\n[conda] torch 2.4.1 pypi_0 pypi\n[conda] torchaudio 2.4.1 pypi_0 pypi\n[conda] torchvision 0.19.1 pypi_0 pypi"},{"role":"assistant","content":"Your image is not displayed for me, but keep in mind that small numerical mismatches would be expected if different kernels are selected for the different workloads.\nThus check the `.abs().max()` error in your comparison instead of assuming equal results."}],"kind":"answer","thread_id":212246,"url":"https://discuss.pytorch.org/t/convert-conv3d-to-conv2d-but-outputs-different/212246","created_at":"2024-10-29T06:46:01.486000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Training loop freezes after certain epoch\n\nI am facing an issue where my training loop suddenly freezes after certain epoch, when my dataset is large. I am currently training a model using the BYOL strategy, when I am running a test run with smaller dataset (6 datapoints), the training loop freezes after 6th epoch and continues after sometime, but when I use the larger dataset, the training loop freezes after 6th epoch and the system memory consumption keeps increasing until it is killed.\n\n```\ndef train_one_epoch(self, train_loader:DataLoader, optimizer:optim.Optimizer, **kwargs) -> Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"\n Train a single loop on the train_loader.\n\n Args:\n train_loader (DataLoader): training dataloader\n optimizer (optim.Optimizer): optimizer\n \n Returns:\n torch.Tensor, Tuple[torch.Tensor, torch.Tensor]: validation loss, (augmented view 1, augmented view 2) for tensorboard logging\n \"\"\"\n\n running_training_loss = 0\n scaler = amp.grad_scaler.GradScaler(device.type)\n self.online_model.train()\n\n pbar = tqdm(train_loader, desc='Validating...', total=len(train_loader), unit='batch', leave=False, position=1)\n\n for _, (view1, view2) in enumerate(pbar):\n view1, view2 = view1.to(device), view2.to(device)\n optimizer.zero_grad(set_to_none=True)\n\n if kwargs['mixed_precision'] == True:\n with amp.autocast_mode.autocast(device.type):\n o1 = self.online_model(view1)\n o2 = self.online_model(view2)\n\n with torch.no_grad():\n t1 = self.target_model(view1)\n t2 = self.target_model(view2)\n\n loss = (self.calculate_loss(o1, t2.detach()) + self.calculate_loss(o2, t1.detach())).mean()\n scaler.scale(loss).backward() \n scaler.step(optimizer)\n scaler.update()\n \n else:\n o1 = self.online_model(view1)\n o2 = self.online_model(view2)\n\n with torch.no_grad():\n t1 = self.target_model(view1)\n t2 = self.target_model(view2)\n \n loss = (self.calculate_loss(o1, t2.detach()) + self.calculate_loss(o2, t1.detach())).mean()\n loss.backward()\n optimizer.step()\n\n running_training_loss += loss.item() / len(train_loader) \n pbar.set_postfix({'Training loss': running_training_loss})\n pbar.update()\n\n torch.cuda.empty_cache()\n\n return running_training_loss, (view1[0], view2[0])\n\n def validate(self, validation_loader:DataLoader, lr_scheduler:optim.lr_scheduler.LRScheduler) -> Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:\n \"\"\"\n Run a single validation loop for the model\n\n Args:\n validation_loader (DataLoader): validation loader\n lr_scheduler (LRScheduler): learning rate scheduler\n\n Returns:\n torch.Tensor, Tuple[torch.Tensor, torch.Tensor]: validation loss, (augmented view 1, augmented view 2) for tensorboard logging\n \"\"\"\n\n running_validation_loss = 0\n self.online_model.eval()\n self.target_model.eval()\n\n pbar = tqdm(validation_loader, desc='Validating...', total=len(validation_loader), unit='batch', leave=False, position=1)\n\n with torch.no_grad():\n for _, (view1, view2) in enumerate(pbar):\n view1, view2 = view1.to(device), view2.to(device)\n \n o1 = self.online_model(view1)\n o2 = self.online_model(view2)\n\n t1 = self.target_model(view1)\n t2 = self.target_model(view2)\n\n loss = (self.calculate_loss(o1, t2) + self.calculate_loss(o2, t1)).mean()\n lr_scheduler.step(loss)\n\n running_validation_loss += loss.item() / len(validation_loader)\n pbar.set_postfix({'Validation loss': running_validation_loss})\n pbar.update()\n\n torch.cuda.empty_cache()\n\n return running_validation_loss, (view1[0], view2[0])\n \n def train(self,\n dataloader:Union[DataLoader, Tuple[DataLoader, DataLoader]],\n epochs:int=100,\n lr_rate:float=1e-4,\n optimizer:optim.Optimizer=optim.Adam,\n lr_scheduler:optim.lr_scheduler.LRScheduler=optim.lr_scheduler.ReduceLROnPlateau,\n logger:Logger=None,\n save_dir:str=\"weights/SegFormer/encoder/\",\n **kwargs) -> nn.Module:\n r\"\"\"\n Implements the BYOL training strategy\n\n Args:\n dataloader (Union[DataLoader, Tuple[DataLoader, DataLoader]]): traning and validation loader (if any)\n epochs (int): number of epochs\n lr_rate (float): learning rate\n optimizer (optim.Optimizer): training optimizer\n lr_scheduler (optim.lr_scheduler.LRScheduler): learning rate scheduler\n logger (Logger): tensorboard logger\n save_dir (str): model save directory\n\n Returns:\n nn.Module: trained encoder\n \"\"\"\n \n train_loader, validation_loader = None, None\n if isinstance(dataloader, list) or isinstance(dataloader, tuple):\n train_loader, validation_loader = dataloader\n else:\n train_loader = dataloader\n\n if logger is not None:\n logger.log_graph(input=torch.randn(1, 3, self.target_model.image_size, self.target_model.image_size).to(device))\n\n optimizer = optimizer(self.online_model.parameters(), lr_rate, eps=1e-4, weight_decay = kwargs['weight_decay'])\n lr_scheduler = lr_scheduler(optimizer, mode=\"min\", threshold=0.01, patience=3, min_lr=1e-5, eps=1e-3)\n\n profiler = logger.gpu_profiler()\n profiler.start()\n\n pbar = tqdm(range(epochs), desc=\"Training...\", unit=\"epoch\", bar_format=\"{l_bar}{bar}{r_bar}\", dynamic_ncols=True, colour=\"#1f5e2a\", position=0, leave=True)\n best_validation_loss = 2.\n for epoch in pbar:\n training_loss, (view1, view2) = self.train_one_epoch(train_loader, optimizer, **kwargs)\n profiler.step()\n pbar.set_postfix({\"Training Loss\": training_loss})\n\n if validation_loader is not None:\n validation_loss, (view1, view2) = self.validate(validation_loader, lr_scheduler)\n \n pbar.set_postfix({\"Training Loss\": training_loss,\n \"Validation Loss\": validation_loss,\n \"Learning Rate\": lr_scheduler.get_last_lr()[-1]})\n\n if logger is not None:\n logger.log_scaler(epoch, \"Learning Rate\", lr_scheduler.get_last_lr()[-1])\n logger.log_scaler(epoch, \"Metrics/Training Loss\", training_loss)\n logger.log_scaler(epoch, \"Metrics/Validation Loss\", validation_loss)\n logger.log_histogram(epoch, \"Weights Distribution/Online Model Embedding Layer\", [p for p in self.online_model.named_parameters()][-4][1])\n logger.log_histogram(epoch, \"Weights Distribution/Target Model Embedding Layer\", [p for p in self.target_model.named_parameters()][-2][1])\n \n if epoch % 10 == 0:\n logger.log_images(epoch, \"Images/View 1\", view1)\n logger.log_images(epoch, \"Images/View 2\", view2)\n with torch.no_grad():\n logger.log_images(epoch, \"Model Ouput/Online Model\", view_attention(self.online_model_encoder.encoder(view1.unsqueeze(0))[0]))\n logger.log_images(epoch, \"Model Output/Target Model\", view_attention(self.target_model.encoder(view1.unsqueeze(0))[0]))\n\n if epoch % 10 == 0:\n if not os.path.exists(save_dir):\n os.makedirs(save_dir, exist_ok=True)\n\n if validation_loss < best_validation_loss:\n save_model(self.online_model_encoder, f\"SegFormer_{self.online_model_encoder.encoder_variant}_{train_loader.batch_size}_{epoch}\", save_dir)\n best_validation_loss = validation_loss\n\n pbar.update()\n profiler.stop()\n\n if logger is not None:\n logger.log_hparams(hparams={\"batch_size\": train_loader.batch_size, \"learning_rate\": lr_rate}, \n metrics={\"Training Loss\": training_loss, \"Validation Loss\": validation_loss}\n )\n\n return self.online_model_encoder\n```"},{"role":"assistant","content":"The freezes came from the TensorBoard profiler's trace file growing very large. Remove tqdm and the profiler to check that. With `active=3` the JSON file was about 20 GB, and with `active=1` about 6.5 GB. Writing and reading a file that size used up memory and swap until the process was killed. Use a profiler schedule like this:\n\n```\nprof = torch.profiler.profile(\n activities=[torch.profiler.ProfilerActivity.CUDA, torch.profiler.ProfilerActivity.CPU],\n schedule=torch.profiler.schedule(wait=1, warmup=1, active=1, repeat=1),\n on_trace_ready=torch.profiler.tensorboard_trace_handler(log_dir),\n with_stack=True,\n with_flops=True,\n profile_memory=True)\n```"}],"kind":"answer","thread_id":212248,"url":"https://discuss.pytorch.org/t/training-loop-freezes-after-certain-epoch/212248","created_at":"2024-10-29T07:43:09.744000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["Rebantadey","ptrblck"]} | |
| {"messages":[{"role":"user","content":"Attempting to run cuBLAS, but there was no current CUDA context!\n\nHi,\n\ni want to calculate a jacobian of an linear layer using torch.func.jacrev(). Unfortunately when doing so i get the warning shown in my minimal example below. Why does this warning occur? When I use it in my main code the runtime of different code blocks changes.\n```\nimport torch\n\ndummy = torch.tensor(1.0).cuda() # dummy to init cuda\nprint(torch.cuda.is_initialized())\n\nf = torch.nn.Sequential(\n torch.nn.Linear(in_features=16, out_features=16, bias=False),\n ).cuda()\n\nX_k = torch.rand(16).cuda()\nH = torch.func.jacrev(f)(X_k)\n\nprint(H.shape)\n```\nOutput Warning:\n```\npython3.10/site-packages/torch/autograd/graph.py:769: UserWarning: Attempting to run cuBLAS, but there was no current CUDA context! Attempting to set the primary context... (Triggered internally at ../aten/src/ATen/cuda/CublasHandlePool.cpp:135.)\n return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass\n```"},{"role":"assistant","content":"PyTorch uses a separate thread in the backward pass. If no other CUDA operation was used before the cuBLAS call, the warning will be raised as we will set the primary context to the current one."}],"kind":"answer","thread_id":212255,"url":"https://discuss.pytorch.org/t/attempting-to-run-cublas-but-there-was-no-current-cuda-context/212255","created_at":"2024-10-29T09:47:29.203000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"RuntimeError: Trying to backward through the graph a second time at my case like BPTT\n\n```\nclass RNN(nn.Module):\n def __init__(self, input_size, hidden_size, output_size):\n super(RNN, self).__init__()\n\n self.hidden_size = hidden_size\n\n self.i2h = nn.Linear(input_size, hidden_size)\n self.h2h = nn.Linear(hidden_size, hidden_size)\n self.h2o = nn.Linear(hidden_size, output_size)\n self.hidden = torch.zeros(1, self.hidden_size)\n self.softmax = nn.LogSoftmax(dim=1)\n\n def forward(self, input):\n self.hidden = F.tanh(self.i2h(input) + self.h2h(self.hidden))\n output = self.h2o(self.hidden)\n output = self.softmax(output)\n return output\n\nrnn = RNN(n_letters, n_hidden, n_categories)\ntemp_layer = nn.Linear(n_categories*2, n_categories)\n\nfor iter in range(1, n_iters + 1):\n category, line, category_tensor, line_tensor = randomTrainingExample()\n rnn.zero_grad()\n outputs = []\n for i in range(0,4): # T = 4 for BPTT\n output = forward_step(line_tensor, i)\n outputs.append(output)\n \n result = torch.cat(outputs, dim=-1)\n result_logit = temp_layer(result)\n loss = criterion(result_logit, category_tensor)\n \n loss.backward()\n optimizer.step()\n```\nThis is a simple RNN example I created to reproduce an issue I encountered in another task, mimicking BPTT. The behavior may slightly differ from a real RNN because I defined `self.hidden` in the init function to recreate my problem. For simplicity, I omitted the dataloader part.\n\nThe issue is that when I run it, I encounter the following error:\n\n> 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.\n\nI suspect this might be because `self.hidden` is being overwritten inside the `forward` function. However, the code works fine for the first couple of iterations but throws the above error around the third iteration.\n\nAlso, I thought the computational graph gets re-initialized in every iteration, so I don’t understand why it’s trying to reference something again."},{"role":"assistant","content":"That's correct if no references are stored to the previous computation graph.\nHowever, in your example `self.hidden` appends to a computation graph in each forward pass and thus keeps it alive.\nYou would thus need to `.detach()` the tensor (or re-initialize `self.hidden`) after the backward is done."},{"role":"user","content":"Thanks for replying!\n\nI'm still confusing the reason...\n\nIn the following line inside the `forward` function:\n```\nself.hidden = F.tanh(self.i2h(input) + self.h2h(self.hidden))\n```\nIs `self.hidden` being appended to the computational graph at this line?\n\nAlso, the layers like `self.h2o`, `self.i2h`, and `self.h2h` are repeatedly used at each iteration.\nBut why aren’t they considered \"alive\" in the computational graph?"},{"role":"assistant","content":"Yes, since you are assigning the output to itself:\n```python\nself.hidden = differentiable_operations(self.hidden)\n```\n\nYes, but their result is not assigned to themselves (which also wouldn't make sense assuming these are layers, not state tensors such as `self.hidden`).\n\nTheir parameters are used in the computation graph."}],"kind":"answer","thread_id":212294,"url":"https://discuss.pytorch.org/t/runtimeerror-trying-to-backward-through-the-graph-a-second-time-at-my-case-like-bptt/212294","created_at":"2024-10-30T02:38:39.683000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"No errors before saving, but an error during testing\n\nWhen training my model, I didn't encounter any errors. However, after saving and loading the model, I encountered an error when testing it with the loaded model. mat1 and mat2 shapes cannot be multiplied (10x576 and 5760x12)"},{"role":"assistant","content":"Thank you, sir. I solved the problem. The error was because when testing with test data, I didn't provide the unsquace. Thank you for helping me with this\n\n```python\nwith torch.inference_mode():\n pred = model(data.unsqueeze(0))\npred\n\n```"}],"kind":"answer","thread_id":212388,"url":"https://discuss.pytorch.org/t/no-errors-before-saving-but-an-error-during-testing/212388","created_at":"2024-11-01T03:04:03.812000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[8],"answer_authors":["Mathews_Vinoy"]} | |
| {"messages":[{"role":"user","content":"No errors before saving, but an error during testing\n\nWhen training my model, I didn't encounter any errors. However, after saving and loading the model, I encountered an error when testing it with the loaded model. mat1 and mat2 shapes cannot be multiplied (10x576 and 5760x12)"},{"role":"assistant","content":"Could you post your model definition as well as the input shapes here, please?"}],"kind":"clarification","thread_id":212388,"url":"https://discuss.pytorch.org/t/no-errors-before-saving-but-an-error-during-testing/212388","created_at":"2024-11-01T03:04:03.812000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"ECC error for working GPU\n\nI have very strange error. I've worked on a server with two GPUs. I've installed python 3.10.11 and torch version for CUDA12.1. \n`nvcc --version` gives me:\n```\nnvcc: NVIDIA (R) Cuda compiler driver\nCopyright (c) 2005-2023 NVIDIA Corporation\nBuilt on Fri_Jan__6_16:45:21_PST_2023\nCuda compilation tools, release 12.0, V12.0.140\nBuild cuda_12.0.r12.0/compiler.32267302_0\n```\n\nHowever `nvidia-smi` gives: `NVIDIA-SMI 550.127.05 Driver Version: 550.127.05 CUDA Version: 12.4 `\n\nBut anyways cuda is avalialbe. I try to test on simple code. \n```\nimport os\nimport torch\n\nos.environ[\"CUDA_LAUNCH_BLOCKING\"] = \"1\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\nprint(\"CUDA available:\", torch.cuda.is_available())\nprint(\"PyTorch version:\", torch.__version__)\nprint(\"CUDA version (PyTorch):\", torch.version.cuda)\n\nif torch.cuda.is_available():\n device = torch.device(\"cuda\")\n torch.device \n\n total_memory = torch.cuda.get_device_properties(device).total_memory\n allocated_memory = torch.cuda.memory_allocated(device)\n reserved_memory = torch.cuda.memory_reserved(device)\n free_memory = total_memory - reserved_memory \n properties = torch.cuda.get_device_properties(device)\n print(f\"Device Name: {properties.name}\")\n\n print(f\"Total memory: {total_memory / 1024**3:.2f} GB\")\n print(f\"Allocated memory: {allocated_memory / 1024**3:.2f} GB\")\n print(f\"Reserved memory: {reserved_memory / 1024**3:.2f} GB\")\n print(f\"Free memory: {free_memory / 1024**3:.2f} GB\")\n\n a = torch.rand(2, 2, device=device)\n b = torch.rand(2, 2, device=device)\n\n result = a + b\n\n print(\"Tensor a:\\n\", a)\n print(\"Tensor b:\\n\", b)\n print(\"Result of a + b:\\n\", result)\n\nelse:\n print(\"CUDA is not available.\")\n```\nAnd i get as a result\n```\nCUDA available: True\nPyTorch version: 2.5.1+cu124\nCUDA version (PyTorch): 12.4\n\nDevice Name: NVIDIA H100 PCIe\nTotal memory: 79.10 GB\nAllocated memory: 0.00 GB\nReserved memory: 0.00 GB\nFree memory: 79.10 GB\nTraceback (most recent call last):\n File \"/home/mnlubov/test/test.py\", line 31, in <module>\n a = torch.rand(2, 2, device=device)\nRuntimeError: CUDA error: uncorrectable ECC error encountered\nCompile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.\n```\n\nI can't understand why there is such error: `CUDA error: uncorrectable ECC error encountered`\nI've checked for ECC errors and everything is fine. \n```\nFri Nov 1 15:17:30 2024\nDriver Version : 550.127.05\nCUDA Version : 12.4\n\nAttached GPUs : 2\nGPU 00000000:81:00.0\n ECC Mode\n Current : Enabled\n Pending : Enabled\n ECC Errors\n Volatile\n SRAM Correctable : 0\n SRAM Uncorrectable Parity : 0\n SRAM Uncorrectable SEC-DED : 0\n DRAM Correctable : 0\n DRAM Uncorrectable : 0\n Aggregate\n SRAM Correctable : 0\n SRAM Uncorrectable Parity : 0\n SRAM Uncorrectable SEC-DED : 0\n DRAM Correctable : 0\n DRAM Uncorrectable : 0\n SRAM Threshold Exceeded : No\n Aggregate Uncorrectable SRAM Sources\n SRAM L2 : 0\n SRAM SM : 0\n SRAM Microcontroller : 0\n SRAM PCIE : 0\n SRAM Other : 0\n```\nThe same is for the second GPU. So, it seems there is no problem with GPU itself. \nWhat is the reason and how to fix it?\nIS it due to incorrect torch version?"},{"role":"assistant","content":"PyTorch is not causing these issues and is only re-raising sticky errors reported to it, so you might want to check if any `Xid`s are detected in `dmesg` and also run any other CUDA example to see if it would also raise these errors."}],"kind":"answer","thread_id":212417,"url":"https://discuss.pytorch.org/t/ecc-error-for-working-gpu/212417","created_at":"2024-11-01T15:18:54.499000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Error while implementing BYOL Training Strategy\n\nHi, I am facing an issue with my code.\n\n```\nRuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [16, 64, 128]], which is output 0 of AddBackward0, is at version 6; expected version 5 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!\n```\n\nI am facing the error in scaler.scale(loss).backward()\n```\no1 = self.online_model(view1)\no2 = self.online_model(view2)\n\nwith torch.no_grad():\n t1 = self.target_model(view1)\n t2 = self.target_model(view2)\n\nloss = (self.calculate_loss(o1, t2) + self.calculate_loss(o2, t1)).mean()\nscaler.scale(loss).backward() \nscaler.step(optimizer)\nscaler.update()\n```"},{"role":"assistant","content":"Could you post a minimal and executable code snippet reproducing this issue, please?\nYour current code does not contain the model definition and also does not show any obvious issues."},{"role":"user","content":"I found the issue with my code, I was implementing a simple Transformer block like this\n```\nclass TransformerBlock(nn.Module):\n \"\"\"\n Transformer Block\n\n Args:\n dim (int): input dimension\n num_heads (int): number of attention heads\n mlp_ratio (float): ratio of mlp hidden dim to input dim\n qkv_bias (bool): if True, add bias to the qkv projection\n qk_scale (float): scale factor for the qk projection\n drop (float): dropout rate\n attn_drop (float): attention dropout rate\n drop_path (float): stochastic depth rate\n act_layer (nn.Module): activation layer\n norm_layer (nn.Module): normalization layer\n sr_ratio (int): spatial reduction ratio\n\n Returns:\n torch.Tensor: output tensor, shape (B, N, C), N=H*W\n \"\"\"\n\n def __init__(self, dim:int, num_heads:int, mlp_ratio:float=4.,\n qkv_bias:bool=False, qk_scale:float=None, drop:float=0., attn_drop:float=0.,\n drop_path:float=0., act_layer:nn.Module=nn.GELU, norm_layer:nn.Module=nn.LayerNorm, sr_ratio:int=1) -> None:\n super(TransformerBlock, self).__init__()\n self.norm1 = norm_layer(dim)\n self.attn = SelfAttention(dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,\n attn_drop=attn_drop, proj_drop=drop, sr_ratio=sr_ratio)\n self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()\n self.norm2 = norm_layer(dim)\n mlp_hidden_dim = int(dim * mlp_ratio)\n self.mlp = MLP(input_dim=dim, hidden_dim=mlp_hidden_dim, act_layer=act_layer, drop=drop)\n\n self.apply(self._init_weights)\n\n def _init_weights(self, m:nn.Module) -> None:\n \"\"\"\n Initialise weights of the layer m\n\n Args:\n m (nn.Module): model layer\n\n Returns:\n None\n \"\"\"\n\n if isinstance(m, nn.Linear):\n trunc_normal_(m.weight, std=.02)\n if isinstance(m, nn.Linear) and m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.LayerNorm):\n nn.init.constant_(m.bias, 0)\n nn.init.constant_(m.weight, 1.0)\n elif isinstance(m, nn.Conv2d):\n fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n fan_out //= m.groups\n m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))\n if m.bias is not None:\n m.bias.data.zero_()\n\n def forward(self, x:torch.Tensor, H:int, W:int) -> torch.Tensor:\n \"\"\"\n forward method\n\n Args:\n x (torch.Tensor): input tensor, shape (B, N, C), N=H*W\n H (int): height\n W (int): width\n \"\"\"\n\n x_ = self.drop_path(self.attn(self.norm1(x), H, W)) + x\n x_ = self.drop_path(self.mlp(self.norm2(x), H, W)) + x_\n\n return x\n```\n\ninitially, my forward method contained a inplace operation\n```\ndef forward(self, x:torch.Tensor, H:int, W:int) -> torch.Tensor:\n \"\"\"\n forward method\n\n Args:\n x (torch.Tensor): input tensor, shape (B, N, C), N=H*W\n H (int): height\n W (int): width\n \"\"\"\n\n x += self.drop_path(self.attn(self.norm1(x), H, W))\n x += self.drop_path(self.mlp(self.norm2(x), H, W))\n\n return x\n```\n\nI am still confused, as to why such inplace operation would cause this error."},{"role":"assistant","content":"If e.g. `self.norm1/2` need the original input tensor `x` for the gradient computation your code will manipulate `x` inplace and thus disallowing the right gradient computation raising the error."}],"kind":"answer","thread_id":212422,"url":"https://discuss.pytorch.org/t/error-while-implementing-byol-training-strategy/212422","created_at":"2024-11-01T18:13:24.323000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Error while implementing BYOL Training Strategy\n\nHi, I am facing an issue with my code.\n\n```\nRuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [16, 64, 128]], which is output 0 of AddBackward0, is at version 6; expected version 5 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!\n```\n\nI am facing the error in scaler.scale(loss).backward()\n```\no1 = self.online_model(view1)\no2 = self.online_model(view2)\n\nwith torch.no_grad():\n t1 = self.target_model(view1)\n t2 = self.target_model(view2)\n\nloss = (self.calculate_loss(o1, t2) + self.calculate_loss(o2, t1)).mean()\nscaler.scale(loss).backward() \nscaler.step(optimizer)\nscaler.update()\n```"},{"role":"assistant","content":"Could you post a minimal and executable code snippet reproducing this issue, please?\nYour current code does not contain the model definition and also does not show any obvious issues."}],"kind":"clarification","thread_id":212422,"url":"https://discuss.pytorch.org/t/error-while-implementing-byol-training-strategy/212422","created_at":"2024-11-01T18:13:24.323000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Pytorch Weighted Regression Loss Functions\n\nIs there an built-in weighted loss function for regression tasks? If there are third party weighted loss functions, please let me know. \n\nI am trying to use Weighted Mean Absolute Error for Unet for semantic segmentation. I need to assign weights so that my model ignores background and focuses on poorly predicted regions."},{"role":"assistant","content":"You can use `nn.L1Loss` with `reduction='none'` and add your weights directly to the computed loss before reducing it. \nAdding an internal weight for floating point inputs does not make sense as this loss function does not have any class knowledge (e.g. what \"background\" means for your use case)."},{"role":"user","content":"Thank you for your response. \n\nMay be, I can explain it better. I would like to have weighted loss such that if the target has a value of range 1 to 0. I would like to have lower weights for targets with value 1.0 (background) and increase the weights as the target value reduces from 1. \n\nI wrote a custom loss function for this. Please let me know if there are any other suggestions.\n\nclass WeightedMAELoss (nn.Module):\n\n def __init__(self, beta=1.0, reduction='mean'):\n super(WeightedMAELoss, self).__init__()\n self.beta = beta\n self.reduction = reduction\n\n def forward(self, inputs, targets):\n diff = torch.abs(inputs-targets)\n\n with torch.no_grad():\n weights = torch.exp(-self.beta * targets)\n weighted_diff = weights * diff\n\n if self.reduction == 'mean':\n return weighted_diff.mean()\n elif self.reduction == 'sum':\n return weighted_diff.sum()\n else:\n return weighted_diff"},{"role":"assistant","content":"You might want to normalize the loss e.g. by dividing by the `weights.sum()` as otherwise the target distribution (the frequency of 0s and 1s) would influence the loss scale."}],"kind":"answer","thread_id":212480,"url":"https://discuss.pytorch.org/t/pytorch-weighted-regression-loss-functions/212480","created_at":"2024-11-03T17:06:32.230000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Loading model from checkpoint results differ to loading model directly\n\nI am encountering issues where depending on how I load a model I obtain different results.\n\nI have built a small test example which I have attached below that illustrates my problem. I have compared three different methods of loading the model:\n\n1. loading the model directly from hugging face\n2. loading the model from a complete model checkpoint file\n3. loading the model from a checkpoint file of the model state dict only\n\nI tested the models on the same randomly generated input images.\n\nThe weights and state dicts of the models using the 3 methods described are identical. \nThe inference results generated by the 1st and the 3rd method are much more similar but still not the same. \n\nAnyone have any ideas? I am completely at a loss what could be the result of this issue and how I should properly save and load my checkpoints to e.g. resume a training.\n\n```\nfrom transformers import ViTMAEForPreTraining\nimport torch\nimport gc\nimport pytorch_lightning as pl\n\nimport numpy as np\ntorch.cuda.empty_cache()\n\n#define model \nclass TransformerModel(pl.LightningModule):\n def __init__(self):\n super().__init__()\n self.model = ViTMAEForPreTraining.from_pretrained(\"facebook/vit-mae-base\")\n self.model.config.mask_ratio = 0.75\n \n def forward(self, x):\n return self.model(x)\n\n def training_step(self, batch, batch_idx):\n imgs, labels = batch\n out = self(imgs)\n loss = out.loss\n self.log(\"train_loss\", loss)\n return loss\n \n def validation_step(self, batch, batch_idx):\n imgs, labels = batch\n out = self(imgs)\n loss = out.loss\n self.log(\"val_loss\", loss)\n return loss\n \n def configure_optimizers(self):\n optimizer = torch.optim.AdamW(self.parameters(), lr=0.001)\n return optimizer\n \n def unpatchify(self, x):\n p = self.model.vit.embeddings.patch_embeddings.patch_size[0]\n h = w = int(x.shape[1]**.5)\n \n assert h * w == x.shape[1]\n \n x = x.reshape(shape=(x.shape[0], h, w, p, p, 3))\n x = torch.einsum('nhwpqc->nchpwq', x)\n imgs = x.reshape(shape=(x.shape[0], 3, h * p, h * p))\n \n return imgs\n\n#load model\nmodel_1 = TransformerModel()\nmodel_1.eval()\n\n#save complete model as checkpoint\ntorch.save(model_1, \"vit_mae_from_hugging_face.pth\")\n\n#save statedict only\ntorch.save(model_1.state_dict(), \"vit_mae_from_hugging_face_statedict.pth\")\n\n#load model from checkpoint\nmodel_2 = torch.load(\"vit_mae_from_hugging_face.cpkt\")\nmodel_2.eval()\n\n#load state-dict only\nmodel_3 = TransformerModel()\nmodel_3.load_state_dict(torch.load(\"vit_mae_from_hugging_face_statedict.pth\"))\nmodel_3.eval()\n\n#initialize hook to get intermediate outputs\nlayer_outputs = {}\ndef get_intermediate_1(module, input, output):\n layer_outputs['encoder_layernorm_1'] = output\n\ndef get_intermediate_2(module, input, output):\n layer_outputs['encoder_layernorm_2'] = output\n\ndef get_intermediate_3(module, input, output):\n layer_outputs['encoder_layernorm_3'] = output\n\nmodel_1.model.vit.layernorm.register_forward_hook(get_intermediate_1)\nmodel_2.model.vit.layernorm.register_forward_hook(get_intermediate_2)\nmodel_3.model.vit.layernorm.register_forward_hook(get_intermediate_3)\n\n#create a seeded random input tensor\ntorch.manual_seed(42)\ntensor = torch.randn(8, 3, 224, 224)\n\n#pass images to the two models\nmodel_1(tensor)\nmodel_2(tensor)\nmodel_3(tensor)\n\noutputs_1 = torch.mean(layer_outputs['encoder_layernorm_1'], axis = 1).detach().numpy()\noutputs_2 = torch.mean(layer_outputs['encoder_layernorm_2'], axis = 1).detach().numpy()\noutputs_3 = torch.mean(layer_outputs['encoder_layernorm_3'], axis = 1).detach().numpy()\n\n#compare outputs\nprint(\"Output 1 vs Output2\")\nprint((outputs_1 == outputs_2).all())\nprint(\"Output 2 vs Output3\")\nprint((outputs_2 == outputs_3).all())\nprint(\"Output 1 vs Output3\")\nprint((outputs_1 == outputs_3).all())\n\n#compare model weights\nprint(((model_1.state_dict()['model.vit.embeddings.patch_embeddings.projection.weight']) == (model_2.state_dict()['model.vit.embeddings.patch_embeddings.projection.weight'])).all())\nprint(((model_1.state_dict()['model.vit.embeddings.patch_embeddings.projection.weight']) == (model_3.state_dict()['model.vit.embeddings.patch_embeddings.projection.weight'])).all())\nprint(((model_2.state_dict()['model.vit.embeddings.patch_embeddings.projection.weight']) == (model_3.state_dict()['model.vit.embeddings.patch_embeddings.projection.weight'])).all())\n\n#compare complete state_dicts\nfor key in model_1.state_dict():\n value = (model_1.state_dict()[key] == model_2.state_dict()[key]).all()\n if not value:\n print(value)\n\nfor key in model_1.state_dict():\n pvalue = (model_1.state_dict()[key] == model_3.state_dict()[key]).all()\n if not value:\n print(value)\n```\n\nThis returns:\n```\nOutput 1 vs Output2\nFalse\nOutput 2 vs Output3\nFalse\nOutput 1 vs Output3\nFalse\ntensor(True)\ntensor(True)\ntensor(True)\n```\nNumerically the outputs generated by approach 1 and approach 3 are much more similar than those generated by approach 2.\n\n[image]"},{"role":"assistant","content":"Thanks for your insights. We managed to find the source of the issue after a helpful tip from a colleague I shared the post with. \n\nThe VitMAE model we are using here randomly masks part of the image which it tries to reconstruct. The `mask_ratio` determines which fraction of the image is masked which was the same across models, but the actual parts of the image that are masked is random. So even on identical images for `mask_ratio != 0` the returned results are not the same. \n\nBy setting the mask_ratio to 0 (and thus removing any remaining randomness) we could recreate our results down to the 1e-8 range which is probably a result of calculation inaccuracies on the GPU resulting from optimisation algorithms. So at the end of the day it was a user error on our part. \n\nWhat we did notice and maybe you can provide some insights on is even if I set the mask ratio to 0 before saving the checkpoint when I loaded the model directly from the checkpoint using serialisation of the entire model the mask_ratio was back to 0.75 after loading which I manually had to set to 0 again.\n\nFor anyone interested here the code with the mask_ratios set that leads to reproducible results:\n\n```\nfrom transformers import ViTMAEForPreTraining\nimport torch\nimport gc\nimport pytorch_lightning as pl\n\nimport numpy as np\ntorch.cuda.empty_cache()\n\n#define model \nclass TransformerModel(pl.LightningModule):\n def __init__(self):\n super().__init__()\n self.model = ViTMAEForPreTraining.from_pretrained(\"facebook/vit-mae-base\")\n self.model.config.mask_ratio = 0.0\n \n def forward(self, x):\n return self.model(x)\n\n def training_step(self, batch, batch_idx):\n imgs, labels = batch\n out = self(imgs)\n loss = out.loss\n self.log(\"train_loss\", loss)\n return loss\n \n def validation_step(self, batch, batch_idx):\n imgs, labels = batch\n out = self(imgs)\n loss = out.loss\n self.log(\"val_loss\", loss)\n return loss\n \n def configure_optimizers(self):\n optimizer = torch.optim.AdamW(self.parameters(), lr=0.001)\n return optimizer\n \n def unpatchify(self, x):\n p = self.model.vit.embeddings.patch_embeddings.patch_size[0]\n h = w = int(x.shape[1]**.5)\n \n assert h * w == x.shape[1]\n \n x = x.reshape(shape=(x.shape[0], h, w, p, p, 3))\n x = torch.einsum('nhwpqc->nchpwq', x)\n imgs = x.reshape(shape=(x.shape[0], 3, h * p, h * p))\n \n return imgs\n\n#load model\nmodel_1 = TransformerModel()\nmodel_1.eval()\n\n#save complete model as checkpoint\ntorch.save(model_1, \"vit_mae_from_hugging_face.pth\")\n\n#save statedict only\ntorch.save(model_1.state_dict(), \"vit_mae_from_hugging_face_statedict.pth\")\n\n#load model from checkpoint\nmodel_2 = torch.load(\"vit_mae_from_hugging_face.cpkt\")\nprint(model_2.model.config.mask_ratio)\nmodel_2.model.config.mask_ratio = 0\nmodel_2.eval()\n\n#load state-dict only\nmodel_3 = TransformerModel()\nmodel_3.load_state_dict(torch.load(\"vit_mae_from_hugging_face_statedict.pth\"))\nmodel_3.eval()\n\n#initialize hook to get intermediate outputs\nlayer_outputs = {}\ndef get_intermediate_1(module, input, output):\n layer_outputs['encoder_layernorm_1'] = output\n\ndef get_intermediate_2(module, input, output):\n layer_outputs['encoder_layernorm_2'] = output\n\ndef get_intermediate_3(module, input, output):\n layer_outputs['encoder_layernorm_3'] = output\n\nmodel_1.model.vit.layernorm.register_forward_hook(get_intermediate_1)\nmodel_2.model.vit.layernorm.register_forward_hook(get_intermediate_2)\nmodel_3.model.vit.layernorm.register_forward_hook(get_intermediate_3)\n\n#create a seeded random input tensor\ntorch.manual_seed(42)\ntensor = torch.randn(8, 3, 224, 224)\n\n#pass images to the two models\nmodel_1(tensor)\nmodel_2(tensor)\nmodel_3(tensor)\n\noutputs_1 = torch.mean(layer_outputs['encoder_layernorm_1'], axis = 1).detach().numpy()\noutputs_2 = torch.mean(layer_outputs['encoder_layernorm_2'], axis = 1).detach().numpy()\noutputs_3 = torch.mean(layer_outputs['encoder_layernorm_3'], axis = 1).detach().numpy()\n\n#compare outputs\nprint(\"Output 1 vs Output2\")\nprint((outputs_1 == outputs_2).all())\nprint(\"Output 2 vs Output3\")\nprint((outputs_2 == outputs_3).all())\nprint(\"Output 1 vs Output3\")\nprint((outputs_1 == outputs_3).all())\n\n#compare model weights\nprint(((model_1.state_dict()['model.vit.embeddings.patch_embeddings.projection.weight']) == (model_2.state_dict()['model.vit.embeddings.patch_embeddings.projection.weight'])).all())\nprint(((model_1.state_dict()['model.vit.embeddings.patch_embeddings.projection.weight']) == (model_3.state_dict()['model.vit.embeddings.patch_embeddings.projection.weight'])).all())\nprint(((model_2.state_dict()['model.vit.embeddings.patch_embeddings.projection.weight']) == (model_3.state_dict()['model.vit.embeddings.patch_embeddings.projection.weight'])).all())\n\n#compare complete state_dicts\nfor key in model_1.state_dict():\n value = (model_1.state_dict()[key] == model_2.state_dict()[key]).all()\n if not value:\n print(value)\n\nfor key in model_1.state_dict():\n pvalue = (model_1.state_dict()[key] == model_3.state_dict()[key]).all()\n if not value:\n print(value)\n```\n\nWhich returns:\n```\n0.75\nOutput 1 vs Output2\nFalse\nOutput 2 vs Output3\nFalse\nOutput 1 vs Output3\nFalse\ntensor(True)\ntensor(True)\ntensor(True)\n```\n[image]"}],"kind":"answer","thread_id":212514,"url":"https://discuss.pytorch.org/t/loading-model-from-checkpoint-results-differ-to-loading-model-directly/212514","created_at":"2024-11-04T17:40:35.061000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["sophiamaedler"]} | |
| {"messages":[{"role":"user","content":"Pytorch GPU via conda not working\n\nI want to run pytorch on GPU (within conda) with the following settings but all attempts failed.\n\n* Ubuntu 24\n* GPU: RTX 4090\n* Driver Version: 550.120 (checked via nvidia-smi)\n* No system-wide cuda installation\n* pytorch install commands I tried:\nconda install pytorch torchvision torchaudio pytorch-cuda=12.4 -c pytorch -c nvidia\nconda install pytorch torchvision torchaudio pytorch-cuda=12.4 -c pytorch-nightly -c nvidia\n\nWhat would you recommend?"},{"role":"assistant","content":"Check if the right binary was installed via `print(torch.version.cuda)`. If it's showing `12.4`, the binary might have trouble communicating with the NVIDIA driver."},{"role":"user","content":"Thank you but this returns None.\nI further checked:\n\n* gcc (Ubuntu 13.2.0-23ubuntu4) 13.2.0\n* torch.__version__ is '2.4.1'\n* conda list:\ncuda-cudart 12.4.127 0 nvidia\ncuda-cupti 12.4.127 0 nvidia\ncuda-libraries 12.4.1 0 nvidia\ncuda-nvrtc 12.4.127 0 nvidia\ncuda-nvtx 12.4.127 0 nvidia\ncuda-opencl 12.6.77 0 nvidia\ncuda-runtime 12.4.1 0 nvidia\ncuda-version 12.6 3 nvidia\nwhere I guess the 12.6 version might be causing the issue?"},{"role":"assistant","content":"No, I don't think so as the install command works for me in a new and empty conda environment:\n```python\nconda install pytorch torchvision torchaudio pytorch-cuda=12.4 -c pytorch -c nvidia\n...\nThe following packages will be downloaded:\n\n package | build\n ---------------------------|-----------------\n blas-1.0 | mkl 6 KB\n brotli-python-1.0.9 | py310h6a678d5_8 356 KB\n certifi-2024.8.30 | py310h06a4308_0 162 KB\n cuda-cudart-12.4.127 | 0 198 KB nvidia\n cuda-cupti-12.4.127 | 0 16.4 MB nvidia\n cuda-libraries-12.4.1 | 0 2 KB nvidia\n cuda-nvrtc-12.4.127 | 0 21.0 MB nvidia\n cuda-nvtx-12.4.127 | 0 58 KB nvidia\n cuda-opencl-12.6.77 | 0 25 KB nvidia\n cuda-runtime-12.4.1 | 0 2 KB nvidia\n cuda-version-12.6 | 3 16 KB nvidia\n...\n pytorch-2.5.1 |py3.10_cuda12.4_cudnn9.1.0_0 1.46 GB pytorch\n pytorch-cuda-12.4 | hc786d27_7 7 KB pytorch\n pytorch-mutex-1.0 | cuda 3 KB pytorch\n...\n```\n```python\npython -c \"import torch; print(torch.__version__); print(torch.version.cuda); print(torch.cuda.is_available()); print(torch.randn(1).cuda())\"\n2.5.1 \n12.4 \nTrue \ntensor([0.3827], device='cuda:0') \n```\n\nHowever, you could also try to use the pip wheels if you are seeing issues with conda as conda binaries will be deprecated as mentioned [here](https://github.com/pytorch/pytorch/issues/138506)."}],"kind":"answer","thread_id":212586,"url":"https://discuss.pytorch.org/t/pytorch-gpu-via-conda-not-working/212586","created_at":"2024-11-06T04:00:56.989000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Does loss.item() affect loss.backward()?\n\nHello, just wanted to ask what is the correct order to call loss.item() and loss.backward(). I read a forum post saying that if you call item() after backward() execution is slower, however I also read that if you use .item() before backward() then the gradient does not flow. Can someone help me find a concrete answer for this?"},{"role":"assistant","content":"Most likely the order won't matter. \nCalling `item()` on a `CUDATensor` will synchronize your code and will thus potentially slow it down (e.g. if it wasn't synchronized before anyway). I wouldn't expect to see a large difference in speed if you synchronize the code before or after the `backward` call. \n\nCalling `loss.item()` does not have any effect on the `loss.backward()` call unless you chain them `loss.item().backward()` which will raise an error."}],"kind":"answer","thread_id":212601,"url":"https://discuss.pytorch.org/t/does-loss-item-affect-loss-backward/212601","created_at":"2024-11-06T07:44:08.135000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Cuda not available when running multi-gpu inference\n\nHi, I am running an inference script on a server with 7 NVIDIA GeForce GTX 1080 Ti. It's currently running on a single GPU, which works fine. However, I'd like to parallelize things (I am using huggingface accelerate for that, this might also be an issue with their tool...). When running my script with `accelerate launch --config_file [my_config_file] run.py` torch cannot find cuda anymore. I am in the same conda env that works fine for single GPU inference. The config file sets `CUDA_VISIBLE_DEVICES` which it does in my case to '[1,2,3,4]' (On GPU '0' I am running the above mentioned script). Same happens when specifically setting `CUDA_VISIBLE_DEVICES=1,2,3,4` before calling `accelerate [...]`.\nI can't seem to figure out why cuda is not available in this case.\n- Cuda driver version 11.8\n- nvcc -version prints `nvcc: NVIDIA (R) Cuda compiler driver\nCopyright (c) 2005-2017 NVIDIA Corporation\nBuilt on Fri_Nov__3_21:07:56_CDT_2017\nCuda compilation tools, release 9.1, V9.1.85`\n- torch.version.cuda is 11.8\n- pytorch version 2.0.0\n- dmesg does not have any entries regarding NVRM hinting at problems"},{"role":"assistant","content":"Could you describe your issue in more detail and what \"CUDA not available\" means in this context given you can use your GPU?"},{"role":"user","content":"After importing torch, torch.cuda.is_available() is false and then during the initialization of an accelerate.PartialState() which under the hood uses torch.nn.parallel.DistributedDataParallel if I'm not mistaken, torch raises an AttributeError 'torch.cpu has no attribute device_count'. Which I guess is due to the cpu being torch's fallback device when no gpus are available and then accelerate calling device_count (checked this during debugging) on that device."},{"role":"assistant","content":"I don't know if `accelerate` uses another PyTorch binary but you could double check it via printing `torch.__version__` and `torch.__path__` inside the standalone run (which is able to detect the GPU) and inside the script used by `accelerate`."}],"kind":"answer","thread_id":212604,"url":"https://discuss.pytorch.org/t/cuda-not-available-when-running-multi-gpu-inference/212604","created_at":"2024-11-06T09:40:57.712000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Cuda not available when running multi-gpu inference\n\nHi, I am running an inference script on a server with 7 NVIDIA GeForce GTX 1080 Ti. It's currently running on a single GPU, which works fine. However, I'd like to parallelize things (I am using huggingface accelerate for that, this might also be an issue with their tool...). When running my script with `accelerate launch --config_file [my_config_file] run.py` torch cannot find cuda anymore. I am in the same conda env that works fine for single GPU inference. The config file sets `CUDA_VISIBLE_DEVICES` which it does in my case to '[1,2,3,4]' (On GPU '0' I am running the above mentioned script). Same happens when specifically setting `CUDA_VISIBLE_DEVICES=1,2,3,4` before calling `accelerate [...]`.\nI can't seem to figure out why cuda is not available in this case.\n- Cuda driver version 11.8\n- nvcc -version prints `nvcc: NVIDIA (R) Cuda compiler driver\nCopyright (c) 2005-2017 NVIDIA Corporation\nBuilt on Fri_Nov__3_21:07:56_CDT_2017\nCuda compilation tools, release 9.1, V9.1.85`\n- torch.version.cuda is 11.8\n- pytorch version 2.0.0\n- dmesg does not have any entries regarding NVRM hinting at problems"},{"role":"assistant","content":"Could you describe your issue in more detail and what \"CUDA not available\" means in this context given you can use your GPU?"}],"kind":"clarification","thread_id":212604,"url":"https://discuss.pytorch.org/t/cuda-not-available-when-running-multi-gpu-inference/212604","created_at":"2024-11-06T09:40:57.712000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Will torchrun --nnodes=1 --nproc_per_node=2 utilize 2 gpu in my PC?\n\nHi, I have node with 2 gpu on it, assume that I have a following code : \n```python\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nimport torch.distributed as dist\nfrom torch.utils.data.distributed import DistributedSampler\n\ndist.init_process_group(\"nccl\")\n\nlocal_rank = int(os.environ[\"LOCAL_RANK\"])\nglobal_rank = int(os.environ[\"RANK\"])\n\nBATCH_SIZE = 256 // int(os.environ[\"WORLD_SIZE\"])\nEPOCHS = 5\nWORKERS = 48\nIMG_DIMS = (336, 336)\nCLASSES = 10\n\nMODEL_NAME = 'resnet50d'\n\ntransform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Resize(IMG_DIMS),\n])\n\ndata = torchvision.datasets.CIFAR10('./',\n train=True,\n download=True,\n transform=transform)\nsampler = DistributedSampler(data)\ndata_loader = torch.utils.data.DataLoader(data,\n batch_size=BATCH_SIZE,\n shuffle=False,\n sampler=sampler,\n num_workers=WORKERS)\n\ntorch.cuda.set_device(local_rank)\ntorch.cuda.empty_cache()\nmodel = timm.create_model(MODEL_NAME, pretrained=True, num_classes=CLASSES)\n\nmodel = model.to('cuda:' + str(local_rank))\nmodel = DDP(model, device_ids=[local_rank])\n\nloss_fn = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.01)\n\nstart = time.perf_counter()\nfor epoch in range(EPOCHS):\n epoch_start_time = time.perf_counter()\n\n model.train()\n for batch in tqdm(data_loader, total=len(data_loader)):\n features, labels = batch[0].to(local_rank), batch[1].to(local_rank)\n\n optimizer.zero_grad()\n\n preds = model(features)\n loss = loss_fn(preds, labels)\n\n loss.backward()\n optimizer.step()\n\n epoch_end_time = time.perf_counter()\n if global_rank == 0:\n print(f\"Epoch {epoch+1} Time\", epoch_end_time - epoch_start_time)\nend = time.perf_counter()\nif global_rank == 0:\n print(\"Training Took\", end - start)\n```\n\nTo execute, I run ```torchrun --nnodes=1 --nproc_per_node=2```, how can we ensure that each gpu will run exactly one process but not one gpu run concurrently two process. Does pytorch automatically do it?"},{"role":"assistant","content":"The GPU won't run a process but processes can use GPUs.\nThe standard approach for DDP is to use a single GPU per process, but there are other use cases where multiple GPUs are used in a single process (e.g. think about naive pipeline parallel approaches).\nYou could try to make a single GPU visible in the process via `CUDA_VISIBLE_DEVICES` disallowing this process to see any other GPU."}],"kind":"answer","thread_id":212617,"url":"https://discuss.pytorch.org/t/will-torchrun-nnodes-1-nproc-per-node-2-utilize-2-gpu-in-my-pc/212617","created_at":"2024-11-06T15:31:50.474000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Runtime error: \"ImportError: /usr/lib64/libtorch_cuda.so: undefined symbol: cudnnSetDropoutDescriptor\"\n\nWhen I `import torch`, I get:\n```shell\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib64/python3.11/site-packages/torch/__init__.py\", line 367, in <module>\n from torch._C import * # noqa: F403\n ^^^^^^^^^^^^^^^^^^^^^^\nImportError: /usr/lib64/libtorch_cuda.so: undefined symbol: cudnnSetDropoutDescriptor\n```\n<sup>This is a bit similar to [#119072](https://github.com/pytorch/pytorch/issues/119072); cf. [#139967](https://github.com/pytorch/pytorch/issues/139967)</sup>\n\n### Versions\n\n<details><summary>python collect_env.py</summary>\n<p>\n\n```\nCollecting environment information...\nPyTorch version: N/A\nIs debug build: N/A\nCUDA used to build PyTorch: N/A\nROCM used to build PyTorch: N/A\n\nOS: Slackware Linux (x86_64)\nGCC version: (GCC) 14.2.0\nClang version: 19.1.3\nCMake version: version 3.30.5\nLibc version: glibc-2.40\n\nPython version: 3.11.10 (main, Sep 8 2024, 13:14:52) [GCC 14.2.0] (64-bit runtime)\nPython platform: Linux-6.11.6-x86_64-AMD_Ryzen_Threadripper_2990WX_32-Core_Processor-with-glibc2.40\nIs CUDA available: N/A\nCUDA runtime version: 12.6.77\nCUDA_MODULE_LOADING set to: N/A\nGPU models and configuration: GPU 0: Quadro RTX 4000\nNvidia driver version: 560.35.03\ncuDNN version: /usr/share/cuda/lib64/libcudnn.so.9.5.1\nHIP runtime version: N/A\nMIOpen runtime version: N/A\nIs XNNPACK available: N/A\n\nCPU:\nArchitecture: x86_64\nCPU op-mode(s): 32-bit, 64-bit\nAddress sizes: 43 bits physical, 48 bits virtual\nByte Order: Little Endian\nCPU(s): 64\nOn-line CPU(s) list: 0-63\nVendor ID: AuthenticAMD\nModel name: AMD Ryzen Threadripper 2990WX 32-Core Processor\nCPU family: 23\nModel: 8\nThread(s) per core: 2\nCore(s) per socket: 32\nSocket(s): 1\nStepping: 2\nFrequency boost: enabled\nCPU(s) scaling MHz: 73%\nCPU max MHz: 3000.0000\nCPU min MHz: 2200.0000\nBogoMIPS: 5988.12\nFlags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid amd_dcm aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb hw_pstate ssbd ibpb vmmcall fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap clflushopt sha_ni xsaveopt xsavec xgetbv1 clzero irperf xsaveerptr arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif overflow_recov succor smca sev sev_es\nVirtualization: AMD-V\nL1d cache: 1 MiB (32 instances)\nL1i cache: 2 MiB (32 instances)\nL2 cache: 16 MiB (32 instances)\nL3 cache: 64 MiB (8 instances)\nNUMA node(s): 4\nNUMA node0 CPU(s): 0-7,32-39\nNUMA node1 CPU(s): 16-23,48-55\nNUMA node2 CPU(s): 8-15,40-47\nNUMA node3 CPU(s): 24-31,56-63\nVulnerability Gather data sampling: Not affected\nVulnerability Itlb multihit: Not affected\nVulnerability L1tf: Not affected\nVulnerability Mds: Not affected\nVulnerability Meltdown: Not affected\nVulnerability Mmio stale data: Not affected\nVulnerability Reg file data sampling: Not affected\nVulnerability Retbleed: Mitigation; untrained return thunk; SMT vulnerable\nVulnerability Spec rstack overflow: Mitigation; Safe RET\nVulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl\nVulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization\nVulnerability Spectre v2: Mitigation; Retpolines; IBPB conditional; STIBP disabled; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected\nVulnerability Srbds: Not affected\nVulnerability Tsx async abort: Not affected\n\nVersions of relevant libraries:\n[pip3] flake8==7.0.0\n[pip3] numpy==1.26.3\n[pip3] torch==2.5.0a0+gitunknown\n[conda] Could not collect\n```\n\n</p>\n</details>"},{"role":"assistant","content":"Yes, this was the issue! I put cuDNN within `/opt/cuda-12.6/`, and `ldd` now shows that `/usr/lib64/libtorch_cuda.so` links to\n```\nlibcudnn.so.9 => /opt/cuda-12.6/lib64/libcudnn.so.9 (0x00007f9b89800000)\n```\nSo, the CMake setup doesn't seem to work with cuDNN in non-standard directories."}],"kind":"answer","thread_id":212671,"url":"https://discuss.pytorch.org/t/runtime-error-importerror-usr-lib64-libtorch-cuda-so-undefined-symbol-cudnnsetdropoutdescriptor/212671","created_at":"2024-11-07T23:33:42.975000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[9],"answer_authors":["Geremia"]} | |
| {"messages":[{"role":"user","content":"Can I split my input in multiple embeddings? How would pytorch compute gradients?\n\nContext: Learning pytorch, I'm trying to predict the next character given the past 1 character (Shakespeare input). ; I'm aware that there are smarter ways to predict things but this is a good toy example to learn the ins and outs of pytorch.\n\nAt first, there is just 1 embedding layer (number of chars as input, number of chars as output) and a loss function. Training works: the loss function decreases with epochs.\n\n```\ndef __init__(self):\n # vocab_size = len(set(chars in shakespear))) = 65\n self.embed = nn.Embedding(vocab_size, vocab_size)\n\ndef forward(self, x):\n return self.embedding(x)\n```\n\nNow I would like to predict the next character based on the past 2 chars.\nSo my input is made of a tensor with 2 values. I aggrzgate the embeddings into a larger tensor and pass that into a prediction layer (linear).\nI do like so:\n\n```\ndef __init__(self):\n # 10 is totally \"random\" \n self.embed = nn.Embedding(vocab_size, 10)\n self.linear = nn.Linear(2 * 10, vocab_size)\n\ndef forward(self, x):\n e1 = self.embedding(x[0])\n e2 = self.embedding(x[1])\n e = torch.cat([e1, e2], dim=1)\n out = self.linear(e)\n```\n\nNow my question is:\ngiven that I'm not \"chaining\" layers properly (e.g with nn.Sequential), and that I'm \"cutting\" my input (`x[0], x[1]`) and reuniting it with `cat`, will gradients be computed correctly?\nI've read about Autograd but it's unclear how it infers the graph and if \"everything\" is accepted.\nThanks!"},{"role":"assistant","content":"Yes, since indexing and `torch.cat` are differentiable operations."}],"kind":"answer","thread_id":212676,"url":"https://discuss.pytorch.org/t/can-i-split-my-input-in-multiple-embeddings-how-would-pytorch-compute-gradients/212676","created_at":"2024-11-08T02:24:12.658000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Training starting again in sampling code\n\n**Training code**\n``import os\nimport torch\nfrom Prepro import Data_orig \nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom sklearn.model_selection import train_test_split\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(\"Using device:\", device)\n\nclass RNNModel(nn.Module):\n def __init__(self, vocab_size, n_embd, n_hidden1, n_hidden2, block_size):\n super(RNNModel, self).__init__()\n self.embedding = nn.Embedding(vocab_size, n_embd)\n self.rnn = nn.RNN(input_size=n_embd, hidden_size=n_hidden1, num_layers=2, batch_first=True, nonlinearity='tanh')\n self.fc1 = nn.Linear(n_hidden1 * block_size, n_hidden2)\n self.fc2 = nn.Linear(n_hidden2, vocab_size)\n self._init_weights()\n\n def _init_weights(self):\n nn.init.normal_(self.embedding.weight, mean=0, std=0.1)\n nn.init.xavier_uniform_(self.fc1.weight)\n nn.init.xavier_uniform_(self.fc2.weight)\n\n def forward(self, x):\n x = self.embedding(x) # (batch_size, block_size, n_embd)\n x, _ = self.rnn(x) # (batch_size, block_size, n_hidden1)\n x = x.reshape(x.size(0), -1) # (batch_size, n_hidden1 * block_size)\n x = F.tanh(self.fc1(x)) # (batch_size, n_hidden2)\n x = self.fc2(x) # (batch_size, vocab_size)\n return x\n\n# Model parameters\nn_embd = 10\nn_hidden1 = 500\nn_hidden2 = 200\nblock_size = 3\ng = torch.Generator().manual_seed(2147483647)\n\n# Load the dataset\ndataset = Data_orig()\nX_train, X_test, y_train, y_test = train_test_split(dataset.X, dataset.Y,test_size=0.1, random_state=42)\n\n# Initialize the model\nmodel = RNNModel(vocab_size=dataset.vocab_size, n_embd=n_embd, n_hidden1=n_hidden1, n_hidden2=n_hidden2, block_size=block_size).to(device)\n\n# Define optimizer, loss function, and scheduler\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)\ncriterion = nn.CrossEntropyLoss()\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10000, gamma=0.5)\n\n# Create a directory to save checkpoints\ncheckpoint_dir = \"checkpoints\"\nos.makedirs(checkpoint_dir, exist_ok=True)\n\n# Training loop with checkpoint saving\nmax_steps = 100000\nbatch_size = 50\ncheckpoint_interval = 10000 # Save every 10,000 steps\n\nfor i in range(max_steps):\n # Mini-batch sampling\n ix = torch.randint(0, X_train.shape[0], (batch_size,))\n x_batch = X_train[ix].to(device)\n y_batch = y_train[ix].to(device)\n\n # Forward pass\n optimizer.zero_grad()\n outputs = model(x_batch)\n loss = criterion(outputs, y_batch)\n\n # Backward pass and optimization\n loss.backward()\n optimizer.step()\n scheduler.step()\n\n # Track stats and print progress\n if i % checkpoint_interval == 0:\n print(f'Step {i}/{max_steps}: Loss = {loss.item():.4f}, Learning Rate = {scheduler.get_last_lr()[0]:.6f}')\n \n # Save checkpoint\n if i % checkpoint_interval == 0 and i > 0:\n checkpoint_path = os.path.join(checkpoint_dir, f'model_step_{i}.pth')\n torch.save({\n 'step': i,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict(),\n 'loss': loss.item(),\n }, checkpoint_path)\n print(f\"Checkpoint saved at step {i} to {checkpoint_path}\")\n\n# Final save at the end of training\nfinal_checkpoint_path = os.path.join(checkpoint_dir, 'model_final.pth')\ntorch.save({\n 'step': max_steps,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict(),\n 'loss': loss.item(),\n}, final_checkpoint_path)\nprint(f\"Final model saved to {final_checkpoint_path}\")``\n\n**Samplng code**\n``import torch\nfrom Prepro import Data_orig\nfrom Rnn_generator import RNNModel\n\ndef sample_and_infer(data, checkpoint_path, device, start_str, num_samples, block_size):\n \"\"\"\n Samples data and performs inference using a pre-trained model.\n \n Parameters:\n data (Data_orig): Preprocessed dataset.\n checkpoint_path (str): Path to the model checkpoint.\n device (torch.device): Device to use for the computation.\n start_str (str): Starting string for the text generation.\n num_samples (int): Number of characters to generate.\n block_size (int): Size of the input sequence.\n \n Returns:\n str: Generated text.\n \"\"\"\n # Load pre-trained model\n model = RNNModel(vocab_size=data.vocab_size, n_embd=10, n_hidden1=500, n_hidden2=200, block_size=block_size).to(device)\n checkpoint = torch.load(checkpoint_path, map_location=device,weights_only=True)\n model.load_state_dict(checkpoint['model_state_dict'])\n model.to(device)\n model.eval() # Set the model to evaluation mode\n\n # Convert starting string to tensor\n input_indices = torch.tensor([data.stoi[ch] for ch in start_str], device=device).unsqueeze(0)\n\n # Generate text\n generated = start_str\n for _ in range(num_samples):\n with torch.no_grad():\n emb = model.embedding(input_indices)\n rnn_out, _ = model.rnn(emb)\n rnn_out = rnn_out.reshape(rnn_out.size(0), -1)\n logits = model.fc2(torch.tanh(model.fc1(rnn_out)))\n probs = torch.softmax(logits, dim=-1)\n next_index = torch.multinomial(probs, num_samples=1).item()\n\n generated += data.itos[next_index]\n input_indices = torch.cat((input_indices, torch.tensor([[next_index]], device=device)), dim=1)\n input_indices = input_indices[:, -block_size:]\n\n return generated\n\n# Usage example\ndataset = Data_orig()\ncheckpoint_path = r\"C:\\Users\\Rick\\Name_generator\\checkpoints\\model_step_90000.pth\"\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nstart_str = \"a\"\nnum_samples = 10\nblock_size = 3\n\ngenerated_text = sample_and_infer(dataset, checkpoint_path, device, start_str, num_samples, block_size)\nprint(\"Generated Text:\")\nprint(generated_text)``\n\nNow when i execute the sampling code instead of loading the pretrained weights it again starts the training from beginning and saves the checkpoints."},{"role":"assistant","content":"Your code is unfortunately not properly formatted, but I assume you are using separate files for the training and sampling.\nIt then seems that running `python sampling.py` is again training the model instead of executing the `sample_and_infer` function as you would expect?\n\nIf that's the case, use `if __name__==\"__main__\"` guards in your scripts guarding the actual function calls, e.g.:\n```python\n# train.py\n\ndef MyModel(...):\n ...\n\ndef train(...):\n ...\n\nif __name__==\"__main__\":\n train()\n```\n```python\n# sampling.py\n\nfrom Rnn_generator import RNNModel # because of the guard this will not execute any functions called in the __main__ block\n...\n\ndef sample_and_infer(...):\n ...\n\nif __name__==\"__main__\":\n sample_and_infer()\n```\nWithout these guards the `import` statement will execute all global function calls and could thus start your training again."}],"kind":"answer","thread_id":212724,"url":"https://discuss.pytorch.org/t/training-starting-again-in-sampling-code/212724","created_at":"2024-11-09T04:13:37.209000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Where can I get all the `operators` of torch?\n\nHi, guys. \nI want to know how to collect all the `operators` of torch (`torch.nn.Conv2d`, `torch.clamp`, etc.)\n\nNOT include other APIs like `torch.utils.model_zoo.load_url`\n\nThx in advance\n\nI mean where can I get all these ops below\n[image]"},{"role":"assistant","content":"@Chillee created this figure in [this post](https://dev-discuss.pytorch.org/t/where-do-the-2000-pytorch-operators-come-from-more-than-you-wanted-to-know/373), but I'm unsure if the scripts to create the data are available."}],"kind":"answer","thread_id":212833,"url":"https://discuss.pytorch.org/t/where-can-i-get-all-the-operators-of-torch/212833","created_at":"2024-11-12T03:29:43.397000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"How to minimize the gaps between kernels on GPU?\n\nI'm currently training multiple small models across several CUDA streams to achieve parallelism with Libtorch. However, each kernel execution is very short (lasting only a few microseconds) and scattered across the timeline, which means they rarely overlap or parallelize effectively. I've attached a screenshot showing how dispersed the kernel executions are.\n\nI'm wondering if it is due to the overhead of launching each kernel? And if so, is there any way to minimize the gaps between these kernels to improve parallelism? Any suggestions would be appreciated!\n\n[image]"},{"role":"assistant","content":"If slow kernel launches are the cause, check whether you can use CUDA graphs, either directly or via `torch.compile`. `torch.compile` doesn't appear to be exposed as a pure C++ API, so with libtorch you could try `torch.export` on your model instead."}],"kind":"answer","thread_id":212841,"url":"https://discuss.pytorch.org/t/how-to-minimize-the-gaps-between-kernels-on-gpu/212841","created_at":"2024-11-12T04:57:40.160000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Compile the PyTorch from source code by using Dockerfile, I got a fishy error. It seems to be related to the ld linker\n\nWhen I tried to compile the PyTorch from source code using a Dockerfile, I got a fishy error. The error seems to be related to the ld linker.\n\n### Error logs\n\n#0 3395.3 [5555/5977] Linking CXX executable bin/cuda_apply_test\n#0 3395.3 FAILED: bin/cuda_apply_test\n#0 3395.3 : && /usr/bin/c++ -Wno-deprecated -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -fopenmp -DNDEBUG -DUSE_KINETO -DUSE_FBGEMM -DUSE_QNNPACK -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -O2 -fPIC -Wno-narrowing -Wall -Wextra -Werror=return-type -Wno-missing-field-initializers -Wno-type-limits -Wno-array-bounds -Wno-unknown-pragmas -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wno-unused-function -Wno-unused-result -Wno-unused-local-typedefs -Wno-strict-overflow -Wno-strict-aliasing -Wno-error=deprecated-declarations -Wno-stringop-overflow -Wno-psabi -Wno-error=pedantic -Wno-error=redundant-decls -Wno-error=old-style-cast -fdiagnostics-color=always -faligned-new -Wno-unused-but-set-variable -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-stringop-overflow -DHAVE_AVX_CPU_DEFINITION -DHAVE_AVX2_CPU_DEFINITION -O3 -DNDEBUG -DNDEBUG -rdynamic caffe2/CMakeFiles/cuda_apply_test.dir/__/aten/src/ATen/test/cuda_apply_test.cpp.o -o bin/cuda_apply_test -Wl,-rpath,/usr/local/cuda/lib64:/opt/conda/envs/pytorch/lib:/pytorch/build/lib: /usr/local/cuda/lib64/libcudart.so lib/libgtest_main.a -Wl,--no-as-needed,\"/pytorch/build/lib/libtorch.so\" -Wl,--as-needed -Wl,--no-as-needed,\"/pytorch/build/lib/libtorch_cpu.so\" -Wl,--as-needed lib/libprotobuf.a /opt/conda/envs/pytorch/lib/libmkl_intel_lp64.so /opt/conda/envs/pytorch/lib/libmkl_gnu_thread.so /opt/conda/envs/pytorch/lib/libmkl_core.so -fopenmp -lpthread -lm /usr/lib/x86_64-linux-gnu/libdl.so lib/libdnnl.a -Wl,--no-as-needed,\"/pytorch/build/lib/libtorch_cuda.so\" -Wl,--as-needed lib/libc10_cuda.so lib/libc10.so /usr/local/cuda/lib64/libnvToolsExt.so /usr/local/cuda/lib64/libcufft_static_nocallback.a /usr/local/cuda/lib64/libcurand_static.a /usr/local/cuda/lib64/libculibos.a /usr/local/cuda/lib64/libcublas_static.a /usr/local/cuda/lib64/libcublasLt_static.a /usr/local/cuda/lib64/libcudart_static.a -lrt -ldl lib/libgtest.a -pthread && :\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasHgemmBatched' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasCgetriBatched'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasCgemm_v2' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasCgetrfBatched'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasDdot_v2' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasDgetrfBatched'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasGetPointerMode_v2' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasDgemmStridedBatched'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasDscal_v2' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasDgetriBatched'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasZgemm_v2' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasGemmEx'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasDestroy_v2' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasCgemv_v2'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasCdotu_v2' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasSaxpy_v2'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasGemmBatchedEx' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasGemmStridedBatchedEx'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasDgemm_v2' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasSgeam'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasHgemm' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasCreate_v2'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasDgeam' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasSetStream_v2'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasSetMathMode' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasSetPointerMode_v2'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasSgemmStridedBatched' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasDotEx'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasZgemv_v2' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasScalEx'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasZgetrfBatched' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasCdotc_v2'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasZdotc_v2' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasZgetriBatched'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasSgemv_v2' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasSgetrfBatched'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasSdot_v2' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasSgetriBatched'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasSgemmEx' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasSgemm_v2'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasDgemv_v2' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasHgemmStridedBatched'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasCgemmStridedBatched' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasSscal_v2'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasSgemmBatched' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasAxpyEx'\n#0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasZdotu_v2' #0 3395.3 /pytorch/build/lib/libtorch_cuda.so: undefined reference to `cublasZgemmStridedBatched'\n#0 3395.3 collect2: error: ld returned 1 exit status\n#0 3395.3 [5556/5977] Linking CXX executable bin/cuda_stream_test\n#0 3395.3 FAILED: bin/cuda_stream_test\n\n### Minified repro\n\nThis is my dockerfile:\n\nFROM nvcr.io/nvidia/cuda:10.2-cudnn8-devel-ubuntu18.04\n\nENV LANG=C.UTF-8 LC_ALL=C.UTF-8\nENV PATH /opt/conda/bin:$PATH\nENV PYTORCH_BUILD_VERSION=1.8.1+cu102\nENV PYTORCH_BUILD_NUMBER=1\n\nRUN apt-get update && apt-get install -y --no-install-recommends\nbuild-essential\ncmake\ngit\ncurl\nca-certificates\nlibjpeg-dev\nlibpng-dev\n&& rm -rf /var/lib/apt/lists/*\n\nRUN curl -o ~/miniconda.sh -O https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh &&\nchmod +x ~/miniconda.sh &&\n~/miniconda.sh -b -p /opt/conda &&\nrm ~/miniconda.sh &&\n/opt/conda/bin/conda clean -ya\n\nRUN conda create -n pytorch python=3.9.20 && conda clean -ya\nENV CONDA_DEFAULT_ENV=pytorch\nENV PATH /opt/conda/envs/pytorch/bin:$PATH\n\nRUN echo \"source activate pytorch\" > ~/.bashrc\nENV BASH_ENV ~/.bashrc\nENV ENV ~/.bashrc\n\nRUN conda install -y numpy=1.23 ninja pyyaml mkl mkl-include setuptools cmake cffi typing_extensions future six requests dataclasses\n\nCOPY pytorch-v1.8.1.tar.gz /pytorch-v1.8.1.tar.gz\nWORKDIR /\nRUN tar xvzf pytorch-v1.8.1.tar.gz\n\nWORKDIR /pytorch\nRUN git submodule sync && git submodule update --init --recursive\n\nENV TORCH_CUDA_ARCH_LIST=\"6.0;6.1;7.0;7.5\"\nENV USE_CUDA=1\nENV USE_CUDNN=1\nENV CMAKE_PREFIX_PATH=\"$(dirname $(which conda))/../\"\nENV USE_STATIC_CUDA=ON\n\nRUN ln -s /usr/lib/x86_64-linux-gnu/libcublasLt_static.a /usr/local/cuda/lib64/libcublasLt_static.a && ln -s /usr/lib/x86_64-linux-gnu/libcublasLt_static.a /usr/local/cuda-10.2/lib64/libcublas_static.a\nRUN python setup.py bdist_wheel\n\n### Versions\n\nthis is the host ENV:\n\nOS: CentOS Linux release 7.7.1908 (Core) (x86_64)\nGCC version: (Anaconda gcc) 11.2.0\nClang version: Could not collect\nCMake version: Could not collect\nLibc version: glibc-2.17\n\nPython version: 3.9.20 (main, Oct 3 2024, 07:27:41) [GCC 11.2.0] (64-bit runtime)\nPython platform: Linux-3.10.0-1062.12.1.el7.x86_64-x86_64-with-glibc2.17\nIs CUDA available: N/A\nCUDA runtime version: 10.2.89\nCUDA_MODULE_LOADING set to: N/A\nGPU models and configuration:\nGPU 0: Tesla V100S-PCIE-32GB\nGPU 1: Tesla V100S-PCIE-32GB"},{"role":"assistant","content":"I have found the solution to this problem!\n\nThe reason this issue occurs is that the NVIDIA image does not contain `libcublasLt_static.a` and `libcublas_static.a`.\n\nThe solution is to mount the corresponding files from the host to the `/usr/local/cuda/include/` path within the Docker container."}],"kind":"answer","thread_id":212866,"url":"https://discuss.pytorch.org/t/compile-the-pytorch-from-source-code-by-using-dockerfile-i-got-a-fishy-error-it-seems-to-be-related-to-the-ld-linker/212866","created_at":"2024-11-12T13:21:13.716000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[6],"answer_authors":["shysuen001"]} | |
| {"messages":[{"role":"user","content":"Tracing a model with control flow in forward operation\n\nI am tracing a model to export it to c++ via the command: \n\ntorch.jit.trace(model.eval(), example_inp).\n\nDoes the tracing done as above still work if I include in the forward pass of the model something like the following code snippet? \n\ndef forward(self,x):\n if self.eval:\n return x + 5\n else:\n return x\n\nOr I have to go through annotation to export the model even with this minimal control flow?"},{"role":"assistant","content":"`torch.jit.trace` will not record any control-flow as described in the [docs](https://pytorch.org/docs/stable/generated/torch.jit.trace.html).\nYour condition in your posted code is wrong since you are comparing against a function:\n```python\nmodel.eval\n<bound method Module.eval of MyModel()>\n```\nwhich will always return true.\nUse `self.training` instead as this attribute will be changed according to `model.train()/.eval()`.\nAfter this fix, the traced model will stick to the recorded code path."},{"role":"user","content":"Thanks a lot for the correction, I am not sure I got the last part of your response though. Using the following code snippet is the recorded code path going to be the one in the else part of the forward?\n\nDef forward(self,x):\n If self.training:\n Return x\n Else:\n Return x+ 5\n\nTorch.jit.trace(model.eval(), example_inp)"},{"role":"assistant","content":"The traced model would take the `else` path even if you want to switch back to training mode:\n```python\nclass MyModel(nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self,x):\n if self.training:\n return x\n else:\n return x + 5\n\nx = torch.ones(10)\nmodel = MyModel()\n\nout = model(x)\nprint(out)\n# tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])\n\nmodel.eval()\nout = model(x)\nprint(out)\n# tensor([6., 6., 6., 6., 6., 6., 6., 6., 6., 6.])\n\n# reset\nmodel.train()\nout = model(x)\nprint(out)\n# tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])\n\nmodel_traced = torch.jit.trace(model.eval(), x)\n\nprint(model_traced(x))\n# tensor([6., 6., 6., 6., 6., 6., 6., 6., 6., 6.])\n\n# does not change the behavior\nmodel_traced.train()\nprint(model_traced(x))\n# tensor([6., 6., 6., 6., 6., 6., 6., 6., 6., 6.])\n```"}],"kind":"answer","thread_id":212884,"url":"https://discuss.pytorch.org/t/tracing-a-model-with-control-flow-in-forward-operation/212884","created_at":"2024-11-12T15:34:02.246000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Inconsistencies between PyTorch and NumPy when performing 32-bit floating-point sums\n\nPerforming the same 32-bit floating-point sums in PyTorch and NumPy gives me noticeably different results in some cases (both yield the same results in 64-bit). The difference in results between 64-bit and 32-bit is expected, as are differences between some of the other sums, but the difference between `torch.sum(xs_f_32 * nscores_32)` and the manual for loop feels more surprising: presumably it's to do with the way the reduction is done internally? Is the inconsistency expected (as in, \"we explicitly don't guarantee that they'll be the same\"), or should they be producing the same result?\n\n```python\nimport numpy as np\nimport torch\n\ndef numpy_example() -> None:\n xs_f = np.array([567.5, 568.5, 567.5, 568.5, 567.5, 568.5])\n scores = np.array([73.5, 73.5, 100.5, 98.5, 41.5, 37.5])\n nscores = scores / np.sum(scores)\n\n print(np.sum(xs_f * scores) / np.sum(scores)) # 567.9929411764706\n print(np.sum(xs_f * nscores)) # 567.9929411764705\n print(xs_f.T @ nscores) # 567.9929411764706\n\n xs_f_32 = xs_f.astype(np.float32)\n scores_32 = scores.astype(np.float32)\n nscores_32 = nscores.astype(np.float32)\n\n print((np.sum(xs_f_32 * scores_32) / np.sum(scores_32)).item()) # 567.992919921875\n print(np.sum(xs_f_32 * nscores_32).item()) # 567.992919921875\n print((xs_f_32.T @ nscores_32).item()) # 567.992919921875\n\ndef torch_example() -> None:\n xs_f = torch.tensor([567.5, 568.5, 567.5, 568.5, 567.5, 568.5], dtype=torch.float64)\n scores = torch.tensor([73.5, 73.5, 100.5, 98.5, 41.5, 37.5], dtype=torch.float64)\n nscores = scores / torch.sum(scores)\n\n print((torch.sum(xs_f * scores) / torch.sum(scores)).item()) # 567.9929411764706\n print(torch.sum(xs_f * nscores).item()) # 567.9929411764706\n print((xs_f @ nscores).item()) # 567.9929411764706\n\n xs_f_32 = xs_f.type(torch.float32)\n scores_32 = scores.type(torch.float32)\n nscores_32 = nscores.type(torch.float32)\n\n print((torch.sum(xs_f_32 * scores_32) / torch.sum(scores_32)).item()) # 567.992919921875\n print(torch.sum(xs_f_32 * nscores_32).item()) # 567.9929809570312 <--\n\n p = torch.tensor(0, dtype=torch.float32)\n for i in range(len(xs_f_32)):\n p += xs_f_32[i] * nscores_32[i]\n\n print(p.item()) # 567.992919921875\n\n print((xs_f_32 @ nscores_32).item()) # 567.9929809570312 <--\n\nif __name__ == \"__main__\":\n numpy_example()\n torch_example()\n```"},{"role":"assistant","content":"Yes, since different algorithms could be used leading to a different expected error compared to a wider dtype."}],"kind":"answer","thread_id":212931,"url":"https://discuss.pytorch.org/t/inconsistencies-between-pytorch-and-numpy-when-performing-32-bit-floating-point-sums/212931","created_at":"2024-11-13T14:10:23.178000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Trying to setup a service, need some quick help with pytorch/cuda compatibility\n\nTrying to setup a python service. Hosting it on AWS with a g4dn.xlarge GPU using Amazon Linux 2023. \n\nDriver: CUDA 12.7\nToolkit: CUDA Toolkit 12.6 Update 2\nPytorch: 2.5.1+cu124\n\nI've been spinning on this trying different things. Do I just need to downgrade my toolkit or pytorch version or something obvious? Wanted to seek some clarification before I keep going round and round. \n\n+-----------------------------------------------------------------------------------------+\n| NVIDIA-SMI 565.57.01 Driver Version: 565.57.01 CUDA Version: 12.7 |\n|-----------------------------------------+------------------------+----------------------+\n| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |\n| | | MIG M. |\n|=========================================+========================+======================|\n| 0 Tesla T4 Off | 00000000:00:1E.0 Off | 0 |\n| N/A 31C P0 26W / 70W | 1MiB / 15360MiB | 10% Default |\n| | | N/A |\n+-----------------------------------------+------------------------+----------------------+\n \n+-----------------------------------------------------------------------------------------+\n| Processes: |\n| GPU GI CI PID Type Process name GPU Memory |\n| ID ID Usage |\n|=========================================================================================|\n| No running processes found |\n+-----------------------------------------------------------------------------------------+\n\nThanks for any help."},{"role":"assistant","content":"It's unclear what the issue is. Your setup looks valid and the locally installed CUDA toolkit won't be used unless you build PyTorch from source or a custom CUDA extension."}],"kind":"answer","thread_id":212941,"url":"https://discuss.pytorch.org/t/trying-to-setup-a-service-need-some-quick-help-with-pytorch-cuda-compatibility/212941","created_at":"2024-11-13T17:12:20.490000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Is it possible to ignore part of the code for torch compile\n\nI have code like \n```\nif condition:\n do foo\nelse:\n do bla\n```\n`do foo` is not compileable, but when using torch.compile I'm never going to enter that code path anyways. Is there a way of letting the compiler know that?"},{"role":"assistant","content":"You could try to use `torch.compiler.disable` as described [here](https://pytorch.org/docs/stable/torch.compiler_fine_grain_apis.html#torch-compiler-disable)."},{"role":"user","content":"I saw that but that seems to just allow for decorating functions? I see now it says \n[here](https://pytorch.org/docs/stable/generated/torch.compiler.disable.html) it's also a context manager so let me using it like that."},{"role":"assistant","content":"I might be misunderstanding - but if you want to ensure that `foo()` is only executed when running with eager, and not when running with `torch.compile`, you can do:\n```\nif torch.compiler.is_compiling():\n return bla()\nelse:\n return foo()\n```"}],"kind":"answer","thread_id":212942,"url":"https://discuss.pytorch.org/t/is-it-possible-to-ignore-part-of-the-code-for-torch-compile/212942","created_at":"2024-11-13T19:16:20.627000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["bdhirsh"]} | |
| {"messages":[{"role":"user","content":"I am trying to implement a Hierarchical Actor Critic model but my neural network doesn't return value with the correct dimension\n\nSo I am trying to build a kind of Actor critic model that uses hierarchical RL, and my problem is that one of my actor network returns an action with shape (1, 512) instead of (1, 6) even though it says that the dimension of the output layer is 6.\n\nI am new to PyTorch and relatively new to RL so I don't understand everything yet, if someone could help me it would be amazing. If you want more informations just ask.\n\nThank you in advance.\n\nActor network :\n```\nimport os\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\nclass ActorNetwork(nn.Module):\n def __init__(self, input_size, l1_dims=512, l2_dims=512,\n output_size=1, name=\"actor\", checkpoint_dir=\"../assets/model\",\n bound=1, offset=0):\n super(ActorNetwork, self).__init__()\n\n self.input_size = input_size\n self.l1_dims = l1_dims\n self.l2_dims = l2_dims\n self.output_size = output_size\n\n self.bound = bound\n self.offset = offset\n\n self.name = name\n self.checkpoint_dir = checkpoint_dir\n self.checkpoint_file = os.path.join(self.checkpoint_dir,\n self.name)\n\n self.l1 = nn.Linear(self.input_size, self.l1_dims)\n self.relu1 = nn.ReLU()\n self.l2 = nn.Linear(self.l1_dims, self.l2_dims)\n self.relu2 = nn.ReLU()\n self.l3 = nn.Linear(self.l2_dims, self.output_size)\n self.tanh = nn.Tanh()\n\n def call(self, state, goal):\n x = torch.cat([state, goal], dim=1)\n linear1 = self.l1(x)\n relu1 = self.relu1(linear1)\n linear2 = self.l2(relu1)\n relu2 = self.relu2(linear2)\n tanh = self.tanh(relu2)\n\n return (tanh.detach().numpy() * self.bound) + self.offset\n```"},{"role":"assistant","content":"You didn't post a minimal and executable code snippet reproducing the unexpected output shape but based on the model definition you should check a few things:\n* your model does not use `self.l3` at all while I assume this is the last linear layer with the desired output shape,\n* you are defining the forward pass in a `call` method while PyTorch expects the definition to be in the `forward` method,\n* applying `tanh` after `relu` sounds strange but is also irrelevant for your issue."}],"kind":"answer","thread_id":213084,"url":"https://discuss.pytorch.org/t/i-am-trying-to-implement-a-hierarchical-actor-critic-model-but-my-neural-network-doesnt-return-value-with-the-correct-dimension/213084","created_at":"2024-11-17T18:51:42.806000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"nn.parameter(requires_grad=False) displayed in summary as Trainable parameter?\n\nHello,\n\nI am building and training a model with a nn parameter set at init with a tensor, which matches a PCA Lowrank output : \nself.PCA_matrix_V_Inv = torch.nn.Parameter(PCAMatrix.clone().transpose(0,1), requires_grad=False)\n\nI do mention requires_grad=False, but torch info summary displays that this parameter count as trainable parameters ? I also tried to set required_grad=False on the initial PCAMatrix tensor, but as expected it did not change the behavior (as it should be False by default on Tensor)\n\nAs I set the requires_grad at init time of my nn.module model, I don't get why it is listed as a trainable parameter ? \n\nAny clue about that anyone ?\nThank you"},{"role":"assistant","content":"The `requires_grad` attribute can easily be changed by calling `.requires_grad_(True)` on the parent module which is why I guess it's returned as a trainable parameter:\n```python\nclass MyModel(nn.Module):\n def __init__(self):\n super().__init__()\n self.param = nn.Parameter(torch.randn(1), requires_grad=False)\n \n def forward(self, x):\n x = x * self.param\n return x\n\nmodel = MyModel()\nprint(dict(model.named_parameters()))\n# {'param': Parameter containing:\n# tensor([1.6849])}\n\nprint(model.param.requires_grad)\n# False\n\nmodel.requires_grad_(True)\nprint(model.param.requires_grad)\n# True\n```\nIf you never want to train it, register the tensor as a buffer.\n\nHowever, it seems the behavior of `torchinfo.summary` might also have changed as I cannot reproduce the issue:\n```python\nmodel = MyModel()\nprint(dict(model.named_parameters()))\n# {'param': Parameter containing:\n# tensor([1.6849])}\n\nprint(model.param.requires_grad)\n# False\n\nsummary(model)\n# =================================================================\n# Layer (type:depth-idx) Param #\n# =================================================================\n# MyModel (1)\n# =================================================================\n# Total params: 1\n# Trainable params: 0\n# Non-trainable params: 1\n# =================================================================\n\nmodel.requires_grad_(True)\nprint(model.param.requires_grad)\n# True\n\nsummary(model)\n# =================================================================\n# Layer (type:depth-idx) Param #\n# =================================================================\n# MyModel 1\n# =================================================================\n# Total params: 1\n# Trainable params: 1\n# Non-trainable params: 0\n# =================================================================\n```"}],"kind":"answer","thread_id":213108,"url":"https://discuss.pytorch.org/t/nn-parameter-requires-grad-false-displayed-in-summary-as-trainable-parameter/213108","created_at":"2024-11-18T11:30:10.703000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Efficiently Combine Two Tensors Based on a Boolean Mask\n\nHi! I have two tensors:\n\n* `tensor_a` ([batch_size, seq_len_a, embedding_dim])\n* `tensor_b` ([batch_size, seq_len_b, embedding_dim])\n\nThe total sequence length is `seq_len_total = seq_len_a + seq_len_b`. I also have a boolean tensor `mask` ([batch_size, seq_len_total]) where `True` corresponds to positions for `tensor_a` and `False` corresponds to positions for `tensor_b`.\n\nHow can I efficiently combine `tensor_a` and `tensor_b` into a single tensor of shape ([batch_size, seq_len_total, embedding_dim]) using the `mask`."},{"role":"assistant","content":"I'm unsure if I understand your use case correctly, but direct indexing with the mask should work:\n```python\nbatch_size, seq_len_a, seq_len_b, embedding_dim = 2, 3, 4, 5\n\na = torch.ones(batch_size, seq_len_a, embedding_dim)\nb = torch.ones(batch_size, seq_len_b, embedding_dim) * 2\n\n# create mask\nmask = torch.cat((torch.tensor([True]*seq_len_a*batch_size), torch.tensor([False]*seq_len_b*batch_size)))\nmask = mask[torch.randperm(len(mask))]\nmask = mask.view(batch_size, -1)\n\nout = torch.zeros(batch_size, seq_len_a+seq_len_b, embedding_dim)\nout[mask] = a.view(-1, embedding_dim)\nout[~mask] = b.view(-1, embedding_dim)\n```"}],"kind":"answer","thread_id":213115,"url":"https://discuss.pytorch.org/t/efficiently-combine-two-tensors-based-on-a-boolean-mask/213115","created_at":"2024-11-18T13:56:03.713000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Computing averages\n\nHi there,\nif have a data matrix x of dim n x d, where n is the batch dimension and d is the dimensionality of my data and a matrix m in d x m.\nI want to use m to compute averages over certain dimensions: e.g. x @ m => in n x m. \nTherefor m[i,j] = 1.0/i_z for j in [idx_i_1,idx_i_2,...,idx_i_z], 0 else\nAs one can see the internal dimension of m is actually d+1, where the parameter 1.0/i_z repeats i_z times in dimension i and the matrix is 0 everywhere else.\nIs there a clever way to produce such a matrix using views?"},{"role":"assistant","content":"Could you post a (slow) reference code using nested loops, please?"},{"role":"user","content":"Gladly:\n```python\n #nested loops\n indices = [[0,1],[2]]\n x = torch.tensor([[1,2,3],[4,5,6],[7,8,9]])\n res = torch.zeros((3,2))\n for i in range(3):\n for j in range(2):\n res[i,j] = torch.sum(x[i,indices[j]]) / len(indices[j])\n print(res)\n\n #with matrix as previously described\n avg_mat = torch.zeros((2,3))\n counter = 0\n for i, idx in enumerate(indices):\n avg_mat[i,idx] = 1.0/len(idx)\n print(x.to(torch.float) @ avg_mat.T)\n print(avg_mat.T)\n```\n--->\n```\ntensor([[1.5000, 3.0000],\n [4.5000, 6.0000],\n [7.5000, 9.0000]])\ntensor([[1.5000, 3.0000],\n [4.5000, 6.0000],\n [7.5000, 9.0000]])\ntensor([[0.5000, 0.0000],\n [0.5000, 0.0000],\n [0.0000, 1.0000]])\n```\n\nI found out about torch.scatter, maybe thats a good solution to my troubles.."},{"role":"assistant","content":"Yes, `.scatter_reduce_` should work, but you would need to modify your index and check the count:\n```python\nidx = torch.tensor(sum([[i]*len(a) for i, a in enumerate(indices)], []))\n_, count = idx.unique(return_counts=True)\nidx = idx.unsqueeze(0).expand(3, 3)\n\nout = torch.zeros(idx.size(0), idx.max()+1, dtype=x.dtype)\nout.scatter_reduce_(1, idx, x, reduce=\"sum\")\nout = out / count\n\nprint(out)\n# tensor([[1.5000, 3.0000],\n# [4.5000, 6.0000],\n# [7.5000, 9.0000]])\n```"}],"kind":"answer","thread_id":213152,"url":"https://discuss.pytorch.org/t/computing-averages/213152","created_at":"2024-11-19T11:26:31.040000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Computing averages\n\nHi there,\nif have a data matrix x of dim n x d, where n is the batch dimension and d is the dimensionality of my data and a matrix m in d x m.\nI want to use m to compute averages over certain dimensions: e.g. x @ m => in n x m. \nTherefor m[i,j] = 1.0/i_z for j in [idx_i_1,idx_i_2,...,idx_i_z], 0 else\nAs one can see the internal dimension of m is actually d+1, where the parameter 1.0/i_z repeats i_z times in dimension i and the matrix is 0 everywhere else.\nIs there a clever way to produce such a matrix using views?"},{"role":"assistant","content":"Could you post a (slow) reference code using nested loops, please?"}],"kind":"clarification","thread_id":213152,"url":"https://discuss.pytorch.org/t/computing-averages/213152","created_at":"2024-11-19T11:26:31.040000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Verbose in dassl\n\nI had to download new version of pytorch because of the Slurm server's limitation.\nThen I planed to use dassl to train a model, but got warning \"UserWarning: The verbose parameter is deprecated\" and it seems that the config VERBOSE have been deprecated in recent versions of Pytorch.\nI'm a rookie of coding in Machine Learning so I have to send this topic for help.\nI'd be appreciated for your answers!!!"},{"role":"assistant","content":"I'm not familiar with `dassl` but could you check which line of code raises this warning?"},{"role":"user","content":"torch/optim/lr_scheduler.py:62: UserWarning: The verbose parameter is deprecated. Please use get_last_lr() to access the learning rate."},{"role":"assistant","content":"Thank you!\nIt seems the `verbose` argument is directly passed to all learning rate schedulers as seen e.g. [here](https://github.com/KaiyangZhou/Dassl.pytorch/blob/c61a1b570ac6333bd50fb5ae06aea59002fb20bb/dassl/optim/lr_scheduler.py#L22). I don't know if `dassl` is still maintained, but you could create an issue in their GitHub repo or submit a fix."}],"kind":"answer","thread_id":213179,"url":"https://discuss.pytorch.org/t/verbose-in-dassl/213179","created_at":"2024-11-20T01:45:36.171000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Verbose in dassl\n\nI had to download new version of pytorch because of the Slurm server's limitation.\nThen I planed to use dassl to train a model, but got warning \"UserWarning: The verbose parameter is deprecated\" and it seems that the config VERBOSE have been deprecated in recent versions of Pytorch.\nI'm a rookie of coding in Machine Learning so I have to send this topic for help.\nI'd be appreciated for your answers!!!"},{"role":"assistant","content":"I'm not familiar with `dassl` but could you check which line of code raises this warning?"}],"kind":"clarification","thread_id":213179,"url":"https://discuss.pytorch.org/t/verbose-in-dassl/213179","created_at":"2024-11-20T01:45:36.171000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Training different stage of model with different loss\n\nI'm trying to train a two-stage model in an end-to-end way. However, I want to update the different stages of models with different losses. For example, suppose the end to end model is composed of two models:model1 and model2. The output is calculated through running \n```\nfeatures = model1(inputs)\noutput = model2(features)\n```\nI want to update the parameters of model1 with loss1, while keeping the parameter of model2 unchanged. Next, I want to update the parameters of model2 with loss2, while keeping the parameter of model1 unchanged. My full implementation is something like:\n```\nimport torch\nimport torch.nn as nn\n\n# Define the first model\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Linear(20, 10)\n self.conv2 = nn.Linear(10, 5)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n return x\n\n# Define the second model\nclass Net1(nn.Module):\n def __init__(self):\n super(Net1, self).__init__()\n self.conv1 = nn.Linear(5, 1)\n\n def forward(self, x):\n x = self.conv1(x)\n return x\n\n# Initialize models\nmodel1 = Net()\nmodel2 = Net1()\n\n# Initialize separate optimizers for each model\noptimizer = torch.optim.SGD(model1.parameters(), lr=0.1)\noptimizer1 = torch.optim.SGD(model2.parameters(), lr=0.1)\n\noptimizer.zero_grad() \noptimizer1.zero_grad()\n\ncriterion = nn.CrossEntropyLoss()\n\n# Sample inputs and labels\ninputs = torch.randn(2, 20)\nlabels = torch.randn(2,1)\n\nfeatures = model1(inputs) \noutputs_model = model2(features) \n\nloss1 = criterion(outputs_model[0], labels[0]) \nloss2 = criterion(outputs_model, labels) \n \nloss1.backward(retain_graph=True) \noptimizer.step() \noptimizer.zero_grad() \noptimizer1.zero_grad() \n\n \nloss2.backward() \noptimizer1.step()\noptimizer.zero_grad() \noptimizer1.zero_grad() \n\nprint(f\"Loss1 (Net): {loss1.item()}\")\nprint(f\"Loss2 (Net1): {loss2.item()}\")\n```\nHowever, this will return\n```\nRuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [10, 5]], which is output 0 of AsStridedBackward0, is at version 2; expected version 1 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).\n```\nThe full error message is\n```\nTraceback (most recent call last):\n File \", line 55, in <module>\n loss2.backward() \n ^^^^^^^^^^^^^^^^\n File \"/opt/homebrew/anaconda3/lib/python3.11/site-packages/torch/_tensor.py\", line 521, in backward\n torch.autograd.backward(\n File \"/opt/homebrew/anaconda3/lib/python3.11/site-packages/torch/autograd/__init__.py\", line 289, in backward\n _engine_run_backward(\n File \"/opt/homebrew/anaconda3/lib/python3.11/site-packages/torch/autograd/graph.py\", line 769, in _engine_run_backward\n return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nRuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [10, 5]], which is output 0 of AsStridedBackward0, is at version 2; expected version 1 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).\n```\nI kinda understand why this is happening, but is there a way to address this? Any help is appreciated"},{"role":"assistant","content":"You are most likely running into [this issue](https://discuss.pytorch.org/t/struggling-with-a-runtime-error-related-to-in-place-operations/102222/6?u=ptrblck) which fails to compute the gradients since the forward activations are stale after a parameter update."}],"kind":"answer","thread_id":213221,"url":"https://discuss.pytorch.org/t/training-different-stage-of-model-with-different-loss/213221","created_at":"2024-11-20T17:20:41.460000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Reset model and optimizer in C++\n\nI am using CUDA graph to train multiple models. I believe the graph captures certain memory spaces, so if I need to train another network using the same graph, I have to use the same memory space of the model and optimizer. My question is how can I create a new model/optimizer in the same memory space, or is there a way to reset the model and the optimizer without changing the memory space?\n\nHere is how I created the model and optimizer:\nstd::shared_ptr< UNet> unet_model = std::make_shared< UNet>(in_chn, out_chn, fea);\n\nstd::shared_ptr< torch::optim::Adam> optimizer = std::make_shared< torch::optim::Adam>(unet_model->parameters(), torch::optim::AdamOptions(1e-2));"},{"role":"assistant","content":"I don't understand what this exactly means. The graph capture will use its own internal memory pool. You can capture any models you want as long as you have enough memory. If previous models are not needed anymore you can delete them."},{"role":"user","content":"Hi @ptrblck , I have a question about using a recorded training graph. If I record the training process of model_0 to build a CUDA graph, can I reuse the same graph to train model_1?\n\nFrom my understanding, the graph seems to record the memory addresses associated with model_0, so during replay, it always references those specific addresses. To train model_1, would I need to copy model_1 to the same GPU memory address used by model_0 for the graph to work? Is this understanding correct?"},{"role":"assistant","content":"No, as your explanation about the captured memory addresses is correct. Replaying the graph will use the same operations and the same memory locations pointing to `model_0`.\n\nA safe option would be to delete `model_0` including its capture and to recapture `model_1`. However, you could also try to experiment with inplace copies (via `tensor.copy_`) to copy all parameters from `model_1` into `model_0` (I haven't tried it and don't know if I'm missing any obvious limitation)."},{"role":"user","content":"Thanks, I forgot to mention that `model_0` and `model_1` share the same architecture, the only difference is their weights. Currently, I am training 4096 identical models, each with different weights. Since each model is relatively small (just a few hundred parameters), I believe reusing the graph could significantly improve performance, as capturing graphs for 4096 models might cause a lot of overhead.\n\nMy initial thought was to reuse the GPU address by creating a new model in the captured memory location, then after training copy it elsewhere, and then load the next model to repeat the process. However, if this approach isn't feasible, I will explore the idea of copying tensors as you suggested."},{"role":"assistant","content":"If the architecture is equal, try to simply load the `state_dict` of another model into the captured one and let me know if you are seeing any issues."}],"kind":"answer","thread_id":213237,"url":"https://discuss.pytorch.org/t/reset-model-and-optimizer-in-c/213237","created_at":"2024-11-20T23:21:53.860000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[6],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Pytorch crashes during tensor multiplication using dtype = float32\n\nPytorch crashes python when multiplying tensors that have datatype float32.\nThe error does not arise when the tensor is converted to float64.\n\nExample code to cause the crash:\n```import torch```\n```x = torch.rand((5,5))```\n```x@x```\n\nThe error received from Visual Studio 2022 is:\nUnhandled exception at 0x00007FF8B441440D (torch_cpu.dll) in python.exe: 0xC0000094: Integer division by zero.\n\nI am running:\nWindows 10\nPython 3.12\nPytorch 2.5.1, cuda 11.8 - installed using anaconda\nCPU AMD Athlon II x4 650\nGPU GTX 1050 Ti\nCuda toolkit 11.8\nCuda dnn 9.5.1\nDriver 566.14\n\nI reinstalled Cuda toolkit, Cuda dnn, and Pytorch due to a fatal bug training an Ultralytics model and came across this bug. I had a similar bug in the past on Pytorch 2.5.0 (I think), but it went away after I installed Cuda dnn."},{"role":"assistant","content":"Your code fails on the host and is not using any CUDA functionality.\nTry to grab the stacktraces to narrow down which call fails."}],"kind":"answer","thread_id":213249,"url":"https://discuss.pytorch.org/t/pytorch-crashes-during-tensor-multiplication-using-dtype-float32/213249","created_at":"2024-11-21T06:06:12.431000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Compiling vmapped custom op\n\nHello,\nI'm trying to compile a vmapped custom operator and getting an \"INTERNAL ASSERT FAILED\" error. Here are four test functions that show that native pytorch operators are able to work with torch.compile and vmap, and custom operators work separately with either torch.compile or vmap, but not together.\n```\nimport torch, os\nfrom torch import Tensor\n\nlib = torch.library.Library('mylib', 'FRAGMENT')\n\n@torch.library.custom_op('mylib::inc_custom', mutates_args=())\ndef inc_custom(x: Tensor) -> Tensor:\n return x + 1\n\n@torch.library.register_fake('mylib::inc_custom')\ndef _(x):\n return torch.empty_like(x)\n\n@torch.library.register_vmap('mylib::inc_custom')\ndef inc_vmap(info, in_dims, x):\n return inc_custom(x), 0\n\ndef inc_simple(x: Tensor) -> Tensor:\n return x + 1\n\nf1 = torch.compile( torch.vmap(inc_simple) )\nf2 = torch.compile(inc_custom)\nf3 = torch.vmap(inc_custom)\nf4 = torch.compile(f3)\n\na = torch.arange(8)\nb = a.view(2, 4)\n\nprint('inc_simple vmap + compile:')\nprint( f1(b) )\n\nprint('inc_custom compile:')\nprint( f2(a) )\n\nprint('inc_custom vmap:')\nprint( f3(b) )\n\nprint('inc_custom vmap + compile:')\nprint( f4(b) )\n```\nOutput:\n```\ninc_simple vmap + compile:\ntensor([[1, 2, 3, 4],\n [5, 6, 7, 8]])\ninc_custom compile:\ntensor([1, 2, 3, 4, 5, 6, 7, 8])\ninc_custom vmap:\ntensor([[1, 2, 3, 4],\n [5, 6, 7, 8]])\ninc_custom vmap + compile:\nTraceback (most recent call last):\n File \"/home/alex/python_tests/test2.py\", line 42, in <module>\n print( f4(b) )\n\n...\n...\n...\n\nFile \"/home/alex/miniconda3/envs/myenv/lib/python3.11/site-packages/torch/_ops.py\", line 716, in __call__\n return self._op(*args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^\ntorch._dynamo.exc.TorchRuntimeError: Failed running call_function mylib.inc_custom.default(*(BatchedTensor(lvl=1, bdim=0, value=\n FakeTensor(..., size=(2, 4), dtype=torch.int64)\n),), **{}):\ntls_on_entry.has_value() INTERNAL ASSERT FAILED at \"/opt/conda/conda-bld/pytorch_1729647429097/work/aten/src/ATen/core/PythonFallbackKernel.cpp\":49, please report a bug to PyTorch. \n\nfrom user code:\n File \"/home/alex/miniconda3/envs/myenv/lib/python3.11/site-packages/torch/_functorch/apis.py\", line 203, in wrapped\n return vmap_impl(\n File \"/home/alex/miniconda3/envs/myenv/lib/python3.11/site-packages/torch/_functorch/vmap.py\", line 331, in vmap_impl\n return _flat_vmap(\n File \"/home/alex/miniconda3/envs/myenv/lib/python3.11/site-packages/torch/_functorch/vmap.py\", line 479, in _flat_vmap\n batched_outputs = func(*batched_inputs, **kwargs)\n File \"/home/alex/miniconda3/envs/myenv/lib/python3.11/site-packages/torch/_library/custom_ops.py\", line 669, in __call__\n return self._opoverload(*args, **kwargs)\n```"},{"role":"assistant","content":"Use the latest nightly binary, where this INTERNAL ASSERT no longer occurs. If it still fails there, create an issue on GitHub."}],"kind":"answer","thread_id":213373,"url":"https://discuss.pytorch.org/t/compiling-vmapped-custom-op/213373","created_at":"2024-11-24T14:51:10.364000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["Space4444","ptrblck"]} | |
| {"messages":[{"role":"user","content":"[CPU] Train network using float 16?\n\nI'm considering ways to improve speed and memory footprint of models and data.\n\nReading SO, this forum and docs, it's still unclear to me whether it's possible to use either float16 or bfloat16 and whether I can set this somewhere as a top level parameter.\n\nWhat I have found is the setting:\n\n```python\ndtype = torch.float16\ntorch.set_default_dtype(dtype)\n```\n\nbut this returns errors due to un-supported ops. (i'm using it with a standard neural network.)\n\nCould anyone offer some hints?\n\nRunning `lscpu | grep dtype` shows apparently support for f16 (not bf16.)"},{"role":"assistant","content":"CPU workloads should support `bfloat16` in `autocast` as described in the [docs](https://pytorch.org/docs/stable/amp.html#automatic-mixed-precision-package-torch-amp):\n> As shown in the CPU example section of [`torch.autocast`](https://pytorch.org/docs/stable/amp.html#torch.autocast), “automatic mixed precision training/inference” on CPU with datatype of `torch.bfloat16` only uses [`torch.autocast`](https://pytorch.org/docs/stable/amp.html#torch.autocast).\n\nI don't know what the status of `float16` support on CPU is and if it's planned."}],"kind":"answer","thread_id":213486,"url":"https://discuss.pytorch.org/t/cpu-train-network-using-float-16/213486","created_at":"2024-11-26T19:22:22.622000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Q: Trying to run Mandelbrot on GPU via PyTorch, but not seeing speed-up\n\nDear PyTorch folks,\n\nMy apologies, I am a PyTorch newbie and am probably missing something basic.\n\nI made a click-to-zoom Mandelbrot set in Google Colab, and am trying to transfer it to Torch, in order to get GPU speed-up. I have selected a GPU runtime and it is showing up in nvidia-smi, and I am passing the tensor to CUDA.\n\nHere is the Colab link:\nhttps://colab.research.google.com/drive/17xHEFdUVG8TCgme8DSQP--ZLo7Wsoe6L?usp=sharing\n\nHere's the relevant piece of code:\n```\ndef raj_mandel_torch(xmin,xmax,ymin,ymax,num_grid_points,max_its):\n real_range = np.linspace(xmin,xmax,num_grid_points)\n imag_range = np.linspace(ymin,ymax,num_grid_points)\n timesteps_in_bound = np.zeros((num_grid_points,num_grid_points))\n real_grid, imag_grid = np.meshgrid(real_range, imag_range)\n complex_array = real_grid + imag_grid * 1j\n \n complex_tensor = torch.from_numpy(complex_array)\n z_old = torch.zeros(num_grid_points, num_grid_points)\n z_new = torch.zeros(num_grid_points, num_grid_points)\n abs_val_sq = torch.zeros(num_grid_points, num_grid_points)\n timesteps_in_bound = torch.zeros(num_grid_points, num_grid_points)\n \n complex_tensor.to(device='cuda')\n z_old.to(device='cuda')\n z_new.to(device='cuda')\n abs_val_sq.to(device='cuda')\n timesteps_in_bound.to(device='cuda')\n\n for this_iter_num in range(0,max_its):\n z_new = z_old**2 + complex_tensor\n abs_val_sq = torch.real(z_new)**2 + torch.imag(z_new)**2\n timesteps_in_bound += (abs_val_sq < 4)\n z_old = z_new\n\n return(timesteps_in_bound)\n```\nI'm not seeing any speed-up or GPU usage, though. Here is a screenshot:\n[image]\n\nAny help greatly appreciated!\n\nRaj"},{"role":"assistant","content":"You need to assign the results to a variable:\n```python\nx = x.to(device='cuda')\n```\nsince tensors won't be moved inplace."}],"kind":"answer","thread_id":213528,"url":"https://discuss.pytorch.org/t/q-trying-to-run-mandelbrot-on-gpu-via-pytorch-but-not-seeing-speed-up/213528","created_at":"2024-11-27T14:37:49.259000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Are batchnorm buffers handled automatically by DataParallel?\n\nI saw from [this](https://discuss.pytorch.org/t/what-pytorch-means-by-buffers/120266) post that within batchnorm layers the mean and std are buffers and not parameters. Does this mean they are handled automatically by dataparallels? I'm working on how to have dataparallels handle some of my buffers and would really like it to be done automatically as well rather than building custom DataParallel and DistributedDataParallel.\n\nJust found [this](https://pytorch.org/docs/stable/_modules/torch/nn/parallel/data_parallel.html#DataParallel) in the dataparallel documentation. So does this mean they're not actually handled and its just only using the mean and std that are calculated being calculated on device[0] and deciding that'll be close enough to the full mean and std, ignoring whats happening on other devices? And most importantly, even if it's ignoring the other values for calculation, will the other devices be using the mean and std calculated on device 0 or they will just have their mean and std not ever be initialized? \n\n .. warning::\n In each forward, :attr:`module` is **replicated** on each device, so any\n updates to the running module in ``forward`` will be lost. For example,\n if :attr:`module` has a counter attribute that is incremented in each\n ``forward``, it will always stay at the initial value because the update\n is done on the replicas which are destroyed after ``forward``. However,\n :class:`~torch.nn.DataParallel` guarantees that the replica on\n ``device[0]`` will have its parameters and buffers sharing storage with\n the base parallelized :attr:`module`. So **in-place** updates to the\n parameters or buffers on ``device[0]`` will be recorded. E.g.,\n :class:`~torch.nn.BatchNorm2d` and :func:`~torch.nn.utils.spectral_norm`\n rely on this behavior to update the buffers."},{"role":"assistant","content":"`nn.DataParallel` will update the running stats on `device0` and will scatter the `state_dict` to all replicas in the forward pass."}],"kind":"answer","thread_id":213618,"url":"https://discuss.pytorch.org/t/are-batchnorm-buffers-handled-automatically-by-dataparallel/213618","created_at":"2024-11-29T16:39:12.968000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Is it possible to keep a chunk of continuous gpu memory (e.g. 20G) in DDP mode for gradient synchronization?\n\nMy training code will produce a large amount of memory fragments. Therefore, in DDP mode, it usually reports that it can't allocate 15.00GB memory in backward stage.\n\nI set gradient_as_bucket_view=True and it works well. However, when I use gradient_accumulation, this method can't work.\n\nSo I want to create a chunk of continuous gpu memory for gradient backward. Are there any methods that can achieve this goal?"},{"role":"assistant","content":"Could you describe why gradient accumulation fails?"},{"role":"user","content":"I guess that when setting gradient_as_bucket_view=True, maybe the backward operation conflicts with the function of gradient_as_bucket_view, because gradient accumulation needs multiple times of backward."},{"role":"assistant","content":"IIUC, `gradient_as_bucket_view ` is trying to solve the fragmentation. Is there any reason why you don't want to use `gradient_as_bucket_view `?\n\ncc: @fegin"}],"kind":"answer","thread_id":213631,"url":"https://discuss.pytorch.org/t/is-it-possible-to-keep-a-chunk-of-continuous-gpu-memory-e-g-20g-in-ddp-mode-for-gradient-synchronization/213631","created_at":"2024-11-30T05:11:51.551000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["fduwjj"]} | |
| {"messages":[{"role":"user","content":"Is it possible to keep a chunk of continuous gpu memory (e.g. 20G) in DDP mode for gradient synchronization?\n\nMy training code will produce a large amount of memory fragments. Therefore, in DDP mode, it usually reports that it can't allocate 15.00GB memory in backward stage.\n\nI set gradient_as_bucket_view=True and it works well. However, when I use gradient_accumulation, this method can't work.\n\nSo I want to create a chunk of continuous gpu memory for gradient backward. Are there any methods that can achieve this goal?"},{"role":"assistant","content":"Could you describe why gradient accumulation fails?"}],"kind":"clarification","thread_id":213631,"url":"https://discuss.pytorch.org/t/is-it-possible-to-keep-a-chunk-of-continuous-gpu-memory-e-g-20g-in-ddp-mode-for-gradient-synchronization/213631","created_at":"2024-11-30T05:11:51.551000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Why is there such a large difference using XLA in this snippet?\n\nThe results for an operation are as follows:\n\n* CUDA enabled GPU=T4 calculation does not even finish after many seconds, maybe minutes. Same happens for CPUs.\n* XLA + CUDA enabled GPU is fast, approximately same speed as TPU\n* XLA enabled TPU are very fast.\n\n## Results and Repro\n\nThis can be issued in a Colab Notebook.\n\n* Remove tensorflow first using:\n```bash\npip uninstall tensorflow -y -q\n```\n* For the test with XLA+CUDA (only) run:\n\n```bash\npip install torch==2.5.1 torch_xla==2.5.1 https://storage.googleapis.com/pytorch-xla-releases/wheels/cuda/12.1/torch_xla_cuda_plugin-2.5.1-py3-none-any.whl -q\n```\n\nThen paste the code:\n\n```\nimport torch\n\ntry:\n import torch_xla\n import torch_xla.core.xla_model as xm\nexcept ModuleNotFoundError:\n print(\"won't use tpu-xla\")\n xm = None\n\n# print(torch_xla.__version__,xm.xla_device())\n\nimport time\n\nsize=20000\nif xm is not None:\n x = torch.randn(size,size).to(xm.xla_device())\n y = torch.randn(size,size).to(xm.xla_device())\nelse:\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n x = torch.randn(size,size).to(device)\n y = torch.randn(size,size).to(device)\n\nprint(x.device, y.device)\n\ntimes =[]\nfor j in range(10):\n s= time.time()\n for i in range(10000):\n x.add(y).matmul(x)\n e= time.time()\n times.append(e-s)\naverage = sum(times)/len(times)\nprint(average)\n\n# avg:xpu:0.13987584114074708\n```\n\nIs there such a huge speed difference, or am I doing something wrong?\n\nThis is observed for smaller sizes as well, but the difference is smaller.\n\nCould one expect like 100x speed up in training a model with XLA?"},{"role":"assistant","content":"You are using host timers without any device synchronization so your profiling is not measuring the kernel execution time but the launch overheads."},{"role":"user","content":"the test tries to reduce anything that's not from the calculation by using a large matrix multiplication that'd consume most of the computing time; im unsure why the timing wouldn't be pointing in the right direction, could you be more explicit or give a simple example?"},{"role":"assistant","content":"CUDA kernels are executed asynchronously, i.e. the host code can run ahead launching kernels while the GPU is busy with the actual kernel execution.\nIf you use host timers and want to measure the real GPU kernel execution time, you would need to synchronize the code before starting and stopping the timers. \n\nHere is a small example showing this:\n```python\nimport torch\nimport time\nfrom torch.profiler import profile, record_function, ProfilerActivity\n\ndevice = \"cuda\"\nactivities = [ProfilerActivity.CPU, ProfilerActivity.CUDA]\nsort_by_keyword = device + \"_time_total\"\n\nx = torch.randn(64, 1024, 1024, device=device)\n\n# warmup\nfor _ in range(10):\n _ = torch.matmul(x, x)\n\nnb_iters = 100\n\ntorch.cuda.synchronize()\nt0 = time.perf_counter()\nfor _ in range(nb_iters):\n _ = torch.matmul(x, x)\ntorch.cuda.synchronize()\nt1 = time.perf_counter()\nprint(\"{:.3f}ms/iter\".format((t1 - t0) / nb_iters * 1000))\n# 7.783ms/iter\n\nt0 = time.perf_counter()\nfor _ in range(nb_iters):\n _ = torch.matmul(x, x)\nt1 = time.perf_counter()\nprint(\"{:.3f}ms/iter\".format((t1 - t0) / nb_iters * 1000))\n# 0.013ms/iter\n\nwith profile(activities=activities, record_shapes=True) as prof:\n for _ in range(nb_iters):\n _ = torch.matmul(x, x)\nprint(prof.key_averages().table(sort_by=sort_by_keyword, row_limit=10))\n# --------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ \n# Name Self CPU % Self CPU CPU total % CPU total CPU time avg Self CUDA Self CUDA % CUDA total CUDA time avg # of Calls \n# --------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ \n# aten::matmul 0.13% 967.727us 0.57% 4.432ms 44.320us 0.000us 0.00% 770.696ms 7.707ms 100 \n# aten::bmm 0.30% 2.286ms 0.36% 2.765ms 27.647us 770.696ms 100.00% 770.696ms 7.707ms 100 \n# ampere_sgemm_128x128_nn 0.00% 0.000us 0.00% 0.000us 0.000us 770.696ms 100.00% 770.696ms 7.707ms 100 \n# aten::expand 0.04% 290.806us 0.05% 366.557us 1.833us 0.000us 0.00% 0.000us 0.000us 200 \n# aten::as_strided 0.01% 75.751us 0.01% 75.751us 0.379us 0.000us 0.00% 0.000us 0.000us 200 \n# aten::reshape 0.02% 121.196us 0.03% 260.900us 1.304us 0.000us 0.00% 0.000us 0.000us 200 \n# aten::view 0.02% 139.704us 0.02% 139.704us 0.699us 0.000us 0.00% 0.000us 0.000us 200 \n# cudaLaunchKernel 0.06% 478.226us 0.06% 478.226us 4.782us 0.000us 0.00% 0.000us 0.000us 100 \n# aten::_unsafe_view 0.01% 72.106us 0.01% 72.106us 0.721us 0.000us 0.00% 0.000us 0.000us 100 \n# cudaDeviceSynchronize 99.43% 768.014ms 99.43% 768.014ms 768.014ms 0.000us 0.00% 0.000us 0.000us 1 \n# --------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ \n# Self CPU time total: 772.446ms\n# Self CUDA time total: 770.696ms\n```\nAs you can see, the properly synchronized code shows the same kernel execution time as the profiler."}],"kind":"answer","thread_id":213684,"url":"https://discuss.pytorch.org/t/why-is-there-such-a-large-difference-using-xla-in-this-snippet/213684","created_at":"2024-12-02T07:42:16.130000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Error: ‘PyArray_Descr’ has no member named ‘elsize’\n\nI'm trying to compile a specific version of PyTorch (2.1.2) from source in Linux, but I'm facing the following issue:\n\n```\n[1861/1881] Building CXX object caffe2/torch/CMakeFiles/torch_python.dir/csrc/utils/tensor_numpy.cpp.o\n FAILED: caffe2/torch/CMakeFiles/torch_python.dir/csrc/utils/tensor_numpy.cpp.o\n /src/pytorch/torch/csrc/utils/tensor_numpy.cpp: In function ‘at::Tensor torch::utils::tensor_from_cuda_array_interface(PyObject*)’:\n /src/pytorch/torch/csrc/utils/tensor_numpy.cpp:404:34: error: ‘PyArray_Descr’ has no member named ‘elsize’\n 404 | dtype_size_in_bytes = descr->elsize;\n | ^~~~~~\n```\n\nMaybe the cause is an incompatible version of NumPy that is being pulled in.\n\nps: my environment is actually a bit different. It's a slightly patched PyTorch being built on riscv64 using qemu. But maybe the error is not related."},{"role":"assistant","content":"Downgrade `numpy` to `<2.0` and try to rebuild PyTorch."}],"kind":"answer","thread_id":213726,"url":"https://discuss.pytorch.org/t/error-pyarray-descr-has-no-member-named-elsize/213726","created_at":"2024-12-03T04:22:38.936000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"No CUDA 12.4 distribution for Linux when using pip?\n\nHi, Thanks for your work!\n\nI'm wondering if this is a typo or if there is no real CUDA 12.4 distribution for Linux when using pip. \n\nCurrently in https://pytorch.org/get-started/locally/, there's no `--index-url` option on Linux with CUDA 12.4.\n\n[image]\n\nUp to CUDA 12.1, it needs to be installed with `--index-url` on Linux as well, but `--index-url` suddenly disappeared with CUDA 12.4.\nI'm wondering if this is an accidental typo in the documentation or if there really is no support for the CUDA 12.4 distribution on Linux when using pip. \n\nI googled to find out, but couldn't confirm this.\n\nThanks for your help!"},{"role":"assistant","content":"I've read elsewhere that it now (`2.5.1`, and probably some earlier versions too.) installs CUDA by default on Linux, from the PyPI index (so no index needed.) I can't see metadata info, you may have to look at what it installs."},{"role":"user","content":"Thanks. I'd like to check myself with\n```\nimport torch\nprint(torch.cuda.is_available())\n```\nafter installing torch if I'm using Linux now, but I'm not.\nIf anyone could confirm this, I'd appreciate it!"},{"role":"assistant","content":"The default `pip install torch` wheels always shipped with CUDA runtime dependencies so just copy/paste the command and you'll see CUDA 12.4 dependencies will be installed too."}],"kind":"answer","thread_id":213783,"url":"https://discuss.pytorch.org/t/no-cuda-12-4-distribution-for-linux-when-using-pip/213783","created_at":"2024-12-04T06:31:14.083000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Install PyTorch 1.7\n\nHello I am trying to install PyTorch 1.7 to use for a Github repo I found quite interesting, however when I run the pip commands found on https://pytorch.org/get-started/previous-versions/, it appears the version of PyTorch could not be found. Is there a way to manually download it, or is the repo simply no longer feasible to use? \n\nCommand I ran:\n\n> pip install torch==1.7.1+cu110 torchvision==0.8.2+cu110 torchaudio==0.7.2 -f https://download.pytorch.org/whl/torch_stable.html\n\nOutput I got\n\n[image]"},{"role":"assistant","content":"A quick search shows PyTorch==1.7 was released in Oct. 2020 while Python==3.11 was released in Oct. 2022, so yes you would need to downgrade your Python version."}],"kind":"answer","thread_id":213881,"url":"https://discuss.pytorch.org/t/install-pytorch-1-7/213881","created_at":"2024-12-05T22:40:54.483000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Average tensor unbind times vary drastically depending on implementation of unrelated code flows\n\nI am running into a strange issue in my code base. The code is complicated but essentially I was noticing that calling unbind(0) on tensors took longer in one commit vs another, and it was noticeably slowing down performance. The old commit has an average per-call runtime of 8.727e-5, while the new commit has an average per-call runtime of 2.36e-4.\n\nI was playing around with unbinding and I noticed that something seems to be getting cached... subsequent calls to unbind(), even on different tensors, seems to be consistently faster than the first call, no matter which tensor is put first.\n\nThe new code could potentially be messing with whatever cache exists and making the unbind call slower, but I am uncertain how to build around this. Is it possible to preserve the cache somehow? Are there any devs who might have insight onto what's going on here?"},{"role":"assistant","content":"I don't know how you are profiling your code and if you are using a GPU, but note that CUDA operations are executed asynchronously. If you are using host timers you would need to synchronize the code before starting and stopping the host timers."}],"kind":"answer","thread_id":213953,"url":"https://discuss.pytorch.org/t/average-tensor-unbind-times-vary-drastically-depending-on-implementation-of-unrelated-code-flows/213953","created_at":"2024-12-08T01:00:15.218000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Access cuDNN convolution grad input and grad weight computation function\n\nHi,\n\nI am currently working on a problem of gradient pruning.\n\nIn the context of convolution computation, during the backpropagation, I need to alter the gradient of the weight (grad_weight) computation by slicing the gradient of the output (grad_output) before doing the actual gradient computation.\n\nSo to achieve this goal I need acces to the functions performing backpropagarion computation for convolution.\n\nI don't want to use the functions **conv2d_input** and **conv2d_weight** because they are slow. Binding the function **convolution_backward** does not solve my problem since I also compute the gradient of the input (grad_input) without slincing grad_output.\n\nI want to use CUDA/cuDNN function to do the job.\n\nMy best guess so far was this example on github:\nhttps://github.com/jordan-g/PyTorch-cuDNN-Convolution/tree/master\n\nThis example uses **cudnn_convolution_backward_weight** and **cudnn_convolution_backward_input** as function to compute the associated gradient.\n\nBut, from what I understand theses functions have been removed from the ATen API (for code rule compliance)and are no longer accessible (they are not anymore written inside native_functions.yaml)\n\nMy point is I really really need to have a fine control over the grad_input and grad_weight (and grad_bias) computation, So how I can do that?\n\nMore generaly, how to make accessible for python/torch binding functions that are not listed inside native_functions.yaml?\n\nSorry for the long post.\nThanks in advance for your answers and guidance."},{"role":"assistant","content":"These methods will still dispatch to `cudnn` as seen here:\n```python\ndevice = \"cuda\"\nx = torch.randn(1, 3, 24, 24, requires_grad=True, device=device)\nw = torch.randn(3, 3, 3, 3, requires_grad=True, device=device)\ngrad_output = torch.randn_like(x)\n\nactivities = [ProfilerActivity.CPU, ProfilerActivity.CUDA]\nsort_by_keyword = device + \"_time_total\"\n\nwith profile(activities=activities, record_shapes=True) as prof:\n wgrad = torch.nn.grad.conv2d_weight(x, w.shape, grad_output, stride=1, padding=1)\nprint(prof.key_averages().table(sort_by=sort_by_keyword, row_limit=10))\n# ------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ \n# Name Self CPU % Self CPU CPU total % CPU total CPU time avg Self CUDA Self CUDA % CUDA total CUDA time avg # of Calls \n# ------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ \n# aten::convolution_backward 12.68% 212.324us 15.07% 252.310us 252.310us 4.608us 100.00% 4.608us 4.608us 1 \n# void cudnn::cnn::wgrad2d_grouped_direct_kernel<false... 0.00% 0.000us 0.00% 0.000us 0.000us 4.608us 100.00% 4.608us 4.608us 1 \n# aten::new_empty 8.46% 141.694us 79.58% 1.332ms 1.332ms 0.000us 0.00% 0.000us 0.000us 1 \n# aten::empty 71.51% 1.197ms 71.51% 1.197ms 598.527us 0.000us 0.00% 0.000us 0.000us 2 \n# aten::expand 0.79% 13.165us 1.06% 17.703us 17.703us 0.000us 0.00% 0.000us 0.000us 1 \n# aten::as_strided 0.27% 4.538us 0.27% 4.538us 4.538us 0.000us 0.00% 0.000us 0.000us 1 \n# aten::to 0.10% 1.703us 0.10% 1.703us 1.703us 0.000us 0.00% 0.000us 0.000us 1 \n# cudaEventRecord 0.34% 5.731us 0.34% 5.731us 5.731us 0.000us 0.00% 0.000us 0.000us 1 \n# cudaStreamIsCapturing 0.06% 1.022us 0.06% 1.022us 1.022us 0.000us 0.00% 0.000us 0.000us 1 \n# cudaStreamGetPriority 0.06% 1.072us 0.06% 1.072us 1.072us 0.000us 0.00% 0.000us 0.000us 1 \n# ------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ \n# Self CPU time total: 1.674ms\n# Self CUDA time total: 4.608us\n```\nso the change in the interface should not affect the runtime."}],"kind":"answer","thread_id":214064,"url":"https://discuss.pytorch.org/t/access-cudnn-convolution-grad-input-and-grad-weight-computation-function/214064","created_at":"2024-12-10T16:18:12.287000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"How to add custom operators to export_for_training?\n\nI am interested in customizing the new torch.export.export_for_training with additional custom operators to add on to the ATen opset.\n\nThe docstring indicates that this may be possible https://github.com/pytorch/pytorch/blob/main/torch/export/__init__.py#L83:\n\"The traced graph (1) produces normalized operators in the all ATen operator set (as well as any user-specified custom operators)\"\n\nI have been unable to locate documentation or examples to show how to add my custom operation to the tracing, but am eager to learn more.\n\nAlso apologies if I have miscategorized this to torch.compile. I think my question is also relevant to the new pt2e quantization approach."},{"role":"assistant","content":"[This tutorial](https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html) might be a good starter explaining different paths to add custom operators (the first link shows how to add custom ops for `torch.compile` and `torch.export`)."}],"kind":"answer","thread_id":214077,"url":"https://discuss.pytorch.org/t/how-to-add-custom-operators-to-export-for-training/214077","created_at":"2024-12-10T22:40:35.173000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Dtype different for eval and train loop with mixed prescison\n\nI just came across a curious behaviour when using mixed-precision with HuggingFace (SFTTrainer and PEFT) when training Mistral-7b.\n\nThe embeddings and layer norms are kept in full precision and therefore the hidden states get silently casted in float32. In their modeling script they therefore cast the states back to half precsion [here](https://github.com/huggingface/transformers/blob/main/src/transformers/models/mistral/modeling_mistral.py#L339). I am usually training in bfloat16. However, in the eval loop the precision is suddenly casted to float16.\n\nWith autocast enabled they call `torch.get_autocast_gpu_dtype()`. Now to my question:\n\nWhat exactly does `torch.get_autocast_gpu_dtype()` do or how does it infer the dtype? I have checked and it returns bfloat16 in the training loop and float16 during eval.\n\n Thanks for your help!"},{"role":"assistant","content":"The return value for the default `autocast` dtype depends on the device and won't change in the eval loop as seen here:\n```python\nprint(torch.get_autocast_dtype(\"cpu\"))\n# torch.bfloat16\nprint(torch.get_autocast_dtype(\"cuda\"))\n# torch.float16\n\nprint(torch.get_autocast_gpu_dtype())\n# DeprecationWarning: torch.get_autocast_gpu_dtype() is deprecated. Please use torch.get_autocast_dtype('cuda') instead.\n# torch.float16\n\nwith torch.no_grad():\n print(torch.get_autocast_dtype(\"cpu\"))\n # torch.bfloat16\n print(torch.get_autocast_dtype(\"cuda\"))\n # torch.float16\n\n print(torch.get_autocast_gpu_dtype())\n # DeprecationWarning: torch.get_autocast_gpu_dtype() is deprecated. Please use torch.get_autocast_dtype('cuda') instead.\n # torch.float16\n\nclass MyModel(nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self, x):\n print(torch.get_autocast_dtype(\"cpu\"))\n # torch.bfloat16\n print(torch.get_autocast_dtype(\"cuda\"))\n # torch.float16\n\n print(torch.get_autocast_gpu_dtype())\n # DeprecationWarning: torch.get_autocast_gpu_dtype() is deprecated. Please use torch.get_autocast_dtype('cuda') instead.\n # torch.float16\n return x\n\nmodel = MyModel()\nx = torch.randn(1, 1)\nout = model(x)\n# torch.bfloat16\n# torch.float16\n# torch.float16\n\nmodel.eval()\nout = model(x)\n# torch.bfloat16\n# torch.float16\n# torch.float16\n\nwith torch.no_grad():\n out = model(x)\n # torch.bfloat16\n # torch.float16\n # torch.float16\n```"},{"role":"user","content":"Interesting.\n\nThese are the warnings that i get. The first one is when i enter the training loop and the second one is the eval.\n```\n[2024-12-11 15:34:08,308][transformers.models.mistral.modeling_mistral][328][WARNING]: The input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in torch.bfloat16.\n{'loss': 3.8342, 'grad_norm': 34.91254425048828, 'learning_rate': 2.5e-06, 'epoch': 0.01} \n[2024-12-11 15:34:35,316][transformers.models.mistral.modeling_mistral][328][WARNING]: The input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in torch.float16.\n```\n\nand they stem from this part of the modeling script\n```\n input_dtype = query_states.dtype\n if input_dtype == torch.float32:\n if torch.is_autocast_enabled():\n target_dtype = torch.get_autocast_gpu_dtype()\n # Handle the case where the model is quantized\n elif hasattr(self.config, \"_pre_quantization_dtype\"):\n target_dtype = self.config._pre_quantization_dtype\n else:\n target_dtype = self.q_proj.weight.dtype\n\n logger.warning_once(\n f\"The input hidden states seems to be silently casted in float32, this might be related to\"\n f\" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in\"\n f\" {target_dtype}.\"\n )\n```\n\nSo `torch.get_autocast_gpu_dtype()` should always return `torch.float16`?\n\nI think I know now what is happening.\n\nFor training the autocast context is explicitly set to `bfloat16`. However, in my custom eval loop\nI only used `torch.amp.autocast('cuda')`. Am I correct in my assumption that therefore `float16` is used since it is the default for `torch.get_autocast_dtype(\"cuda\")` ?"},{"role":"assistant","content":"Yes, if you don't specify the `dtype` in `autocast` the default will be used:\n```python\nwith torch.autocast(device_type=\"cuda\"):\n print(torch.get_autocast_dtype(\"cpu\"))\n print(torch.get_autocast_dtype(\"cuda\"))\n# torch.bfloat16\n# torch.float16\n\nwith torch.autocast(device_type=\"cuda\", dtype=torch.bfloat16):\n print(torch.get_autocast_dtype(\"cpu\"))\n print(torch.get_autocast_dtype(\"cuda\"))\n# torch.bfloat16\n# torch.bfloat16\n```"}],"kind":"answer","thread_id":214095,"url":"https://discuss.pytorch.org/t/dtype-different-for-eval-and-train-loop-with-mixed-prescison/214095","created_at":"2024-12-11T09:51:59.380000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Pytorch support SM_87 cuda architecture\n\nCan anyone kindly help me download PyTorch, which supports sm_87 on aarch64? Right now, I am using the version below.\n\n>>> import torch\n>>> print(torch.version.cuda)\n12.2\n>>> print(torch.cuda.get_arch_list()) \n['sm_50', 'sm_80', 'sm_86', 'sm_89', 'sm_90', 'sm_90a']"},{"role":"assistant","content":"Check [this post](https://discuss.pytorch.org/t/cuda-and-pytorch/209517/2?u=ptrblck)."},{"role":"user","content":"Hi, i tried that and having issue. I have RHEL 9.4\n\n(myenv) [yajuvendra@llmhost pytorch_wheel]$ python -m pip install torch-2.3.0-cp310-cp310-linux_aarch64.whl\n\nERROR: torch-2.3.0-cp310-cp310-linux_aarch64.whl is not a supported wheel on this platform.\n\n(myenv) [yajuvendra@llmhost pytorch_wheel]$ uname -m\n\naarch64\n\n(myenv) [yajuvendra@llmhost pytorch_wheel]$ uname -a\n\nLinux llmhost 5.14.0-427.22.1.el9_4.aarch64 #1 SMP PREEMPT_DYNAMIC Mon Jun 10 15:57:50 UTC 2024 aarch64 aarch64 aarch64 GNU/Linux\n\nbr..\nYaju"},{"role":"assistant","content":"Your Python version might be different as the wheel is built for Python 3.10.\nIf you get stuck, you can use a pre-built container from [here](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/l4t-pytorch)."}],"kind":"answer","thread_id":214103,"url":"https://discuss.pytorch.org/t/pytorch-support-sm-87-cuda-architecture/214103","created_at":"2024-12-11T12:01:08.814000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Forward Pass through different modules based on input type\n\nI want to use a DeIT model with different tokenizers based on the input type. For example, if my dataset has four types of data, I want to use four different tokenizers, one for each type but one single encoder block. Each batch will have a mix of all types of data. If a sample is of type 0, the forward pass should look like tokenizer0 -> encoder -> classifier, and so on for different types. \nCode:\n```\nclass DeitWithClassifier(nn.Module):\n def __init__(self):\n super(DeitWithClassifier, self).__init__()\n self.tokenizers = {\n 0: DeiTModel.from_pretrained(\"facebook/deit-tiny-distilled-patch16-224\").embeddings,\n 1: DeiTModel.from_pretrained(\"facebook/deit-tiny-distilled-patch16-224\").embeddings, \n 2: DeiTModel.from_pretrained(\"facebook/deit-tiny-distilled-patch16-224\").embeddings, \n 3: DeiTModel.from_pretrained(\"facebook/deit-tiny-distilled-patch16-224\").embeddings, \n }\n deit_model = DeiTModel.from_pretrained(\"facebook/deit-tiny-distilled-patch16-224\")\n self.encoder = deit_model.encoder\n self.layer_norm = deit_model.layernorm\n self.pooler = deit_model.pooler\n self.projector = nn.Linear(192, 512)\n self.classifier = nn.Linear(512, 1)\n\n def forward(self, batch):\n output, embedding = [], []\n\n for t in range(len(batch['type'])):\n tokenizer = self.tokenizers[batch['type'][t]]\n\n tokenized = tokenizer(batch['pixel_values'][t].unsqueeze(0).to(device))\n encoded = self.encoder(tokenized).last_hidden_state\n normalized = self.layer_norm(encoded)\n\n emb = self.projector(normalized[0][0])\n logits = self.classifier(emb)\n\n output.append(logits)\n embedding.append(emb)\n\n output = torch.stack(output)\n embedding = torch.stack(embedding)\n\n return output, embedding\n```\nEach batch has 'type' which indicates the type of the samples and 'pixel_values'. \nThough this code works, I am not sure if the backpropogation is happening like it is supposed to. \nIs using a list in the forward pass ok? \nDoes it mess with the gradients/backpropogation? How else can I implement this?"},{"role":"assistant","content":"Yes, using a `list` to `append` activations is fine and you won't break the computation graph if you create a single tensor via `torch.cat` or `torch.stack` from this `list`. You should not create a new tensor via `torch.tensor(list_entries)` since this will detach the newly created tensor from the computation graph."}],"kind":"answer","thread_id":214110,"url":"https://discuss.pytorch.org/t/forward-pass-through-different-modules-based-on-input-type/214110","created_at":"2024-12-11T14:42:23.507000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Batch normalization - don't see all the parameters\n\nI've saved a batch normalization layer (2d) and I only see the weights and bias but not 'running_mean', nor the 'running_var'. I've used: torch.save(model.state_dict()..\n\nI may doing something funny. I'm not loading those with torch, but with regular Python code, as a dict. Is there a way to figure those out ('running_mean', nor the 'running_var') from weight and bias? I don't see them explicitly in the dictionary.\n\nWhy am I not using PyTorch to load? Don't ask, Kaggle competition limitation.\n\nOkay, it is more involved. I print to the \"standard output\" and then it goes into a Python file. Probably the issue is not PyTorch related. I'll have to check why it was not included in the output. I believe the issue as raised above (by me) can be close.\n\nHere is my code that includes the \"bug\":\n\n> my_state_dict = {\n> name: param.tolist()\n> for name, param in model.named_parameters() \n> }\n\nI'm now adding the running_mean and running_var \"manually\"."},{"role":"assistant","content":"Running stats are buffers, not parameters, which is why they are not returned via `.named_parameters()`. Use the `state_dict` directly or make sure to save `.named_buffers()` as well."}],"kind":"answer","thread_id":214192,"url":"https://discuss.pytorch.org/t/batch-normalization-dont-see-all-the-parameters/214192","created_at":"2024-12-13T11:31:33.905000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Model works fine while jit gives weird results\n\nHello everyone, I've trained a bird identification model and want to deploy it on mobile apps. So I converted it to torchscript. However, the jit model does not work correctly as the original model.\n\nHere is the [model](https://github.com/sun-jiao/MetaFGNet/releases/tag/20240824/), `model20240824.pth` is the weight dict, and `birdinfo.json` is the label map.\n\nHere is my code used for export jit ([my result](https://drive.google.com/file/d/1Vs6Q_pTGbGSzchdH5mWI1G03pkbedMcV/view?usp=drive_link)): \n\n```\nimport torch\nfrom torch import nn\nfrom torchvision.models import resnet34\n\nfrom torch.utils.mobile_optimizer import optimize_for_mobile\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nmodel = resnet34()\nmodel.fc = nn.Linear(model.fc.in_features, 11000)\nmodel.load_state_dict(torch.load('model20240824.pth'))\nmodel = model.to(device)\n\nmodel.eval()\n\nexample = torch.rand(1, 3, 224, 224)\n\ntraced_script_module = torch.jit.trace(model, example)\noptimized_traced_model = optimize_for_mobile(traced_script_module)\noptimized_traced_model._save_for_lite_interpreter(\"model20240824.pt\")\n```\n\nAnd here is my code for predict:\n\n```\nimport json\n\nimport torch\nfrom torch import nn\n\nfrom PIL import Image\nfrom torchvision.models import resnet34\nfrom torchvision.transforms import transforms\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nimage_path = \"test_images/86810585ED8E85C2CE8525BB8E17CF07.jpg\"\n\nwith open('birdinfo.json', 'r') as f:\n data = f.read()\n\nbird_info = json.loads(data)\n\ndef image_proprecess(img_path):\n img = Image.open(img_path).convert('RGB')\n data = data_transforms(img)\n data = torch.unsqueeze(data, 0)\n img_resize = img.resize((384, 384))\n return img_resize, data\n\ndata_transforms = transforms.Compose([\n transforms.Resize(224),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n# uncomment to use jit\n# model = torch.jit.load('model20240824.pt')\n\n# model = resnet34()\n# model.fc = nn.Linear(model.fc.in_features, 11000)\n# model.load_state_dict(torch.load('model20240824.pth'))\n\nmodel = model.to(device).eval()\n\nimg, data = image_proprecess(image_path)\ndata = data.to(device)\n\noutputs = model(data)\n\nprobs_full = torch.nn.functional.softmax(outputs, dim=1)\nprobs, indices = torch.topk(probs_full, k=5, dim=1)\nprobs = probs.squeeze().tolist()\n\nindices = indices.squeeze().tolist()\nindices_zh = [bird_info[indice][0] for indice in indices]\nindices_en = [bird_info[indice][1] for indice in indices]\nindices_scientific_name = [bird_info[indice][2] for indice in indices]\nprobs_round = [f'{round(prob * 100, 3)}%' for prob in probs]\n\nprint(indices)\n# print(indices_zh)\nprint(indices_en)\nprint(indices_scientific_name)\nprint(probs_round)\n```\n\ntest image:\n\n[image]\n\nresults given by the original model, the top result Oriental Magpie-Robin \\(*Copsychus saularis*\\) is correct:\n```\n[8835, 6214, 8837, 9096, 8834]\n['Oriental Magpie-Robin', 'Tropical Boubou', 'Madagascan Magpie-Robin', 'Pied Bush Chat', 'Indian Robin']\n['Copsychus saularis', 'Laniarius major', 'Copsychus albospecularis', 'Saxicola caprata', 'Copsychus fulicatus']\n['85.64%', '1.469%', '1.035%', '0.928%', '0.647%']\n```\n\nresults given by the jit:\n```\n[1190, 10226, 8901, 2395, 2498]\n['Eastern Buzzard', 'Altamira Oriole', 'Sunda Blue Flycatcher', 'Siau Scops Owl', 'Northern Hawk-Owl']\n['Buteo japonicus', 'Icterus gularis', 'Cyornis caerulatus', 'Otus siaoensis', 'Surnia ulula']\n['0.029%', '0.02%', '0.02%', '0.02%', '0.019%']\n```\n\nI am really confused. Could anyone please tell me what I did wrong? Greatly appreciate.\n\ntorch: 2.1.1 (cpu)\ntorchvision: 0.16.1\nPython 3.8.18\n\nsystem:\n```\n -` name@arch-83al \n .o+` ----------------- \n `ooo/ OS: Arch Linux x86_64 \n `+oooo: Host: 83AL XiaoXinPro 14 IRH8 \n `+oooooo: Kernel: 6.12.4-zen1-1-zen \n -+oooooo+: Uptime: 3 days, 4 hours, 48 mins \n `/:-:++oooo+: Packages: 1793 (pacman) \n `/++++/+++++++: Shell: bash 5.2.37 \n `/++++++++++++++: Resolution: 2880x1800 \n `/+++ooooooooooooo/` DE: Plasma 6.2.4 \n ./ooosssso++osssssso+` WM: kwin \n .oossssso-````/ossssss+` WM Theme: Lavanda-Sea-Light \n -osssssso. :ssssssso. Theme: [Plasma], FRESH-Blueberries [GTK2/3] \n :osssssss/ osssso+++. Icons: Fluent [Plasma], Fluent [GTK2/3] \n /ossssssss/ +ssssooo/- Terminal: pycharm-profess \n `/ossssso+/:- -:/+osssso+- CPU: 13th Gen Intel i5-13500H (16) @ 4.700GHz \n `+sso+:-` `.-/+oso: GPU: Intel Raptor Lake-P [Iris Xe Graphics] \n `++:. `-/+/ Memory: 19090MiB / 31816MiB \n .` `/\n \n \n```"},{"role":"assistant","content":"Could you compare the model accuracy in the same script where it's exported? \nIf the accuracy matches, you could check the data preprocessing pipeline in your inference script next as the difference might come from this part of your code."}],"kind":"answer","thread_id":214261,"url":"https://discuss.pytorch.org/t/model-works-fine-while-jit-gives-weird-results/214261","created_at":"2024-12-16T09:46:17.003000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Error in loading tensor/model/input to CUDA\n\nI am getting the following error: \n\n>>> import torch\n>>> torch.randn(3,3).to(\"\"cuda\")\n File \"<stdin>\", line 1\n torch.randn(3,3).to(\"\"cuda\")\n ^\nSyntaxError: unterminated string literal (detected at line 1)\n>>> torch.randn(3,3).to(\"cuda\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nRuntimeError: CUDA error: CUDA-capable device(s) is/are busy or unavailable\nCUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.\nFor debugging consider passing CUDA_LAUNCH_BLOCKING=1\nCompile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.\n\n>>> torch.cuda.is_available()\nTrue\n\nEven though torch.cuda.is_available() is true and no other processes are running in GPU as shown in nvidia-smi\n\nue Dec 17 10:07:21 2024\n+-----------------------------------------------------------------------------------------+\n| NVIDIA-SMI 550.127.05 Driver Version: 550.127.05 CUDA Version: 12.4 |\n|-----------------------------------------+------------------------+----------------------+\n| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |\n| | | MIG M. |\n|=========================================+========================+======================|\n| 0 NVIDIA A10-24Q On | 00000002:00:00.0 Off | 0 |\n| N/A N/A P8 N/A / N/A | 1MiB / 24512MiB | 0% Default |\n| | | N/A |\n+-----------------------------------------+------------------------+----------------------+\n\n+-----------------------------------------------------------------------------------------+\n| Processes: |\n| GPU GI CI PID Type Process name GPU Memory |\n| ID ID Usage |\n|=========================================================================================|\n| No running processes found |\n+-----------------------------------------------------------------------------------------+"},{"role":"assistant","content":"Your setup seems to have issues communicating with your GPU. Cou could build any CUDA Sample, execute it, and would most likely see the same issue. \nI don't know if this setups worked before or not, but you could try to e.g. reinstall the driver."}],"kind":"answer","thread_id":214301,"url":"https://discuss.pytorch.org/t/error-in-loading-tensor-model-input-to-cuda/214301","created_at":"2024-12-17T10:14:23.276000Z","tier":"silver","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"Please Help: `torchaudio` does not find the `sox` backend on macOS\n\nHello,\n\nI've been struggling with `torchaudio` since I migrated to my new macBook Pro. \n\nThe problem is the following: `torchaudio` can not initialize the `sox` backend when \n- the Python environment is managed by `uv`,\n- and I debug from PyCharm or VSCode (the two IDEs I use for Python, I did not test any other),\n- even though `sox` is installed and the scripts run perfectly from the terminal (with the environment managed by `uv`).\n\nThe issue seems related to `uv` as I don't have any problem if I manage the environment manually with `venv` and `pip`. \nMore details in [my issue on `uv` repo](https://github.com/astral-sh/uv/issues/9941).\n\nHowever, the problems seems related to my environment somehow:\n- I did not encounter the issue on my previous computer (also a macBook Pro Apple Silicon).\n- If I work in a bash session with a much simpler environment (I have a quite complicated `.zprofile` file but no `.bash_profile` or `.profile` file), the problem is even worse as it appears even in scripts launched from the terminal with the environment managed by `uv`.\n\nMy questions are the following (I tried to look at the source code but couldn't figure out the answers):\n- How does `torchaudio` links to the `sox` backend?\n- In what conditions does `torchaudio.list_audio_backends()` return an empty list even though `shutil.which(\"sox\")` returns the path to `sox` properly?\n\nThank you for your help :pray:"},{"role":"assistant","content":"I found the solution after some time digging the web.\n\nThis was indeed a problem of `LC_RPATH`. The problem disappeared when I deleted and re-installed my Python interpreters.\n\nI am not sure what happened, my guess is that my libraries paths were not setup correctly when I originally installed my Python interpreters, which resulting in missing `LC_RPATH`. \n\nSince I re-installed the Python interpreters (in my case with `uv`) with a clean and fully functional environment, everything works fine."}],"kind":"answer","thread_id":214313,"url":"https://discuss.pytorch.org/t/please-help-torchaudio-does-not-find-the-sox-backend-on-macos/214313","created_at":"2024-12-17T13:37:05.011000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ThomasHezard"]} | |
| {"messages":[{"role":"user","content":"Is it safe to assume labels will be the same for two different directories using datasets.ImageFolder\n\nI have images dataset in two different directories `Train_images` and `Test_images`. Both directories are organized the same way where images are inside another directory with their associated label. \n\nI am loading the images into `train_dataset = datasets.ImageFolder(root='path/to/dataset/Train_images')` and `test_dataset = datasets.ImageFolder(root='path/to/dataset/Test_images')`. I wanted to know if ImageFolder sort the directories before loading them for consistency or does some smart way for making sure that labels will be the same from the two different folders. If this is not the case, would you help me understand how the function `ImageFolder` work."},{"role":"assistant","content":"`ImageFolder` will call into [`find_classes`](https://github.com/pytorch/vision/blob/f7b1cfa8f7e10e0c157da6e55dc6f0237397faec/torchvision/datasets/folder.py#L36-L46) to create the class labels and will sort the folders. On the same system and OS you should see the same classes. However, I think I've seen differences in sorting between e.g. Linux and Windows, but don't know if this was an artifact of older Python versions."}],"kind":"answer","thread_id":214336,"url":"https://discuss.pytorch.org/t/is-it-safe-to-assume-labels-will-be-the-same-for-two-different-directories-using-datasets-imagefolder/214336","created_at":"2024-12-17T21:53:56.157000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"`num_features` parameter of `nn.InstanceNorm2d` does not change results\n\nI was wondering what would happen if the `num_features` specified for `nn.InstanceNorm2d` mismatch that of the number of features in the input and thus decided to test it. I learned that the `num_features` parameter does not really matter as the results remain the same.\n\nWhy doesn't `num_features` matter? If it doesn't matter, why is the parameter not optional? (I know there is a `nn.LazyInstanceNorm2d` which dynamically detect the input feature size.)\n\nThanks for your insight,\n\n### Minimal working code:\n```python\nimport torch\nimport torch.nn as nn\nimport sys\n\nprint(f\"Python version: {sys.version}; Torch version: {torch.__version__}\")\n\ninput = torch.randint(low=0, high=255, size=(5, 3, 256, 256)).double()\noutput_base = nn.InstanceNorm2d(num_features=1)(input)\n\nfor i in range(2, 20):\n IN_layer = nn.InstanceNorm2d(num_features=i)\n \n output = IN_layer(input)\n result_check_same = (output_base == output).all()\n \n print(i, result_check_same)\n\n if not result_check_same:\n break\n```\n\n### Output:\n```bash\nPython version: 3.10.8 | packaged by conda-forge | (main, Nov 22 2022, 08:25:13) [Clang 14.0.6 ]; Torch version: 2.3.0.post100\n2 tensor(True)\n3 tensor(True)\n4 tensor(True)\n5 tensor(True)\n6 tensor(True)\n7 tensor(True)\n8 tensor(True)\n9 tensor(True)\n10 tensor(True)\n11 tensor(True)\n12 tensor(True)\n13 tensor(True)\n14 tensor(True)\n15 tensor(True)\n16 tensor(True)\n17 tensor(True)\n18 tensor(True)\n19 tensor(True)\n```"},{"role":"assistant","content":"A warning will be raised from [here](https://github.com/pytorch/pytorch/blob/a8ac3a6b20b154e661e80ef930c6b0c563f3bb2d/torch/nn/modules/instancenorm.py#L108-L119) since you are using the default `affine=False` argument. If you use affine parameters, the code will fail with a shape mismatch."}],"kind":"answer","thread_id":214610,"url":"https://discuss.pytorch.org/t/num-features-parameter-of-nn-instancenorm2d-does-not-change-results/214610","created_at":"2024-12-24T23:59:04.629000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"]} | |
| {"messages":[{"role":"user","content":"AttributeError: module 'torch' has no attribute '_six'\n\nHello! I issued this command to install torch on a Conda environment:\n`pip install torch==2.5.0 torchvision==0.20.0 torchaudio==2.5.0` (I also tried the equivalent `conda install pytorch...` command, but got the same result). I even tried to install it in a Docker container, but I'm still encountering the same issue!\n\nif I do:\n```\nfrom torch.utils.data import DataLoader\ndataset = datasets.ImageFolder(root=dataset_path, transform=transform)\n```\n\nWhat I will get out is going to be: `AttributeError: module 'torch' has no attribute '_six'`. I really can't figure this issue out. I tried downgrading Torch and TorchVision, but nothing seemed to work. Do you know how to fix this?\n\nThanks in advance :slight_smile:"},{"role":"assistant","content":"Turns out there's a better way to load the model from the hub, which is `model = models.mobilenet_v2(pretrained=True)`. This fixed the last error (the nms one).\n\nAs far as the first error is concerned, I'm not sure of what happened! I'm now running everything in docker using the `pytorch/pytorch:2.5.1-cuda12.4-cudnn9-devel` and the error is not showing up anymore. I read that even doing a `pip install torch` can mess up with cache and other things, so I guess nothing should be issued on this container, at least as far as torch & co are concerned."}],"kind":"answer","thread_id":214757,"url":"https://discuss.pytorch.org/t/attributeerror-module-torch-has-no-attribute-six/214757","created_at":"2024-12-29T17:34:50.849000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[10],"answer_authors":["Alberto_Zurini"]} | |