itr-methods 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.
Files changed (35) hide show
  1. itr_methods/__init__.py +31 -0
  2. itr_methods/__main__.py +2 -0
  3. itr_methods/_nscf/__init__.py +6 -0
  4. itr_methods/_nscf/api.py +536 -0
  5. itr_methods/_nscf/core/__init__.py +1 -0
  6. itr_methods/_nscf/core/audit_hooks.py +8 -0
  7. itr_methods/_nscf/core/config.py +240 -0
  8. itr_methods/_nscf/core/fusion_solver.py +94 -0
  9. itr_methods/_nscf/core/model.py +132 -0
  10. itr_methods/_nscf/core/penalty.py +100 -0
  11. itr_methods/_nscf/core/refit_selection.py +806 -0
  12. itr_methods/_nscf/core/solver_admm.py +279 -0
  13. itr_methods/_nscf/core/solver_alt.py +881 -0
  14. itr_methods/_nscf/core/trainer.py +309 -0
  15. itr_methods/_nscf/defaults.json +70 -0
  16. itr_methods/_nscf/estimator.py +267 -0
  17. itr_methods/_nscf/exact_prox.py +56 -0
  18. itr_methods/_validation.py +53 -0
  19. itr_methods/doctor.py +35 -0
  20. itr_methods/plotting.py +169 -0
  21. itr_methods/scaf/__init__.py +678 -0
  22. itr_methods/scaf/_solver.py +159 -0
  23. itr_methods-0.1.0.data/data/share/itr_methods/README.md +321 -0
  24. itr_methods-0.1.0.data/data/share/itr_methods/docs/NSCF_TUTORIAL.ipynb +1500 -0
  25. itr_methods-0.1.0.data/data/share/itr_methods/docs/SCAF_TUTORIAL.ipynb +1408 -0
  26. itr_methods-0.1.0.data/data/share/itr_methods/examples/nscf_dendrogram_figure.py +75 -0
  27. itr_methods-0.1.0.data/data/share/itr_methods/examples/quickstart.py +38 -0
  28. itr_methods-0.1.0.data/data/share/itr_methods/examples/scaf_path_figure.py +56 -0
  29. itr_methods-0.1.0.dist-info/METADATA +347 -0
  30. itr_methods-0.1.0.dist-info/RECORD +35 -0
  31. itr_methods-0.1.0.dist-info/WHEEL +5 -0
  32. itr_methods-0.1.0.dist-info/entry_points.txt +2 -0
  33. itr_methods-0.1.0.dist-info/licenses/LICENSE +408 -0
  34. itr_methods-0.1.0.dist-info/licenses/NOTICE.txt +24 -0
  35. itr_methods-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,279 @@
