l0-python 0.1.1__py3-none-any.whl → 0.3.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.
l0/calibration.py ADDED
@@ -0,0 +1,495 @@
1
+ """
2
+ L0-regularized calibration weights for survey data.
3
+
4
+ Implements sparse calibration weights that are constrained to be non-negative,
5
+ suitable for survey weighting and importance sampling applications.
6
+ """
7
+
8
+ # ruff: noqa: N803 N806
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ import numpy as np
13
+ from scipy import sparse as sp
14
+
15
+
16
+ class SparseCalibrationWeights(nn.Module):
17
+ """
18
+ L0-regularized calibration weights with positivity constraint.
19
+
20
+ Designed for survey calibration where weights must be non-negative
21
+ and sparsity is desired to select a subset of households/units.
22
+
23
+ Parameters
24
+ ----------
25
+ n_features : int
26
+ Number of calibration weights (e.g., number of households)
27
+ beta : float
28
+ Temperature parameter for Hard Concrete distribution
29
+ gamma : float
30
+ Lower bound of stretched concrete distribution
31
+ zeta : float
32
+ Upper bound of stretched concrete distribution
33
+ init_keep_prob : float or array-like
34
+ Initial probability of keeping each weight active.
35
+ If float, all weights use the same probability.
36
+ If array, must have shape (n_features,)
37
+ init_weights : float, array-like, or None
38
+ Initial weight values (on original scale, not log).
39
+ If float, all weights initialized to this value.
40
+ If array, must have shape (n_features,).
41
+ If None, defaults to 1.0 for all weights.
42
+ log_weight_jitter_sd : float
43
+ Standard deviation of noise added to log weights at start of fit() to break symmetry.
44
+ Set to 0 to disable jitter. Default is 0.0 (no jitter).
45
+ log_alpha_jitter_sd : float
46
+ Standard deviation of noise added to log_alpha at initialization to break symmetry.
47
+ Set to 0 to disable jitter. Default is 0.01 (following Louizos et al.).
48
+ device : str or torch.device
49
+ Device to run computations on ('cpu' or 'cuda')
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ n_features: int,
55
+ beta: float = 2 / 3,
56
+ gamma: float = -0.1,
57
+ zeta: float = 1.1,
58
+ init_keep_prob: float | np.ndarray = 0.5,
59
+ init_weights: float | np.ndarray | None = None,
60
+ log_weight_jitter_sd: float = 0.0,
61
+ log_alpha_jitter_sd: float = 0.01,
62
+ device: str | torch.device = "cpu",
63
+ ):
64
+ super().__init__()
65
+ self.n_features = n_features
66
+ self.beta = beta
67
+ self.gamma = gamma
68
+ self.zeta = zeta
69
+ self.log_weight_jitter_sd = log_weight_jitter_sd
70
+ self.log_alpha_jitter_sd = log_alpha_jitter_sd
71
+ self.device = torch.device(device)
72
+
73
+ # Initialize weights (on original scale)
74
+ if init_weights is None:
75
+ # Default: all weights start at 1.0
76
+ weight_values = torch.ones(n_features, device=self.device)
77
+ elif isinstance(init_weights, (int, float)):
78
+ # Scalar: all weights start at this value
79
+ weight_values = torch.full(
80
+ (n_features,), float(init_weights), device=self.device
81
+ )
82
+ else:
83
+ # Array: use provided values
84
+ weight_values = torch.tensor(
85
+ init_weights, dtype=torch.float32, device=self.device
86
+ )
87
+ if weight_values.shape != (n_features,):
88
+ raise ValueError(
89
+ f"init_weights array must have shape ({n_features},), "
90
+ f"got {weight_values.shape}"
91
+ )
92
+
93
+ # Convert to log space to ensure positivity via exp transformation
94
+ # Add small epsilon to avoid log(0)
95
+ self.log_weight = nn.Parameter(torch.log(weight_values + 1e-8))
96
+
97
+ # L0 gate parameters
98
+ # Handle init_keep_prob as scalar or array
99
+ if isinstance(init_keep_prob, (int, float)):
100
+ # Scalar: broadcast to all features
101
+ keep_prob_values = torch.full(
102
+ (n_features,), float(init_keep_prob), device=self.device
103
+ )
104
+ else:
105
+ # Array: use provided values
106
+ keep_prob_values = torch.tensor(
107
+ init_keep_prob, dtype=torch.float32, device=self.device
108
+ )
109
+ if keep_prob_values.shape != (n_features,):
110
+ raise ValueError(
111
+ f"init_keep_prob array must have shape ({n_features},), "
112
+ f"got {keep_prob_values.shape}"
113
+ )
114
+ # Clip to valid probability range to avoid log(0) or log(inf)
115
+ keep_prob_values = keep_prob_values.clamp(1e-6, 1 - 1e-6)
116
+
117
+ # Convert probabilities to log_alpha
118
+ mu = torch.log(keep_prob_values / (1 - keep_prob_values))
119
+ # Add jitter to break symmetry (if specified)
120
+ if self.log_alpha_jitter_sd > 0:
121
+ jitter = (
122
+ torch.randn(n_features, device=self.device)
123
+ * self.log_alpha_jitter_sd
124
+ )
125
+ self.log_alpha = nn.Parameter(mu + jitter)
126
+ else:
127
+ self.log_alpha = nn.Parameter(mu)
128
+
129
+ # Cache for sparse tensor conversion
130
+ self._cached_M_torch: torch.sparse.Tensor | None = None
131
+ self._cached_M_shape: tuple[int, int] | None = None
132
+
133
+ def _convert_sparse_to_torch(
134
+ self, M_sparse: sp.spmatrix
135
+ ) -> torch.sparse.Tensor:
136
+ """
137
+ Convert scipy sparse matrix to torch sparse tensor.
138
+
139
+ Caches the result if the shape matches to avoid redundant conversions.
140
+ """
141
+ if (
142
+ self._cached_M_torch is not None
143
+ and self._cached_M_shape == M_sparse.shape
144
+ and M_sparse.nnz == self._cached_M_torch._nnz()
145
+ ):
146
+ return self._cached_M_torch
147
+
148
+ M_coo = M_sparse.tocoo()
149
+ indices = torch.LongTensor(np.vstack([M_coo.row, M_coo.col])).to(
150
+ self.device
151
+ )
152
+ values = torch.FloatTensor(M_coo.data).to(self.device)
153
+ M_torch = torch.sparse_coo_tensor(
154
+ indices,
155
+ values,
156
+ M_sparse.shape,
157
+ dtype=torch.float32,
158
+ device=self.device,
159
+ )
160
+
161
+ # Cache for future use
162
+ self._cached_M_torch = M_torch
163
+ self._cached_M_shape = M_sparse.shape
164
+
165
+ return M_torch
166
+
167
+ def _sample_gates(self) -> torch.Tensor:
168
+ """Sample gates using Hard Concrete distribution."""
169
+ eps = 1e-6
170
+ u = torch.rand_like(self.log_alpha).clamp(eps, 1 - eps)
171
+ s = (torch.log(u) - torch.log(1 - u) + self.log_alpha) / self.beta
172
+ s = torch.sigmoid(s)
173
+ s_bar = s * (self.zeta - self.gamma) + self.gamma
174
+ return s_bar.clamp(0, 1)
175
+
176
+ def get_deterministic_gates(self) -> torch.Tensor:
177
+ """Get deterministic gate values (for inference)."""
178
+ s = torch.sigmoid(self.log_alpha / self.beta)
179
+ s_bar = s * (self.zeta - self.gamma) + self.gamma
180
+ return s_bar.clamp(0, 1)
181
+
182
+ def get_weights(self, deterministic: bool = False) -> torch.Tensor:
183
+ """
184
+ Get effective calibration weights.
185
+
186
+ Parameters
187
+ ----------
188
+ deterministic : bool
189
+ Whether to use deterministic gates (for inference)
190
+
191
+ Returns
192
+ -------
193
+ torch.Tensor
194
+ Positive calibration weights with L0 sparsity applied
195
+ """
196
+ # Sample or get deterministic gates
197
+ if deterministic:
198
+ gates = self.get_deterministic_gates()
199
+ else:
200
+ gates = self._sample_gates()
201
+
202
+ # Apply exp transformation and gates together
203
+ # This ensures gradient flow matches successful implementations
204
+ return torch.exp(self.log_weight) * gates
205
+
206
+ def forward(
207
+ self,
208
+ M: sp.spmatrix,
209
+ deterministic: bool = False,
210
+ ) -> torch.Tensor:
211
+ """
212
+ Apply calibration weights to metric matrix.
213
+
214
+ Parameters
215
+ ----------
216
+ M : scipy.sparse matrix
217
+ Metric matrix of shape (n_targets, n_features)
218
+ deterministic : bool
219
+ Whether to use deterministic gates (for inference)
220
+
221
+ Returns
222
+ -------
223
+ torch.Tensor
224
+ Weighted sums of shape (n_targets,)
225
+ """
226
+ # Convert sparse matrix to torch
227
+ M_torch = self._convert_sparse_to_torch(M)
228
+
229
+ # Get effective weights
230
+ weights = self.get_weights(deterministic=deterministic)
231
+
232
+ # Sparse matrix multiplication
233
+ y = torch.sparse.mm(M_torch, weights.unsqueeze(1)).squeeze(1)
234
+
235
+ return y
236
+
237
+ def get_l0_penalty(self) -> torch.Tensor:
238
+ """
239
+ Compute L0 complexity penalty.
240
+
241
+ Returns expected number of active weights.
242
+ """
243
+ c = -self.beta * torch.log(
244
+ torch.tensor(-self.gamma / self.zeta, device=self.device)
245
+ )
246
+ pi = torch.sigmoid(self.log_alpha + c)
247
+ return pi.sum()
248
+
249
+ def get_l2_penalty(self) -> torch.Tensor:
250
+ """
251
+ Compute L2 penalty on positive weights.
252
+
253
+ Helps prevent weight explosion when gates are partially open.
254
+
255
+ Returns
256
+ -------
257
+ torch.Tensor
258
+ L2 norm of positive weights
259
+ """
260
+ positive_weights = torch.exp(self.log_weight)
261
+ return (positive_weights**2).sum()
262
+
263
+ def get_sparsity(self) -> float:
264
+ """
265
+ Get current sparsity level.
266
+
267
+ Returns
268
+ -------
269
+ float
270
+ Fraction of weights that are effectively zero
271
+ """
272
+ with torch.no_grad():
273
+ gates = self.get_deterministic_gates()
274
+ return (gates == 0).float().mean().item()
275
+
276
+ def get_active_weights(self) -> dict:
277
+ """
278
+ Get indices and values of active (non-zero) weights.
279
+
280
+ Returns
281
+ -------
282
+ dict
283
+ Dictionary with 'indices' and 'values' of active weights
284
+ """
285
+ with torch.no_grad():
286
+ weights = self.get_weights(deterministic=True)
287
+ active_mask = weights > 0
288
+
289
+ return {
290
+ "indices": torch.where(active_mask)[0],
291
+ "values": weights[active_mask],
292
+ "count": active_mask.sum().item(),
293
+ }
294
+
295
+ def fit(
296
+ self,
297
+ M: sp.spmatrix,
298
+ y: np.ndarray,
299
+ lambda_l0: float = 0.01,
300
+ lambda_l2: float = 0.0,
301
+ lr: float = 0.01,
302
+ epochs: int = 1000,
303
+ loss_type: str = "mse",
304
+ verbose: bool = False,
305
+ verbose_freq: int = 100,
306
+ target_groups: np.ndarray | None = None,
307
+ ) -> "SparseCalibrationWeights":
308
+ """
309
+ Fit calibration weights using gradient descent.
310
+
311
+ Parameters
312
+ ----------
313
+ M : scipy.sparse matrix
314
+ Metric matrix of shape (n_targets, n_features)
315
+ y : numpy.ndarray
316
+ Target values to match
317
+ lambda_l0 : float
318
+ L0 regularization strength
319
+ lambda_l2 : float
320
+ L2 regularization strength on positive weights
321
+ lr : float
322
+ Learning rate
323
+ epochs : int
324
+ Number of training epochs
325
+ loss_type : str
326
+ Type of loss function: 'mse' or 'relative'
327
+ verbose : bool
328
+ Whether to print progress
329
+ verbose_freq : int
330
+ How often to print progress
331
+ target_groups : numpy.ndarray, optional
332
+ Array of group IDs for each target. Targets in the same group
333
+ will be averaged together so each group contributes equally to loss.
334
+ If None, all targets are treated independently.
335
+
336
+ Returns
337
+ -------
338
+ self
339
+ Fitted model
340
+ """
341
+ # Convert y to tensor
342
+ y = torch.tensor(y, dtype=torch.float32, device=self.device)
343
+
344
+ # Convert M to torch sparse (will be cached)
345
+ M_torch = self._convert_sparse_to_torch(M)
346
+
347
+ # Compute group weights for loss averaging
348
+ if target_groups is not None:
349
+ # Convert to tensor
350
+ target_groups = torch.tensor(
351
+ target_groups, dtype=torch.long, device=self.device
352
+ )
353
+
354
+ # Calculate group weights: 1 / group_size for each target
355
+ unique_groups = torch.unique(target_groups)
356
+ group_weights = torch.zeros_like(y)
357
+
358
+ for group_id in unique_groups:
359
+ group_mask = target_groups == group_id
360
+ group_size = group_mask.sum().item()
361
+ # Each target in the group gets weight 1/group_size
362
+ # so the group's total contribution is 1
363
+ group_weights[group_mask] = 1.0 / group_size
364
+ else:
365
+ # No grouping - all targets weighted equally
366
+ group_weights = torch.ones_like(y)
367
+
368
+ # Add jitter to weights to break symmetry (if jitter_sd > 0)
369
+ if self.log_weight_jitter_sd > 0:
370
+ with torch.no_grad():
371
+ jitter = (
372
+ torch.randn_like(self.log_weight)
373
+ * self.log_weight_jitter_sd
374
+ )
375
+ self.log_weight.data += jitter
376
+
377
+ # Setup optimizer
378
+ optimizer = torch.optim.Adam([self.log_weight, self.log_alpha], lr=lr)
379
+
380
+ # Training loop
381
+ for epoch in range(epochs):
382
+ # Forward pass
383
+ y_pred = self.forward(M, deterministic=False)
384
+
385
+ # Compute loss with group weighting
386
+ if loss_type == "relative":
387
+ # Relative error: (y - y_pred)^2 / (y + 1)^2
388
+ # Adding 1 to avoid division by zero
389
+ relative_errors = (y - y_pred) / (y + 1)
390
+ # Apply group weights and then average
391
+ weighted_squared_errors = (
392
+ relative_errors.pow(2) * group_weights
393
+ )
394
+ data_loss = (
395
+ weighted_squared_errors.sum()
396
+ ) # Sum because weights already normalize
397
+ else:
398
+ # Standard MSE with group weighting
399
+ squared_errors = (y - y_pred).pow(2)
400
+ weighted_squared_errors = squared_errors * group_weights
401
+ data_loss = (
402
+ weighted_squared_errors.sum()
403
+ ) # Sum because weights already normalize
404
+
405
+ l0_loss = self.get_l0_penalty()
406
+ loss = data_loss + lambda_l0 * l0_loss
407
+
408
+ # Add L2 penalty if specified
409
+ if lambda_l2 > 0:
410
+ l2_loss = self.get_l2_penalty()
411
+ loss = loss + lambda_l2 * l2_loss
412
+
413
+ # Backward pass
414
+ optimizer.zero_grad()
415
+ loss.backward()
416
+ optimizer.step()
417
+
418
+ # Print progress
419
+ if verbose and (epoch + 1) % verbose_freq == 0:
420
+ with torch.no_grad():
421
+ active_info = self.get_active_weights()
422
+ weights = self.get_weights(deterministic=True)
423
+ active_weights = weights[weights > 0]
424
+
425
+ # Compute relative errors for meaningful output
426
+ y_det = self.forward(M, deterministic=True)
427
+ if loss_type == "relative":
428
+ rel_errors = torch.abs((y - y_det) / (y + 1))
429
+ else:
430
+ # For MSE, show relative errors anyway for interpretability
431
+ rel_errors = torch.abs((y - y_det) / (y + 1))
432
+
433
+ # For reporting, we can show both overall and group-averaged errors
434
+ mean_rel_err = rel_errors.mean().item()
435
+ max_rel_err = rel_errors.max().item()
436
+
437
+ # Compute mean group loss if groups are used
438
+ if target_groups is not None:
439
+ # Calculate mean loss per group
440
+ group_losses = []
441
+ for group_id in torch.unique(target_groups):
442
+ group_mask = target_groups == group_id
443
+ group_mean_err = (
444
+ rel_errors[group_mask].mean().item()
445
+ )
446
+ group_losses.append(group_mean_err)
447
+ mean_group_loss = np.mean(group_losses)
448
+ else:
449
+ mean_group_loss = mean_rel_err
450
+
451
+ # Calculate sparsity percentage
452
+ sparsity_pct = 100 * (
453
+ 1 - active_info["count"] / self.n_features
454
+ )
455
+
456
+ # Calculate components of the actual loss being minimized
457
+ actual_data_loss = data_loss.item()
458
+ actual_l0_loss = l0_loss.item()
459
+ actual_total_loss = loss.item()
460
+
461
+ if target_groups is not None:
462
+ print(
463
+ f"Epoch {epoch+1:4d}: "
464
+ f"mean_group_loss={mean_group_loss:.1%}, "
465
+ f"max_error={max_rel_err:.1%}, "
466
+ f"total_loss={actual_total_loss:.3f}, "
467
+ f"active={active_info['count']:4d}/{self.n_features} ({sparsity_pct:.1f}% sparse)"
468
+ )
469
+ else:
470
+ print(
471
+ f"Epoch {epoch+1:4d}: "
472
+ f"mean_error={mean_rel_err:.1%}, "
473
+ f"max_error={max_rel_err:.1%}, "
474
+ f"total_loss={actual_total_loss:.3f}, "
475
+ f"active={active_info['count']:4d}/{self.n_features} ({sparsity_pct:.1f}% sparse)"
476
+ )
477
+
478
+ return self
479
+
480
+ def predict(self, M: sp.spmatrix) -> torch.Tensor:
481
+ """
482
+ Apply calibration weights to new data.
483
+
484
+ Parameters
485
+ ----------
486
+ M : scipy.sparse matrix
487
+ Metric matrix of shape (n_targets, n_features)
488
+
489
+ Returns
490
+ -------
491
+ torch.Tensor
492
+ Calibrated predictions
493
+ """
494
+ with torch.no_grad():
495
+ return self.forward(M, deterministic=True)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: l0-python
3
- Version: 0.1.1
3
+ Version: 0.3.1
4
4
  Summary: L0 regularization for sparse neural networks and intelligent sampling
5
5
  Author-email: PolicyEngine <hello@policyengine.org>
6
6
  License: MIT License
@@ -36,7 +36,7 @@ Classifier: License :: OSI Approved :: MIT License
36
36
  Classifier: Programming Language :: Python :: 3
37
37
  Classifier: Programming Language :: Python :: 3.13
38
38
  Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
39
- Requires-Python: >=3.13
39
+ Requires-Python: >=3.11
40
40
  Description-Content-Type: text/markdown
41
41
  License-File: LICENSE
42
42
  Requires-Dist: torch>=2.0.0
@@ -46,11 +46,10 @@ Provides-Extra: dev
46
46
  Requires-Dist: pytest>=7.0; extra == "dev"
47
47
  Requires-Dist: pytest-cov>=3.0; extra == "dev"
48
48
  Requires-Dist: black>=22.0; extra == "dev"
49
- Requires-Dist: mypy>=0.900; extra == "dev"
50
- Requires-Dist: ruff>=0.0.280; extra == "dev"
51
- Requires-Dist: pre-commit>=3.0; extra == "dev"
52
49
  Requires-Dist: build>=1.3; extra == "dev"
53
50
  Requires-Dist: scikit-learn>=1.0; extra == "dev"
51
+ Requires-Dist: yaml-changelog>=0.3.0; extra == "dev"
52
+ Requires-Dist: twine>=4.0.0; extra == "dev"
54
53
  Provides-Extra: docs
55
54
  Requires-Dist: mystmd>=1.3; extra == "docs"
56
55
  Requires-Dist: jupyter>=1.0; extra == "docs"
@@ -1,11 +1,12 @@
1
1
  l0/__init__.py,sha256=ezGVLGbdU_jAElAJSdLKjSWCnZRILAZi8qMBPjcHwQc,1192
2
+ l0/calibration.py,sha256=EnIhQPkC6yvRp0-o1qG3SCVUp6pIqwkqkx3DX3uWdG0,17838
2
3
  l0/distributions.py,sha256=GvVoDasdxoDlPPdzt33lFzkuJgQsfkEn9e-abxru3nM,6325
3
4
  l0/gates.py,sha256=54OORMg9qSsdbIyzYIL9t9CCHWsKbumSKl_d4-YFuNU,11443
4
5
  l0/layers.py,sha256=j_DPEFdfUc37ojtoK2ufGzVYzZ_DwusqTcJXCVxZS68,13785
5
6
  l0/penalties.py,sha256=okqXgX2eGUmg5prcDclicTQALPPPF9FA5eQP09V4GTE,9569
6
7
  l0/sparse.py,sha256=UVpkrrJBnQ9iSNDoWK5F_sr43tQareWXzYHyMq_cKss,9726
7
- l0_python-0.1.1.dist-info/licenses/LICENSE,sha256=LoyFJ8qmpwWPp5RmxFGHhdBxsemvp_BqGyiCgNAZHlk,1069
8
- l0_python-0.1.1.dist-info/METADATA,sha256=RoKU7uVltzW11jyMiaL3GoPLvQjc7sz1w0qL6B9I6-0,6871
9
- l0_python-0.1.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
10
- l0_python-0.1.1.dist-info/top_level.txt,sha256=brP2SoElgmGhNJk-qRFEQZ5UE-d1e87Tr60hSSh8n34,3
11
- l0_python-0.1.1.dist-info/RECORD,,
8
+ l0_python-0.3.1.dist-info/licenses/LICENSE,sha256=LoyFJ8qmpwWPp5RmxFGHhdBxsemvp_BqGyiCgNAZHlk,1069
9
+ l0_python-0.3.1.dist-info/METADATA,sha256=nsOQQL-M3CKPcWkU_cEtzVNf3T1Rku1it7sm2rh2xoI,6833
10
+ l0_python-0.3.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
11
+ l0_python-0.3.1.dist-info/top_level.txt,sha256=brP2SoElgmGhNJk-qRFEQZ5UE-d1e87Tr60hSSh8n34,3
12
+ l0_python-0.3.1.dist-info/RECORD,,