Auto-ML via Generalized Cross-Validation (GCV)¶
Navigation:
Theory introduction: See the Intro
Related mathematical theory: See the Mathematical Theory
Hyperparameter tuning via standard Grid Search is computationally expensive. While earlier versions relied heavily on “Multi-Start” Coordinate Descent for all parameters, the framework fully automated the continuous penalty optimization via StaticTAM.auto_fit().
This engine leverages the smart_solve_gcv dispatcher, implementing Golub’s trace trick [Golub et al., 1979] to find the optimal regularization parameter (\(\lambda\)) for each effect simultaneously (for each margin of a te(): an effect exposes penalty_coordinates() and set_penalty_coordinates(), one coordinate by default and one per margin for a tensor product), without requiring K-fold retraining.
The Orchestrator and API Entry Point¶
The auto_fit method acts as the user-facing bridge. It aligns the data, establishes the loss bounds, and initializes the Multiple Smoothing Parameter (MSP) estimation algorithm.
def auto_fit(
self,
data_train: pd.DataFrame,
alpha_p_bounds: Tuple[float, float] = (-30.0, 6.0),
number_of_steps: int = 10,
alpha_p_list: Optional[List[float]] = None,
gamma: float = 1.4,
verbose: bool = False,
criterion: str = "gcv"
) -> 'StaticTAM':
"""
Automatically trains the model by finding the optimal regularization per effect.
Uses Generalized Cross Validation (GCV) with Multiple Smoothing Parameter (MSP)
estimation to balance model fit (bias) and complexity (variance) without
requiring a validation set.
It utilizes a Coordinate Descent algorithm starting from the formula's initial values.
Args:
data_train: Training DataFrame.
alpha_p_bounds: Search range constraints for local steps (e.g., -30.0 to 6.0).
number_of_steps: Number of subdivisions within alpha_p_bounds to define the step size.
alpha_p_list: Explicit list of log10(lambda_p) coordinates to test. If provided,
alpha_p_bounds and number_of_steps are ignored.
gamma: Inflation factor for the effective degrees of freedom. Values > 1.0
(typically 1.4 to 1.5) force smoother models, preventing GCV
from overfitting when data has autocorrelated errors.
verbose: print verbose details if True
criterion: ``"gcv"`` (default) or ``"reml"``. ``"reml"`` maximises the Laplace restricted marginal likelihood by L-BFGS on
log(lambda) (analytic gradient): less prone than GCV to undersmooth on autocorrelated or clustered data. ``gamma`` is not used.
The fitted model keeps ``smoothing_criterion_`` and, with ``"reml"``, ``reml_score_``.
Returns:
self: The trained model instance with optimal lambda_ps applied.
"""
if criterion not in ("gcv", "reml"):
raise ValueError(f"criterion must be 'gcv' or 'reml'; got {criterion!r}")
print(f"--- Auto-Fitting with MSP-{criterion.upper()} (Multiple Smoothing Parameters) ---")
self.smoothing_criterion_, self.reml_score_ = criterion, None
data_train = self._transformed_frame(data_train, estimate=True)
transformed_train = data_train
data_train = _ensure_dummies(data_train, self.group_col_, self.date_col_)
_, balanced_data = _balance_groups(
dataset=data_train, group_col=self.group_col_, date_col=self.date_col_, method="drop"
)
x_train, y_train, self.unique_groups_ = self._prepare_data(
balanced_data, target_col=self.target_col_
)
loss_L = self._build_loss_matrix()
if getattr(self, "_reweighting_strategy_", None) is not None:
best_lambda_ps, gcv_score = self._auto_fit_reweighted(
x_train, y_train, loss_L, alpha_p_bounds, number_of_steps, alpha_p_list, gamma, verbose, criterion
)
elif criterion == "reml":
offset = self._offset_of(x_train)
self.coefficients_, best_lambda_ps, gcv_score = smart_solve_reml(
x_data=x_train,
y_data=y_train if offset is None else y_train - offset.to(y_train.dtype),
effects_list=self.effects_list_,
loss_matrix=loss_L,
alpha_p_bounds=alpha_p_bounds,
alpha_p_list=alpha_p_list,
verbose=verbose,
)
else:
offset = self._offset_of(x_train)
self.coefficients_, best_lambda_ps, gcv_score = smart_solve_gcv(
x_data=x_train,
y_data=y_train if offset is None else y_train - offset.to(y_train.dtype),
effects_list=self.effects_list_,
loss_matrix=loss_L,
alpha_p_bounds=alpha_p_bounds,
number_of_steps=number_of_steps,
alpha_p_list=alpha_p_list,
gamma=gamma,
verbose=verbose
)
if criterion == "reml":
self.reml_score_ = float(gcv_score)
print(f"\nFinal REML criterion: {gcv_score:.4f}")
else:
print(f"\nFinal GCV Score: {gcv_score:.4f}")
print("Optimal lambda_ps found per effect (per margin for a tensor product):")
position = 0
for effect in self.effects_list_:
count = effect.n_penalty_coordinates
values = best_lambda_ps[position:position + count]
position += count
effect.set_penalty_coordinates([float(v) for v in values])
if isinstance(effect, TensorProductEffect):
for label, value in zip(effect.coordinate_labels(), values):
print(f" - te({', '.join(m.feature_name for m in effect.effects)})[{label}]: {value:.2e} (log10 = {np.log10(value):.2f})")
else:
for part, value in enumerate(values):
label = effect.feature_name if len(values) == 1 else f"{effect.feature_name}#{part + 1}"
print(f" - {label}: {value:.2e} (log10 = {np.log10(value):.2f})")
self._effect_states_ = self._collect_effect_states(x_train)
if self._transform_active():
self._finish_transform_fit(transformed_train)
return self
VRAM Protection and Chunked Covariances¶
The smart_solve_gcv function operates as the exact algebraic engine. However, computing the trace of the inverse matrix requires the explicit instantiation of the global covariance matrix \(\Phi^T \Phi\).
To strictly prevent Out-Of-Memory (OOM) faults during the iterative search, the engine queries the hardware oracle to enforce an advanced 3-Tiered Memory Waterfall specifically designed for Coordinate Descent:
The Caching Fast-Path (< 30% Limit): If caching the unpenalized covariance matrices (
cov_Xandcov_XY) for all spatial groups requires less than \(30\%\) of available VRAM, the orchestrator caches the entire system strictly on the GPU. This completely bypasses the massive \(\mathcal{O}(G \times T \times D^2)\) tensor product during the search phase.The Iterative Accumulation (< 40% Limit): If a global GPU cache is impossible, but a single data group requires less than \(40\%\) of VRAM, the engine falls back to looping over the groups on the GPU natively, accumulating covariances iteratively and aggressively freeing memory per step.
Extreme CPU Offloading (> 40% Fallback): If evaluating a single group exceeds the \(40\%\) VRAM safety threshold (frequently triggered by massive Neural or Tensor interactions), the orchestrator intercepts the impending GPU crash and gracefully forces
eval_device = torch.device('cpu'), offloading the entire cyclic trace resolution to the Host system’s RAM.
Because the system allows different regularization weights for different topological bases (e.g., one \(\lambda\) for Splines, another for Fourier), the global penalty matrix \(P\) must be updated dynamically during the optimization loop.
The dispatcher pre-calculates the index boundaries (start, end) for every individual effect in the formula and maps them to a spans array. During each evaluation of the GCV objective function, sync_penalty_blocks injects the actively tested \(\lambda\) values strictly into their corresponding diagonal blocks, ensuring zero cross-contamination between distinct structural penalties.
Discrete Coordinate Descent Optimization¶
To optimize the multiple parameters efficiently across the block-diagonal structure, smart_solve_gcv deploys a memory-safe Discrete Coordinate Descent loop [Wright, 2015].
Initialization: It extracts the starting \(\log_{10}(\lambda)\) values from the
effects_list.Iterative Search: For a maximum of 15 cycles, it iterates through each individual effect.
Local Perturbation: It tests localized candidates (
original - step_sizeandoriginal + step_size) while holding all other effects’ penalties constant.Scoring: The system recalculates the exact cyclic trace and GCV score for each perturbation. If a candidate improves the global GCV score, it becomes the new baseline.
The loop naturally terminates early if a full cycle completes without any parameter achieving a lower GCV score. Once optimal parameters are found, it triggers a final dense inversion using solve_linear_system to map the optimal coefficients exactly to the target distribution.
Penalty parity. Step 3 does not rescale a block built once from the formula’s own lambda_p. sync_penalty_blocks assigns \(\lambda_p = 10^{\alpha}\) to the effect and asks the effect to rebuild its block, so the matrix being scored is the one _build_penalty_matrix() reassembles from the selected weights: on the default loss="l2" path, auto_fit() followed by fit() returns the same estimator. That is the contract AutoTAM depends on when refit_on_full_train=True puts a champion back on the full training window. At most two blocks are rebuilt per candidate, the coordinate under test, plus the previous one when its own search settled on a value other than the last one tried, and the trial weight is written on the effect only for the duration of that rebuild, so a search that raises leaves the caller’s effects as the formula declared them.
Non-Gaussian losses. When the model has a reweighting strategy (poisson, gamma, binomial, negative_binomial, tweedie), auto_fit() calls _auto_fit_reweighted: it fits the model, takes the working response and Fisher weights at the fitted linear predictor, and passes them to smart_solve_gcv(..., sample_weights=w), which scales \(\Phi\) and \(z\) by \(\sqrt w\) before forming the covariances (Y_sq and the trace follow from them). The fit and the search alternate until the selected \(\log_{10}\lambda\) moves by less than 0.25, with at most four passes, and a last reweighted fit at the selected parameters sets coefficients_ and dispersion_. grid_search_fit() follows the same rule for its candidates: each is fitted by the reweighted loop and scored on the response scale (inverse link applied); the returned model keeps the loss and carries the winning score in validation_rmse_.
REML. auto_fit(criterion='reml') calls smart_solve_reml (_reml.py) instead. PenaltyBasis writes the penalty of the effects as S0 + sum_c lambda_c Q_c, one Q_c per smoothing coordinate, by evaluating each effect’s penalty at weights 1 and 2 (every penalty of the library is linear in its weights, so this covers m_pen, the margins of a te(), mode='per_level' and the second weight of a thin-plate spline), and the subspace where the penalty acts (its null space, of dimension null_dim, is fixed by the structure and not by the current weights). reml_objective returns minus the criterion summed over the groups and its analytic gradient in log(lambda); smart_solve_reml starts from the best common weight of a 12-point grid and runs L-BFGS-B inside the bounds of alpha_p_bounds (alpha_p_list narrows them). It builds the dense design of a group at once (no sample chunking) and a dense Cholesky of the D x D system, with D <= 7500. For a GLM loss _auto_fit_reweighted passes the working response and weights, and the known scale 1 / mean(w) for Poisson, binomial and negative binomial (the weights are normalised to unit mean). The fitted model keeps smoothing_criterion_ and reml_score_.
def reml_objective(
rho,
cov_x: torch.Tensor,
cov_xy: torch.Tensor,
y_sq: torch.Tensor,
basis: PenaltyBasis,
n_samples: int,
known_scale: Optional[float] = None,
) -> Tuple[float, np.ndarray]:
r"""Minus the REML criterion summed over the groups and its gradient in ``rho = log(lambda)``.
Args:
rho: log smoothing weights, one per coordinate of ``basis``.
cov_x, cov_xy, y_sq: ``Phi'W Phi`` (G, D, D), ``Phi'W z`` (G, D, 1) and ``z'W z`` (G,), float64.
basis: the penalty of the effects.
n_samples: rows of a group, ``T_eff`` (the scale of the penalty, as in the fit).
known_scale: the scale ``phi`` when it is known (Poisson, binomial); estimated from the penalized residual sum of squares otherwise.
"""
rho = np.asarray(rho, dtype=float)
n = float(n_samples)
lam = np.exp(rho)
groups, size = cov_x.shape[0], cov_x.shape[-1]
penalty = n * basis.penalty(rho).to(cov_x.device)
ridge = 1e-6 * n * torch.eye(size, dtype=cov_x.dtype, device=cov_x.device)
system = cov_x + penalty + ridge
factor = torch.linalg.cholesky(system)
beta = torch.cholesky_solve(cov_xy, factor)
log_det_a = 2.0 * torch.log(torch.diagonal(factor, dim1=-2, dim2=-1)).sum(dim=-1) # (G,)
inverse = torch.cholesky_inverse(factor) # (G, D, D)
deviance = (y_sq - (beta * cov_xy).sum(dim=(1, 2))).clamp_min(1e-300) # D_p, (G,)
reduced = n * basis.reduced_penalty(rho)
sign, log_det_s = torch.linalg.slogdet(reduced)
reduced_inverse = torch.linalg.inv(reduced)
dof = n - basis.null_dim
if known_scale is None:
value = -0.5 * log_det_a + 0.5 * log_det_s - 0.5 * dof * torch.log(deviance / dof)
else:
value = -0.5 * log_det_a + 0.5 * log_det_s - deviance / (2.0 * known_scale)
gradient = np.zeros(basis.n_coordinates)
for c, ((begin, end, q), reduced_q) in enumerate(zip(basis.blocks, basis._reduced)):
scaled_q = n * lam[c] * q.to(cov_x.device)
trace_a = (inverse[:, begin:end, begin:end] * scaled_q.T).sum(dim=(1, 2)) # tr(A^-1 dP_c), (G,)
trace_s = (reduced_inverse * (n * lam[c] * reduced_q).T).sum()
beta_block = beta[:, begin:end, 0]
quad = torch.einsum("gi,ij,gj->g", beta_block, scaled_q, beta_block) # theta' dP_c theta
if known_scale is None:
scale_term = -dof / (2.0 * deviance) * quad
else:
scale_term = -quad / (2.0 * known_scale)
gradient[c] = float((-0.5 * trace_a + 0.5 * trace_s + scale_term).sum())
return -float(value.sum()) if sign > 0 else float("inf"), -gradient
def smart_solve_gcv(
x_data: torch.Tensor,
y_data: torch.Tensor,
effects_list: List[BaseEffect],
loss_matrix: torch.Tensor,
alpha_p_bounds: Tuple[float, float],
number_of_steps: int = 10,
alpha_p_list: Optional[List[float]] = None,
gamma: float = 1.4,
verbose: bool = False,
sample_weights: Optional[torch.Tensor] = None,
trace_method: str = "exact"
) -> Tuple[torch.Tensor, np.ndarray, float]:
r"""
Memory-safe Generalized Cross Validation (GCV) solver.
Dynamically routes matrix inversions and chunking based on available VRAM.
On return, every effect in `effects_list` carries the smoothing weights that were selected
for it, so rebuilding the penalty from the effects reproduces the fit. A search
that raises leaves the formula's own weights in place.
The search runs over one coordinate per smoothing parameter: one per effect, and one per margin
for a tensor product (`effect.penalty_coordinates()`). The returned `best_lambda_ps` is the flat
vector of all coordinates, effect after effect; `effect.n_penalty_coordinates` splits it.
`sample_weights` (shape (n_groups, n_samples, 1), non-negative) scores the weighted system: with the working
response and the Fisher weights of a GLM it is the working-weight GCV of one reweighting pass. None is the plain path.
"""
run_device = x_data.device
num_samples = x_data.shape[1]
n_groups = x_data.shape[0]
dummy_x = x_data[:, 0:1, :].to(run_device)
dummy_phi = build_phi_from_effects(dummy_x, effects_list)
total_d = dummy_phi.shape[-1]
del dummy_x, dummy_phi
if total_d > 7500 and trace_method == "exact":
raise MemoryError(
f"Feature dimension D={total_d} is too massive for Generalized Cross Validation (GCV). "
"GCV requires computing the exact trace of the dense inverse covariance matrix, "
"which will cause a severe Out-Of-Memory (OOM) crash on your GPU. "
"Please use `grid_search_fit()` instead, which utilizes matrix-free Conjugate Gradient routing."
)
spans = []
c_idx = 0
for e in effects_list:
k = e.get_n_coeffs()
spans.append((c_idx, c_idx + k))
c_idx += k
# One GCV coordinate per smoothing parameter: one per effect, except a tensor product, which has one per margin.
coords_per_effect = [e.n_penalty_coordinates for e in effects_list]
coord_spans = []
c_start = 0
for count in coords_per_effect:
coord_spans.append((c_start, c_start + count))
c_start += count
n_coords = c_start
def sync_penalty_blocks(
penalty: torch.Tensor,
applied_alpha_ps: np.ndarray,
alpha_ps: np.ndarray,
device: torch.device
) -> None:
r"""
Writes the penalty blocks for `alpha_ps`, rebuilding only the ones that moved.
Each block is produced by the effect itself at lambda_p = 10**alpha, so the
matrix scored here is exactly the one `fit()` reassembles from the lambdas this
search returns. Rescaling a prebuilt block would instead score the product of
the formula's own lambda_p and the tested one, leaving the selected weight
unable to reproduce the model it was selected on.
The trial weight lives on the effect only while its block is built: a search
that raises must not leave the caller's effects holding a candidate.
"""
for i, effect in enumerate(effects_list):
c0, c1 = coord_spans[i]
if np.array_equal(alpha_ps[c0:c1], applied_alpha_ps[c0:c1]):
continue
formula_coordinates = effect.penalty_coordinates()
try:
effect.set_penalty_coordinates([float(10.0 ** a) for a in alpha_ps[c0:c1]])
mat = effect.build_penalty_matrix()
finally:
effect.set_penalty_coordinates(formula_coordinates)
if mat.is_sparse:
mat = mat.to_dense()
start, end = spans[i]
penalty[start:end, start:end] = mat.to(device)
applied_alpha_ps[c0:c1] = alpha_ps[c0:c1]
bytes_per_group = (total_d * total_d * 8) * 5
total_bytes = bytes_per_group * n_groups
available_mem = hw.get_available_memory()
def _get_chunked_covs(x_subset: torch.Tensor, y_subset: torch.Tensor, w_subset: Optional[torch.Tensor] = None):
nonlocal run_device
n_groups_in_subset = x_subset.shape[0]
num_samples_in_subset = x_subset.shape[1]
cov_x_total = torch.zeros((n_groups_in_subset, total_d, total_d), dtype=torch.get_default_dtype(), device=run_device)
cov_xy_total = torch.zeros((n_groups_in_subset, total_d, y_subset.shape[-1]), dtype=torch.get_default_dtype(), device=run_device)
Y_sq_total = torch.zeros(n_groups_in_subset, dtype=torch.get_default_dtype(), device=run_device)
available_bytes = hw.get_available_memory()
allocatable_bytes = available_bytes * 0.8
bytes_per_group_full_n = num_samples_in_subset * total_d * 8 * 5.0
safe_group_batch = max(1, int(allocatable_bytes // bytes_per_group_full_n)) if bytes_per_group_full_n > 0 else 1
g_start = 0
while g_start < n_groups_in_subset:
g_end = min(g_start + safe_group_batch, n_groups_in_subset)
current_sub_batch_size = g_end - g_start
try:
x_chunk = x_subset[g_start:g_end, :, :].to(run_device)
y_chunk = y_subset[g_start:g_end, :, :].to(run_device)
phi_chunk = build_phi_from_effects(x_chunk, effects_list)
if w_subset is not None:
root_w = w_subset[g_start:g_end].to(device=run_device, dtype=phi_chunk.dtype).clamp_min(0).sqrt()
phi_chunk = phi_chunk * root_w
y_chunk = y_chunk.to(phi_chunk.dtype) * root_w
if loss_matrix.shape[0] == 1:
L_sqrt = loss_matrix[0, 0].sqrt()
phi_weighted = phi_chunk * L_sqrt
cov_x_total[g_start:g_end] = phi_weighted.mT @ phi_weighted
cov_xy_total[g_start:g_end] = phi_chunk.mT @ (y_chunk * loss_matrix[0, 0])
Y_sq_total[g_start:g_end] = torch.sum(torch.abs(y_chunk)**2 * loss_matrix[0, 0], dim=1).squeeze(-1)
del phi_weighted, L_sqrt
else:
cov_x_total[g_start:g_end] = phi_chunk.mT @ phi_chunk
y_weighted = y_chunk.to(phi_chunk.dtype) @ loss_matrix
cov_xy_total[g_start:g_end] = phi_chunk.mT @ y_weighted
Y_sq_total[g_start:g_end] = torch.sum(torch.abs(y_chunk)**2, dim=1).squeeze(-1)
del y_weighted
del x_chunk, y_chunk, phi_chunk
g_start += current_sub_batch_size
except (torch.OutOfMemoryError, MemoryError):
if safe_group_batch > 1:
safe_group_batch, run_device = hw.handle_oom(
current_batch=safe_group_batch,
device=run_device,
context="GCV covariance group reduction",
allow_cpu_fallback=False
)
continue
else:
raise RuntimeError("A single full group exceeds available physical memory during GCV covariance computation.")
return cov_x_total, cov_xy_total, Y_sq_total
initial_alpha_ps = np.array([
np.log10(c) if c > 0 else alpha_p_bounds[0]
for e in effects_list for c in e.penalty_coordinates()
], dtype=np.float64)
if alpha_p_list is None:
# The local steps stay inside the box, so the seed has to start inside it.
# An explicit coordinate list ignores the bounds, and so does its seed.
initial_alpha_ps = np.clip(initial_alpha_ps, alpha_p_bounds[0], alpha_p_bounds[1])
step_size = (alpha_p_bounds[1] - alpha_p_bounds[0]) / float(number_of_steps)
if total_bytes < available_mem * 0.3:
if verbose:
print("[GCV Engine] VRAM footprint < 30%. Caching covariances globally on GPU.")
cov_X, cov_XY, Y_sq = _get_chunked_covs(x_data, y_data, sample_weights)
current_penalty = torch.zeros((total_d, total_d), dtype=torch.get_default_dtype(), device=run_device)
applied_alpha_ps = np.full(n_coords, np.nan, dtype=np.float64)
def gcv_objective(alpha_ps: np.ndarray) -> float:
sync_penalty_blocks(current_penalty, applied_alpha_ps, alpha_ps, run_device)
score = compute_gcv_score(
cov_X=cov_X,
cov_XY=cov_XY,
Y_sq=Y_sq,
penalty_M_star_M=current_penalty,
lambda_p=1.0,
n_samples=num_samples,
gamma=gamma,
trace_method=trace_method
)
return score.item()
current_alpha_ps = np.copy(initial_alpha_ps)
best_gcv = gcv_objective(current_alpha_ps)
cycle = 0
max_cycles = 15
while cycle < max_cycles:
cycle += 1
improved_in_cycle = False
for i in range(n_coords):
original_val = current_alpha_ps[i]
best_val_for_effect = original_val
if alpha_p_list is not None:
candidates = alpha_p_list
else:
candidates = [
np.clip(original_val - step_size, alpha_p_bounds[0], alpha_p_bounds[1]),
np.clip(original_val + step_size, alpha_p_bounds[0], alpha_p_bounds[1])
]
for cand in candidates:
if np.isclose(cand, original_val):
continue
current_alpha_ps[i] = cand
score = gcv_objective(current_alpha_ps)
if score < best_gcv:
best_gcv = score
best_val_for_effect = cand
improved_in_cycle = True
current_alpha_ps[i] = best_val_for_effect
if not improved_in_cycle:
break
best_lambda_ps = 10.0 ** current_alpha_ps
sync_penalty_blocks(current_penalty, applied_alpha_ps, current_alpha_ps, run_device)
for effect, (c0, c1) in zip(effects_list, coord_spans):
effect.set_penalty_coordinates([float(v) for v in best_lambda_ps[c0:c1]])
coeffs = solve_linear_system(cov_X, cov_XY, current_penalty, num_samples)
return coeffs, best_lambda_ps, best_gcv
else:
eval_device = run_device if bytes_per_group < available_mem * 0.4 else torch.device('cpu')
if eval_device.type == 'cpu':
print("Notice: KxK matrix inversions exceed GPU VRAM. Routing solver to CPU.")
else:
print("Notice: Total system exceeds VRAM. Processing GCV in group chunks.")
cov_X_list, cov_XY_list, Y_sq_list = [], [], []
for g in range(n_groups):
cx, cxy, y_sq = _get_chunked_covs(x_data[g:g+1], y_data[g:g+1], None if sample_weights is None else sample_weights[g:g+1])
cov_X_list.append(cx.cpu())
cov_XY_list.append(cxy.cpu())
Y_sq_list.append(y_sq.cpu())
hw.empty_cache()
current_penalty = torch.zeros((total_d, total_d), dtype=torch.get_default_dtype(), device=eval_device)
applied_alpha_ps = np.full(n_coords, np.nan, dtype=np.float64)
def gcv_objective(alpha_ps: np.ndarray) -> float:
try:
sync_penalty_blocks(current_penalty, applied_alpha_ps, alpha_ps, eval_device)
except (torch.OutOfMemoryError, MemoryError):
# Basis assembly runs on the compute device even when scoring was
# offloaded to the host; a block that does not fit rejects the
# candidate instead of aborting the search.
hw.empty_cache()
return float('inf')
total_score = 0.0
for g in range(n_groups):
try:
score = compute_gcv_score(
cov_X=cov_X_list[g].to(eval_device),
cov_XY=cov_XY_list[g].to(eval_device),
Y_sq=Y_sq_list[g].to(eval_device),
penalty_M_star_M=current_penalty,
lambda_p=1.0,
n_samples=num_samples,
gamma=gamma,
trace_method=trace_method
)
total_score += score.item()
except (torch.OutOfMemoryError, MemoryError):
hw.empty_cache()
return float('inf')
return total_score / n_groups
current_alpha_ps = np.copy(initial_alpha_ps)
best_gcv = gcv_objective(current_alpha_ps)
cycle = 0
max_cycles = 15
while cycle < max_cycles:
cycle += 1
improved_in_cycle = False
for i in range(n_coords):
original_val = current_alpha_ps[i]
best_val_for_effect = original_val
if alpha_p_list is not None:
candidates = alpha_p_list
else:
candidates = [
np.clip(original_val - step_size, alpha_p_bounds[0], alpha_p_bounds[1]),
np.clip(original_val + step_size, alpha_p_bounds[0], alpha_p_bounds[1])
]
for cand in candidates:
if np.isclose(cand, original_val):
continue
current_alpha_ps[i] = cand
score = gcv_objective(current_alpha_ps)
if score < best_gcv:
best_gcv = score
best_val_for_effect = cand
improved_in_cycle = True
current_alpha_ps[i] = best_val_for_effect
if not improved_in_cycle:
break
best_lambda_ps = 10.0 ** current_alpha_ps
sync_penalty_blocks(current_penalty, applied_alpha_ps, current_alpha_ps, eval_device)
for effect, (c0, c1) in zip(effects_list, coord_spans):
effect.set_penalty_coordinates([float(v) for v in best_lambda_ps[c0:c1]])
group_coeffs = []
for g in range(n_groups):
coeffs_g = solve_linear_system(
cov_X_list[g].to(eval_device),
cov_XY_list[g].to(eval_device),
current_penalty,
num_samples
)
group_coeffs.append(coeffs_g.cpu())
coeffs = torch.cat(group_coeffs, dim=0)
return coeffs, best_lambda_ps, best_gcv