torchregress 0.3.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.
Files changed (160) hide show
  1. torchregress/__init__.py +87 -0
  2. torchregress/algorithms/__init__.py +84 -0
  3. torchregress/algorithms/adaptive_prior_vi.py +284 -0
  4. torchregress/algorithms/covariance_pseudo_labels.py +222 -0
  5. torchregress/algorithms/error_aware.py +164 -0
  6. torchregress/algorithms/forward_inversion.py +1102 -0
  7. torchregress/algorithms/group_dro.py +844 -0
  8. torchregress/algorithms/heteroscedastic_laplace.py +333 -0
  9. torchregress/algorithms/irls.py +603 -0
  10. torchregress/algorithms/irls_fit.py +892 -0
  11. torchregress/algorithms/ivon.py +335 -0
  12. torchregress/algorithms/latentnn.py +260 -0
  13. torchregress/algorithms/rc.py +290 -0
  14. torchregress/algorithms/simex.py +289 -0
  15. torchregress/algorithms/tictac.py +160 -0
  16. torchregress/algorithms/vir.py +1368 -0
  17. torchregress/algorithms/warmup_mc.py +156 -0
  18. torchregress/calibration/__init__.py +59 -0
  19. torchregress/calibration/metrics.py +446 -0
  20. torchregress/calibration/multisource.py +340 -0
  21. torchregress/calibration/posthoc.py +667 -0
  22. torchregress/calibration/semicp.py +202 -0
  23. torchregress/calibration/shift.py +288 -0
  24. torchregress/causal/__init__.py +11 -0
  25. torchregress/causal/diagnostics.py +61 -0
  26. torchregress/causal/dr.py +427 -0
  27. torchregress/comparison.py +167 -0
  28. torchregress/constraints/__init__.py +11 -0
  29. torchregress/constraints/heads.py +84 -0
  30. torchregress/ensemble/__init__.py +59 -0
  31. torchregress/ensemble/_variance.py +39 -0
  32. torchregress/ensemble/base.py +421 -0
  33. torchregress/ensemble/bnn.py +456 -0
  34. torchregress/ensemble/combiners.py +125 -0
  35. torchregress/ensemble/laplace.py +266 -0
  36. torchregress/ensemble/layers.py +104 -0
  37. torchregress/ensemble/mc_dropout.py +166 -0
  38. torchregress/ensemble/models.py +727 -0
  39. torchregress/ensemble/packed.py +208 -0
  40. torchregress/ensemble/snapshot.py +179 -0
  41. torchregress/ensemble/swag.py +534 -0
  42. torchregress/ensemble/utils.py +13 -0
  43. torchregress/estimators.py +1073 -0
  44. torchregress/health.py +84 -0
  45. torchregress/inference/__init__.py +43 -0
  46. torchregress/inference/orthogonal.py +499 -0
  47. torchregress/inference/ppi.py +759 -0
  48. torchregress/inference/ratio.py +508 -0
  49. torchregress/losses/__init__.py +420 -0
  50. torchregress/losses/_poisson_gaussian_kernel.py +386 -0
  51. torchregress/losses/balanced_mse.py +252 -0
  52. torchregress/losses/balanced_mse_bmc.py +713 -0
  53. torchregress/losses/base.py +553 -0
  54. torchregress/losses/beta_nll.py +153 -0
  55. torchregress/losses/cdf.py +75 -0
  56. torchregress/losses/censored.py +323 -0
  57. torchregress/losses/conformal.py +3079 -0
  58. torchregress/losses/contrastive.py +137 -0
  59. torchregress/losses/eiv.py +1812 -0
  60. torchregress/losses/evidential.py +532 -0
  61. torchregress/losses/expectile.py +464 -0
  62. torchregress/losses/faithful_gaussian.py +157 -0
  63. torchregress/losses/families.py +911 -0
  64. torchregress/losses/forward_quadrature.py +318 -0
  65. torchregress/losses/gaussian.py +409 -0
  66. torchregress/losses/gaussian_wasserstein.py +286 -0
  67. torchregress/losses/imbalanced.py +912 -0
  68. torchregress/losses/loss_registry.py +83 -0
  69. torchregress/losses/mdn.py +576 -0
  70. torchregress/losses/multisource.py +461 -0
  71. torchregress/losses/multisource_robust.py +325 -0
  72. torchregress/losses/nflows.py +1177 -0
  73. torchregress/losses/noise_aware_density.py +753 -0
  74. torchregress/losses/nre.py +675 -0
  75. torchregress/losses/ordinal.py +214 -0
  76. torchregress/losses/poisson.py +414 -0
  77. torchregress/losses/poisson_gaussian.py +744 -0
  78. torchregress/losses/prime.py +990 -0
  79. torchregress/losses/quantile.py +401 -0
  80. torchregress/losses/rank_sim.py +570 -0
  81. torchregress/losses/robust.py +708 -0
  82. torchregress/losses/sls.py +786 -0
  83. torchregress/losses/split_eiv.py +536 -0
  84. torchregress/losses/student_t.py +138 -0
  85. torchregress/losses/transforms.py +176 -0
  86. torchregress/losses/tweedie.py +325 -0
  87. torchregress/losses/uncertain_gt.py +403 -0
  88. torchregress/losses/utils_robust.py +46 -0
  89. torchregress/losses/waldo.py +729 -0
  90. torchregress/losses/wasserstein1d.py +134 -0
  91. torchregress/method_catalog.py +2892 -0
  92. torchregress/metrics/__init__.py +254 -0
  93. torchregress/metrics/censored.py +116 -0
  94. torchregress/metrics/decision.py +265 -0
  95. torchregress/metrics/density.py +203 -0
  96. torchregress/metrics/distribution.py +1436 -0
  97. torchregress/metrics/ensemble.py +287 -0
  98. torchregress/metrics/interval.py +288 -0
  99. torchregress/metrics/multivariate.py +85 -0
  100. torchregress/metrics/ood.py +461 -0
  101. torchregress/metrics/ordinal.py +122 -0
  102. torchregress/metrics/point.py +817 -0
  103. torchregress/metrics/representation.py +202 -0
  104. torchregress/metrics/sbi.py +685 -0
  105. torchregress/metrics/tac.py +131 -0
  106. torchregress/metrics/uncertain.py +91 -0
  107. torchregress/metrics/utils.py +109 -0
  108. torchregress/models/__init__.py +32 -0
  109. torchregress/models/copula_spline.py +262 -0
  110. torchregress/models/flow_matching.py +115 -0
  111. torchregress/models/ft_transformer.py +66 -0
  112. torchregress/models/normalizing_flow_map.py +467 -0
  113. torchregress/models/preprocessing.py +235 -0
  114. torchregress/models/tabular_mlp.py +170 -0
  115. torchregress/models/training.py +489 -0
  116. torchregress/prediction.py +281 -0
  117. torchregress/py.typed +0 -0
  118. torchregress/semi_supervised.py +1195 -0
  119. torchregress/test_time/__init__.py +101 -0
  120. torchregress/test_time/base.py +65 -0
  121. torchregress/test_time/bayes.py +453 -0
  122. torchregress/test_time/benchmark.py +229 -0
  123. torchregress/test_time/cosa.py +226 -0
  124. torchregress/test_time/dynamic.py +43 -0
  125. torchregress/test_time/joint_tta.py +386 -0
  126. torchregress/test_time/label_shift.py +581 -0
  127. torchregress/test_time/ot_conformal.py +491 -0
  128. torchregress/test_time/ot_conformal_predictive.py +64 -0
  129. torchregress/test_time/selection.py +238 -0
  130. torchregress/test_time/shift_weights.py +235 -0
  131. torchregress/test_time/subspace.py +206 -0
  132. torchregress/test_time/transport.py +1191 -0
  133. torchregress/utils/__init__.py +62 -0
  134. torchregress/utils/augment.py +195 -0
  135. torchregress/utils/bspline.py +339 -0
  136. torchregress/utils/distributions.py +19 -0
  137. torchregress/utils/gaussian_output.py +114 -0
  138. torchregress/utils/numpy_stats.py +65 -0
  139. torchregress/utils/openml_relaxed.py +236 -0
  140. torchregress/utils/ordinal.py +234 -0
  141. torchregress/utils/propensity.py +46 -0
  142. torchregress/utils/pytorch_compat.py +65 -0
  143. torchregress/utils/quantile.py +76 -0
  144. torchregress/utils/reduction.py +44 -0
  145. torchregress/utils/security.py +27 -0
  146. torchregress/utils/semisupervised.py +70 -0
  147. torchregress/utils/tensor_ops.py +391 -0
  148. torchregress/utils/transform.py +157 -0
  149. torchregress/utils/validation.py +309 -0
  150. torchregress/viz/__init__.py +125 -0
  151. torchregress/viz/diagnostic.py +2109 -0
  152. torchregress/viz/monitoring.py +673 -0
  153. torchregress/viz/results.py +1533 -0
  154. torchregress/viz/utils.py +456 -0
  155. torchregress-0.3.0.dist-info/METADATA +218 -0
  156. torchregress-0.3.0.dist-info/RECORD +160 -0
  157. torchregress-0.3.0.dist-info/WHEEL +5 -0
  158. torchregress-0.3.0.dist-info/entry_points.txt +2 -0
  159. torchregress-0.3.0.dist-info/licenses/LICENSE +21 -0
  160. torchregress-0.3.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,87 @@
