diffcb 0.1.0__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.
dcb/utils.py ADDED
@@ -0,0 +1,183 @@
1
+ """
2
+ dcb.utils — Adaptive Hyperparameter Defaults, Grid Construction, and Helpers
3
+
4
+ This module provides utilities for constructing the evaluation grid Ω and for
5
+ setting the softening hyperparameters ε and τ adaptively from data, following
6
+ the data-adaptive defaults described in the DCB paper: ε = 0.1 · std_{x∈Ω}[f'_{h0}(x)]
7
+ and τ = 0.2 · median_{x∈Ω}[|f''_{h0}(x)|], where h0 is a pilot bandwidth
8
+ (Silverman's rule). The function `make_grid(X, G, margin_sigma)` returns a
9
+ G-point uniform grid over [min(X) - margin·σ, max(X) + margin·σ]; the
10
+ function `adaptive_eps_tau(X, h0, grid)` returns the tuple (ε, τ) computed
11
+ from the pilot KDE derivatives; and `cosine_anneal(eps, tau, step, T_max)`
12
+ returns annealed versions that tighten the smoothing over the course of
13
+ training. The stabilized reciprocal `sg(u, delta)` is also defined here.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+
20
+ import torch
21
+ from torch import Tensor
22
+
23
+
24
+ def silverman_bandwidth(X: Tensor) -> float:
25
+ """Return Silverman's rule-of-thumb bandwidth h0 = 0.9 * std(X) * n^{-0.2}.
26
+
27
+ Parameters
28
+ ----------
29
+ X:
30
+ 1-D sample tensor of shape (n,).
31
+
32
+ Returns
33
+ -------
34
+ float
35
+ Positive scalar bandwidth estimate.
36
+ """
37
+ n = X.shape[0]
38
+ std = X.std(unbiased=True).item()
39
+ return 0.9 * std * (n ** -0.2)
40
+
41
+
42
+ def make_grid(X: Tensor, G: int, margin_sigma: float = 3.0) -> Tensor:
43
+ """Return a G-point uniform grid over [min(X) - margin_sigma*std, max(X) + margin_sigma*std].
44
+
45
+ Parameters
46
+ ----------
47
+ X:
48
+ 1-D sample tensor of shape (n,).
49
+ G:
50
+ Number of grid points.
51
+ margin_sigma:
52
+ Number of standard deviations to extend beyond the data range.
53
+
54
+ Returns
55
+ -------
56
+ Tensor
57
+ Shape (G,), same dtype and device as X.
58
+ """
59
+ std = X.std().item()
60
+ lo = X.min().item() - margin_sigma * std
61
+ hi = X.max().item() + margin_sigma * std
62
+ return torch.linspace(lo, hi, G, dtype=X.dtype, device=X.device)
63
+
64
+
65
+ def sg(u: Tensor, delta: float = 1e-4) -> Tensor:
66
+ """Stabilized gradient operator: sign(u) * max(|u|, delta).
67
+
68
+ Handles u=0 by returning delta (not 0), ensuring the output is never zero.
69
+
70
+ Parameters
71
+ ----------
72
+ u:
73
+ Input tensor of any shape.
74
+ delta:
75
+ Minimum absolute value floor. Default 1e-4.
76
+
77
+ Returns
78
+ -------
79
+ Tensor
80
+ Same shape as u; zero inputs map to +delta.
81
+ """
82
+ # sign(0) == 0, so zero inputs would give 0*delta == 0 — treat zero as +1
83
+ sign = torch.where(u >= 0, torch.ones_like(u), -torch.ones_like(u))
84
+ return sign * u.abs().clamp(min=delta)
85
+
86
+
87
+ def adaptive_eps_tau(
88
+ X: Tensor,
89
+ h0: float,
90
+ grid: Tensor,
91
+ eps_coeff: float = 0.1,
92
+ tau_coeff: float = 0.2,
93
+ ) -> tuple[float, float]:
94
+ """Compute adaptive (eps, tau) from pilot KDE derivatives on the grid.
95
+
96
+ Uses the analytical Gaussian kernel derivative formulas to estimate the
97
+ first and second derivatives of the pilot KDE at bandwidth h0, then sets:
98
+ eps = eps_coeff * std(f')
99
+ tau = tau_coeff * median(|f''|)
100
+ Both values are clamped to at least 1e-8.
101
+
102
+ Parameters
103
+ ----------
104
+ X:
105
+ 1-D sample tensor of shape (n,).
106
+ h0:
107
+ Pilot bandwidth (e.g. from silverman_bandwidth).
108
+ grid:
109
+ Evaluation grid of shape (G,).
110
+ eps_coeff:
111
+ Scaling coefficient for eps. Default 0.1.
112
+ tau_coeff:
113
+ Scaling coefficient for tau. Default 0.2.
114
+
115
+ Returns
116
+ -------
117
+ tuple[float, float]
118
+ (eps, tau), both positive floats >= 1e-8.
119
+ """
120
+ # diff[i, j] = (grid[j] - X[i]) / h0 — shape (n, G)
121
+ diff = (grid.unsqueeze(0) - X.unsqueeze(1)) / h0 # (n, G)
122
+ K = torch.exp(-0.5 * diff ** 2) / (math.sqrt(2 * math.pi) * h0)
123
+ f_prime = (-diff / h0 * K).mean(dim=0) # (G,)
124
+ f_double_prime = ((diff ** 2 - 1) / h0 ** 2 * K).mean(dim=0) # (G,)
125
+
126
+ eps = eps_coeff * f_prime.std().item()
127
+ tau = tau_coeff * f_double_prime.abs().median().item()
128
+
129
+ eps = max(eps, 1e-8)
130
+ tau = max(tau, 1e-8)
131
+ return eps, tau
132
+
133
+
134
+ def anneal_eps_tau(eps: float, tau: float, anneal_factor: float) -> tuple[float, float]:
135
+ """Scale (eps, tau) by anneal_factor to sharpen the soft mode-count approximation.
136
+
137
+ At anneal_factor=1.0 returns the original adaptive defaults.
138
+ At anneal_factor→0, M̃(h) converges to the true integer mode count M(h),
139
+ but IFT gradients become ill-conditioned. Typical evaluation values:
140
+ 0.05–0.10 for best accuracy; use 1.0 during gradient-based training.
141
+
142
+ Parameters
143
+ ----------
144
+ eps : float
145
+ Base Gaussian-delta width (from adaptive_eps_tau).
146
+ tau : float
147
+ Base sigmoid temperature (from adaptive_eps_tau).
148
+ anneal_factor : float
149
+ Multiplicative scale ∈ (0, 1]. Clamped to [1e-6, 1.0].
150
+
151
+ Returns
152
+ -------
153
+ tuple[float, float]
154
+ (eps_annealed, tau_annealed), both >= 1e-8.
155
+ """
156
+ factor = max(1e-6, min(1.0, anneal_factor))
157
+ return max(eps * factor, 1e-8), max(tau * factor, 1e-8)
158
+
159
+
160
+ def cosine_anneal(val_init: float, val_final: float, step: int, T_max: int) -> float:
161
+ """Cosine annealing schedule from val_init to val_final over T_max steps.
162
+
163
+ At step=0 returns val_init exactly; at step=T_max returns val_final exactly.
164
+ Steps beyond T_max are clamped to T_max (returns val_final).
165
+
166
+ Parameters
167
+ ----------
168
+ val_init:
169
+ Starting value (returned at step=0).
170
+ val_final:
171
+ Ending value (returned at step=T_max).
172
+ step:
173
+ Current step index (0-based).
174
+ T_max:
175
+ Total number of annealing steps.
176
+
177
+ Returns
178
+ -------
179
+ float
180
+ Annealed value at the given step.
181
+ """
182
+ t = min(step, T_max)
183
+ return val_final + 0.5 * (val_init - val_final) * (1 + math.cos(math.pi * t / T_max))
@@ -0,0 +1,148 @@
1
+ Metadata-Version: 2.4
2
+ Name: diffcb
3
+ Version: 0.1.0
4
+ Summary: Differentiable Critical Bandwidth: Silverman's modality test as a differentiable PyTorch layer with IFT backward pass.
5
+ Project-URL: Homepage, https://github.com/ryZhangHason/differentiable-critical-bandwidth
6
+ Project-URL: Repository, https://github.com/ryZhangHason/differentiable-critical-bandwidth
7
+ Project-URL: Documentation, https://github.com/ryZhangHason/differentiable-critical-bandwidth#readme
8
+ Project-URL: Bug Tracker, https://github.com/ryZhangHason/differentiable-critical-bandwidth/issues
9
+ Author-email: Ruiyu Zhang <dhhhason@gmail.com>
10
+ License: MIT License
11
+
12
+ Copyright (c) 2026 Ruiyu Zhang
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.
31
+ License-File: LICENSE
32
+ Keywords: PyTorch,anomaly detection,critical bandwidth,differentiable programming,generative models,kernel density estimation,mode counting,nonparametric statistics
33
+ Classifier: Development Status :: 3 - Alpha
34
+ Classifier: Intended Audience :: Science/Research
35
+ Classifier: License :: OSI Approved :: MIT License
36
+ Classifier: Programming Language :: Python :: 3
37
+ Classifier: Programming Language :: Python :: 3.9
38
+ Classifier: Programming Language :: Python :: 3.10
39
+ Classifier: Programming Language :: Python :: 3.11
40
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
41
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
42
+ Requires-Python: >=3.9
43
+ Requires-Dist: matplotlib>=3.7.0
44
+ Requires-Dist: numpy>=1.24.0
45
+ Requires-Dist: scikit-learn>=1.3.0
46
+ Requires-Dist: scipy>=1.10.0
47
+ Requires-Dist: torch>=2.0.0
48
+ Provides-Extra: dev
49
+ Requires-Dist: black>=23.0.0; extra == 'dev'
50
+ Requires-Dist: pytest-cov>=4.1.0; extra == 'dev'
51
+ Requires-Dist: pytest>=7.4.0; extra == 'dev'
52
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
53
+ Provides-Extra: notebooks
54
+ Requires-Dist: ipywidgets>=8.0.0; extra == 'notebooks'
55
+ Requires-Dist: jupyter>=1.0.0; extra == 'notebooks'
56
+ Description-Content-Type: text/markdown
57
+
58
+ # DCB — Differentiable Critical Bandwidth
59
+
60
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
61
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/)
62
+
63
+ A PyTorch package that makes **Silverman's critical bandwidth test (1981)** fully differentiable, enabling end-to-end gradient-based optimization over the modal structure of continuous distributions.
64
+
65
+ ## Overview
66
+
67
+ The critical bandwidth `h_crit` is the minimum KDE bandwidth at which a distribution appears to have at most `m` modes — a classical nonparametric statistic for modality testing. DCB replaces every non-differentiable operation in its computation with a smooth surrogate, then uses the **Implicit Function Theorem** to compute exact gradients through the root-finding step at O(1) memory cost.
68
+
69
+ ```python
70
+ import torch
71
+ from dcb import DCBLayer
72
+
73
+ X = torch.randn(256, requires_grad=True) # 1D samples
74
+ layer = DCBLayer(target_modes=1)
75
+ h_crit = layer(X) # differentiable scalar
76
+ h_crit.backward() # exact IFT gradients
77
+ ```
78
+
79
+ ## Installation
80
+
81
+ ```bash
82
+ pip install dcb
83
+ ```
84
+
85
+ Or from source:
86
+
87
+ ```bash
88
+ git clone https://github.com/ryZhangHason/dcb
89
+ cd dcb
90
+ pip install -e ".[dev]"
91
+ ```
92
+
93
+ ## Paper
94
+
95
+ > Ruiyu Zhang. "Differentiable Critical Bandwidth: Making Silverman's Modality Test End-to-End Trainable." *Journal of Machine Learning Research*, 2026 (in preparation).
96
+
97
+ ## Confirmed Experimental Results
98
+
99
+ All results produced on Kaggle GPU (T4 / P100) — see `experiments/` and `outputs/`.
100
+
101
+ | Experiment | Result | Criterion |
102
+ |---|---|---|
103
+ | **Validation (m≥2)** | R²=0.91, MAE=0.07, Spearman ρ=0.89 | R²≥0.85, MAE≤0.10 ✓ |
104
+ | **Speedup vs scipy (n=8192)** | **10.5×** on T4 | ≥3× ✓ |
105
+ | **GAN mode preservation** | h_crit=1.232 >> 0.3 | h_crit>0.3 ✓ |
106
+ | **Anomaly AUC (KDDCup99)** | DCB=**0.9982** vs IF=0.9867 | DCB≥IF ✓ |
107
+
108
+ ## Repository Structure
109
+
110
+ ```
111
+ dcb/ Core PyTorch package (layer.py, solver.py, kde.py, utils.py)
112
+ experiments/ Reproduction scripts for all paper figures and tables
113
+ phase1_validation.py Figure 1: DCB vs reference h_crit scatter
114
+ phase1_speedup.py Figure 2: GPU speedup benchmark
115
+ phase1_ablation.py Figures S1–S2: ε/τ sensitivity heatmaps
116
+ phase2_gan.py Figure 3: GAN mode-collapse prevention
117
+ phase3_anomaly.py Table 2 + Figure 5: anomaly detection benchmark
118
+ tests/ Unit tests (pytest, 35/35 passing)
119
+ outputs/ All generated figures and tables (PDFs, PNGs, CSVs)
120
+ notebooks/ Quickstart and demo notebooks
121
+ ```
122
+
123
+ ## Reproducing Paper Results
124
+
125
+ ```bash
126
+ # Phase 1: validation, speedup, ablation
127
+ python experiments/phase1_validation.py
128
+ python experiments/phase1_speedup.py
129
+ python experiments/phase1_ablation.py
130
+
131
+ # Phase 2: GAN mode collapse experiment
132
+ python experiments/phase2_gan.py
133
+
134
+ # Phase 3: anomaly detection benchmark
135
+ python experiments/phase3_anomaly.py
136
+ ```
137
+
138
+ For GPU runs, use the provided Kaggle kernels:
139
+ - Phase 1–2: `hsingle/dcb-full-experiments`
140
+ - Phase 3: `hsingle/dcb-phase-3-anomaly-detection`
141
+
142
+ ## Kaggle GPU Notes
143
+
144
+ Kaggle may assign a P100 (sm_60) instead of T4. The Phase 3 kernel handles this automatically by installing `torch==2.2.2+cu118` (the earliest PyTorch release with both Python 3.12 and sm_60 support) when P100 is detected.
145
+
146
+ ## License
147
+
148
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,11 @@
1
+ dcb/__init__.py,sha256=M8ML4Ih1-VCAXwnzaTJqhY_NAL7xSRqV_YvYu6ztx_I,943
2
+ dcb/diagnostics.py,sha256=oVWjgvlzCFN_hjGfIFU8BGgHJZ6xyVW2OnqlcBM-Dr4,6176
3
+ dcb/fft_kde.py,sha256=euNX9rF8nXSJql0MtCDe_pasX-epWQ2L88ATNwKKIKM,4408
4
+ dcb/kde.py,sha256=OSRqWV9_N_kaO9iOPXe9177mU32vMBgyTk0Bt4T13Tk,14147
5
+ dcb/layer.py,sha256=6naZ0cm59orGz1eHKbt_Ih9qrIcfrOMzrtJJ5SAJ7xE,9787
6
+ dcb/solver.py,sha256=97YFDR5Zjgxh3s9dghd00GljFVBWWYedv2cmi1F0Wzc,23206
7
+ dcb/utils.py,sha256=beEVAwYcesK3WE0fSR1fsWL-y_t7TgcQQ5aWxXXNYRM,5787
8
+ diffcb-0.1.0.dist-info/METADATA,sha256=72zc5v7w9yS0n4uxW7Hji4fSz-CJbZ64IXczeTa1pWc,6434
9
+ diffcb-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
10
+ diffcb-0.1.0.dist-info/licenses/LICENSE,sha256=HS739ewRDP0n8t75HCwgUl5UDFH4Ab8eVrbAnBD11BA,1068
11
+ diffcb-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ruiyu Zhang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.