Repository: kornia/kornia

Issue:
Wrong shape check on `pos_weight` in focal loss
### Describe the bug
The shape checking mechanism for the argument `pos_weight` of the focal loss function is wrong.

https://github.com/kornia/kornia/blob/master/kornia/losses/focal.py#L206

### Reproduction steps

```bash
input_shape: [B, C, H, W]
pos_weight_shape: [C]

if C != W, then the check failed.
```


### Expected behavior

dim index should be 1 instead of -1.

```python
KORNIA_CHECK(input.shape[1] == pos_weight.shape[0], "Expected pos_weight equals number of classes.")
```

### Environment

```shell
PyTorch version: 1.13.0+cu117
Is debug build: False
CUDA used to build PyTorch: 11.7
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.5 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.31

Python version: 3.9.16 (main, Dec  9 2022, 13:50:07)  [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.15.0-53-generic-x86_64-with-glibc2.31
Is CUDA available: False
CUDA runtime version: 11.2.152
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: 
GPU 0: NVIDIA GeForce GTX 1080 Ti
GPU 1: NVIDIA GeForce GTX 1080 Ti
GPU 2: NVIDIA GeForce GTX 1080 Ti

Nvidia driver version: 515.86.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
Byte Order:                      Little Endian
Address sizes:                   46 bits physical, 48 bits virtual
CPU(s):                          20
On-line CPU(s) list:             0-19
Thread(s) per core:              2
Core(s) per socket:              10
Socket(s):                       1
NUMA node(s):                    1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           79
Model name:                      Intel(R) Xeon(R) CPU E5-2630 v4 @ 2.20GHz
Stepping:                        1
CPU MHz:                         1200.000
CPU max MHz:                     3100.0000
CPU min MHz:                     1200.0000
BogoMIPS:                        4397.68
L1d cache:                       320 KiB
L1i cache:                       320 KiB
L2 cache:                        2.5 MiB
L3 cache:                        25 MiB
NUMA node0 CPU(s):               0-19
Vulnerability Itlb multihit:     KVM: Mitigation: VMX unsupported
Vulnerability L1tf:              Mitigation; PTE Inversion
Vulnerability Mds:               Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown:          Mitigation; PTI
Vulnerability Mmio stale data:   Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:          Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Retpolines, IBPB conditional, IBRS_FW, STIBP conditional, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Mitigation; Clear CPU buffers; SMT vulnerable
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single pti intel_ppin ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap intel_pt xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts md_clear flush_l1d

Versions of relevant libraries:
[pip3] flake8==5.0.4
[pip3] numpy==1.23.5
[pip3] pytorch-lightning==1.8.3.post0
[pip3] torch==1.13.0+cu117
[pip3] torch-tb-profiler==0.4.0
[pip3] torchdata==0.5.0
[pip3] torchmetrics==0.11.4
[pip3] torchvision==0.14.0+cu117
[conda] Could not collect
```


### Additional context

_No response_


Discussion:
Nice catch, probably this is wrong https://github.com/kornia/kornia/blob/master/kornia/losses/focal.py#L203 too. Can you submit a PR to fix it? 😄 
Sure~!

Resolving patch:
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -200,10 +200,10 @@ def binary_focal_loss_with_logits(
     )
 
     if pos_weight is None:
-        pos_weight = torch.ones(input.shape[-1], device=input.device, dtype=input.dtype)
+        pos_weight = torch.ones([input.shape[1], *([1] * len(input.shape[2:]))], device=input.device, dtype=input.dtype)
 
     KORNIA_CHECK_IS_TENSOR(pos_weight)
-    KORNIA_CHECK(input.shape[-1] == pos_weight.shape[0], "Expected pos_weight equals number of classes.")
+    KORNIA_CHECK(input.shape[1] == pos_weight.shape[0], "Expected pos_weight equals number of classes.")
 
     probs_pos = input.sigmoid()
     probs_neg = (-input).sigmoid()


Test patch:
diff --git a/test/losses/test_losses.py b/test/losses/test_losses.py
--- a/test/losses/test_losses.py
+++ b/test/losses/test_losses.py
@@ -59,7 +59,7 @@ def test_smoke_pos_weight(self, device, dtype, pos_weight):
                 reduction="mean",
                 pos_weight=None
                 if pos_weight is None
-                else torch.full([logits.size(-1)], pos_weight, dtype=dtype, device=device),
+                else torch.full([logits.size(1), 1], pos_weight, dtype=dtype, device=device),
             ).shape
             == ()
         )