torchpsort 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
torchpsort/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .ops import soft_rank, soft_sort
2
+
3
+ __all__ = ["soft_sort", "soft_rank"]
torchpsort/isotonic.py ADDED
@@ -0,0 +1,180 @@
1
+ # Copyright 2007-2020 The scikit-learn developers.
2
+ # Copyright 2020 Google LLC.
3
+ # Copyright 2021 Teddy Koker.
4
+ # Copyright 2026 RektPunk
5
+ #
6
+ # All rights reserved.
7
+ #
8
+ # Redistribution and use in source and binary forms, with or without
9
+ # modification, are permitted provided that the following conditions are met:
10
+ #
11
+ # a. Redistributions of source code must retain the above copyright notice,
12
+ # this list of conditions and the following disclaimer.
13
+ # b. Redistributions in binary form must reproduce the above copyright
14
+ # notice, this list of conditions and the following disclaimer in the
15
+ # documentation and/or other materials provided with the distribution.
16
+ # c. Neither the name of the Scikit-learn Developers nor the names of
17
+ # its contributors may be used to endorse or promote products
18
+ # derived from this software without specific prior written
19
+ # permission.
20
+ #
21
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
25
+ # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27
+ # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28
+ # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29
+ # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30
+ # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
31
+ # DAMAGE.
32
+
33
+ import torch
34
+ from torch import Tensor
35
+
36
+
37
+ @torch.jit.script
38
+ def isotonic_l2_forward(x: Tensor) -> Tensor:
39
+ batch_size, p = x.shape
40
+ solution = x.clone()
41
+ block_sums = x.clone()
42
+ block_counts = torch.ones_like(x)
43
+ block_end = (
44
+ torch.arange(p, device=x.device, dtype=torch.long)
45
+ .expand(batch_size, -1)
46
+ .clone()
47
+ )
48
+ for b in range(batch_size):
49
+ block = 0
50
+ while block < p:
51
+ next_block = block_end[b, block] + 1
52
+ if next_block == p:
53
+ break
54
+ if solution[b, block] > solution[b, next_block]:
55
+ block = next_block
56
+ continue
57
+
58
+ block_sum = block_sums[b, block]
59
+ block_count = block_counts[b, block]
60
+
61
+ while True:
62
+ last_value = solution[b, next_block]
63
+ block_sum += block_sums[b, next_block]
64
+ block_count += block_counts[b, next_block]
65
+ next_block = block_end[b, next_block] + 1
66
+
67
+ if next_block == p or last_value > solution[b, next_block]:
68
+ solution[b, block] = block_sum / block_count
69
+ block_sums[b, block] = block_sum
70
+ block_counts[b, block] = block_count
71
+ block_end[b, block] = next_block - 1
72
+ block_end[b, next_block - 1] = block
73
+
74
+ if block > 0:
75
+ block = block_end[b, block - 1]
76
+ break
77
+
78
+ block = 0
79
+ while block < p:
80
+ next_block = block_end[b, block] + 1
81
+ solution[b, (block + 1) : next_block] = solution[b, block]
82
+ block = next_block
83
+
84
+ return solution
85
+
86
+
87
+ @torch.jit.script
88
+ def isotonic_kl_forward(x: Tensor, w: Tensor) -> Tensor:
89
+ batch_size, p = x.shape
90
+ solution = x - w
91
+ block_lse_x = x.clone()
92
+ block_lse_w = w.clone()
93
+ block_end = (
94
+ torch.arange(p, device=x.device, dtype=torch.long)
95
+ .expand(batch_size, -1)
96
+ .clone()
97
+ )
98
+
99
+ for b in range(batch_size):
100
+ block = 0
101
+ while block < p:
102
+ next_block = block_end[b, block] + 1
103
+ if next_block == p:
104
+ break
105
+ if solution[b, block] > solution[b, next_block]:
106
+ block = next_block
107
+ continue
108
+
109
+ curr_lse_x = block_lse_x[b, block]
110
+ curr_lse_w = block_lse_w[b, block]
111
+
112
+ while True:
113
+ last_value = solution[b, next_block]
114
+ curr_lse_x = torch.logaddexp(curr_lse_x, block_lse_x[b, next_block])
115
+ curr_lse_w = torch.logaddexp(curr_lse_w, block_lse_w[b, next_block])
116
+ next_block = block_end[b, next_block] + 1
117
+
118
+ if next_block == p or last_value > solution[b, next_block]:
119
+ solution[b, block] = curr_lse_x - curr_lse_w
120
+ block_lse_x[b, block] = curr_lse_x
121
+ block_lse_w[b, block] = curr_lse_w
122
+ block_end[b, block] = next_block - 1
123
+ block_end[b, next_block - 1] = block
124
+
125
+ if block > 0:
126
+ block = block_end[b, block - 1]
127
+ break
128
+
129
+ block = 0
130
+ while block < p:
131
+ next_block = block_end[b, block] + 1
132
+ solution[b, (block + 1) : next_block] = solution[b, block]
133
+ block = next_block
134
+
135
+ return solution
136
+
137
+
138
+ @torch.jit.script
139
+ def isotonic_l2_backward(sol: Tensor, grad_output: Tensor) -> Tensor:
140
+ batch_size, p = sol.shape
141
+ grad_input = torch.empty_like(grad_output)
142
+ tol = 1e-6 if sol.dtype == torch.float32 else 1e-12
143
+ for b in range(batch_size):
144
+ start = 0
145
+ while start < p:
146
+ end = start + 1
147
+ while end < p and torch.abs(sol[b, end] - sol[b, start]) < tol:
148
+ end += 1
149
+
150
+ val = 1.0 / float(end - start)
151
+
152
+ grad_sum = grad_output[b, start:end].sum()
153
+ grad_input[b, start:end] = val * grad_sum
154
+
155
+ start = end
156
+
157
+ return grad_input
158
+
159
+
160
+ @torch.jit.script
161
+ def isotonic_kl_backward(s: Tensor, sol: Tensor, grad_output: Tensor) -> Tensor:
162
+ batch_size, p = sol.shape
163
+ grad_input = torch.empty_like(grad_output)
164
+ tol = 1e-6 if sol.dtype == torch.float32 else 1e-12
165
+ for b in range(batch_size):
166
+ start = 0
167
+ while start < p:
168
+ end = start + 1
169
+ while end < p and torch.abs(sol[b, end] - sol[b, start]) < tol:
170
+ end += 1
171
+
172
+ block_s = s[b, start:end]
173
+ softmax_weights = torch.softmax(block_s, dim=0)
174
+
175
+ grad_sum = grad_output[b, start:end].sum()
176
+ grad_input[b, start:end] = softmax_weights * grad_sum
177
+
178
+ start = end
179
+
180
+ return grad_input
torchpsort/ops.py ADDED
@@ -0,0 +1,160 @@
1
+ # Copyright 2020 Google LLC
2
+ # Copyright 2021 Teddy Koker
3
+ # Copyright 2026 RektPunk
4
+
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # https://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from typing import Literal
18
+
19
+ import torch
20
+ from torch import Tensor
21
+
22
+ from .isotonic import (
23
+ isotonic_kl_backward,
24
+ isotonic_kl_forward,
25
+ isotonic_l2_backward,
26
+ isotonic_l2_forward,
27
+ )
28
+
29
+
30
+ @torch.jit.script
31
+ def _index_range(x: Tensor) -> Tensor:
32
+ return torch.arange(
33
+ x.shape[1],
34
+ dtype=x.dtype,
35
+ device=x.device,
36
+ ).expand(x.shape[0], -1)
37
+
38
+
39
+ @torch.jit.script
40
+ def _descending_ranks(x: Tensor) -> Tensor:
41
+ return torch.arange(
42
+ x.shape[1],
43
+ 0,
44
+ -1,
45
+ dtype=x.dtype,
46
+ device=x.device,
47
+ ).expand_as(x)
48
+
49
+
50
+ @torch.jit.script
51
+ def _inv_permutation(permutation: Tensor) -> Tensor:
52
+ inv_permutation = torch.empty_like(permutation)
53
+ inv_permutation.scatter_(1, permutation, _index_range(permutation))
54
+ return inv_permutation
55
+
56
+
57
+ def _validate_inputs(x: Tensor, reg: Literal["l2", "kl"], tau: float) -> None:
58
+ if x.ndim != 2:
59
+ raise ValueError("x must be a 2D tensor")
60
+
61
+ if reg not in ("l2", "kl"):
62
+ raise ValueError(f"Unknown reg: {reg}")
63
+
64
+ if tau <= 0:
65
+ raise ValueError("tau must be positive")
66
+
67
+
68
+ class SoftRank(torch.autograd.Function):
69
+ @staticmethod
70
+ def forward(ctx, x: Tensor, reg: Literal["l2", "kl"] = "l2", tau: float = 1.0):
71
+ _validate_inputs(x, reg, tau)
72
+
73
+ ctx.scale = 1.0 / tau
74
+ ctx.is_l2 = reg == "l2"
75
+ w = _descending_ranks(x)
76
+ theta = x * ctx.scale
77
+ s, permutation = torch.sort(theta, descending=True)
78
+ inv_permutation = _inv_permutation(permutation)
79
+ if ctx.is_l2:
80
+ dual_sol = isotonic_l2_forward(s - w)
81
+ ret = (s - dual_sol).gather(1, inv_permutation)
82
+ ctx.save_for_backward(dual_sol, permutation, inv_permutation)
83
+ else:
84
+ dual_sol = isotonic_kl_forward(s, torch.log(w))
85
+ ret = torch.exp((s - dual_sol).gather(1, inv_permutation))
86
+ ctx.save_for_backward(ret, s, dual_sol, permutation, inv_permutation)
87
+
88
+ return ret
89
+
90
+ @staticmethod
91
+ def backward(ctx, *grad_outputs):
92
+ if ctx.is_l2:
93
+ dual_sol, permutation, inv_permutation = ctx.saved_tensors
94
+ grad_iso = isotonic_l2_backward(
95
+ dual_sol,
96
+ grad_outputs[0].gather(1, permutation),
97
+ )
98
+ grad = grad_outputs[0] - grad_iso.gather(1, inv_permutation)
99
+ else:
100
+ ret, s, dual_sol, permutation, inv_permutation = ctx.saved_tensors
101
+ grad_iso = isotonic_kl_backward(
102
+ s,
103
+ dual_sol,
104
+ (grad_outputs[0] * ret).gather(1, permutation),
105
+ )
106
+ grad = (grad_outputs[0] * ret) - grad_iso.gather(1, inv_permutation)
107
+
108
+ return grad * ctx.scale, None, None
109
+
110
+
111
+ class SoftSort(torch.autograd.Function):
112
+ @staticmethod
113
+ def forward(ctx, x: Tensor, reg: Literal["l2", "kl"] = "l2", tau: float = 1.0):
114
+ _validate_inputs(x, reg, tau)
115
+
116
+ ctx.is_l2 = reg == "l2"
117
+ w = _descending_ranks(x) / tau
118
+ s, permutation = torch.sort(-x, descending=True)
119
+ inv_permutation = _inv_permutation(permutation)
120
+ if ctx.is_l2:
121
+ sol = isotonic_l2_forward(w - s)
122
+ ctx.save_for_backward(sol, inv_permutation)
123
+ else:
124
+ sol = isotonic_kl_forward(w, s)
125
+ ctx.save_for_backward(s, sol, inv_permutation)
126
+
127
+ return sol - w
128
+
129
+ @staticmethod
130
+ def backward(ctx, *grad_outputs):
131
+ if ctx.is_l2:
132
+ sol, inv_permutation = ctx.saved_tensors
133
+ grad = isotonic_l2_backward(sol, grad_outputs[0])
134
+ else:
135
+ s, sol, inv_permutation = ctx.saved_tensors
136
+ grad = isotonic_kl_backward(s, sol, grad_outputs[0])
137
+
138
+ return grad.gather(1, inv_permutation), None, None
139
+
140
+
141
+ def soft_rank(x: Tensor, reg: Literal["l2", "kl"] = "l2", tau: float = 1.0) -> Tensor:
142
+ """Differentiable approximation of the rank operator.
143
+
144
+ Args:
145
+ x: Input tensor of shape (batch, p)
146
+ reg: Regularization type ("l2" or "kl")
147
+ tau: Regularization strength (temperature)
148
+ """
149
+ return SoftRank.apply(x, reg, tau)
150
+
151
+
152
+ def soft_sort(x: Tensor, reg: Literal["l2", "kl"] = "l2", tau: float = 1.0) -> Tensor:
153
+ """Differentiable approximation of the sort operator.
154
+
155
+ Args:
156
+ x: Input tensor of shape (batch, p)
157
+ reg: Regularization type ("l2" or "kl")
158
+ tau: Regularization strength (temperature)
159
+ """
160
+ return SoftSort.apply(x, reg, tau)
torchpsort/py.typed ADDED
File without changes
@@ -0,0 +1,26 @@
1
+ Metadata-Version: 2.3
2
+ Name: torchpsort
3
+ Version: 0.0.1
4
+ Summary: Fast, differentiable sorting in pure PyTorch without C++ or CUDA
5
+ Author: RektPunk
6
+ Author-email: RektPunk <rektpunk@gmail.com>
7
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
8
+ Requires-Dist: numpy>=2.5.1
9
+ Requires-Dist: torch>=2.13.0
10
+ Requires-Python: >=3.12, <=3.14
11
+ Project-URL: repository, https://github.com/RektPunk/torchpsort
12
+ Description-Content-Type: text/markdown
13
+
14
+ <div style="text-align: center;">
15
+ <img src="https://capsule-render.vercel.app/api?type=transparent&fontColor=0047AB&text=torchpsort&height=120&fontSize=90">
16
+ </div>
17
+
18
+ Fast, differentiable sorting and ranking in **pure PyTorch without C++ or CUDA**. This is a lightweight implementation of [Fast Differentiable Sorting and Ranking (Blondel et al.)](https://arxiv.org/abs/2002.08871) and inspired by [torchsort](https://github.com/teddykoker/torchsort). Unlike the [torchsort](https://github.com/teddykoker/torchsort), this version contains **no C++ or CUDA extensions**, making it easy to install, portable, and compatible with any environment where PyTorch runs. While the original C++/CUDA implementation may have a performance edge for extremely large batch sizes, this pure PyTorch version is optimized to be efficient for standard deep learning workflows. Try it here:
19
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/RektPunk/torchpsort/blob/main/examples/notebook.ipynb)
20
+
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ pip install torchpsort
26
+ ```
@@ -0,0 +1,7 @@
1
+ torchpsort/__init__.py,sha256=uGQfsZ-ZTg1gCbIi43YefATxKxwD-1M8jAtx6d-5lOQ,76
2
+ torchpsort/isotonic.py,sha256=7T3KsXHz-8T5IScTIc9fVACrTk4H2snJa_u7q8NqAqI,6445
3
+ torchpsort/ops.py,sha256=UJeRUreEXEaLr7KjMH7zFO4M9ArFk8z0YsdnmamuVmk,5074
4
+ torchpsort/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ torchpsort-0.0.1.dist-info/WHEEL,sha256=YR4QUxGCbsyoOnWBVTv-p1I4yc3seKGPev46mvmc8Cg,81
6
+ torchpsort-0.0.1.dist-info/METADATA,sha256=VU1zI_3qQ7vsYcS5bnXHq0oL97cWxAWuUE9u1RIY9GM,1556
7
+ torchpsort-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.11.29
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any