Utils#

Utility functions for NumPy-based optimizers.

Includes: - Parameter flatten/deflatten helpers - Total loss wrapper (Task + 0.5*(Consistency + Coherence)) - Empirical covariance, conjugate gradient solver - A simple symmetric KL proxy over state statistics

qmlhc.optim.numpy_optim.utils.cg_solve(A_mul, b, iters=10, tol=1e-06)[source]#

Conjugate Gradient solver on an implicit SPD operator A_mul.

Return type:

ndarray

qmlhc.optim.numpy_optim.utils.cov_empirical(X)[source]#

Empirical covariance (unbiased) of samples X (N x D).

Return type:

ndarray

qmlhc.optim.numpy_optim.utils.deflatten_params(vec, layout, like)[source]#

Rebuild a parameter dict from a flat vector and a layout spec.

Return type:

Dict[str, Any]

qmlhc.optim.numpy_optim.utils.flatten_params(params)[source]#

Flatten a dict of parameters into a 1D vector with a layout spec.

Return type:

Tuple[ndarray, list[tuple[str, int]]]

qmlhc.optim.numpy_optim.utils.kl_proxy(old_info, new_info, eps=1e-08)[source]#

Symmetric KL-like proxy using Gaussian approximations over state branches. Not a true KL unless states are Gaussian; intended as a safe divergence proxy.

KL_sym ≈ 0.5 * [ tr(S1^{-1} S0 + S0^{-1} S1) + (m1-m0)^T (S^{-1}_avg) (m1-m0) - D ] Where S0,S1 are covariances and m0,m1 means. We avoid explicit inverses via CG on S_avg.

Falls back to ||mean diff||^2 if covariance is unavailable.

Return type:

float

qmlhc.optim.numpy_optim.utils.total_loss_for(model, theta, context)[source]#
Return type:

float

Compute total loss:

L = Task(s_t, target) + 0.5*(Consistency + Coherence)

Expected context fields:
  • x0, drift, target

  • losses: (task_loss, cons_loss, coh_loss)

  • branches: int