1
+ import csv
2
+ from . import audit_hooks
3
+ import os
4
+ import time
5
+ import numpy as np
6
+ import torch
7
+ import torch.nn.functional as F
8
+
9
+ from .fusion_solver import solve_Z_update
10
+ from .penalty import fusion_penalty
11
+
12
+
13
+ def _min_pairwise_linf(M: np.ndarray) -> float:
14
+ C = M.shape[0]
15
+ if C < 2:
16
+ return float("inf")
17
+ vals = []
18
+ for i in range(C):
19
+ for j in range(i + 1, C):
20
+ vals.append(np.max(np.abs(M[i] - M[j])))
21
+ return float(np.min(vals)) if vals else float("inf")
22
+
23
+
24
+ def _reg_loss(y_hat: torch.Tensor, y: torch.Tensor, loss_type: str, huber_delta: float) -> torch.Tensor:
25
+ """
26
+ y_hat, y: shape (n,)
27
+ """
28
+ if loss_type == "mse":
29
+ return F.mse_loss(y_hat, y)
30
+ elif loss_type == "huber":
31
+ return F.huber_loss(y_hat, y, delta=huber_delta)
32
+ else:
33
+ raise ValueError(f"Unknown loss_type={loss_type}, use mse|huber")
34
+
35
+
36
+ def run_admm_path(
37
+ model,
38
+ H_train: torch.Tensor,
39
+ A_train: torch.Tensor, # NEW
40
+ y_train: torch.Tensor, # continuous y
41
+ lambda_values: np.ndarray,
42
+ args,
43
+ H_val=None,
44
+ A_val=None,
45
+ y_val=None,
46
+ init_Z=None,
47
+ init_U=None,
48
+ log_fn=print,
49
+ outdir: str | None = None,
50
+ save_tag: str | None = None,
51
+ save_last_ZU: bool = False,
52
+ ):
53
+ """
54
+ ADMM over lambda path, optimizing ONLY treatment parameters gamma (model.gamma.weight).
55
+
56
+ Objective (theta-step) for fixed lambda:
57
+ min_gamma 1/n * sum_i loss(y_i, yhat_i(H_i, A_i; gamma)) + (rho/2)||gamma - Z + U||^2
58
+
59
+ Z-step:
60
+ Z = argmin_Z fusion_penalty(Z; lambda) + (rho/2)||Z - (gamma + U)||^2
61
+
62
+ Returns:
63
+ all_Z: list[np.ndarray] each element is Z(lam) with shape (K, r)
64
+ metrics: list[dict]
65
+ Z_final, U_final
66
+ """
67
+ device = H_train.device
68
+ rho = float(args.rho)
69
+
70
+ # ----------------------------
71
+ # 0) pick which parameter to fuse: gamma
72
+ # ----------------------------
73
+ if not hasattr(model, "gamma"):
74
+ raise AttributeError("Model must have attribute `gamma` (e.g., nn.Embedding(K, r)) for fusion.")
75
+
76
+ # gamma_param is a Parameter tensor of shape (K, r)
77
+ gamma_param = model.gamma.weight if hasattr(model.gamma, "weight") else model.gamma
78
+ gamma_param = gamma_param.to(device)
79
+
80
+ # optimizer on gamma only
81
+ lr_gamma = float(getattr(args, "lr_gamma", getattr(args, "lr_beta", 1e-3)))
82
+ opt_gamma = torch.optim.Adam([gamma_param], lr=lr_gamma)
83
+
84
+ # loss config
85
+ loss_type = str(getattr(args, "loss_type", "mse"))
86
+ huber_delta = float(getattr(args, "huber_delta", 1.0))
87
+
88
+ # init Z, U
89
+ with torch.no_grad():
90
+ gamma0 = gamma_param.detach().clone()
91
+
92
+ Z = gamma0.clone() if init_Z is None else init_Z.detach().clone().to(device)
93
+ U = torch.zeros_like(Z) if init_U is None else init_U.detach().clone().to(device)
94
+
95
+ all_Z: list[np.ndarray] = []
96
+ metrics: list[dict] = []
97
+ trace_rows: list[dict] = []
98
+ save_trace = bool(getattr(args, "save_admm_trace", False))
99
+
100
+ # ----------------------------
101
+ # ADMM along lambda path
102
+ # ----------------------------
103
+ for li, lam in enumerate(lambda_values):
104
+ lam = float(lam)
105
+ t0 = time.time()
106
+
107
+ for epoch_idx in range(int(args.admm_epochs)):
108
+ # ---- theta/gamma update: approx solve regression + quadratic tether to (Z - U)
109
+ for _ in range(int(args.theta_steps)):
110
+ opt_gamma.zero_grad(set_to_none=True)
111
+
112
+ # yhat from precomputed H + A
113
+ if hasattr(model, "predict_from_HA"):
114
+ y_hat = model.predict_from_HA(H_train, A_train) # (n,)
115
+ else:
116
+ raise AttributeError(
117
+ "Model must implement `predict_from_HA(H, A)` for ADMM stage "
118
+ "(because H_train is precomputed and backbone may be frozen)."
119
+ )
120
+
121
+ reg = _reg_loss(y_hat, y_train, loss_type=loss_type, huber_delta=huber_delta)
122
+ quad = 0.5 * rho * torch.sum((gamma_param - Z + U) ** 2)
123
+ obj = reg + quad
124
+
125
+ obj.backward()
126
+ torch.nn.utils.clip_grad_norm_([gamma_param], max_norm=5.0)
127
+ opt_gamma.step()
128
+
129
+ # ---- Z update
130
+ with torch.no_grad():
131
+ gamma_k1 = gamma_param.detach()
132
+ Z_prev = Z.detach().clone()
133
+ U_prev = U.detach().clone()
134
+ W = gamma_k1 + U
135
+
136
+ Z = solve_Z_update(
137
+ W=W,
138
+ lam=lam,
139
+ rho=rho,
140
+ penalty=str(args.penalty),
141
+ gamma_mcp=float(getattr(args, "gamma_mcp", 2.0)),
142
+ a_scad=float(getattr(args, "a_scad", 3.7)),
143
+ z_steps=int(args.z_steps),
144
+ z_lr=float(args.z_lr),
145
+ normalize_fusion=bool(getattr(args, "normalize_fusion", False)),
146
+ early_tol=float(getattr(args, "z_early_tol", 1e-4)),
147
+ early_patience=int(getattr(args, "z_early_patience", 6)),
148
+ snap_eps=float(getattr(args, "snap_eps", 1e-3)),
149
+ )
150
+
151
+ # ---- dual update
152
+ U = U + (gamma_k1 - Z)
153
+ audit_hooks.call("admm_epoch", model, H_train, A_train, y_train, gamma_k1, Z, Z_prev, U_prev, U, li, lam, epoch_idx + 1, args)
154
+
155
+ if save_trace:
156
+ with torch.no_grad():
157
+ primal_gap = gamma_k1 - Z
158
+ primal_residual = float(torch.norm(primal_gap, p="fro").item())
159
+ dual_residual = float((rho * torch.norm(Z - Z_prev, p="fro")).item())
160
+ constraint_linf = float(torch.max(torch.abs(primal_gap)).item())
161
+ y_hat_trace = model.predict_from_HA(H_train, A_train).view(-1)
162
+ y_train_trace = y_train.view(-1)
163
+ reg_trace = _reg_loss(
164
+ y_hat_trace,
165
+ y_train_trace,
166
+ loss_type=loss_type,
167
+ huber_delta=huber_delta,
168
+ )
169
+ fusion_trace = fusion_penalty(
170
+ Z,
171
+ lam,
172
+ penalty=str(args.penalty),
173
+ gamma_mcp=float(getattr(args, "gamma_mcp", 2.0)),
174
+ a_scad=float(getattr(args, "a_scad", 3.7)),
175
+ normalize=bool(getattr(args, "normalize_fusion", False)),
176
+ )
177
+ primal_objective = reg_trace + fusion_trace
178
+ augmented_lagrangian = (
179
+ primal_objective
180
+ + 0.5 * rho * torch.sum((primal_gap + U_prev) ** 2)
181
+ - 0.5 * rho * torch.sum(U_prev ** 2)
182
+ )
183
+ trace_rows.append(
184
+ {
185
+ "lambda_index": int(li),
186
+ "lambda": float(lam),
187
+ "epoch": int(epoch_idx + 1),
188
+ "rho": float(rho),
189
+ "reg_loss": float(reg_trace.item()),
190
+ "fusion_penalty": float(fusion_trace.item()),
191
+ "primal_objective": float(primal_objective.item()),
192
+ "augmented_lagrangian": float(augmented_lagrangian.item()),
193
+ "primal_residual": primal_residual,
194
+ "dual_residual": dual_residual,
195
+ "constraint_linf": constraint_linf,
196
+ }
197
+ )
198
+
199
+ # ---- record
200
+ Z_np = Z.detach().cpu().numpy().copy()
201
+ all_Z.append(Z_np)
202
+
203
+ # ---- metrics
204
+ c2 = int(np.unique(np.round(Z_np, 2), axis=0).shape[0])
205
+ c3 = int(np.unique(np.round(Z_np, 3), axis=0).shape[0])
206
+ linf = _min_pairwise_linf(Z_np)
207
+ dt = time.time() - t0
208
+
209
+ # optional: record objective value at end of lambda
210
+ with torch.no_grad():
211
+ if hasattr(model, "predict_from_HA"):
212
+ y_hat_end = model.predict_from_HA(H_train, A_train).view(-1)
213
+ y_train_flat = y_train.view(-1)
214
+ reg_end = float(_reg_loss(y_hat_end, y_train_flat, loss_type, huber_delta).item())
215
+ train_mse = float(F.mse_loss(y_hat_end, y_train_flat).item())
216
+ else:
217
+ reg_end = float("nan")
218
+ train_mse = float("nan")
219
+ msg = (
220
+ f"[ADMM] {li+1:3d}/{len(lambda_values)} "
221
+ f"λ={lam:7.4f} | C2={c2:2d} C3={c3:2d} | "
222
+ f"minLinf={linf:.2e} | reg={reg_end:.4f} | T={dt:6.2f}s"
223
+ )
224
+ log_fn(msg)
225
+
226
+ val_mse = None
227
+ if H_val is not None and A_val is not None and y_val is not None:
228
+ with torch.no_grad():
229
+ y_hat_val = model.predict_from_HA(H_val, A_val).view(-1)
230
+ y_val_flat = y_val.view(-1)
231
+ val_mse = float(F.mse_loss(y_hat_val, y_val_flat).item())
232
+
233
+ metrics.append(
234
+ {
235
+ "lambda_index": li,
236
+ "lambda": lam,
237
+ "rho": rho,
238
+ "clusters_2d": c2,
239
+ "clusters_3d": c3,
240
+ "min_linf": linf,
241
+ "time_sec": dt,
242
+ "reg_loss": reg_end,
243
+ "val_mse": val_mse,
244
+ "train_mse": train_mse,
245
+ }
246
+ )
247
+
248
+ # ----------------------------
249
+ # Save Z_path
250
+ # ----------------------------
251
+ if outdir is not None:
252
+ os.makedirs(outdir, exist_ok=True)
253
+ tag = f"_{save_tag}" if (save_tag is not None and len(str(save_tag)) > 0) else ""
254
+
255
+ if len(all_Z) > 0:
256
+ Z_path = np.stack(all_Z, axis=0) # (L, K, r)
257
+ zpath_file = os.path.join(outdir, f"Z_path{tag}.npy")
258
+ np.save(zpath_file, Z_path)
259
+ log_fn(f"[Save] Z_path -> {zpath_file} (shape={Z_path.shape})")
260
+ else:
261
+ log_fn("[Save] Warning: all_Z empty; did not save Z_path.")
262
+
263
+ if save_last_ZU:
264
+ zlast_file = os.path.join(outdir, f"Z_last{tag}.npy")
265
+ ulast_file = os.path.join(outdir, f"U_last{tag}.npy")
266
+ np.save(zlast_file, Z.detach().cpu().numpy())
267
+ np.save(ulast_file, U.detach().cpu().numpy())
268
+ log_fn(f"[Save] Z_last -> {zlast_file}")
269
+ log_fn(f"[Save] U_last -> {ulast_file}")
270
+
271
+ if save_trace and trace_rows:
272
+ trace_file = os.path.join(outdir, f"admm_trace{tag}.csv")
273
+ with open(trace_file, "w", newline="", encoding="utf-8") as handle:
274
+ writer = csv.DictWriter(handle, fieldnames=list(trace_rows[0].keys()))
275
+ writer.writeheader()
276
+ writer.writerows(trace_rows)
277
+ log_fn(f"[Save] ADMM trace -> {trace_file} (rows={len(trace_rows)})")
278
+
279
+ return all_Z, metrics, Z.detach(), U.detach()