1
+ """
2
+ torchregress: PyTorch-based regression modeling toolkit.
3
+
4
+ This package provides utilities, models, and loss functions for
5
+ various regression tasks, with a focus on uncertainty
6
+ estimation and robust regression techniques.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from importlib import import_module
12
+ from importlib.metadata import PackageNotFoundError, version
13
+ from typing import Any
14
+
15
+ try:
16
+ __version__ = version("torchregress")
17
+ except PackageNotFoundError:
18
+ __version__ = "0.0.0+dev"
19
+
20
+ # Eager import only the small, high-value top-level symbols.
21
+ from .algorithms.irls import reweight_fixed_predictions
22
+ from .algorithms.irls_fit import iteratively_reweighted_fit
23
+ from .losses.base import BaseLoss, DistributionLoss, RegressionLoss
24
+
25
+ # Keep top-level import light; large subpackages are resolved lazily to reduce
26
+ # import overhead and avoid pulling optional/heavy plotting dependencies unless used.
27
+ _LAZY_SUBMODULES = {
28
+ "losses",
29
+ "metrics",
30
+ "algorithms",
31
+ "ensemble",
32
+ "semi_supervised",
33
+ "test_time",
34
+ "method_catalog",
35
+ "inference",
36
+ "constraints",
37
+ "calibration",
38
+ "causal",
39
+ "prediction",
40
+ "viz",
41
+ "comparison",
42
+ "utils",
43
+ "models",
44
+ "estimators",
45
+ }
46
+
47
+
48
+ def __getattr__(name: str) -> Any:
49
+ if name in _LAZY_SUBMODULES:
50
+ module = import_module(f".{name}", __name__)
51
+ globals()[name] = module
52
+ return module
53
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
54
+
55
+
56
+ def __dir__() -> list[str]:
57
+ return sorted(set(globals()) | set(__all__) | _LAZY_SUBMODULES)
58
+
59
+
60
+ __all__ = [
61
+ # Main modules
62
+ "losses",
63
+ "metrics",
64
+ "algorithms",
65
+ "ensemble",
66
+ "semi_supervised",
67
+ "test_time",
68
+ "method_catalog",
69
+ "inference",
70
+ "constraints",
71
+ "calibration",
72
+ "causal",
73
+ "prediction",
74
+ "viz",
75
+ "comparison",
76
+ "utils",
77
+ "models",
78
+ "estimators",
79
+ # Core classes
80
+ "BaseLoss",
81
+ "RegressionLoss",
82
+ "DistributionLoss",
83
+ # Core functions
84
+ "iteratively_reweighted_fit",
85
+ "reweight_fixed_predictions",
86
+ "__version__",
87
+ ]
@@ -0,0 +1,84 @@
1
+ """
2
+ Specialized algorithms for regression tasks.
3
+
4
+ This module provides implementations of algorithms for various
5
+ regression tasks, including IRLS, RC, SIMEX, and latent-input EIV training.
6
+ """
7
+ # ruff: noqa: F401 — re-exports
8
+ # ponytail: __all__ kept because test_public_api_contracts reads it
9
+
10
+ from .adaptive_prior_vi import (
11
+ AdaptivePriorGuide,
12
+ VIDSRegressor,
13
+ sample_synthetic_environments,
14
+ )
15
+ from .covariance_pseudo_labels import (
16
+ NeighborhoodCovarianceConfig,
17
+ NeighborhoodCovariancePseudoLabeler,
18
+ )
19
+ from .error_aware import ErrorAwareFeatureEncoder, NoiseAwareRegressor
20
+ from .forward_inversion import ForwardInversionRegressor, build_decoder_mlp
21
+ from .group_dro import ContinuousGroupDRO, GroupDROTrainer
22
+ from .heteroscedastic_laplace import (
23
+ HeteroscedasticLaplaceRegressor,
24
+ NaturalHeteroscedasticHead,
25
+ NaturalReparamHead,
26
+ )
27
+ from .irls import (
28
+ IRLSConfig,
29
+ reweight_fixed_predictions,
30
+ )
31
+ from .irls_fit import (
32
+ IRLSBreakdownError,
33
+ IRLSCallbacks,
34
+ IRLSContinuationStage,
35
+ IRLSFitConfig,
36
+ IRLSFitResult,
37
+ IRLSIteration,
38
+ IRLSProblem,
39
+ iteratively_reweighted_fit,
40
+ robust_weights,
41
+ )
42
+ from .ivon import IVON
43
+ from .latentnn import LatentNN
44
+ from .rc import RegressionCalibration
45
+ from .simex import SIMEX
46
+ from .tictac import TaylorInducedCovarianceHead
47
+ from .vir import VIRLoss, VIRRegressor
48
+ from .warmup_mc import WarmupMCTrainer
49
+
50
+ __all__ = [
51
+ "IVON",
52
+ "iteratively_reweighted_fit",
53
+ "reweight_fixed_predictions",
54
+ "robust_weights",
55
+ "IRLSProblem",
56
+ "IRLSCallbacks",
57
+ "IRLSFitConfig",
58
+ "IRLSContinuationStage",
59
+ "IRLSIteration",
60
+ "IRLSFitResult",
61
+ "IRLSBreakdownError",
62
+ "IRLSConfig",
63
+ "RegressionCalibration",
64
+ "SIMEX",
65
+ "LatentNN",
66
+ "ErrorAwareFeatureEncoder",
67
+ "NeighborhoodCovarianceConfig",
68
+ "NeighborhoodCovariancePseudoLabeler",
69
+ "NoiseAwareRegressor",
70
+ "TaylorInducedCovarianceHead",
71
+ "NaturalHeteroscedasticHead",
72
+ "NaturalReparamHead",
73
+ "HeteroscedasticLaplaceRegressor",
74
+ "AdaptivePriorGuide",
75
+ "VIDSRegressor",
76
+ "sample_synthetic_environments",
77
+ "WarmupMCTrainer",
78
+ "ForwardInversionRegressor",
79
+ "build_decoder_mlp",
80
+ "ContinuousGroupDRO",
81
+ "GroupDROTrainer",
82
+ "VIRLoss",
83
+ "VIRRegressor",
84
+ ]
@@ -0,0 +1,284 @@
1
+ """
2
+ Adaptive-Prior Bayesian Uncertainty under Distribution Shift (VIDS-style).
3
+
4
+ Reference: Slavutsky & Blei, "Quantifying Uncertainty in the Presence of
5
+ Distribution Shifts" (arXiv:2506.18283 / NeurIPS 2025).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from typing import Optional, Tuple
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+
16
+ from ..prediction import PredictiveBatch
17
+
18
+
19
+ def sample_synthetic_environments(
20
+ X: torch.Tensor, Y: torch.Tensor, *, bootstrap_fraction: float = 0.3, n_environments: int = 32
21
+ ) -> list[tuple[torch.Tensor, torch.Tensor]]:
22
+ N = X.shape[0]
23
+ k = max(1, int(bootstrap_fraction * N))
24
+ environments = []
25
+ for _ in range(n_environments):
26
+ indices = torch.randint(0, N, (k,), device=X.device)
27
+ environments.append((X[indices], Y[indices]))
28
+ return environments
29
+
30
+
31
+ class _AdaptivePriorMLP(nn.Module):
32
+ """Shared MLP for guide and prior networks."""
33
+
34
+ def __init__(self, input_dim: int, hidden_dim: int, param_dim: int) -> None:
35
+ super().__init__()
36
+ self.net = nn.Sequential(
37
+ nn.Linear(input_dim, hidden_dim),
38
+ nn.ReLU(),
39
+ nn.Linear(hidden_dim, hidden_dim),
40
+ nn.ReLU(),
41
+ nn.Linear(hidden_dim, 2 * param_dim),
42
+ )
43
+
44
+ def forward(self, inp: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
45
+ out = self.net(inp)
46
+ mean, log_var = torch.chunk(out, 2, dim=-1)
47
+ log_var = torch.clamp(log_var, min=-10.0, max=5.0)
48
+ return mean, log_var
49
+
50
+
51
+ class AdaptivePriorGuide(nn.Module):
52
+ """Posterior guide network."""
53
+
54
+ def __init__(
55
+ self, in_features: int, target_dim: int, param_dim: int, hidden_dim: int = 64
56
+ ) -> None: # noqa: E501
57
+ super().__init__()
58
+ self.net = _AdaptivePriorMLP(2 * in_features + 2 * target_dim, hidden_dim, param_dim)
59
+
60
+ def forward(
61
+ self, context_X: torch.Tensor, context_Y: torch.Tensor
62
+ ) -> Tuple[torch.Tensor, torch.Tensor]: # noqa: E501
63
+ return self.net(torch.cat([context_X, context_Y], dim=-1))
64
+
65
+
66
+ class AdaptivePriorNetwork(nn.Module):
67
+ """Prior network mapping training context and query test features to parameter prior parameters.""" # noqa: E501
68
+
69
+ def __init__(self, in_features: int, param_dim: int, hidden_dim: int = 64) -> None:
70
+ super().__init__()
71
+ self.net = _AdaptivePriorMLP(3 * in_features, hidden_dim, param_dim)
72
+
73
+ def forward(
74
+ self, context_X: torch.Tensor, x_query: torch.Tensor
75
+ ) -> Tuple[torch.Tensor, torch.Tensor]: # noqa: E501
76
+ B = x_query.shape[0]
77
+ inp = torch.cat([context_X.unsqueeze(0).expand(B, -1), x_query], dim=-1)
78
+ return self.net(inp)
79
+
80
+
81
+ class VIDSRegressor(nn.Module):
82
+ """
83
+ VIDS Variational Regressor under covariate shifts.
84
+
85
+ References
86
+ ----------
87
+ .. [1] Slavutsky, et al. (2025). VIDS: Variational Inference under Covariate Shift.
88
+ In *NeurIPS 2025*. https://arxiv.org/abs/2506.18283
89
+ """
90
+
91
+ def __init__(
92
+ self,
93
+ in_features: int,
94
+ target_dim: int = 1,
95
+ hidden_dim: int = 64,
96
+ prior_variance_init: float = 1.0,
97
+ noise_variance_init: float = 0.1,
98
+ jitter: float = 1e-6,
99
+ ) -> None:
100
+ super().__init__()
101
+ self.in_features = in_features
102
+ self.target_dim = target_dim
103
+ self.jitter = jitter
104
+
105
+ # Weight and bias parameter dimension: P = target_dim * in_features + target_dim
106
+ self.param_dim = target_dim * in_features + target_dim
107
+
108
+ # Guide and Prior networks
109
+ self.guide = AdaptivePriorGuide(in_features, target_dim, self.param_dim, hidden_dim)
110
+ self.prior_net = AdaptivePriorNetwork(in_features, self.param_dim, hidden_dim)
111
+
112
+ # Log observation noise variance
113
+ self.log_noise_var = nn.Parameter(torch.tensor(math.log(noise_variance_init)))
114
+
115
+ self.register_buffer("x_train_mean", torch.tensor(0.0))
116
+ self.register_buffer("x_train_std", torch.tensor(0.0))
117
+ self.is_fitted = False
118
+
119
+ def _get_context(
120
+ self, X: torch.Tensor, Y: Optional[torch.Tensor] = None
121
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
122
+ mean_X = X.mean(dim=0)
123
+ std_X = X.std(dim=0) + self.jitter
124
+ context_X = torch.cat([mean_X, std_X], dim=-1)
125
+
126
+ context_Y = None
127
+ if Y is not None:
128
+ mean_Y = Y.mean(dim=0)
129
+ std_Y = Y.std(dim=0) + self.jitter
130
+ context_Y = torch.cat([mean_Y, std_Y], dim=-1)
131
+
132
+ return context_X, context_Y
133
+
134
+ def _split_weights_bias(
135
+ self, params_sampled: torch.Tensor
136
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
137
+ # params_sampled shape: [S, P]
138
+ S = params_sampled.shape[0]
139
+ w_size = self.target_dim * self.in_features
140
+ w_flat = params_sampled[:, :w_size]
141
+ b = params_sampled[:, w_size:]
142
+ w = w_flat.reshape(S, self.target_dim, self.in_features)
143
+ return w, b
144
+
145
+ def fit(
146
+ self,
147
+ x_train_features: torch.Tensor,
148
+ y_train: torch.Tensor,
149
+ n_environments: int = 32,
150
+ bootstrap_fraction: float = 0.3,
151
+ lr: float = 1e-3,
152
+ epochs: int = 50,
153
+ beta: float = 1.0,
154
+ n_samples: int = 10,
155
+ ) -> VIDSRegressor:
156
+ """
157
+ Fits the variational posterior and adaptive prior using bootstrapped environments.
158
+ """
159
+ device = x_train_features.device
160
+ self.to(device)
161
+
162
+ # Store training context summaries for test-time prior conditioning
163
+ self.x_train_mean = x_train_features.mean(dim=0)
164
+ self.x_train_std = x_train_features.std(dim=0) + self.jitter
165
+
166
+ optimizer = torch.optim.Adam(self.parameters(), lr=lr)
167
+
168
+ self.train()
169
+ for epoch in range(epochs):
170
+ envs = sample_synthetic_environments(
171
+ x_train_features,
172
+ y_train,
173
+ bootstrap_fraction=bootstrap_fraction,
174
+ n_environments=n_environments,
175
+ )
176
+ epoch_loss = 0.0
177
+
178
+ for X_env, Y_env in envs:
179
+ optimizer.zero_grad()
180
+
181
+ context_X, context_Y = self._get_context(X_env, Y_env)
182
+
183
+ # 1. Predict posterior guide parameters
184
+ post_mean, post_log_var = self.guide(context_X, context_Y)
185
+ post_std = torch.exp(0.5 * post_log_var)
186
+
187
+ # 2. Sample parameters from variational posterior
188
+ eps = torch.randn(n_samples, self.param_dim, device=device)
189
+ params_sampled = post_mean.unsqueeze(0) + eps * post_std.unsqueeze(
190
+ 0
191
+ ) # [n_samples, P]
192
+
193
+ # Split parameters into weight and bias
194
+ w_samples, b_samples = self._split_weights_bias(
195
+ params_sampled
196
+ ) # [S, target_dim, in_features], [S, target_dim]
197
+
198
+ # 3. Compute expected NLL over the environment
199
+ # Compute predictions: [S, B, target_dim]
200
+ # X_env: [B, in_features], w_samples: [S, target_dim, in_features]
201
+ y_pred = torch.einsum("bi,sji->sbj", X_env, w_samples) + b_samples.unsqueeze(1)
202
+
203
+ noise_var = torch.exp(self.log_noise_var)
204
+ # Sum NLL over target dimensions and data points
205
+ se = (Y_env.unsqueeze(0) - y_pred) ** 2 # [S, B, target_dim]
206
+ nll = 0.5 * (se / (noise_var + 1e-8) + self.log_noise_var + math.log(2 * math.pi))
207
+ # ponytail: mean over S*B*D for scale comparable to KL mean
208
+ nll_loss = nll.mean()
209
+ prior_mean, prior_log_var = self.prior_net(context_X, X_env) # [B, P], [B, P]
210
+ prior_var = torch.exp(prior_log_var)
211
+ post_var = post_std**2
212
+ # Analytical KL for diagonal Gaussians: post w.r.t prior
213
+ # KL = 0.5 * sum( log(prior_var/post_var) +
214
+ # (post_var + (post_mean - prior_mean)^2)/prior_var - 1 )
215
+ kl = 0.5 * (
216
+ prior_log_var
217
+ - post_log_var.unsqueeze(0)
218
+ + (post_var.unsqueeze(0) + (post_mean.unsqueeze(0) - prior_mean) ** 2)
219
+ / (prior_var + 1e-8)
220
+ - 1.0
221
+ ) # [B, P]
222
+ # ponytail: mean over B and P so KL not dominated by param_dim P
223
+ # (previously mean(dim=0).sum() summed over P, making KL ~P× too strong)
224
+ kl_loss = kl.mean()
225
+ loss = nll_loss + beta * kl_loss
226
+ loss.backward()
227
+ optimizer.step()
228
+
229
+ epoch_loss += loss.item()
230
+
231
+ self.is_fitted = True
232
+ return self
233
+
234
+ def predict_distribution(
235
+ self, x_test: torch.Tensor, n_samples: Optional[int] = None
236
+ ) -> PredictiveBatch:
237
+ if not self.is_fitted:
238
+ raise RuntimeError("Model must be fitted before calling predict_distribution")
239
+
240
+ n = n_samples or 30
241
+ self.eval()
242
+
243
+ device = x_test.device
244
+ context_X = torch.cat([self.x_train_mean, self.x_train_std], dim=-1)
245
+ B = x_test.shape[0]
246
+ w_size = self.target_dim * self.in_features
247
+
248
+ with torch.no_grad():
249
+ prior_mean, prior_log_var = self.prior_net(context_X, x_test) # [B, P]
250
+ prior_std = torch.exp(0.5 * prior_log_var) # [B, P]
251
+
252
+ eps = torch.randn(n, B, self.param_dim, device=device) # [n, B, P]
253
+ params_sampled = prior_mean.unsqueeze(0) + eps * prior_std.unsqueeze(0) # [n, B, P]
254
+
255
+ w_flat = params_sampled[..., :w_size] # [n, B, w_size]
256
+ b = params_sampled[..., w_size:] # [n, B, target_dim]
257
+ w = w_flat.reshape(
258
+ n, B, self.target_dim, self.in_features
259
+ ) # [n, B, target_dim, in_features] # noqa: E501
260
+
261
+ pred_mean = (w * x_test.unsqueeze(0).unsqueeze(2)).sum(dim=-1) + b # [n, B, target_dim]
262
+
263
+ noise_var = torch.exp(self.log_noise_var)
264
+ noise = torch.randn_like(pred_mean) * torch.sqrt(noise_var + 1e-8)
265
+ points_tensor = pred_mean + noise # [n, B, target_dim]
266
+
267
+ epistemic = pred_mean.var(dim=0)
268
+ aleatoric = torch.exp(self.log_noise_var) + torch.zeros_like(epistemic)
269
+ total_var = epistemic + aleatoric
270
+ total_std = torch.sqrt(total_var + 1e-8)
271
+ final_mean = pred_mean.mean(dim=0)
272
+
273
+ if self.target_dim == 1:
274
+ samples_flat = points_tensor.squeeze(-1).transpose(0, 1)
275
+ else:
276
+ samples_flat = points_tensor.transpose(0, 1)
277
+
278
+ return PredictiveBatch(
279
+ point=final_mean,
280
+ mean=final_mean,
281
+ std=total_std,
282
+ samples=samples_flat,
283
+ extra={"epistemic_variance": epistemic, "aleatoric_variance": aleatoric},
284
+ )
@@ -0,0 +1,222 @@
1
+ """
2
+ Heuristic **neighbourhood target covariance** pseudo-labels for multivariate regression.
3
+
4
+ Estimates a per-sample SPD covariance of targets from weighted neighbours in input space,
5
+ following the self-supervision sketch in the Wasserstein-supervision research plan. This is
6
+ experimental: quality depends on representation geometry and local linearity.
7
+
8
+ See ``docs/losses/gaussian_wasserstein.md`` for pairing with ``GaussianWassersteinBoundLoss``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass
14
+ from typing import Any, Literal
15
+
16
+ import torch
17
+
18
+ from ..utils.tensor_ops import float_dtype
19
+
20
+ Metric = Literal["mahalanobis", "euclidean"]
21
+ Weighting = Literal["softmax"]
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class NeighborhoodCovarianceConfig:
26
+ """
27
+ Configuration for neighbourhood covariance pseudo-labeling.
28
+
29
+ Attributes:
30
+ n_neighbors: Neighbour count per row (excluding self).
31
+ metric: ``"mahalanobis"`` uses pooled feature precision; ``"euclidean"`` uses squared
32
+ Euclidean distances in ``x`` space.
33
+ weighting: Only ``"softmax"`` is supported in v1 (negative distance / temperature).
34
+ regularization: Diagonal jitter on feature precision and on output covariances.
35
+ temperature: Softmax temperature on negative squared distances.
36
+ """
37
+
38
+ n_neighbors: int = 32
39
+ metric: Metric = "mahalanobis"
40
+ weighting: Weighting = "softmax"
41
+ regularization: float = 1e-5
42
+ temperature: float = 1.0
43
+
44
+
45
+ _BLOCK_ELEMS = 1 << 24
46
+
47
+
48
+ def _as_tensor_2d(x: torch.Tensor | Any, *, name: str) -> torch.Tensor:
49
+ # Keep a floating input dtype (float64 stays float64); integers/bools and python
50
+ # sequences use the default dtype.
51
+ t = torch.as_tensor(x)
52
+ if not t.is_floating_point():
53
+ t = t.to(torch.get_default_dtype())
54
+ if t.dim() != 2:
55
+ raise ValueError(f"{name} must be 2D [n, dim], got shape {tuple(t.shape)}")
56
+ return t
57
+
58
+
59
+ def _precision_from_features(x: torch.Tensor, *, reg: float) -> torch.Tensor:
60
+ """Inverse covariance of features with diagonal jitter (symmetric)."""
61
+ n, p = x.shape
62
+ if n < 2:
63
+ raise ValueError("Need at least 2 reference rows to build a feature covariance.")
64
+ x_c = x - x.mean(dim=0, keepdim=True)
65
+ cov = (x_c.T @ x_c) / max(n - 1, 1)
66
+ eye = torch.eye(p, device=x.device, dtype=x.dtype)
67
+ return torch.linalg.inv(cov + reg * eye)
68
+
69
+
70
+ def _pairwise_quad_form(diff: torch.Tensor, m: torch.Tensor) -> torch.Tensor:
71
+ """diff [a, b, p], m [p, p] symmetric -> v^T M v for each pair, shape [a, b]."""
72
+ mv = torch.matmul(diff, m.T)
73
+ return (diff * mv).sum(dim=-1)
74
+
75
+
76
+ def _spdize(cov: torch.Tensor, *, jitter: float) -> torch.Tensor:
77
+ sym = 0.5 * (cov + cov.transpose(-1, -2))
78
+ evals, evecs = torch.linalg.eigh(sym)
79
+ evals = torch.clamp(evals, min=jitter)
80
+ # Coverage invariants (TOR003): chain .to() on torch.diag_embed because
81
+ # torch.diag_embed does not accept device=/dtype= kwargs natively. Pin
82
+ # to the input covariance's device/dtype so that mixed-precision callers
83
+ # do not silently promote the diagonal into float64.
84
+ return (
85
+ evecs
86
+ @ torch.diag_embed(evals).to(device=cov.device, dtype=cov.dtype)
87
+ @ evecs.transpose(-1, -2)
88
+ )
89
+
90
+
91
+ class NeighborhoodCovariancePseudoLabeler:
92
+ """
93
+ Per-sample weighted covariance of neighbour targets in ``(x, y)`` space.
94
+
95
+ For each index ``i``, neighbours are the ``n_neighbors`` smallest metric distances to
96
+ ``j != i``. Weights are a softmax over ``-distance / temperature``. The pseudo covariance
97
+ is the weighted covariance of neighbour ``y`` values plus diagonal ``regularization`` on
98
+ the target dimensions.
99
+
100
+ This is **not** a statistically calibrated estimator; use for auxiliary supervision only.
101
+ """
102
+
103
+ def __init__(
104
+ self,
105
+ config: NeighborhoodCovarianceConfig | None = None,
106
+ ) -> None:
107
+ if config is None:
108
+ config = NeighborhoodCovarianceConfig()
109
+ if config.n_neighbors < 1:
110
+ raise ValueError("n_neighbors must be >= 1")
111
+ if config.weighting != "softmax":
112
+ raise ValueError("weighting must be 'softmax' in v1")
113
+ if config.regularization <= 0:
114
+ raise ValueError("regularization must be positive")
115
+ if config.temperature <= 0:
116
+ raise ValueError("temperature must be positive")
117
+ self.config = config
118
+
119
+ @torch.no_grad()
120
+ def fit_predict(
121
+ self,
122
+ x: torch.Tensor,
123
+ y: torch.Tensor,
124
+ ) -> torch.Tensor:
125
+ x0 = _as_tensor_2d(x, name="x")
126
+ y0 = _as_tensor_2d(y, name="y")
127
+ if x0.shape[0] != y0.shape[0]:
128
+ raise ValueError("x and y must have the same number of rows")
129
+ dtype = float_dtype(x0, y0)
130
+ x0, y0 = x0.to(dtype), y0.to(dtype)
131
+ n = x0.shape[0]
132
+ if n < self.config.n_neighbors + 1:
133
+ raise ValueError(
134
+ f"Need at least n_neighbors + 1 = {self.config.n_neighbors + 1} rows, got {n}"
135
+ )
136
+ return self._pseudo_cov_batch(x0, x0, y0, exclude_self=True)
137
+
138
+ @torch.no_grad()
139
+ def predict_for_query(
140
+ self,
141
+ x_query: torch.Tensor,
142
+ *,
143
+ x_reference: torch.Tensor,
144
+ y_reference: torch.Tensor,
145
+ ) -> torch.Tensor:
146
+ """Pseudo covariances for query rows using neighbour sets in ``x_reference`` space."""
147
+ xq = _as_tensor_2d(x_query, name="x_query")
148
+ xr = _as_tensor_2d(x_reference, name="x_reference")
149
+ yr = _as_tensor_2d(y_reference, name="y_reference")
150
+ if xr.shape[0] != yr.shape[0]:
151
+ raise ValueError("x_reference and y_reference must have the same number of rows")
152
+ dtype = float_dtype(xq, xr, yr)
153
+ xq, xr, yr = xq.to(dtype), xr.to(dtype), yr.to(dtype)
154
+ n_ref = xr.shape[0]
155
+ if n_ref < self.config.n_neighbors:
156
+ raise ValueError(
157
+ f"Reference set must have at least n_neighbors={self.config.n_neighbors} "
158
+ f"rows, got {n_ref}"
159
+ )
160
+ return self._pseudo_cov_batch(xq, xr, yr, exclude_self=False)
161
+
162
+ def _pseudo_cov_batch(
163
+ self,
164
+ x_query: torch.Tensor,
165
+ x_ref: torch.Tensor,
166
+ y_ref: torch.Tensor,
167
+ *,
168
+ exclude_self: bool,
169
+ ) -> torch.Tensor:
170
+ n = x_ref.shape[0]
171
+ d = y_ref.shape[1]
172
+ device = x_ref.device
173
+ dtype = x_ref.dtype
174
+ reg = self.config.regularization
175
+ if exclude_self:
176
+ k = min(self.config.n_neighbors, n - 1)
177
+ else:
178
+ k = min(self.config.n_neighbors, n)
179
+
180
+ if self.config.metric == "mahalanobis":
181
+ prec = _precision_from_features(x_ref, reg=reg)
182
+ elif self.config.metric == "euclidean":
183
+ prec = None
184
+ else:
185
+ raise ValueError(f"Unknown metric {self.config.metric!r}")
186
+
187
+ # Process query rows in blocks so the (block, Nref, D) difference tensor stays
188
+ # bounded by ~_BLOCK_ELEMS elements.
189
+ n_ref, p = x_ref.shape
190
+ n_query = x_query.shape[0]
191
+ block = max(1, _BLOCK_ELEMS // max(1, n_ref * p))
192
+ vals_blocks: list[torch.Tensor] = []
193
+ idx_blocks: list[torch.Tensor] = []
194
+ for start in range(0, max(n_query, 1), block):
195
+ xq = x_query[start : start + block]
196
+ diff = xq.unsqueeze(1) - x_ref.unsqueeze(0)
197
+ if prec is not None:
198
+ dist = _pairwise_quad_form(diff, prec)
199
+ else:
200
+ dist = (diff * diff).sum(dim=-1)
201
+ if exclude_self:
202
+ # Global query row i has its self-match in reference column i.
203
+ rows = torch.arange(start, start + xq.shape[0], device=device)
204
+ dist = dist.clone()
205
+ dist[torch.arange(xq.shape[0], device=device), rows] = float("inf")
206
+ v, i = dist.topk(k, largest=False)
207
+ vals_blocks.append(v)
208
+ idx_blocks.append(i)
209
+ vals = torch.cat(vals_blocks, dim=0)
210
+ idx = torch.cat(idx_blocks, dim=0)
211
+
212
+ logits = -vals / self.config.temperature
213
+ w = torch.softmax(logits, dim=-1)
214
+
215
+ neigh_y = y_ref[idx]
216
+ wmean = (w.unsqueeze(-1) * neigh_y).sum(dim=1)
217
+ centered = neigh_y - wmean.unsqueeze(1)
218
+ outer = centered.unsqueeze(-1) @ centered.unsqueeze(-2)
219
+ cov = (w.unsqueeze(-1).unsqueeze(-1) * outer).sum(dim=1)
220
+ eye_d = torch.eye(d, device=device, dtype=dtype)
221
+ cov = cov + reg * eye_d
222
+ return _spdize(cov, jitter=reg)