id
stringlengths
3
8
text
stringlengths
1
115k
st48468
mrshenli: init_process_group Thank you very much for your reply. I checked by printing the NCCL_SOCKET_IFNAME in my python script like this: os.environ.setdefault("NCCL_DEBUG", "INFO") os.environ.setdefault("NCCL_IB_DISABLE", "1") print("Setting NCCL_SOCKET_IFNAME") os.environ.setdefault("NCCL_SOCKET_IFNAME", "^lo,docker") print("Finished NCCL_SOCKET_IFNAME") print(os.environ.get("NCCL_SOCKET_IFNAME")) # See: # https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group os.environ.setdefault("NCCL_BLOCKING_WAIT", "1") print("self.dist_backend:",self.dist_backend) print("self.dist_init_method:", self.dist_init_method) print("self.dist_world_size:",self.dist_world_size) print("self.dist_rank:",self.dist_rank) torch.distributed.init_process_group( backend=self.dist_backend, init_method=self.dist_init_method, world_size=self.dist_world_size, rank=self.dist_rank, ) the output of one node is like this: Setting NCCL_SOCKET_IFNAME Finished NCCL_SOCKET_IFNAME ^lo,docker self.dist_backend: nccl self.dist_init_method: file:///home/storage15/huangying/tools/espnet/egs2/voxforge/asr1/vox.init self.dist_world_size: 3 self.dist_rank: 2 MASTER_ADDR : None MASTER_PORT : None Besides , I use ifconfig to check the network of one of the failed node: eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 10.38.10.174 netmask 255.255.255.0 broadcast 10.38.10.255 inet6 fe80::9a03:9bff:fe0e:ff72 prefixlen 64 scopeid 0x20 ether 98:03:9b:0e:ff:72 txqueuelen 1000 (Ethernet) RX packets 265553414516 bytes 374221992683088 (340.3 TiB) RX errors 0 dropped 827204 overruns 0 frame 0 TX packets 101116217165 bytes 122158006104703 (111.1 TiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 eth1: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500 ether 98:03:9b:0e:ff:73 txqueuelen 1000 (Ethernet) RX packets 0 bytes 0 (0.0 B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 0 bytes 0 (0.0 B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536 inet 127.0.0.1 netmask 255.0.0.0 inet6 ::1 prefixlen 128 scopeid 0x10 loop txqueuelen 0 (Local Loopback) RX packets 17752724 bytes 17788869931 (16.5 GiB) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 17752724 bytes 17788869931 (16.5 GiB) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
st48469
Thanks for sharing more details. Three questions: Since you are using file:///home/storage15/huangying/tools/espnet/egs2/voxforge/asr1/vox.init as the init_method, I assume all ranks can access the same file to rendezvous? I haven’t tried this within a docker. What is the reason for setting it to ^lo,docker instead of just lo? And does it work if you set it to eth0 or eth1? What does it return when you run the following command? getent hosts `hostname`
st48470
I have two matrices of sizes (32, 512, 7,7) and (32, 512) respectively, where 32 is the batch size and 512 is the channel size. Let us call them A and B. Now what I need to do is this: for i in range(batch_size): for j in range(channel_size): A[i,j,:,:]=A[i,j,:,:]*B[i,j] In other words, I want to have each elements of the 7x7 matrix (of i th batch and j th channel) multiplied by the corresponding value from B matrix’s corresponding scalar for i th batch and j th channel number. Using for loops becomes higly inefficient when I have to increasing batch size. Is there any other way of doing the same? Any help will be appreciated.
st48471
Broadcasting: A *= B[:, :, None, None] Note that this (like your version) changes A in place, but the usual * will work similarly. Best regards Thomas
st48472
Thanks @tom for you reply. Is there be any other solution to this problem? I have shown a simple example here. My actual implementation is very much similar, except it requires out of place implementation (C=A * B[:, :, None, None]). As I have seen that the out place implementation of the solution given by @tom, in my case is highly memory inefficient for a batch size of 64. The error messege is: RuntimeError: CUDA out of memory. Tried to allocate 256.00 GiB (GPU 0; 23.65 GiB total capacity; 2.12 GiB already allocated; 20.16 GiB free; 2.20 GiB reserved in total by PyTorch)
st48473
File “C:/Users/CT/Desktop/TIAN/VasNet-pytorch-code/src/train-new_dataloader.py”, line 2, in import torch ModuleNotFoundError: No module named ‘torch’ !
st48474
Most likely you are starting spyder in another environment than the one which is used in your terminal. Make sure the env is correctly activated before starting the IDE.
st48475
Thank you for your reply! It seemed that I didn’t run the spyder from the ‘pytorch_gpu’ in the Anaconda Navigator. Now i am installing the spyder in pytorch_gpu.@2FV}MMO(}QAOE%2~FWTOQB1920×1048 112 KB
st48476
i want to try the model on windows which is not supported to the distrubution. And i change the net = torch.nn.SyncBatchNorm.convert_sync_batchnorm(net) into net = torch.nn.BatchNorm2d(net) but i got a error which is “TypeError: new(): data must be a sequence (got DeepV3PlusHANet)”. And what should i do to run the code on windows, and how to change SyncBatchNorm with BatchNorm2d?
st48477
If you don’t want to use SyncBatchNorm you could just remove the convert_sync_batchnorm call and keep the original nn.BatchNorm*D layers. From the docs 14: Helper function to convert all BatchNorm*D layers in the model to torch.nn.SyncBatchNorm 14 layers.
st48478
If you see other usages of any SyncBatchNorm calls, I would remove them as well. Yes, convert_sync_batchnorm converts the nn.BatchNorm*D layers to their sync-equivalent. If you don’t want to use this, just keep the model as it is without calling any SyncBatchNorm functions and it will use the standard nn.BatchNorm*D layers.
st48479
it sitll don’t work, i got the same error after removing the convert_sync_batchnorm.
st48480
Could you post an executable code snippet, so that we could have a look at this error?
st48481
Sorry the code is complex and i couldn’t give you a code snippet. You can get the rar file from this https://drive.google.com/file/d/1biA7CJnPibJAKS7Liw60JPuKFqpV9il8/view?usp=sharing 2, just run the train.py and may be you can get this error. i use windows 10 and pytorch 1.4.0. Thank you so much.
st48482
Could you try to slim down the code and post it here, please? Alternatively, could you create a gist on GitHub and post the link here?
st48483
I want to know what are wrong in the plotted diagrams.They are train loss and validation loss.If it is informal,please answer how can I solve the problem.Thanks in advance!![loss|640x476](upload://rqPczFdZ8naAVCLpj9kTtKB0fS t.png)
st48484
The figure shows noisy losses and indicates that your model is not training. Generally, if you are stuck and your training isn’t working properly, I would recommend to start by overfitting a small dataset, e.g. just 10 samples, and make sure it’s working fine by playing around with hyperparameters.
st48485
Please explain that model is not training.How can I overfit small dataset.Thanks a lot in advance!
st48486
The model is not training since the graph shows the loss is not decreasing, and the goal of a ML model is to minimize the loss between the actual and predicted values. If the model were training correctly, you would see a decrease in the loss as the epochs go up (it may still be a bit noisy, but it will be a notable decrease). Onto the overfitting part, say you have 10000 samples. Use only 100 of them and train your model on that subset. Play around with number of hidden layers, number of neurons in each layer, different optimizers (and their parameters) until you can achieve near perfect accuracy. The reply to this question 2 gives a comprehensive in-depth explanation.
st48487
If I use deep learning and samples are only about 2000,what parameters should be played.Does the figure improve slightly or not.Thanks a lot in advance!
st48488
No, your model still isn’t learning. The loss is still extremely noisy. The parameters that you can look into are: Number of Hidden Layers. Number of Neurons in the Hidden Layers. Batch Sizes. Add Dropout Layers in the Network Optimizers (and their parameters like learn rate, weight decay, etc). Do all of the above only on the small subset of data. The goal is to overfit the model on this tiny batch. Losses1465×2507 190 KB I’ve attached an image from one of my projects. As you can see, it is still noisy, but there is a definite decrease. This is the kind of curve you should expect.
st48489
I would like to request for any examples of hyperparameter tuning using PyTorch and ray tune with respect to validation loss to avoid over fitting my model. Any link or example would work for me, thanks in advance.
st48490
Hi @nivesh_gadipudi, here are a couple examples for using Ray Tune with Pytorch 2. An easy way to prevent overfitting is simply to return “done=True” when validation losses begins to diverge. tune.report(done=True, ...) # or if using class API: def step(self): ... return {"done": True, ...} Hope that helps!
st48491
I am trying to build a test .cpp in CLION as in the tutorial https://pytorch.org/cppdocs/installing.html#minimal-example I am using Cuda version 11.1 the nightly c++ release of pytorch (the one released today) CUDNN version 8.0.4 for Cuda 11.1 The cygwin 64 compiler After reloading the CMakeLists.txt file I get the message: Caffe2: CUDA cannot be found. Depending on whether you are building Caffe2 or a Caffe2 dependent library, the next warning / error will give you more info. Where in cuda.cmake there is a call to the function find_package(CUDA). I have set my environment variables to be: CUDA_PATH = C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.1 as well as added Toolkit\CUDA\v11.1\libnvvp;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.1\bin; to my path variable Any insights to how to solve this problem appreciated.
st48492
As the doc says, " If your network has multiple losses, you must call scaler.scale on each of them individually." And this it looks like: scaler = torch.cuda.amp.GradScaler() with autocast(): loss0 = some_loss loss1 = another_loss scaler.scale(loss0).backward(retain_graph=True) scaler.scale(loss1).backward() It is relatively inconvenient especially when we want to have many weighted losses. What if we just sum all the losses to one and backward once? It looks like this: scaler = torch.cuda.amp.GradScaler() with autocast(): loss0 = some_loss loss1 = another_loss loss_all = w0 * loss0 + w1 * loss1 scaler.scale(loss_all).backward() Is this kind of implementation correct?
st48493
I have the same problem here, this use case is not very well explained in the docs. Can anyone provide an explanation?
st48494
Zequn_Qin: scaler = torch.cuda.amp.GradScaler() with autocast(): loss0 = some_loss loss1 = another_loss loss_all = w0 * loss0 + w1 * loss1 scaler.scale(loss_all).backward() yes that would work, and you could do the same without amp. There’s no need for retain_graph=True on the first backward unless the two losses share backward graph. scaler.scale(loss0).backward(retain_graph=True) in the example 7 only uses retain_graph=True because the two losses share some backward graph, it has nothing to do with amp.
st48495
Hey, I never got a reply to my other question. I’m now at a point where things are working well on 1 GPU and I want to run on a bigger model. Can someone please help me get to the bottom of this Multi GPU Hook not correctly filling buffer 5
st48496
Hi all, I wanted to check the validity of an idea. I was thinking of having integrated support of ETL in PyTorch. Is this feasible ? Wanted to know if someone has done anything around this and if not, any particular reasons for not doing so ?
st48497
I’m not sure if ETL stand for “Extract, Transform, Load”, but if so how would PyTorch come into play combining data from multiple systems into a single database? Could you explain your idea a bit and correct me, if ETL stand for something else?
st48498
What I meant was that would it make sense to support different database bindings for Extract-Transform-Load, instead of having multiple frameworks like Spark, Hadoop etc. ?
st48499
I’m still unsure, if this is a PyTorch-specific question. Are you referring to some Spark/Hadoop-to-PyTorch bindings?
st48500
Hello everyone, I am doing reinforcement learning using a policy gradient algo. However I have impossible actions, therefore I modify the logits of my impossible actions before using categorical. When applying this mask I use a torch.where. I have profiled the code and one of the biggest bottlenecks comes from this. Do you have any optimization to do to make it faster? Best regards import torch from torch.distributions import Categorical class CategoricalMasked(Categorical): LOGIT_INF_VALUE = -1E10 def __init__(self, mask, logits): # dtype of mask torch.float32 # size example logit and mask (4096, 5) self.mask = mask self.mask = torch.gt(self.mask,0.5) logits = torch.where(self.mask, logits, torch.ones_like(logits) * torch.tensor(CategoricalMasked.LOGIT_INF_VALUE, device=logits.device) super(CategoricalMasked, self).__init__(None, logits, None) def entropy(self): p_log_p = self.logits * self.probs p_log_p = torch.where(self.mask, p_log_p, torch.tensor(0., device=self.logits.device) return -p_log_p.sum(-1)
st48501
Hi, If you run on GPU, the following might be faster: self.mask = self.mask.to(logits.dtype) logits = self.mask * logits + (1 - self.mask) * CategoricalMasked.LOGIT_INF_VALUE
st48502
albanD: logits = self.mask * logits + (1 - self.mask) * CategoricalMasked.LOGIT_INF_VALUE that shouldn’t be faster than: torch.lerp(LOGIT_INF_TENSOR, logits, self.mask) AdilZouitine: p_log_p = torch.where(self.mask, p_log_p, torch.tensor(0., device=self.logits.device) p_log_p *= self.mask
st48503
Thanks II’l try it ! Just one question why where is slower than lerp ? @googlebot
st48504
lerp should just fuse x1*w+x2*(1-w) expressions, like the one @albanD suggested, avoiding memory allocations I don’t know whether this or torch.where is faster. The latter could be slower if it screws memory access patterns on cuda (but this is avoidable, I’d think)
st48505
Ho I don’t have the answer for which one is faster. But I know that point-wise addition/multiplication kernels are heavily optimized and being worked on. While the where kernel is not scrutinized as much. But curious to know which one is faster actually compared to Alex’s proposal as well.
st48506
Hello, I am currently debugging an error which causes my program to crash when resuming a training. Resuming the scheduler causes an out of memory error and I might create a seperate thread about this problem. Currently I am investigating my scheduler and I am wondering why the size of the saved scheduler.state_dict() is so big. I use an SGD optimizer and the OneCycleLR scheduler. optimizer = torch.optim.SGD(objective_params, lr=lr, momentum=mo, weight_decay=wd) scheduler = OneCycleLR(optimizer, max_lr=lr, total_steps=conf.max_iter) Now I immediatly save the state_dicts of the model, the optimizer and the scheduler. torch.save(model.state_dict(), modelpath) torch.save(scheduler.state_dict(), schedpath") torch.save(optimizer.state_dict(), optpath) The files have the following sizes: model: 852,7 MiB optimizer: 1,9 KiB scheduler: 851,9 MiB Then I start the training and because I use mixed precision it takes some stepts until the optimizer actually performs the step() function. After it has the optimizer has stepped the sizes of the saved state dicts is the following: model: 852,7 MiB optimizer: 843,9 MiB scheduler: 1,7 GiB Why the size of the scheduler so enourmous? It makes sense that SGD uses the same amount of memory as the model because every weight has a momentum value but I do not understand why the scheduler takes up so much memory. Printing out the scheduler state_dict does not answer my question as it is basically empty: {'total_steps': 200000, 'step_size_up': 59999.0, 'step_size_down': 140000.0, 'anneal_func': <bound method OneCycleLR._annealing_cos of <lib.lr.OneCycleLR object at 0x7fd8a1061390>>, 'cycle_momentum': True, 'use_beta1': False, 'base_lrs': [4e-05], 'last_epoch': 10, '_step_count': 10} Greetings Rupert
st48507
What I would like to do if predict future actions of pedestrians over time. I am using the Keypoint R-CNN model to generate the keypoints, which I will be using to create a skeleton. Based on the evolution of the skeleton over time, I would like to predict what they may do after a number of frames. Where I am stuck is how to use the images and keypoints together to do this. How would I feed a model the images and keypoints in a way that it will learn the evolution of skeleton over time? I believe I would be using 3D conv nets, but I am unsure of what the best to feed the data. Do I extract the features of a number of concatenated images and fuse those features with concatenated keypoints for those images and then feed that into a classifier for learning the actions? Can I used torchvision.ops.MultiScaleRoIAlign to downsample the images with respect to predicted keypoints (I hope that is how pooling using MultiScaleRoIAlign works?) Thanks in advance.
st48508
So, I installed pytorch using the following command: conda install pytorch-cpu==1.0.0 torchvision-cpu==0.2.1 cpuonly -c pytorch The following works: import torch x = torch.rand(5, 3) print(x) But import torchvision fails with the error ImportError: libcudart.so.10.0: cannot open shared object file: No such file or directory What am I missing?
st48509
Could you post the log from the installation please? Also, PyTorch 1.0.0 and torchvision 0.2.1 are quite old by now so you might want to install the latest stable releases.
st48510
Okay, so I created a new conda environment like this: conda create -n dl1 python=3.6 Then, I activated the environment created above and ran the command to install the latest version: conda install pytorch torchvision cpuonly -c pytorch After that, at the python prompt: >>> import torchvision Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/iseadmin/.local/lib/python3.6/site-packages/torchvision/__init__.py", line 1, in <module> from torchvision import models File "/home/iseadmin/.local/lib/python3.6/site-packages/torchvision/models/__init__.py", line 11, in <module> from . import detection File "/home/iseadmin/.local/lib/python3.6/site-packages/torchvision/models/detection/__init__.py", line 1, in <module> from .faster_rcnn import * File "/home/iseadmin/.local/lib/python3.6/site-packages/torchvision/models/detection/faster_rcnn.py", line 7, in <module> from torchvision.ops import misc as misc_nn_ops File "/home/iseadmin/.local/lib/python3.6/site-packages/torchvision/ops/__init__.py", line 1, in <module> from .boxes import nms, box_iou File "/home/iseadmin/.local/lib/python3.6/site-packages/torchvision/ops/boxes.py", line 2, in <module> from torchvision import _C ImportError: libcudart.so.10.0: cannot open shared object file: No such file or directory
st48511
Could you print the installation log you are getting, please? I just installed it locally and can see that the CPU version is being installed.
st48512
Here it is (dl1) iseadmin@iseadmin:~/Downloads/trucks/course-v3/nbs/dl1$ conda install pytorch torchvision cpuonly -c pytorch Collecting package metadata (current_repodata.json): done Solving environment: done ==> WARNING: A newer version of conda exists. <== current version: 4.7.11 latest version: 4.8.2 Please update conda by running $ conda update -n base conda ## Package Plan ## environment location: /home/iseadmin/anaconda3/envs/dl1 added / updated specs: - cpuonly - pytorch - torchvision The following NEW packages will be INSTALLED: cpuonly pytorch/noarch::cpuonly-1.0-0 freetype conda-forge/linux-64::freetype-2.10.0-he983fc9_1 intel-openmp pkgs/main/linux-64::intel-openmp-2020.0-166 jpeg conda-forge/linux-64::jpeg-9c-h14c3975_1001 libblas conda-forge/linux-64::libblas-3.8.0-14_openblas libcblas conda-forge/linux-64::libcblas-3.8.0-14_openblas libgfortran-ng conda-forge/linux-64::libgfortran-ng-7.3.0-hdf63c60_5 liblapack conda-forge/linux-64::liblapack-3.8.0-14_openblas libopenblas conda-forge/linux-64::libopenblas-0.3.7-h5ec1e0e_6 libpng conda-forge/linux-64::libpng-1.6.37-hed695b0_0 libtiff conda-forge/linux-64::libtiff-4.1.0-hc3755c2_3 lz4-c conda-forge/linux-64::lz4-c-1.8.3-he1b5a44_1001 mkl pkgs/main/linux-64::mkl-2020.0-166 ninja conda-forge/linux-64::ninja-1.10.0-hc9558a2_0 numpy conda-forge/linux-64::numpy-1.18.1-py36h95a1406_0 olefile conda-forge/noarch::olefile-0.46-py_0 pillow conda-forge/linux-64::pillow-7.0.0-py36hefe7db6_0 pytorch pytorch/linux-64::pytorch-1.4.0-py3.6_cpu_0 six conda-forge/linux-64::six-1.14.0-py36_0 torchvision pytorch/linux-64::torchvision-0.5.0-py36_cpu zstd conda-forge/linux-64::zstd-1.4.4-h3b9ef0a_1 Proceed ([y]/n)? y Preparing transaction: done Verifying transaction: done Executing transaction: done
st48513
Hello Vishal, I believe that Python Prompt in which you tried to run the command import torchvision is NOT inside the conda environment. You see if it was inside the conda environment it was supposed to look in /home/iseadmin/anaconda3/envs/dl1/lib/python3.6/site-packages/torchvision So run the following commands in a sequence and let me know the result: conda activate dl1 python3 and then try to import Let me know if it works or not.
st48514
Do you have any other torchvision or PyTorch installations on this machine and environment? I just tried to reproduce the import issue by installing PyTorch 1.7.0 and torchvision==0.8.1 as the CPU-only packages in a new conda env via: conda install pytorch torchvision torchaudio cpuonly -c pytorch and I can import torchvision: >>> import torch >>> torch.__version__ '1.7.0' >>> import torchvision >>> torchvision.__version__ '0.8.1'
st48515
Yes, that was the problem, I thought conda prioritizes the environment packages over the local ones. Seems that’s not the case, so I just uninstall the local torchvision and it worked!. Thanks!
st48516
I am relative new to pytorch. After doing a pretty exhaustive search online, I still couldn’t obtain the operation I want. My question is How do do matrix multiplication (matmal) along certain axis? For example, if I want to multiply a vector by a matrix, that would just be the following: a = torch.rand(3,5) b = torch.rand(3) torch.matmul(b,a) One can interpret this as each element in b scale each row of a, and summing those scaled row together. What if we have the dimension of a and b as following: a = torch.rand(3,5,10) b = torch.rand(3,10) and we want to do matrix multiplication along the first axis, basically, here’s what I want to do in a for loop form: product = [] for i in range(10): a_i = a[:,:,i] b_i = b[:,i] a_i_mul_b_i = torch.matmul(b_i,a_i) product.append(a_i_mul_b_i) Although product is not a tensor but a list of tensor, but if we ignore the datatype, this is the end result I want.
st48517
Solved by KFrank in post #2 Hello Zeyuyun! The general-purpose tool for taking a product of (contracting) multiple tensors along various axes is torch.einsum() (named after “Einstein summation”). (You can also fiddle with the dimensions to get them to line up as needed and use matmul() or bmm().) Here is a script that c…
st48518
Hello Zeyuyun! zeyuyun1: How do do matrix multiplication (matmal) along certain axis? … here’s what I want to do in a for loop form: product = [] for i in range(10): a_i = a[:,:,i] b_i = b[:,i] a_i_mul_b_i = torch.matmul(b_i,a_i) product.append(a_i_mul_b_i) The general-purpose tool for taking a product of (contracting) multiple tensors along various axes is torch.einsum() 100 (named after “Einstein summation”). (You can also fiddle with the dimensions to get them to line up as needed and use matmul() or bmm().) Here is a script that compares your loop code to einsum() (as well as to bmm() and matmul()): import torch torch.__version__ torch.random.manual_seed (2020) a = torch.rand(3,5,10) b = torch.rand(3,10) product = [] for i in range(10): a_i = a[:,:,i] b_i = b[:,i] a_i_mul_b_i = torch.matmul(b_i,a_i) product.append(a_i_mul_b_i) # make product a tensor product = torch.stack (product) einsum_prod = torch.einsum ('ijk, ik -> kj', a, b) print ('check einsum_prod ...\n', torch.eq (einsum_prod, product).all()) matmul_prod = torch.matmul (b.unsqueeze (1).transpose (0, 2), a.permute (2, 0, 1)).squeeze() print ('check matmul_prod ...\n', torch.eq (matmul_prod, product).all()) bmm_prod = torch.bmm (b.unsqueeze (1).transpose (0, 2), a.permute (2, 0, 1)).squeeze() print ('check bmm_prod ...\n', torch.eq (bmm_prod, product).all()) print ('product = ...\n', product) Here is its output >>> import torch >>> torch.__version__ '1.6.0' >>> torch.random.manual_seed (2020) <torch._C.Generator object at 0x7f8997a636f0> >>> >>> a = torch.rand(3,5,10) >>> b = torch.rand(3,10) >>> >>> product = [] >>> for i in range(10): ... a_i = a[:,:,i] ... b_i = b[:,i] ... a_i_mul_b_i = torch.matmul(b_i,a_i) ... product.append(a_i_mul_b_i) ... >>> # make product a tensor >>> product = torch.stack (product) >>> >>> einsum_prod = torch.einsum ('ijk, ik -> kj', a, b) >>> print ('check einsum_prod ...\n', torch.eq (einsum_prod, product).all()) check einsum_prod ... tensor(True) >>> >>> matmul_prod = torch.matmul (b.unsqueeze (1).transpose (0, 2), a.permute (2, 0, 1)).squeeze() >>> print ('check matmul_prod ...\n', torch.eq (matmul_prod, product).all()) check matmul_prod ... tensor(True) >>> >>> bmm_prod = torch.bmm (b.unsqueeze (1).transpose (0, 2), a.permute (2, 0, 1)).squeeze() >>> print ('check bmm_prod ...\n', torch.eq (bmm_prod, product).all()) check bmm_prod ... tensor(True) >>> >>> print ('product = ...\n', product) product = ... tensor([[0.8785, 0.5736, 0.3109, 0.5423, 0.6269], [0.7494, 1.4107, 0.9018, 1.1483, 1.2441], [0.9368, 0.9044, 0.9225, 0.9634, 0.1672], [0.1231, 0.4003, 0.4123, 0.1015, 0.4601], [0.9209, 1.1959, 0.5452, 1.0301, 0.8842], [0.2887, 1.1165, 0.9888, 0.8110, 0.4526], [0.9565, 1.2474, 0.1234, 1.6425, 0.9914], [1.1996, 0.8205, 1.0448, 1.3298, 1.0197], [0.3437, 0.3698, 0.4044, 0.4140, 0.8048], [0.7642, 1.4165, 0.7622, 0.6675, 1.2127]]) >>> Best. K. Frank
st48519
Thank you so much!! That’s exactly what I want. I think the key I am missing is “unsqueeze”, but eigenstein summation is another really good interpretation!
st48520
on github it seems the latest commit supports image of type tensor for rotation. also on documentation. still when i run the command i get an error saying image must be PIL object. i can bypass it by simply transforming to PIL but it causes trouble debugging another error occuring further down the chain. so do i need to switch to nightly in order to get the rotate function to work with tensors?
st48521
Solved by Nikronic in post #2 Hi, Transform on tensors has been added to PyTorch 1.7, released few days ago, you need to update torchvision package to 0.8. Simply, update to latest stable build. Bests
st48522
Hi, Transform on tensors has been added to PyTorch 1.7, released few days ago, you need to update torchvision package to 0.8. Simply, update to latest stable build. Bests
st48523
I’m writing a reinforcement learning program and I’m using nn.BatchNorm1d for the first time. The code trains fine but when it goes into evaluating the policy I get the “Expected more than 1 value per channel when training” error because nn.BatchNorm1d expects a batch of observations but I’m sending a single observation. I know why I’m getting the error, what I don’t know is how to set up the call to the policy to avoid the error, that is, to use the running estimates to normalize the single observation. Any suggestions?
st48524
Solved by ptrblck in post #2 You would have to call model.eval() to use the running stats in batchnorm layers and disable dropout layers.
st48525
You would have to call model.eval() to use the running stats in batchnorm layers and disable dropout layers.
st48526
Oh gee thanks. Did some search on the .eval() method. So it turns out that to evaluate we should # Evaluation mode model.eval() with torch.no_grad(): ... out_data = model(data) ... and then turn the training method back on # Training mode ... model.train() ... Again, first time me doing this.
st48527
Hi all, I am a physicist and I use deep learning on physical systems, where usually the physics is linear/simple when using complex values. That’s why I try to use complex values ANN, and I already use a custom set of functions/layers to implement complex layers: GitHub wavefrontshaping/complexPyTorch 75 A high-level toolbox for using complex valued neural networks in PyTorch - wavefrontshaping/complexPyTorch So far, all my functions work taking two arguments, one tensor for the real part, one for the imaginary part, I am now wondering if it is the best way to go. I recently discovered that PyTorch does have one type of complex layer, as it allows complex FFTs (which is awesome by the way): https://pytorch.org/docs/master/torch.html?highlight=fft#torch.fft 43 This takes a tensor with an additional last dimension of size 2. My question is, is it better to keep two tensors as arguments, or one with an additional dimension? The advantage of the 2 arguments scheme is that, as most of the complex functions simply require to make independent operations on the imaginary and real part, it allows passing directly the two tensors to the builtin (real) PyTorch function. The simplest example being the C-relu: def complex_relu(input_r,input_i): return relu(input_r), relu(input_i) The problem is that the syntax is then not simple (especially for cost functions as they take two complex vectors, then 4 tensors). If I want to use the one tensor argument, as in torch.fft, I then have to separate the real and imaginary part: def complex_relu(complex_input): return torch.stack(relu(complex_input[...,0]), relu(complex_input[...,1]), dim = -1) Is it really optimal? It seems that is would make copies of the sliced tensors, is it memory efficient? Is there a better way to do it?
st48528
As far as I understand the bug report tracking complex 23, the current favourite implementations are through the external modules pytorch-cpu-strided-complex 51 and the cuda equivalent (note that you need to import the cpp submodule). For me, they seem to have more than a few rough edges at the moment, but I’d imagine that if you’re keen on helping out, noone will complain. One thing I didn’t find is how to get zero-copy access to the real and imaginary part. I would imagine that that should be possible (because that’s how they’re saved in memory, after all) but .real and .imag stay in the complex datatypes rather than returning the real ones. Best regards Thomas
st48529
Hi Tom and thank you for your quick reply, Thanks for the links, but frankly, this seems to be out of my league. Moreover, as far as I understand, pytorch-cpu-strided-complex would help me get complex type tensors, but not so much to getting complex operations. Am I wrong about that? And without complex matrix multiplication, for instance, it is no use to me. I am good for now using my rough Python implementation, while I am perfectly aware of the fact that it is far from optimal. My question is them, from the two methods I proposed, which is the best? Is the slicing thing in the second forward implementation reasonable or does it create useless memory usage?
st48530
For the functions above. I personally prefer to use explicit functions instead of advanced indexing to be sure no copy happens. In you case, you can replace complex_input[...,0] by complex_input.select(-1, 0). .select() never does copy and is really cheap (cheaper than advanced indexing) so that should be optional.
st48531
Well, I did some tests and select() does not seem so cheap, here is what I tested: from torch.nn.functional import relu import torch def complex_relu(input_r,input_i): return relu(input_r), relu(input_i) def complex_relu2(complex_input): return torch.stack((relu(complex_input[...,0]), relu(complex_input[...,1])), dim = -1) def complex_relu3(complex_input): complex_input[...,0] = relu(complex_input.select(-1, 0)) complex_input[...,1] = relu(complex_input.select(-1, 1)) return complex_input def complex_relu4(complex_input): return torch.stack((relu(complex_input.select(-1, 0)), relu(complex_input[...,1])), dim = -1) device = torch.device("cuda:0" ) n = 1000 X_r = torch.randn(n,n).to(device) X_i = torch.randn(n,n).to(device) X = torch.stack((X_r,X_i),dim=-1).to(device) %timeit complex_relu(X_r,X_i) 33.1 µs ± 6.04 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) %timeit complex_relu2(X) 148 µs ± 32.6 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) %timeit complex_relu3(X) 130 µs ± 12.5 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) %timeit complex_relu4(X) 148 µs ± 33.1 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) So, any thoughts on how to have the two layer system to be as fast as the two separate arguments?
st48532
Obviously, this one is a good option for relu: def complex_relu5(complex_input): return torch.clamp(complex_input,min = 0) 31.6 µs ± 1.7 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) Still, for other types of functions, I would still need to slice/stack real and imaginary part.
st48533
Hi, I would guess that most of the runtime there comes from the .stack() function, not how you do the slicing. Also be careful if you’re doing timings on cuda because the api is asynchronous. So you need to introduce torch.cuda.synchronize() to make sure you measure actual runtimes.
st48534
albanD: torch.cuda.synchronize() Thanks for the tip, I did not know. Stacking slows down the code but slicing too: A = torch.randn(20000).to(device) %timeit AA = A %timeit AA = A[:-1] %timeit A[:-1] = A[:-1] 18.4 ns ± 3.15 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) 1.7 µs ± 3.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) 14.6 µs ± 2.1 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) Is that the best I can do? Moreover, I discovered that there is now complex value related functions with PyTorch! https://pytorch.org/docs/stable/torch.html 20 We find torch.angle(), torch.real() and torch.imag(). So I upgraded PyTorch to the latest (1.5) on my calculation server and ran the usage example from the official website for the torch.angle() function: torch.angle(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]))*180/3.14159 and got: RuntimeError: Could not infer dtype of complex Instead of the results from PyTorch documentation: tensor([ 135., 135, -45]) If there is still no official complex tensor support, how one can use those functions?
st48535
We are starting to do so. But not many functions are implemented yet I’m afraid. Is that the best I can do? 1 micro second is actually quite good already for pytorch standard. This is basically only the overhead of the framework. You won’t find any pytorch function that is cheaper than that.
st48536
Good to know, thanks! About the complex tensors, as it is on the official documentation, can anybody tell me how to reproduce the output of the example?
st48537
You’ll need to install the extension mentioned earlier, https://gitlab.com/pytorch-complex/pytorch-cpu-strided-complex 27 , first, before the complex operations work. We’re planning to move them into PyTorch, maybe even by 1.5, so you don’t have to do a complicated installation step first.
st48538
ezyang: You’ll need to install the extension mentioned earlier, https://gitlab.com/pytorch-complex/pytorch-cpu-strided-complex I did (though I had to modify the .cpp that seems to use an older version of the API), but even after a successful compilation and installation, it fails the tests. Never mind, if it goes in the next release, I am good with it. Thanks! Will it be only CPU though?
st48539
As of 1.7.0, complex numbers largely work as expected, but a substantial number of functions aren’t implemented with CUDA acceleration or backwards propagation. However, if you’re happy to take your own derivatives and not use the GPU acceleration, it works great. Also when you find an unimplemented feature you need, check the issues on GitHub first, but feel free to create an issue.
st48540
Could you post an executable code snippet to reproduce this error as well as the full error message?
st48541
Hi for the explanation of shuffle as an argument to Dataloader it’s mentioned that: ’ set to True to have the data reshuffled at every epoch’ shouldn’t it be at every iteration or I’m missing something?
st48542
Solved by ptrblck in post #2 The indices will be shuffled for the complete dataset once per epoch and then used to create batches. Each batch will thus contain random samples and I think the documentation explains it correctly.
st48543
The indices will be shuffled for the complete dataset once per epoch and then used to create batches. Each batch will thus contain random samples and I think the documentation explains it correctly.
st48544
PyTorch 1.7 debug build returns True, run with python -m torch.utils.collect_env Installed with pip install torch==1.7.0+cu101 torchvision==0.8.1+cu101 torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html from pytorch.org 9. Collecting environment information... PyTorch version: 1.7.0+cu101 Is debug build: True CUDA used to build PyTorch: 10.1 ROCM used to build PyTorch: N/A OS: Ubuntu 18.04.5 LTS (x86_64) GCC version: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0 Clang version: 6.0.0-1ubuntu2 (tags/RELEASE_600/final) CMake version: version 3.12.0 Python version: 3.6 (64-bit runtime) Is CUDA available: True CUDA runtime version: 10.1.243 GPU models and configuration: GPU 0: Tesla T4 Nvidia driver version: 418.67 cuDNN version: /usr/lib/x86_64-linux-gnu/libcudnn.so.7.6.5 HIP runtime version: N/A MIOpen runtime version: N/A Versions of relevant libraries: [pip3] numpy==1.18.5 [pip3] torch==1.7.0+cu101 [pip3] torchaudio==0.7.0 [pip3] torchsummary==1.5.1 [pip3] torchtext==0.3.1 [pip3] torchvision==0.8.1+cu101 [conda] Could not collect While in 1.6 Collecting environment information... PyTorch version: 1.6.0+cu101 Is debug build: No CUDA used to build PyTorch: 10.1 OS: Ubuntu 18.04.5 LTS GCC version: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0 CMake version: version 3.12.0 Python version: 3.6 Is CUDA available: Yes CUDA runtime version: 10.1.243 GPU models and configuration: GPU 0: Tesla T4 Nvidia driver version: 418.67 cuDNN version: /usr/lib/x86_64-linux-gnu/libcudnn.so.7.6.5 Versions of relevant libraries: [pip3] numpy==1.18.5 [pip3] torch==1.6.0+cu101 [pip3] torchsummary==1.5.1 [pip3] torchtext==0.3.1 [pip3] torchvision==0.7.0+cu101 [conda] Could not collect Environment: Colab What does it mean? Is this a new changes in 1.7? I can’t see in the release notes. Thank you.
st48545
Solved by ptrblck in post #2 Thanks for raising this issue. We’ll check, if this needs to be removed.
st48546
Thank you for your answer @ptrblck I raised the GH issue here: https://github.com/pytorch/pytorch/issues/46973 52
st48547
With respect to the paper below. https://core.ac.uk/download/pdf/82384172.pdf. I am interested in computing the invariant subspace of the two matrices. Any help in this regard
st48548
Just getting started with PyTorch (very nice system, btw). Unfortunately, The last couple days I’ve been trying to run unmodified tutorial code in PyCharm (mostly transformer_tutorial.py). Sometimes I get the following error in PyCharm: THCudaCheck FAIL file=/opt/conda/conda-bld/pytorch_1579022060824/work/aten/src/THC/THCCachingHostAllocator.cpp line=278 error=719 : unspecified launch failure At this point, if I open a separate ipython console and try to check my GPU status, I get this: THCudaCheck FAIL file=/opt/conda/conda-bld/pytorch_1579022060824/work/aten/src/THC/THCGeneral.cpp line=50 error=999 : unknown error RuntimeError Traceback (most recent call last) in 1 import torch ----> 2 torch.cuda.current_device() ~/Software/anaconda3/lib/python3.7/site-packages/torch/cuda/init.py in current_device() 375 def current_device(): 376 r""“Returns the index of a currently selected device.”"" –> 377 _lazy_init() 378 return torch._C._cuda_getDevice() 379 ~/Software/anaconda3/lib/python3.7/site-packages/torch/cuda/init.py in _lazy_init() 195 "Cannot re-initialize CUDA in forked subprocess. " + msg) 196 _check_driver() –> 197 torch._C._cuda_init() 198 _cudart = _load_cudart() 199 _cudart.cudaGetErrorName.restype = ctypes.c_char_p At other times, I have no problem checking my GPU and code accessing the GPU runs without problems. Things have broken twice now since yesterday evening and the problem doesn’t go away until I restart my computer, which is a pain given how much I have open (including VMs). My configuration is Ubuntu 18.04, up to date; am using nvidia-driver-440 and all dependencies; and conda shows: pytorch 1.4.0 py3.7_cuda10.1.243_cudnn7.6.3_0 pytorch cudatoolkit 10.1.243 h6bb024c_0 I do not have cuda or cudnn installed on my computer, but gather they are unnecessary when cudatoolkit is installed (I hope)? nvidia-smi is as follows. I have the system using the cpu’s graphics to free up my GPU. But the following seems to show that the GPU is running the PyTorch code (it’s stopped in my debugger). One disconnect is, if I understand correctly, my version of PyTorch above wants cuda 10.1, while nvidia-smi seems to think it’s using (or wants to use?) cuda 10.2 (which would be the default for driver 440 I guess). However, as already noted, I don’t have cuda installed on my system as indicated above, other than through cudatools in anaconda, which I gather has cuda 10.1. $ nvidia-smi Thu Feb 13 15:26:28 2020 ±----------------------------------------------------------------------------+ | NVIDIA-SMI 440.33.01 Driver Version: 440.33.01 CUDA Version: 10.2 | |-------------------------------±---------------------±---------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 GeForce RTX 2080 On | 00000000:01:00.0 Off | N/A | | 12% 55C P2 41W / 225W | 761MiB / 7982MiB | 0% Default | ±------------------------------±---------------------±---------------------+ ±----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | 0 16432 C …armProjects/PytorchTest/venv/bin/python 747MiB | ±----------------------------------------------------------------------------+ Any thoughts?
st48549
Solved by Red-Eyed in post #21 Hello, I ended up with this solution, no reboot requires: sudo rmmod nvidia_uvm sudo modprobe nvidia_uvm After executing such commands, I can use PyTorch again.
st48550
Oh, and I tried "os.environ[“CUDA_VISIBLE_DEVICES”] = ‘0’ " with no positive effect. And ‘torch.version.cuda’ gives me ‘10.1’ .
st48551
If I’m right and I don’t need to install cuda and cudnn on my system so long as I have cudatools installed in Anaconda (could someone confirm this?), then the most likely source of my problem may be the nvidia driver, which is designed for CUDA 10.2 while PyTorch uses 10.1. I fell back to nvidia-driver-435. nvidia-smi now shows CUDA version as 10.1 and so far I haven’t run into any errors in PyTorch. Fingers crossed.
st48552
Yes, you are correct in the assumption that you don’t need a local CUDA and cudnn installation, if you are installing the binaries. The NVIDIA driver should be sufficient. Are you getting some other CUDA error while running the code or is this error raised randomly?
st48553
Thanks for the confirmation ptrblck! Looking this up online brings up a lot of older pages that seem to suggest it’s necessary to put CUDA and cuDNN on your system. But looking closely at others suggests otherwise. The pytorch install page doesn’t mention a separate install, but could be clearer in saying explicitly that these are not required. I’m running unaltered tutorial code, so I wouldn’t expect runtime errors (there’s an error in one of the function implementations, but it won’t throw a runtime error). So, no, I get no other runtime errors and, as far as I can tell, these cudacheck errors are occurring at random. Cheers, Peter
st48554
Thanks for the update. Based on the description it sounds like your current setups might have some issues. Were you seeing these errors before or did you just build your machine? Also, do you see any other applications raising CUDA errors? Could you run a stress test on the GPU?
st48555
Is there a GPU stress test you recommend? I am a bit worried that this computer, which was thrown together, may not have the capacity to handle a lot of heat. But I guess I can monitor that for a while. Also note that I have my GPU turned off from graphics duties–it’s not driving my X windows–but is available for calculation tasks. I So far, the system with the 435 driver seems much more stable, though I continue to run into problems less frequently. So far, after a couple days of use, I had to reboot to get CUDA back again (same problem as my initial post here). Also, after starting / stopping the debugger (and a suspend thrown in), the debugger says no gpu is free, even when I open an ipython console in the debugger. However, when I open ipython from terminal, it sees the gpu. PyCharm problem I guess. Peter
st48556
peterm: I am a bit worried that this computer, which was thrown together, may not have the capacity to handle a lot of heat. What do the temperature sensors report? Are you seeing high temperatures on your GPU or the system in general?
st48557
Hi ptrblck: If you’re thinking that heat may be why I’m having these problems, it’s not. I’m very slowly stepping through PyTorch’s transformer implementation using PyCharm, not running code, at least on my work computer which has had the problem I’ve described. (I worry about heat on the system because I ran a HLTA analysis that took 3 days and the sensors reported momentary temperatures above 90C, where 100C is a critical temperature for my chips according to lmsensors. The run was not on the GPU and encountered no errors.) There’s also another reason to think the problem I’ve reported is not due to hardware. My home computer, which is entirely different hardware (different manufacturer, chipset, GPU), is encountering the same problem I reported here. So, two different hardware setups, the same software setup, the same error–which suggests a software issue. I’m going to do some experimenting with suspend because it seems that I run into this problem after waking from suspend.
st48558
Thanks for the update. A software issue related to the suspend mode on two different machines sounds quite unlucky, but might of course be the issue. Just out of curiosity, which OS are you using?
st48559
I’m using up-to-date Ubuntu 18.04. Yesterday I didn’t put my work computer to suspend and didn’t run into any CUDA problem all day (should have suspended at end of day to see its effect but got caught up in something else). Rebooted my home computer and also didn’t run into any CUDA problem. Suspended it overnight and this morning, CUDA was no longer accessibly via Python. Maybe worth noting that the GPU was still being used by Xorg and programs running on Xorg (my home computer uses GPU for video, work computer does not). Will continue to test today. If this is a suspend issue, anywhere in particular I should report it to? Peter
st48560
You could try to reload the nvidia kernel module via: sudo rmmod nvidia_uvm sudo modprobe nvidia_uvm Ubuntu seems to have some issues with sleep/suspend (or maybe Linux in general?). While I never suspend my workstation, my laptop isn’t able to connect via VPN after waking up. Not sure where to report it.
st48561
I can confirm that the problem only seems to occur and seems to occur fairly reliably when I suspend and resume, but with PyCharm active and perhaps my debugger on. I just tried twice to cause CUDA to destabilize w/o PyCharm on and suspending / resuming, just using ipython to check for availability of cuda. Encountered no problem. Then I tried to destablize CUDA by having PyCharm on but not debugging. Also encountered no problem. Late today, I’ll try to try to again, but with the debugger running. I suspect that’s when it’ll fail–which should give me a good way to avoid breakdowns. Also, tried rmmod nvidia_uvm (good suggestion–makes sense). Unfortunately, it gives an error msg saying nvidia_uvm is in use. I tried a variety of things, including removing other nvidia kernel modules, but whatever I do nvidia_uvm ‘is in use.’ I have to have ‘sudo prime-select nvidia’ in place or otherwise cuda is inaccessible, but the moment I use ‘sudo prime-select nvidia’ all the nvidia modules load. I can go back to ‘sudo prime-select intel’, but it takes a reboot to have any effect.
st48562
Yup, CUDA remains much more stably accessible when the PyCharm debugger is terminated before suspending a machine. I can use it all day with multiple suspends. Overnight CUDA did crash and I thought I had terminated the debugger but perhaps not. Anyway, a workaround to the problem, most of the time, seems to be to terminate the PyCharm debugger before suspending, otherwise CUDA will almost certainly become inaccessible (at least on my Ubuntu 18.04 system).
st48563
For a full solution, something needs to be fixed in PyTorch (maybe Python?) or in CUDA. I just ran the transformer tutorial code in Python directly, w/o PyCharm. During the run, I momentarily suspended the linux system and then woke it. Immediately I got errors about CUDA and now CUDA is inaccessible in python, ipython, etc.
st48564
My best bet would still be on the weird interactions I see with Linux (Ubuntu?) suspend and usually a lot of drivers. Googling for issues with suspend yield a lot of this “undefined behavior”.
st48565
This worked for me. I’ve also had issues with suspend. Error : RuntimeError: cuda runtime error (999) : unknown error at /pytorch/aten/src/THC/THCGeneral.cpp:47 Ubuntu 20.04 RTX 2080 Super
st48566
For some reason, having a local jupyter notebook running uses the gpu in a mysterious way that it doesn’t like. I run most of my stuff on .py’s. The workaround is not so nice. Just have to launch a docker to use jupyter notebook which is definitely a little less than ideal.
st48567
Hello, I ended up with this solution, no reboot requires: sudo rmmod nvidia_uvm sudo modprobe nvidia_uvm After executing such commands, I can use PyTorch again.