id
stringlengths
3
8
text
stringlengths
1
115k
st102900
If you look at this post: How to combine multiple criterions to a loss function? 269 code from your second point seems to be in line with what has been said above. From the tutorials, when you call backward() on the loss it does the following: The backward function receives the gradient of the output Tensors with respect to some scalar value, and computes the gradient of the input Tensors with respect to that same scalar value. When you call step() for optimiser it does the following: Calling the step function on an Optimizer makes an update to its parameters
st102901
I adopted a 2-layer neural network in the tutorial: model = nn.Sequential( nn.Linear(D_in, H), nn.Tanh(), nn.Linear(H, D_out), ) Then I trained the model, save and load the model in the way as they mentioned here 1 (second answer, case #1). But when the output yields a SyntaxError: File "eval01.py", line 63 model.eval() ^ SyntaxError: invalid syntax I don’t have any Batchnorm or Dropout layer in my model. Is this the reason of this error?
st102902
Solved by ptrblck in post #2 Could you post the code for loading the state dict? Your error is most likely due to a typo, e.g. a missing parenthesis.
st102903
Could you post the code for loading the state dict? Your error is most likely due to a typo, e.g. a missing parenthesis.
st102904
Thanks for the hint! It’s indeed a missing parenthesis at the very beginning of the code and the mismatch tracks down to these line. I’m really really sorry
st102905
Hey there, I am currently trying to build a RNN to detect certain events in a video input stream. Let’s say the RNN rolls out over a given input sequence and produces an output for each timestep t, but during training I want to backpropagate only after each 4th timestep t_i+3. Do I have to sum up all the losses t_i, t_i+1, t_i+2 and t_i+3 and run backprop on this sum or do I only have to run backprop on the loss of timestep t_i+3? My understanding is, when I run backprop on the sum of the losses from t_i to t_4 it is like running backprop after each timestep, is this assumption correct? Here an image, the pink backpropagation is what I would like to achieve. IMG_8954.JPG4032×3024 1.7 MB
st102906
You’re correct. You can just extract whatever portion of the output you want to run backprop on and use that in the calculation of your loss function. This is very common in many to one RNNs where a series of inputs are used to predict one outcome.
st102907
@aplassard Thanks! Just to be clear: So hypothetically, if I want to run backpropagation after each timestep t_i I have to sum up all the errors of the t_0 to t_n with torch.sum() and it is like running backprop after each timestep t_i?
st102908
I believe you can pass an output of size (<num_time_steps>, batch_size, num_outputs) to your loss function directly.
st102909
One thing, I am using Cross Entropy Loss, which I give the output of my RNN of size (batch, seq_length, feature_size) and it tells me it only would like to have (batch, feature_size). Will there be a problem with backprop if I do change my outputs with tensor.view() to have the size (batch, seq_length * feature_size)? EDIT: Nvm, changed Loss to Binary Cross Entropy, should work that way.
st102910
When I am using CUDA_VISIBLE_DEVICES before python main.py, just like: CUDA_VISIBLE_DEVICES=0,1,2,3 python main.py --args... this command make the other gpu, i.e. [4,5,6,7] suddenly disappear! No matter in my account or other users’. When I type nvidia-smi, I can only see four gpu: +-----------------------------------------------------------------------------+ | NVIDIA-SMI 384.111 Driver Version: 384.111 | |-------------------------------+----------------------+----------------------+ | 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 GTX 108... Off | 00000000:04:00.0 Off | N/A | | 23% 33C P2 54W / 250W | 595MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 1 GeForce GTX 108... Off | 00000000:05:00.0 Off | N/A | | 23% 34C P2 55W / 250W | 569MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 2 GeForce GTX 108... Off | 00000000:08:00.0 Off | N/A | | 23% 34C P2 55W / 250W | 569MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 3 GeForce GTX 108... Off | 00000000:09:00.0 Off | N/A | | 23% 33C P2 54W / 250W | 569MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ While it ought to be: +-----------------------------------------------------------------------------+ | NVIDIA-SMI 384.111 Driver Version: 384.111 | |-------------------------------+----------------------+----------------------+ | 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 GTX 108... Off | 00000000:04:00.0 Off | N/A | | 23% 30C P0 56W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 1 GeForce GTX 108... Off | 00000000:05:00.0 Off | N/A | | 23% 31C P0 58W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 2 GeForce GTX 108... Off | 00000000:08:00.0 Off | N/A | | 23% 30C P0 58W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 3 GeForce GTX 108... Off | 00000000:09:00.0 Off | N/A | | 23% 29C P0 56W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 4 GeForce GTX 108... Off | 00000000:84:00.0 Off | N/A | | 23% 30C P0 56W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 5 GeForce GTX 108... Off | 00000000:85:00.0 Off | N/A | | 23% 29C P0 56W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 6 GeForce GTX 108... Off | 00000000:88:00.0 Off | N/A | | 23% 30C P0 57W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 7 GeForce GTX 108... Off | 00000000:89:00.0 Off | N/A | | 23% 27C P0 56W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ Pytorch version: 0.4.0 Cuda version: V8.0.61 GPU driver: 384.111 Compared to another user, who can correctly run CUDA_VISIBLE_DEVICES=0,1,2,3 python main.py --args..., the only difference I can figure out is I am using Anaconda environment. I don’t know how this can affect the running. I am not using sudo before writing CUDA_VISIBLE_DEVICES. Thanks you for replying~
st102911
Your behavior is the expected result - https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#env-vars 1.0k
st102912
Thank for your reply! I don’t think it is expected. Because people using this command to assign specified gpu to a task in order to spare the other gpus for other task. If me using CUDA_VISIBLE_DEVICES can affect other user’s observed gpu, then they can’t using the gpu that omitted by my task. And what’s more, my coworker can using this command CUDA_VISIBLE_DEVICES=0,1,2 python main.py to specify the gpu his task used, without influence my task. Again, thanks for your reply but I am still not understand
st102913
Hi, How do you bring these gpus back up after they disapear? Do you have to reboot? Or opening a new shell works?
st102914
Turn off the old shell can make them appear, in my new opened shell or my coworker’s shell.
st102915
Does that happen for any script that you execute or just for this one? If it’s only this one, what does it do? Is it doing multigpu work? Are you doing anything else fancy with your gpu?
st102916
Concretely, even though I type CUDA_VISIBLE_DEVICES=0,1,2,3 after I enter the conda environment, without running any python code, this phenomena also happens. In fact, the main.py does a simple PyTorch based neural network training, with dataloader, dataparallel in it. More info: Dataparallel using 20 workers. Instead of setting the environment variable, using os.environ["CUDA_VISIBLE_DEVICES"] = "0, 1, 2, 3" inside the python code can also cause the problem. Turn off the shell, or kill the running process, or waiting it finish can solve it. for target in loader: target_var = target.cuda(async=True) is used. Maybe the async=True will cause some problem? Thanks for your fast and quick reply!
st102917
Can you send us a few things to help? The output of nvidia-smi on your shell when you open a new terminal The output of nvidia-smi on your coworker’s shell the output of CUDA_VISIBLE_DEVICES=0,1,2,3 nvidia-smi on your coworker’s shell the output nvidia-smi on your shell after they have run that the output of CUDA_VISIBLE_DEVICES=0,1 nvidia-smi on your shell the output of nvidia-smi on your coworker’s shell ofter you have run that?
st102918
@aplassard Note that nvidia-smi is not impacted by the CUDA_VISIBLE_DEVICES env variable. @PengZhenghao from a state where it works, could you open two new shells. Check that nvidia-smi shows all the gpus in both. Run CUDA_VISIBLE_DEVICES=0,1 on one shell. Check that nvidia-smi shows all the gpus in both still. Is that the case? Run export CUDA_VISIBLE_DEVICES=0,1 on one shell. Check that nvidia-smi shows all the gpus in both still. Is that still the case? In each shell, run python then inside import torch and print(torch.cuda.device_count()). One should return 2 (the shell that had the export command) and the other 8. Is that the case?
st102919
The nvidia-smi in newly opened terminal of me or my coworker +-----------------------------------------------------------------------------+ | NVIDIA-SMI 384.111 Driver Version: 384.111 | |-------------------------------+----------------------+----------------------+ | 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 GTX 108... Off | 00000000:04:00.0 Off | N/A | | 23% 31C P0 57W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 1 GeForce GTX 108... Off | 00000000:05:00.0 Off | N/A | | 23% 32C P0 58W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 2 GeForce GTX 108... Off | 00000000:08:00.0 Off | N/A | | 23% 32C P0 58W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 3 GeForce GTX 108... Off | 00000000:09:00.0 Off | N/A | | 23% 30C P0 56W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 4 GeForce GTX 108... Off | 00000000:84:00.0 Off | N/A | | 23% 31C P0 56W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 5 GeForce GTX 108... Off | 00000000:85:00.0 Off | N/A | | 23% 30C P0 56W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 6 GeForce GTX 108... Off | 00000000:88:00.0 Off | N/A | | 23% 31C P0 57W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 7 GeForce GTX 108... Off | 00000000:89:00.0 Off | N/A | | 23% 28C P0 56W / 250W | 0MiB / 11172MiB | 2% Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | No running processes found | +-----------------------------------------------------------------------------+ My coworker see exactly the same as me if I do nothing. Nothing happen after “CUDA_VISIBLE_DEVICES=0,1,2,3 nvidia-smi” No matter in my shell or coworker’s shell, the same as above shown in nvidia-smi, with or without conda environment. When running python script, gpu disappear! When I run sh train.sh inside the conda environment, wherein codes following is inside: #!/usr/bin/env bash CUDA_VISIBLE_DEVICES=0,1,2,3 nohup python main.py --fuse-type=average --batch-size=64 --tsn --model=mlp --epochs=1 --lr=5e-4 2>&1 & At that time, I can see the GPU disappear one-by-one! Start from No.7 gpu. Till all 4-7 gpu disappear. This phenomena can be observed exactly the same in my and my coworker’s shells. When the script still running and half of the gpu disappear, in nvidia-smi: +-----------------------------------------------------------------------------+ | NVIDIA-SMI 384.111 Driver Version: 384.111 | |-------------------------------+----------------------+----------------------+ | 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 GTX 108... Off | 00000000:04:00.0 Off | N/A | | 23% 29C P2 53W / 250W | 525MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 1 GeForce GTX 108... Off | 00000000:05:00.0 Off | N/A | | 23% 31C P2 55W / 250W | 521MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 2 GeForce GTX 108... Off | 00000000:08:00.0 Off | N/A | | 23% 29C P2 54W / 250W | 521MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 3 GeForce GTX 108... Off | 00000000:09:00.0 Off | N/A | | 23% 26C P8 10W / 250W | 18MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | 0 50371 C python 515MiB | | 1 50371 C python 511MiB | | 2 50371 C python 511MiB | | 3 50371 C python 8MiB | +-----------------------------------------------------------------------------+ After the script ran, everything restore +-----------------------------------------------------------------------------+ | NVIDIA-SMI 384.111 Driver Version: 384.111 | |-------------------------------+----------------------+----------------------+ | 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 GTX 108... Off | 00000000:04:00.0 Off | N/A | | 23% 30C P0 55W / 250W | 595MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 1 GeForce GTX 108... Off | 00000000:05:00.0 Off | N/A | | 23% 31C P0 56W / 250W | 569MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 2 GeForce GTX 108... Off | 00000000:08:00.0 Off | N/A | | 23% 31C P0 56W / 250W | 569MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 3 GeForce GTX 108... Off | 00000000:09:00.0 Off | N/A | | 23% 29C P0 55W / 250W | 569MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 4 GeForce GTX 108... Off | 00000000:84:00.0 Off | N/A | | 23% 28C P0 56W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 5 GeForce GTX 108... Off | 00000000:85:00.0 Off | N/A | | 23% 28C P0 56W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 6 GeForce GTX 108... Off | 00000000:88:00.0 Off | N/A | | 23% 30C P0 57W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 7 GeForce GTX 108... Off | 00000000:89:00.0 Off | N/A | | 23% 27C P0 56W / 250W | 0MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | No running processes found | +-----------------------------------------------------------------------------+
st102920
albanD: export CUDA_VISIBLE_DEVICES=0,1 After “Run export CUDA_VISIBLE_DEVICES=0,1 on one shell”, both shell nvidia-smi show 8 gpu Checking torch.cuda.device_count() in both shell, after one of them run Step1, the phenomena as you wish happen: the user that conduct Step1 get the 2 result, while the other get 8. In short, everything happen as you wish.
st102921
Ok, So it is something in your actual script that causes this. Could you disable the DataParallel? It will run on only one of the 4 available gpus but that should work. When this is disabled, do you still see the gpus disapear while the script runs? Also what do you mean by “Dataparallel using 20 workers.” there is no notion of workers for DataParallel. Do you repeat some gpus in the device_ids list? If so try and set each gpu once and see what it does.
st102922
Yes, all GPU still there! I only comment DataParallel in my code and rerun the script. model = model.cuda() # model = torch.nn.DataParallel(model) +-----------------------------------------------------------------------------+ | NVIDIA-SMI 384.111 Driver Version: 384.111 | |-------------------------------+----------------------+----------------------+ | 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 GTX 108... Off | 00000000:04:00.0 Off | N/A | | 23% 26C P2 56W / 250W | 549MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 1 GeForce GTX 108... Off | 00000000:05:00.0 Off | N/A | | 23% 23C P8 9W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 2 GeForce GTX 108... Off | 00000000:08:00.0 Off | N/A | | 23% 22C P8 9W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 3 GeForce GTX 108... Off | 00000000:09:00.0 Off | N/A | | 23% 22C P8 8W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 4 GeForce GTX 108... Off | 00000000:84:00.0 Off | N/A | | 23% 23C P8 8W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 5 GeForce GTX 108... Off | 00000000:85:00.0 Off | N/A | | 23% 23C P8 8W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 6 GeForce GTX 108... Off | 00000000:88:00.0 Off | N/A | | 23% 25C P8 9W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 7 GeForce GTX 108... Off | 00000000:89:00.0 Off | N/A | | 23% 23C P8 8W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | 0 51957 C python 539MiB | +-----------------------------------------------------------------------------+ In both shells, thing looks exactly the same! So in your judgement, what is the key point that trigger this phenomena? Thanks a lot!
st102923
DataParallel use quite complex backend methods in CUDA and have some “unpredictable” (by me) behaviour when not used in a classical way. In particular it uses nccl2 that has some system-wide impact on the gpu. When the gpu disapear, is your code actually running? If so does it uses multiple gpus or just one? I am not sure what happens when you do not provide any device_ids to DataParallel by reading the doc 2. I would replace your line by model = torch.nn.DataParallel(model, device_ids=[0, 1, 2, 3]) and check if that works and properly uses all the 4 gpus. Setting only [0, 1] should use only 2.
st102924
Yes it works! Using DataParallel(model, device_ids=[0,1,2,3]) First I try CUDA_VISIBLE_DEVICES=2,3,4,5 ... model = model.cuda() model = torch.nn.DataParallel(model, device_ids=[0,1]) And we got: +-----------------------------------------------------------------------------+ | NVIDIA-SMI 384.111 Driver Version: 384.111 | |-------------------------------+----------------------+----------------------+ | 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 GTX 108... Off | 00000000:04:00.0 Off | N/A | | 23% 24C P8 8W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 1 GeForce GTX 108... Off | 00000000:05:00.0 Off | N/A | | 23% 25C P8 8W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 2 GeForce GTX 108... Off | 00000000:08:00.0 Off | N/A | | 23% 27C P2 54W / 250W | 595MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 3 GeForce GTX 108... Off | 00000000:09:00.0 Off | N/A | | 23% 26C P2 53W / 250W | 569MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 4 GeForce GTX 108... Off | 00000000:84:00.0 Off | N/A | | 23% 26C P8 8W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 5 GeForce GTX 108... Off | 00000000:85:00.0 Off | N/A | | 23% 25C P8 8W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 6 GeForce GTX 108... Off | 00000000:88:00.0 Off | N/A | | 23% 27C P8 8W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 7 GeForce GTX 108... Off | 00000000:89:00.0 Off | N/A | | 23% 25C P8 9W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | 2 52106 C python 585MiB | | 3 52106 C python 559MiB | +-----------------------------------------------------------------------------+ Then tried: CUDA_VISIBLE_DEVICES=2,3,4,5 ... model = model.cuda() model = torch.nn.DataParallel(model, device_ids=[0,1,2,3]) +-----------------------------------------------------------------------------+ | NVIDIA-SMI 384.111 Driver Version: 384.111 | |-------------------------------+----------------------+----------------------+ | 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 GTX 108... Off | 00000000:04:00.0 Off | N/A | | 23% 24C P8 8W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 1 GeForce GTX 108... Off | 00000000:05:00.0 Off | N/A | | 23% 25C P8 9W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 2 GeForce GTX 108... Off | 00000000:08:00.0 Off | N/A | | 23% 32C P2 55W / 250W | 595MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 3 GeForce GTX 108... Off | 00000000:09:00.0 Off | N/A | | 23% 30C P2 54W / 250W | 569MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 4 GeForce GTX 108... Off | 00000000:84:00.0 Off | N/A | | 23% 30C P2 53W / 250W | 569MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 5 GeForce GTX 108... Off | 00000000:85:00.0 Off | N/A | | 23% 29C P2 53W / 250W | 569MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 6 GeForce GTX 108... Off | 00000000:88:00.0 Off | N/A | | 23% 27C P8 8W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ | 7 GeForce GTX 108... Off | 00000000:89:00.0 Off | N/A | | 23% 25C P8 8W / 250W | 10MiB / 11172MiB | 0% Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | 2 52926 C python 585MiB | | 3 52926 C python 559MiB | | 4 52926 C python 559MiB | | 5 52926 C python 559MiB | +-----------------------------------------------------------------------------+ Now you can see everything work well! Thank you very much for your patiently help! Never think about this problem is triggered by DataParallel. It should use all GPU that visible to python. I don’t know why it failed when I don’t provide device_ids. Sincerely thanks you @albanD and @aplassard . PyTorch community is prosperous thanks to your quick and helpful help. (Never think a library forum is so activated before I join here
st102925
Great, everything works as expected there ! I will report the problem when no device_ids is provided, not sure what was the intended behaviour but I’m sure making GPU disapear is not what we want !
st102926
I am sorry. But today this phenomena happens again. After tons of testing, I find the key point: Using device_id=0,1,2,3 in DataParallel Using nohup to run your python script Using a bash script to set CUDA_VISIBLE_DEVICES and run python I don’t have time to find why this happen. So just run my code under those odd requirements. Codes are provided in case it may help somebody or staff to figure the reason. In my bash script: #!/usr/bin/env bash CUDA_VISIBLE_DEVICES=0,1,2,3 nohup python main.py --fuse-type=cnn --batch-size=256 --model=cnn --epochs=50 --lr=5e-4 2>&1 & echo 'Start training!' In my code: if args.model == 'cnn': model = CNNBase(4, feature_length, num_class) elif args.model == 'mlp': model = MLPBase(feature_length, num_class) model = model.cuda() model = torch.nn.DataParallel(model, device_ids=[0,1,2,3]) UPDATE: I find a more clean way to deal with this problem… That is declare device_id in DataParallel without setting the environment variable. When I use device_id=[0,1,2,3] and let torch.cuda.device_count() return 8. The program still work in 4 gpus and in nvidia-smi 8 gpus are visible.
st102927
I am trying to use the example given below to construct a custom convolution module which will be used in the network instead of the torch.nn.conv2d. inp = torch.randn(1, 3, 10, 12) w = torch.randn(2, 3, 4, 5, requires_grad = True) inp_unf = torch.nn.functional.unfold(inp, (4, 5)) out_unf = inp_unf.transpose(1, 2).matmul(w.view(w.size(0), -1).t()).transpose(1, 2) out = torch.nn.functional.fold(out_unf, (7, 8), (1, 1)) Link to the example: [https://github.com/pytorch/pytorch/blob/e8536c08a16b533fe0a9d645dd4255513f9f4fdd/torch/nn/modules/fold.py 106] How do I I go about this? Do I just make a class and write a forward function? If I have to make a class, what would be the base module? Thank you.
st102928
Solved by ptrblck in post #2 You could just derive nn.Module like when creating a model. In the __init__ function you should create your parameters and the forward will perform your computation. Since you used just pure PyTorch methods, autograd will be able to create the backward call.
st102929
You could just derive nn.Module like when creating a model. In the __init__ function you should create your parameters and the forward will perform your computation. Since you used just pure PyTorch methods, autograd will be able to create the backward call.
st102930
Or is cuda code most of the time faster? I have seen quite a couple of repos writing backward themselves using cuda code and I have not yet have time to test which one is faster. Hopefully autograd is highly optimized that I do not have to worry about writing cuda
st102931
This has been asked before, e.g. How to use sparse Tensor as input? 33 and Error when using sparse tensor as input to module 19, but there are no answers yet. The question is how to feed in a sparse tensor to the training. My code is like longTensors = [[], []] floatTensors = [] with open(filename) as fp: for line in fp: word = re.split(r'\t+', line) longTensors[0].extend([int(word[0]), int(word[1])]) longTensors[1].extend([int(word[1]), int(word[0])]) # value is tuple that (index, value) floatTensors.extend([float(word[2]),float(word[2])]) i = torch.LongTensor(longTensors) v = torch.FloatTensor(floatTensors) # matrix size may need for torch.sparse.FloatTensor(i, v, torch.Size([n, n])) sparse_tensor = torch.sparse.FloatTensor(i, v) dataLoader = data.DataLoader(sparse_tensor) for epoch in range(5): for record in dataLoader: # do the training But got the error that for record in dataLoader: File "/opt/conda/envs/pytorch-py3.6/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 286, in __next__ return self._process_next_batch(batch) File "/opt/conda/envs/pytorch-py3.6/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 307, in _process_next_batch raise batch.exc_type(batch.exc_msg) RuntimeError: Traceback (most recent call last): File "/opt/conda/envs/pytorch-py3.6/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 57, in _worker_loop samples = collate_fn([dataset[i] for i in batch_indices]) File "/opt/conda/envs/pytorch-py3.6/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 57, in <listcomp> samples = collate_fn([dataset[i] for i in batch_indices]) RuntimeError: Sparse tensors do not have strides. Any suggestion on how to solve this issue? Thanks
st102932
I am using 0.4.0 version of pytorch. To get the output gradient w.r.t the input, I used the following code. m = nn.Linear(20, 30) input = torch.randn(128, 20) input.requires_grad = True output = m(input).sum() output.backward() print(input.grad.data) Am I correct ? Thanks!
st102933
Looks good to me, but the most idiomatic way have input require gradients seems to be input = torch.randn(128, 20, requires_grad=True) Best regards Thomas
st102934
Thanks for your reply. Now, I can perform it with only single data input, but the process is too slow. Is there a way to perform it with data batch at once ?
st102935
I am sorry for late response. My question is that there is a way to apply .backward() when the output dimension is larger than one and each dimension corresponds to each input data in a batch data input.
st102936
You can feed a tensor backward as in x.backward(weight)’ this is mathematically equivalent to (x * weight).sum().backward(). There isn’t anything that let’s you get arbitrary derivatives of vectors (i.e. Jacobians). Best regards Thomas
st102937
Here is a simple model I wrote below that utilizes CrossEntropyLoss : f = [] f.append([1,1,1]) f.append([0,1,0]) f.append([0,1,0]) x = torch.FloatTensor(np.array(f)) t = [] t.append(0) t.append(1) t.append(1) y = torch.LongTensor(np.array(t)) dimensions_input = 3 hidden_layer_nodes = 3 output_dimension = 3 class Model(torch.nn.Module): def __init__(self): super(Model, self).__init__() self.linear = torch.nn.Linear(dimensions_input,hidden_layer_nodes) self.linear2 = torch.nn.Linear(hidden_layer_nodes,output_dimension) def forward(self, x): l_out1 = self.linear(x) y_pred = self.linear2(l_out1) return y_pred model = Model() criterion = torch.nn.CrossEntropyLoss() optim = torch.optim.SGD(model.parameters(), lr = 0.0001) def main(): for i in range(50000): y_pred = model(x) loss = criterion(y_pred, y) if i % 1000 == 0: print(loss) optim.zero_grad() loss.backward() optim.step() main() I achieve a low loss value for this implementation : tensor(0.1186) But when i attempt to predict a value using model(x[0]) the returned value is not close to ground truth of [1,1,1] as value : tensor([ 2.7715, 0.7934, -1.1497]) is returned. Have I implemented this model correctly ?
st102938
I am trying to use xavier_uniform_ initialization for batch and layer normalization layers however I am receiving a valueerror: Fan in and fan out can not be computed for tensor with less than 2 dimensions. Is there anyway I can rectify this problem? Also when I try to initialize my bias layers using: for key, value in network.state_dict().items(): if 'bias' in key: network.state_dict()[key] = torch.full_like(network.state_dict()[key], 0, requires_grad=True) # or network.state_dict()[key] = torch.full_like(network.state_dict()[key], 0) When I go to print the state_dict after I initialized all the weights and biases, the biases still turn up to be random numbers instead of 0. Am I using the wrong function or reassigning the wrong variable? How can I fix this?
st102939
I think you would need to modify your current state dict and reload it in your model. An alternative approach would be: model = nn.Sequential( nn.Conv2d(3, 6, 3, 1, 1), nn.BatchNorm2d(6) ) for child in model.children(): if isinstance(child, nn.BatchNorm2d): with torch.no_grad(): child.bias = nn.Parameter(torch.empty(6).uniform_())
st102940
@ptrblck I am trying to use kaiming and xavier initialization, but the initialized weights are not saving to the model. The code I am using to try accomplish this: new_weights = collections.OrderedDict() for key, value in network.state_dict().items(): try: if 'bias' in key: new_weights[key] = torch.full_like(network.state_dict()[key], 0) elif 'ltsm' in key: new_weights[key] = torch.nn.init.xavier_uniform_(value, gain=5/3) elif 'batch' in key or 'norm' in key: new_weights[key] = torch.nn.init.xavier_uniform_(value) # Is the right initialization to use for batch and layer normalization? else: new_weights[key] = torch.nn.init.kaiming_uniform_(value, a=0, mode='fan_out', nonlinearity = 'relu') except: new_weights[key] = torch.full_like(network.state_dict[key], 0) I initially tried to directly reassign the weights but that did not work.
st102941
Did you load the state dict afterwards? Could you try my approach of iterating the children?
st102942
Thank you very much, iterating over the children worked! I’ve been trying to find recommendations on how to initialize the batchnorm weights, biases, running_mean, and running_var and the layernorm weights and biases but can’t find any recommendations, do you know if there is any special way to initialize those layers?
st102943
I am trying to train a few different types of multilayer networks. In each of these networks the weights and biases for each of the layers are not updating except for the weights and biases of the final layer and the normalization of the final ltsm layer. I printed out the gradients for each layer and although for some layers its really small (10^-8 or 0), for other layers its only 10^-2 or 10^-1 and those weights also don’t update. I have ltsm layers. convolutional layers, batch and layer normalizations, and fully connected layers in these networks. I am using the relu activation function for all layers except for the ltsm layer where I am using the tanh activation. Additionally for each layer first the layer operation is done then the batch/layer normalization and then the activation function. How can I make sure that the weights update for the gradients that are not to small and how can I combat against really small weights? Also is there a way to programmatically check if the weights changed for each layer?
st102944
To see if your weight got updated you could use the following scheme: # Save init values old_state_dict = {} for key in model.state_dict(): old_state_dict[key] = model.state_dict()[key].clone() # Your training procedure ... # Save new params new_state_dict = {} for key in model.state_dict(): new_state_dict[key] = model.state_dict()[key].clone() # Compare params for key in old_state_dict: if not (old_state_dict[key] == new_state_dict[key]).all(): print('Diff in {}'.format(key)) Let’s see, if the weight updates are just small or not happening.
st102945
@ptrblck according to the test code the weights and biases for the final linear layer and the final layer normalization (for the ltsm layer) is changing, however the weights and biases for the rest of the normalizations and layers are not updating. I printed out the gradients to check if there is a problem there and found that a large minority of the gradients are 0 with the rest mostly being in the 10^-1 to the 10^4 region. Is there a way to fix these two problems (which are probably related)?
st102946
A proper weight initialization might avoid the vanishing gradients. Also, normalization layers will help (which you are using already). Are you using pure PyTorch code in your model? Can you make sure you are not detaching some tensors? Also, a small code snippet might help, if that’s possible.
st102947
@ptrblck For one of my models I am using a pytorch loss function. I do some calculations before hand but in the end the loss is being handled by pytorch. a = torch.sum(outputs * one_hot) F.mse_loss(a, desired).backward(retain_graph=True) self.optimizer.step() For another model I implemented the loss function: loss = -(obj_func + tau * entropy) loss.backward(retain_graph=True) self.optimizer.step() Yet the results for both are the same, the last layer and layer normalizations are updating but the remaining are not with the gradient distribution mentioned above. I am trying to use kaiming and xavier initialization, but the initialized weights are not saving to the model. The code I am using to try accomplish this: new_weights = collections.OrderedDict() for key, value in network.state_dict().items(): try: if 'bias' in key: new_weights[key] = torch.full_like(network.state_dict()[key], 0) elif 'ltsm' in key: new_weights[key] = torch.nn.init.xavier_uniform_(value, gain=5/3) elif 'batch' in key or 'norm' in key: new_weights[key] = torch.nn.init.xavier_uniform_(value) # Is the right initialization to use for batch and layer normalization? else: new_weights[key] = torch.nn.init.kaiming_uniform_(value, a=0, mode='fan_out', nonlinearity = 'relu') except: new_weights[key] = torch.full_like(network.state_dict[key], 0) I initially tried to directly reassign the weights but that did not work.
st102948
Hi, Is there a good introduction soemwhere (I haven’t found one) on the concept of the various types of databases (DBs) and their different types (minidb, leveldb, etc.)? With a particular focus on their interaction with protobuffers would be great. Thanks! Rasmus
st102949
I have a problem converting a simple model to onnx in the master branch. The full post can be found here: stackoverflow.com `torch.onnx._optimize_trace` fails for simple example in python 3.5 59 python-3.5, pytorch asked by Jus on 12:52PM - 20 Jul 18
st102950
I am going to test my simple linear regression. However I got trouble with my program below: x_train = x.reshape(-1, 1).astype('float32') y_train = y.reshape(-1, 1).astype('float32') class LinearRegressionModel(nn.Module): def __init__(self, input_dim, output_dim): super(LinearRegressionModel, self).__init__() self.linear = nn.Linear(input_dim, output_dim) def forward(self, x): out = self.linear(x) return out input_dim = x_train.shape[1] output_dim = y_train.shape[1] input_dim, output_dim model = LinearRegressionModel(input_dim, output_dim) criterion = nn.MSELoss() [w, b] = model.parameters() def get_param_values(): return w.data[0][0], b.data[0] and my definition of graph def plot_current_fit(title=""): plt.figure(figsize=(12,4)) plt.title(title) plt.scatter(x, y, s=8) w1 = w.data[0][0] b1 = b.data[0] x1 = np.array([0., 1.]) y1 = x1 * w1 + b1 plt.plot(x1, y1, 'r', label='Current Fit ({:.3f}, {:.3f})'.format(w1, b1)) plt.xlabel('x (input)') plt.ylabel('y (target)') plt.legend() plt.show() and I got this error RuntimeError Traceback (most recent call last) in () 1 2 ----> 3 plot_current_fit(‘Before training’) 4 in plot_current_fit(title) 6 b1 = b.data[0] 7 x1 = np.array([0., 1.]) ----> 8 y1 = x1 * w1 + b1 9 plt.plot(x1, y1, ‘r’, label=‘Current Fit ({:.3f}, {:.3f})’.format(w1, b1)) 10 plt.xlabel(‘x (input)’) RuntimeError: Expected object of type torch.DoubleTensor but found type torch.FloatTensor for argument #3 'other ’
st102951
Your x1 was created as np.float64. Try the following: x1 = np.array([0., 1.], dtype=np.float32)
st102952
Thanks for your message. After I followed your instructions: def plot_current_fit(title=""): plt.figure(figsize=(12,4)) plt.title(title) plt.scatter(x, y, s=8) w1 = w.data[0][0] b1 = b.data[0] # x1 = np.array([0., 1.]) **x1 = np.array([0., 1.], dtype=np.float32)** y1 = x1 * w1 + b1 plt.plot(x1, y1, 'r', label='Current Fit ({:.3f}, {:.3f})'.format(w1, b1)) plt.xlabel('x (input)') plt.ylabel('y (target)') plt.legend() plt.show() and %matplotlib notebook import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation fig, (ax1) = plt.subplots(1, figsize=(12, 6)) ax1.scatter(x, y, s=8) w1, b1 = get_param_values() # x1 = np.array([0., 1.]) **x1 = np.array([0., 1.], dtype=np.float32)** y1 = x1 * w1 + b1 fit, = ax1.plot(x1, y1, 'r', label='Predicted'.format(w1, b1)) ax1.plot(x1, x1 * m + c, 'g', label='Real') ax1.legend() ax1.set_title('Linear Regression') def init(): ax1.set_ylim(0, 6) return fit, def animate(i): loss = run_epoch(i) w1, b1 = get_param_values() y1 = x1 * w1 + b1 fit.set_ydata(y1) epochs = np.arange(1, 250) ani = FuncAnimation(fig, animate, epochs, init_func=init, interval=100, blit=True, repeat=False) plt.show() However, I got other error like this: AttributeError Traceback (most recent call last) in () 10 x1 = np.array([0., 1.], dtype=np.float32) 11 y1 = x1 * w1 + b1 —> 12 fit, = ax1.plot(x1, y1, ‘r’, label=‘Predicted’.format(w1, b1)) 13 ax1.plot(x1, x1 * m + c, ‘g’, label=‘Real’) 14 ax1.legend() /usr/local/lib/python3.6/dist-packages/matplotlib/init.py in inner(ax, *args, **kwargs) 1853 “the Matplotlib list!)” % (label_namer, func.name), 1854 RuntimeWarning, stacklevel=2) -> 1855 return func(ax, *args, **kwargs) 1856 1857 inner.doc = _add_data_doc(inner.doc, /usr/local/lib/python3.6/dist-packages/matplotlib/axes/_axes.py in plot(self, *args, **kwargs) 1525 kwargs = cbook.normalize_kwargs(kwargs, _alias_map) 1526 -> 1527 for line in self._get_lines(*args, **kwargs): 1528 self.add_line(line) 1529 lines.append(line) /usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _grab_next_args(self, *args, **kwargs) 404 this += args[0], 405 args = args[1:] –> 406 for seg in self._plot_args(this, kwargs): 407 yield seg 408 /usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _plot_args(self, tup, kwargs) 381 x, y = index_of(tup[-1]) 382 –> 383 x, y = self._xy_from_xy(x, y) 384 385 if self.command == ‘plot’: /usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _xy_from_xy(self, x, y) 241 raise ValueError("x and y must have same first dimension, but " 242 “have shapes {} and {}”.format(x.shape, y.shape)) –> 243 if x.ndim > 2 or y.ndim > 2: 244 raise ValueError("x and y can be no greater than 2-D, but have " 245 “shapes {} and {}”.format(x.shape, y.shape)) AttributeError: ‘Tensor’ object has no attribute ‘ndim’
st102953
Hello, I’ve read nn.Module with multiple inputs 25, and this is more of a follow-up question here. I’m curious if there is a way to concatenate a tensor in the middle of sequential. Or in the middle of a model, for example: def __init__(self, z_dim=10, nc=1,stim=np.random.randint(13,size=8)): super(BetaVAE_H_wStim, self).__init__() torch.backends.cudnn.benchmark = True self.z_dim = z_dim self.nc = nc self.stim = stim self.encoder = nn.Sequential( nn.Conv3d(nc, 32, 3, (1,2,2), 1), # B, 32, 4, 48, 48 nn.ReLU(True), nn.Conv3d(32, 32, 3, (1,2,2), 1), # B, 32, 2, 24, 24 nn.ReLU(True), nn.Conv3d(32, 64, 3, 2, 1), # B, 64, 1, 12, 12 nn.ReLU(True), nn.Conv3d(64, 64, 3, 2, 1), # B, 64, 6, 6 nn.ReLU(True), nn.Conv3d(64, 256, 3, 2, 1), # B, 64, 6, 6 nn.ReLU(True), View((-1,256)), # B, 256 # i want to concat here nn.Linear(256,z_dim*2), # B, z_dim*2 ) Where my comment is is where I’m hoping to concat a numpy array of size 8 (1 axis) to my tensor in the model. It’s different from the problem posted above. I actually want those values to be fully connected to the output of this model. Is there an easy way to do this?
st102954
Sure it’s possible, though only during the forward pass; meaning that you should declare your encoder and the final Linear separately. Finally during the forward pass, take the ouput of the encoder, reshape with .view, concat with the other tensor with torch.cat (https://pytorch.org/docs/stable/torch.html#torch.cat 109) and pass it to the Linear module.
st102955
Ok thank you very much. Along the same lines, I have a decoder that looks like this: self.decoder = nn.Sequential( nn.Linear(z_dim, 256), # B, 256 # I want to separate here View((-1, 256, 1, 1)), # B, 256, 1, 1 nn.ReLU(True), nn.ConvTranspose2d(256, 64, 4), # B, 64, 4, 4 nn.ReLU(True), nn.ConvTranspose2d(64, 64, 4, 2, 1), # B, 64, 8, 8 nn.ReLU(True), nn.ConvTranspose2d(64, 32, 4, 2, 1), # B, 32, 16, 16 nn.ReLU(True), nn.ConvTranspose2d(32, 32, 4, 2, 1), # B, 32, 32, 32 nn.ReLU(True), nn.ConvTranspose2d(32, nc, 4, 2, 1), # B, nc, 64, 64 ) And I want to somehow remove that tensor I just concatenated after my 1st linear layer in the decoder. Is this likewise as simple?
st102956
Yes it’s possible, though I am confused about where the concatenation happens in the encoder as the parameters of Linear seem to be incorrect : should be nn.Linear(256+8,z_dim*2) if you concatenate with previous View. Try to make a first working model with initialization and forward, and I will help.
st102957
I’m new to using PyTorch for RNNs and loving it so far. Nonetheless, my model is only training on individual sequences (i.e., batch size = 1). As I move towards training in batch, I’ve been going through many different implementations for padding and batching the tensors, such as: https://medium.com/@sonicboom8/sentiment-analysis-with-variable-length-sequences-in-pytorch-6241635ae130 35 https://github.com/hunkim/PyTorchZeroToAll/blob/master/13_2_rnn_classification.py 20 I also noticed PyTorch has pad_sequence which seems useful, though it does not return a PackedSequence object. Is there a PyTorch recommended way to do padding and batching?
st102958
Simple working example how to use packing for variable-length sequence inputs for rnn Hi, Updated - here’s a simple example of how I think you use pack_padded_sequence and pad_packed_sequence, but I don’t know if it’s the right way to use them? import torch import torch.nn as nn from torch.autograd import Variable batch_size = 3 max_length = 3 hidden_size = 2 n_layers =1 # container batch_in = torch.zeros((batch_size, 1, max_length)) #data vec_1 = torch.FloatTensor([[1, 2, 3]]) vec_2 = torch.FloatTensor([[1, 2, 0]]) vec_3 = torch.FloatTensor([[1, 0, 0]]) batch_in[0] = vec_1…
st102959
I stumbled upon this paper: https://www.researchgate.net/profile/Yavuz_Sari/publication/257406249_A_neural-network_committee_machine_approach_to_the_inverse_kinematics_problem_solution_of_robotic_manipulators/links/571cdbcb08ae6eb94d0e4b90/A-neural-network-committee-machine-approach-to-the-inverse-kinematics-problem-solution-of-robotic-manipulators.pdf?origin=publication_detail 6 The problem I have is with understanding how committee machines work. The only relevant info I find in this article is this: “The neural networks are executed simulta- neously for the given input data and their outputs are evaluated and combined to produce the final committee output to obtain better generalization and performance. The output combination module was often performed based on simple functions on the outputs of individual members in the committee machine, such as majority voting for clas- sification and simple/weighted averaging for regression, without involving the input vectors of attributes” So what does that mean, exactly? I have 10 different neural networks, compute their result, average them, and use that average in error estimation and then do backprop? Or do I simply train 10 different neural networks, then run my test sample through all of them and average the result?
st102960
Based on the sentence before the snippet you posted: In the neural-network committee machine approach, n neural network are trained for solving the same problem independently. I assume the latter is right. It seems to be basically an ensemble of models for the final classification. Regarding the method, it seems they just use majority voting without any learnable weights.
st102961
Given this is regression not classification, by “majority voting” you’re saying they simply average the results of all outputs of all 10 neural nets?
st102962
In a classification majority voting is just the most frequent prediction. For regression they just average the predictions.
st102963
A more general version would be boosting 5. This can be done for almost every type of classifier or regressor and with fixed (as in your case) or learnable weights.
st102964
Average then. Thank you. I’ll try training different NNs and see if I get results they do in the paper.
st102965
Okay, so it’s been a while and I trained an ensemble. Indeed, training more than one NN and averaging the results yields more accurate results. Usually… The error of a single NN in my case is (in Cartesian coordinates) about 2.2 cm, whereas with an ensemble it goes down to 1.5 cm. In the paper I mentioned there the authors report 10x better accuracy with using 6 NN which is definitely not the case for me and I wonder why is that. I can say that I trained my NNs with far more epochs and used the same NN architecture with the same hyperparameters but different seed for random number generator was provided for each NN. Is doing it this way much different form using different hyperparameters for each NN as the authors did and showed in table 3? One more thing that bugs me in the article is this sentence: In Eq. (10), the euclidian distance equation has been given. This equation has been used to calculate the distance between end effector and the target known as end effector error. The selection of the best result among neural-network results in the committee machine has been done using this equation. I don’t understand what “selection of the best result” means. During inference we can hardly tell to which one of those NNs the output is closest to so we can’t really “compare” the result to those NNs.
st102966
Using the same hyperparameters for the models in an ensemble is usually not the best idea. This might lead to correlated outputs of the models and thus a low model variety. I think this toy example was used in Stanford’s CS231n, but I cannot find the source anymore. We compare an ensemble of good but correlated and worse but uncorrelated models: target - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 case 1: modelA - 1, 1, 1, 1, 1, 1, 1, 1, 0, 0 - 0.8 modelB - 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 - 0.9 modelC - 1, 1, 1, 1, 1, 1, 1, 1, 0, 0 - 0.8 ------------------------------------------- majority - 1, 1, 1, 1, 1, 1, 1, 1, 0, 0 - 0.8 case 2: modelA - 1, 0, 1, 1, 1, 1, 1, 0, 0, 1 - 0.7 modelB - 0, 1, 1, 1, 1, 1, 0, 1, 0, 1 - 0.7 modelC - 1, 1, 1, 0, 1, 1, 1, 1, 1, 0 - 0.8 ------------------------------------------- majority - 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 - 0.9 As you can see this is a toy example, but even though we ensemble worse models, the benefit comes from uncorrelated outputs, i.e. a high model variety.
st102967
I see. I have now run 6 different trainings with different random seeds, neurons for hidden layer and different learning rates. The training has barely started, the error is not that big but when I compute ensemble error the result is often worse than that from one or two currently best nets. I’ll wait till morning for final results but at the moment the ensemble doesn’t look promising.
st102968
Also note that for ensemble method the trainset is usually splitted into N random subsets when training N models. Thus every model is trained on a different subset (they may overlap). This would lead to the case that every model learns slightly different features, becoming an “expert” on it’s own type of data (they usually tend to overfit). Afterwards the negative results of overfitting in a single model should be canceled out by running the ensemble classifier.
st102969
Okay so I’ve tried all your suggestions: using different subsets of the training set for each nn, using different hyperparams for each nn. None of these produces networks that combined together give me more than 20-30% more accuracy. Instead of relying on the committee I trained one more network, which also has 24 neurons in a layer, but has two (hidden) layers, not one. And that network managed to get 10x more accuracy than each of the 1-hidden-layer network. Nevertheless I would be happy to figure out how to get the committee working. I wonder what the authors mean by “selection of the best result among neural-network results in the committee machine”. Since they’re training 10 nns and say that only 6 are needed I would guess this “selection” refers to picking these 6 nns out of those 10 nns.
st102970
20-30% in increased accuracy sounds like a big improvement when using ensembles. Usually you will get approx. 1-2% increase in accuracy. If another architecture works better, I would go for it and maybe try an ensemble at the end of your experiments.
st102971
The authors of the paper report 10x increase in accuracy. Although the article is not clear to me in many aspects. They didn’t even say explicitly what kind of error function they are optimizing. I wonder if they just didn’t train dozens of NNs and picked best six; that’s what “selection of the best result among neural-network results in the committee machine” could mean.
st102972
The pytorch tag starts at 0. How to make the tag input according to its own category. For example, this type of data is 3, and the other class is 4, instead of starting from 0.I want to do this because the network output does not use softmax, but instead outputs the result of linear regression, compared to my own category label. thanks.
st102973
When i what to change the model trained on 2 gpus to 4 gpus, there is some mistake. Maybe the nn.Parallel has been used twice? But if i want change the gpu numbers, i can’t have any ideas.
st102974
Are there any flag which is equivalent to the tensorflow’s allow_soft_placement?
st102975
Hi, I would like to parallelize the loss function computation. I customize the loss function by wraping it as a module. In the last line of the module, I need to compute the mean of the loss for the whole batch: loss = torch.mean(loss_per_sample) It seems that this line makes the data parallel difficult. Before that, the loss for each data sample can be computed in parallel on different GPUs. How to make the overall loss function computed in parallel? Thanks!
st102976
I understand that I can freeze weights in an entire layer. Can i freeze a selected part of a layer while leaving some filters active? I don’t want to override weights or gradients. I would rather avoid the overhead of the gradient computation and the overriding step since I’m not going to use them. is this possible? and how?
st102977
I’m not sure if this is possible. Would you be able to divide the layer into two pieces? One which includes the part you will eventually want to freeze and one that does not?
st102978
So I guess the answer is probably not. Im not sure about splitting layers because the backprop still would have to go thru those neurons, only they would simply let the gradients pass unmodified; I would have to see how to rewire the graph. Even if that were possible, Im trying to do something dynamic - a bit like dropout but a. not random but assigned b. on gradients c. i dont want to kill the gradients that go there, just let them thru. I wonder if the overhead of rebuilding the layers is not more than flattening the gradients before backprop. In my case ideally one would pass a mask to the forward graph that only computes gradients on some layers assigning a passthru to the others. But I dont know enough about the guts of pytorch or cuda to understand if that would break the parallel computations. I guess I just will have to test to measure how costly this is. thanks
st102979
Directly modify the gradient won’t add too much cost given that you choose the right way to implement it.
st102980
I was hoping to avoid the cost of computing the gradients when I didnt need to. Ill use as is for now. thanks.
st102981
I want to tile a single channel map to multi-channel map, and map in each channel is equal to the original map, how I realize this? Any suggestion is appreciated. Thank you!!!
st102982
Do you just want to repeat the channel? batch_size, c, h, w = 1, 1, 10, 10 x = torch.randn(batch_size, c, h, w) x = x.repeat(1, 3, 1, 1) print(x.shape)
st102983
Pytorch has gained a number of new features since the last release (off the top of my head, torch.where and LayerNorm). I believe I read somewhere that pytorch is on a 90-day release cycle between major releases, which puts the next release around now. Is there an expected release date yet?
st102984
Hi, I’m not sure if there is a given date yet, but there is still a bit of work to be done before it as you can see in this issue 60 tracking the progress toward 0.4.
st102985
As for 1.0, “1.0 issue tracking” exists? or https://github.com/pytorch/pytorch/issues/9280 26 is the 1.0 issue tracking?
st102986
https://github.com/pytorch/pytorch/issues/9280 28 is the issues tracking for 0.4.1.
st102987
nccl_reduce_bucket_size is set to a fixed 256MB, is there any reason that this is not a larger number? Increasing this seems like will make reduction faster.
st102988
Hey there, I am having some problems with a Video Detection RNN. My Architecture looks like the following: For training, I am having a video with vid_length=2048 frames, I divide the the video into vid_length / delta separate blocks. These blocks are used as input for a (3D-ConvNet) C3D-feature-extractor so this Conv3d net is encoding the features from delta=16 frames. I then flatten the output and use it as input for GRU layer this outputs a value between 0 - 1 which is the classification for the the delta=16 frames at time_step=n (where n is from 1 to vid_lenght / delta. Now to my question: My seq_length=512 frames ergo feature_seq_length=32 so the input for the GRU is of size (batch, 32, C3D_output_size). How do I process the input for the C3D so I that I have the 32 outputs as inputs for the GRU. I would like that the model is trainable end-to-end? My approach would be to run the C3D on the 512 frames to get 32 outputs and use those as a sequence for the GRU. What is your opinion on this?
st102989
I feel bad with tagging you here, but you are a nice person, right? Thanks for your previous help @ptrblck. Looking forward to contribute here, it’s an amazing forum!
st102990
We have a lot of awesome guys here, but thanks for the kind words. I don’t quite understand your second paragraph. Do you want to use only 512 frames for the GRU and then reset it?
st102991
I know. Hopefully I will be one of them soon too :D. So, during training time I have example videos of vid_length=2048 frames but the max length my RNN rolls out is seq_length=512 frames, because it takes the output from the Conv3D which itself acts as a feature-detector on delta=16 frames so the actual input for the RNN is seq_length=32 (32 * 16 = 512) because I have this Conv3D which ‘summarizes’ 16 frames into one feature map. a timestep t_n to t_n+1 is 16 frames. So I want to use 32 feature maps (512 frames) for the RNN and then reset it, yes.
st102992
OK, thanks for the info. I had a bit of spare time and tried to create a starter code: class MyModel(nn.Module): def __init__(self, window=16): super(MyModel, self).__init__() self.conv_model = nn.Sequential( nn.Conv3d( in_channels=3, out_channels=6, kernel_size=3, stride=1, padding=1), nn.MaxPool3d((1, 2, 2)), nn.ReLU() ) self.rnn = nn.RNN( input_size=6*16*12*12, hidden_size=1, num_layers=1, batch_first=True ) self.hidden = torch.zeros(1, 1, 1) self.window = window def forward(self, x): self.hidden = torch.zeros(1, 1, 1) # reset hidden activations = [] for idx in range(0, x.size(2), self.window): x_ = x[:, :, idx:idx+self.window] x_ = self.conv_model(x_) x_ = x_.view(x_.size(0), 1, -1) activations.append(x_) x = torch.cat(activations, 1) out, hidden = self.rnn(x, self.hidden) return out, hidden class MyDataset(Dataset): def __init__(self, frames=512): self.data = torch.randn(3, 2048, 24, 24) self.frames = frames def __getitem__(self, index): index = index * self.frames x = self.data[:, index:index+self.frames] return x def __len__(self): return self.data.size(1) / self.frames model = MyModel() dataset = MyDataset() x = dataset[0] output, hidden = model(x.unsqueeze(0)) As I’m not that experienced with RNNs, you should definitely check for logical errors. Let me know, if you find something weird. Also, currently I’m using the output of the RNN. If you want, you could add a linear layer after the RNN, use a bigger hidden size, and return the linear layer with a sigmoid as the non-linearity. This would probably better fit your use case.
st102993
Wow thanks a lot, that is almost like I have implemented it , the dataset part is really helpful, WOW! <3<3<3 Gonna implement it further and will let you know!
st102994
Is there any document for C API of pytorch. For example, how to convert between a THFloatTensor and a C array. I cant find it on websites of PyTorch and torch7.
st102995
No, I’m afraid you have to read the source code or ask. To get the data pointer you can use THFloatTensor_data(tensor).
st102996
I am trying to use THFloatTensor_data(tensor), but I don’t see how to get the value [i,j] of a 2d tensor: Imagine input is a 2d tensor, what I can do is: float *int input_data = THFloatTensor_data(input) Then, I have access to input_data[i]. But how can I have input_data[i][j] ?
st102997
@apaszke I’m not in the pytorch slack yet, but would you consider making a channel for people to discuss the C API specifically? Seen a few questions and have a few myself… would be nice to have it all in one place.
st102998
You can use THFloatTensor_get2d(input,i,j) to accese ipnut[i][j]. A general method is to compute the index of the value by hand. In the 2d tensor case, for input[i,j]: long offset = input->storageOffset+i*input->stride[0]+j*input->stride[1]; float val = THFloatStorage_get(input->storage, offset);
st102999
@ncullen93 Sure! Come to #cffi. Also, note that it might be way faster to use input->storage->data directly. THFloatStorage_get will do that + bound checking, so it will be slower in tight loops.