Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Gradient can be backpropagated through only certain distributions #152703

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
AlbertoSinigaglia opened this issue May 2, 2025 · 4 comments
Closed
Labels
module: autograd Related to torch.autograd, and the autograd engine in general module: distributions Related to torch.distributions triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Comments

@AlbertoSinigaglia
Copy link

AlbertoSinigaglia commented May 2, 2025

πŸ› Describe the bug

Using Normal, I can avoid having to preserve gradients:

params = torch.tensor([[0.2], [0.3]]).float().to(device)
params.requires_grad = True
with torch.no_grad():
    distr = torch.distributions.normal.Normal(params, params*0+1)
    sample = distr.sample().squeeze()
distr.log_prob(sample).mean().backward()
print(params.grad)

# runs fine

Using Categorical, this is not the case:

params = torch.tensor([[0.2, 0.8], [0.3, 0.7]]).float().to(device)
params.requires_grad = True
with torch.no_grad():
    distr = torch.distributions.categorical.Categorical(params)
    sample = distr.sample().squeeze()
distr.log_prob(sample).mean().backward()
print(params.grad)

# RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn

I'm not sure why this is the case, log-probs might be something like torch.log(probs[one_hot(samples)].mean(axis=-1)) and it's completely differntiable, so should be able to do it without gradient in the distribution

Versions

Collecting environment information...
PyTorch version: 2.7.0+cu126
Is debug build: False
CUDA used to build PyTorch: 12.6
ROCM used to build PyTorch: N/A

OS: Debian GNU/Linux 12 (bookworm) (x86_64)
GCC version: (Debian 12.2.0-14) 12.2.0
Clang version: Could not collect
CMake version: version 3.25.1
Libc version: glibc-2.36

Python version: 3.10.14 | packaged by conda-forge | (main, Mar 20 2024, 12:45:18) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-6.1.0-31-amd64-x86_64-with-glibc2.36
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA L40S
GPU 1: NVIDIA L40S
GPU 2: NVIDIA L40S
GPU 3: NVIDIA L40S
GPU 4: NVIDIA L40S
GPU 5: NVIDIA L40S

Nvidia driver version: 535.216.01
cuDNN version: Could not collect
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                         x86_64
CPU op-mode(s):                       32-bit, 64-bit
Address sizes:                        52 bits physical, 57 bits virtual
Byte Order:                           Little Endian
CPU(s):                               96
On-line CPU(s) list:                  0-95
Vendor ID:                            AuthenticAMD
Model name:                           AMD EPYC 9224 24-Core Processor
CPU family:                           25
Model:                                17
Thread(s) per core:                   2
Core(s) per socket:                   24
Socket(s):                            2
Stepping:                             1
Frequency boost:                      enabled
CPU(s) scaling MHz:                   58%
CPU max MHz:                          3706.0540
CPU min MHz:                          1500.0000
BogoMIPS:                             4999.84
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good amd_lbr_v2 nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 invpcid_single hw_pstate ssbd mba perfmon_v2 ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif x2avic v_spec_ctrl avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid overflow_recov succor smca fsrm flush_l1d
Virtualization:                       AMD-V
L1d cache:                            1.5 MiB (48 instances)
L1i cache:                            1.5 MiB (48 instances)
L2 cache:                             48 MiB (48 instances)
L3 cache:                             128 MiB (8 instances)
NUMA node(s):                         2
NUMA node0 CPU(s):                    0-23,48-71
NUMA node1 CPU(s):                    24-47,72-95
Vulnerability Gather data sampling:   Not affected
Vulnerability Itlb multihit:          Not affected
Vulnerability L1tf:                   Not affected
Vulnerability Mds:                    Not affected
Vulnerability Meltdown:               Not affected
Vulnerability Mmio stale data:        Not affected
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Not affected
Vulnerability Spec rstack overflow:   Mitigation; safe RET
Vulnerability Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:             Mitigation; Enhanced / Automatic IBRS; IBPB conditional; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] numpy==2.2.5
[pip3] nvidia-cublas-cu12==12.6.4.1
[pip3] nvidia-cuda-cupti-cu12==12.6.80
[pip3] nvidia-cuda-nvrtc-cu12==12.6.77
[pip3] nvidia-cuda-runtime-cu12==12.6.77
[pip3] nvidia-cudnn-cu12==9.5.1.17
[pip3] nvidia-cufft-cu12==11.3.0.4
[pip3] nvidia-curand-cu12==10.3.7.77
[pip3] nvidia-cusolver-cu12==11.7.1.2
[pip3] nvidia-cusparse-cu12==12.5.4.2
[pip3] nvidia-cusparselt-cu12==0.6.3
[pip3] nvidia-nccl-cu12==2.26.2
[pip3] nvidia-nvjitlink-cu12==12.6.85
[pip3] nvidia-nvtx-cu12==12.6.77
[pip3] torch==2.7.0
[pip3] torchvision==0.22.0
[pip3] triton==3.3.0
[conda] No relevant packages

cc @fritzo @neerajprad @alicanb @nikitaved @ezyang @albanD @gqchen @soulitzer @Varal7 @xmfan

@aishwaryar12309
Copy link
Contributor

aishwaryar12309 commented May 2, 2025

I agree that mathematically, computing log_prob from probs and sample is differentiable as long as probs.requires_grad=True and sample is treated as a constant tensor, but I believe the issue is in how the sample was created (in no_grad() vs not). I believe if you sample the way you are doing, the sample will be a detached tensor. PyTorch doesn't retain the link between sample and probs. So even though log_prob(sample) uses probs under the hood (via gather or one-hot), the indexing operation is non-differentiable because sample is just a static integer at that point.

Maybe a more meaningful error message could be produced for using Categorial.log_prob() with a detached sample...

Or you could try to use gumbel_softmax docs or RelaxedOneHotCategorical

@AlbertoSinigaglia
Copy link
Author

@aishwaryar12309 yup that makes sense, but I'm not expecting the sample to be differentiable, but the log-likelihood of it to be differentiable. Gumbel or Straight though allows you to have the sample with a gradient, but in this case it's much simpler the problem.

@aishwaryar12309
Copy link
Contributor

aishwaryar12309 commented May 2, 2025

@AlbertoSinigaglia I see. That's reasonable -- to expect that log_prob(sample) should still be differentiable with respect to the distribution params. I agree with you that it should hold true, even if the sample is detached. I think the issue is when the sample is drawn inside a torch.no_grad() block. PyTorch may not track the internal log and gather ops in log_prob, which likely kills the grad path.

This seems like more of expected-but-confusing issue rather than a bug. Off the top of my head, I think a warning would be helpful if .log_prob() gets called w/ a detached sample and probs.requires_grad = True. I hope that made sense!

@soulitzer

@zou3519 zou3519 added module: distributions Related to torch.distributions module: autograd Related to torch.autograd, and the autograd engine in general triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module labels May 6, 2025
@fritzo
Copy link
Collaborator

fritzo commented May 7, 2025

I'd move the distribution construction outside of the no_grad context. It seems mere luck that Normal can be constructed in a no_grad context, and I wouldn't expect that to work in general.

@fritzo fritzo closed this as completed May 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
module: autograd Related to torch.autograd, and the autograd engine in general module: distributions Related to torch.distributions triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module
Projects
None yet
Development

No branches or pull requests

4 participants