Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
242 lines
10 KiB
Python
242 lines
10 KiB
Python
"""Bounded linear capacity/optimizer control over frozen features, offline only.
|
|
|
|
This changes both capacity and optimizer relative to the MLP control; it does not
|
|
isolate either cause or qualify transfer. Inputs contain only known binary labels.
|
|
Timeouts are cooperative between tensor operations; an external process deadline
|
|
must bound a stalled kernel. No torch import or fitting occurs at module import.
|
|
"""
|
|
|
|
import math
|
|
import time
|
|
|
|
L2 = 0.01
|
|
MAX_ITER = 300
|
|
MAX_EVAL = 400
|
|
TOLERANCE_GRAD = 1e-5
|
|
TOLERANCE_CHANGE = 1e-10
|
|
STATIONARITY_LIMIT = 1e-4
|
|
FIT_TIMEOUT_SECONDS = 120.0
|
|
EVALUATION_TIMEOUT_SECONDS = 120.0
|
|
ARMS = frozenset({"coarse_only", "scene_features"})
|
|
|
|
|
|
def network(seed=0, channels=256):
|
|
"""Return a zero-initialized head compatible with feature_refinement.predict.
|
|
|
|
``seed`` is accepted for the existing factory interface but cannot affect the
|
|
zero initialization. Creating this head does not consume the torch RNG.
|
|
"""
|
|
import torch
|
|
from torch import nn
|
|
|
|
if type(channels) is not int or channels < 1:
|
|
raise ValueError("Positive integer feature channel count required")
|
|
|
|
class Head(nn.Module):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.weight = nn.Parameter(torch.zeros(1, channels + 1))
|
|
self.bias = nn.Parameter(torch.zeros(1))
|
|
|
|
def forward(self, fine, coarse, arm):
|
|
if arm not in ARMS:
|
|
raise ValueError("Unknown feature arm")
|
|
if fine.ndim != 2 or fine.shape[1] != channels:
|
|
raise ValueError("Expected points by feature channels")
|
|
if coarse.shape != (len(fine), 1):
|
|
raise ValueError("Expected points by one coarse logits")
|
|
for value in (fine, coarse):
|
|
if value.dtype != self.weight.dtype or value.device != self.weight.device:
|
|
raise ValueError("Head and features must have the same dtype and device")
|
|
x = fine if arm == "scene_features" else torch.zeros_like(fine)
|
|
return coarse + nn.functional.linear(
|
|
torch.cat((x, coarse), dim=1), self.weight, self.bias
|
|
)
|
|
|
|
return Head()
|
|
|
|
|
|
def _validate(Xfine, coarse, target, weights, arm, chunk):
|
|
import torch
|
|
|
|
if arm not in ARMS:
|
|
raise ValueError("Unknown feature arm")
|
|
if type(chunk) is not int or chunk < 1:
|
|
raise ValueError("Positive integer chunk required")
|
|
values = (Xfine, coarse, target, weights)
|
|
if not all(isinstance(value, torch.Tensor) for value in values):
|
|
raise ValueError("All inputs must be torch tensors")
|
|
if Xfine.ndim != 2 or min(Xfine.shape) < 1:
|
|
raise ValueError("Expected nonempty points by feature channels")
|
|
n = len(Xfine)
|
|
if coarse.shape != (n, 1):
|
|
raise ValueError("Expected points by one coarse logits")
|
|
if target.shape not in {(n,), (n, 1)} or weights.shape not in {(n,), (n, 1)}:
|
|
raise ValueError("Expected one target and weight per point")
|
|
if Xfine.dtype not in {torch.float32, torch.float64}:
|
|
raise ValueError("Features must be float32 or float64")
|
|
if coarse.dtype != Xfine.dtype or weights.dtype != Xfine.dtype:
|
|
raise ValueError("Features, coarse logits and weights must share a floating dtype")
|
|
if target.is_complex() or target.dtype not in {
|
|
torch.bool, torch.uint8, torch.int8, torch.int16, torch.int32,
|
|
torch.int64, torch.float32, torch.float64,
|
|
}:
|
|
raise ValueError("Targets must have a real binary dtype")
|
|
if any(value.device != Xfine.device for value in values):
|
|
raise ValueError("All inputs must share a device")
|
|
if any(value.requires_grad for value in values):
|
|
raise ValueError("Inputs must be frozen, without input gradients")
|
|
if not all(bool(torch.isfinite(value).all()) for value in values):
|
|
raise ValueError("Inputs must be finite")
|
|
if not bool(((target == 0) | (target == 1)).all()):
|
|
raise ValueError("Only binary known targets 0/1 allowed, including at zero weight")
|
|
if not bool((weights >= 0).all()):
|
|
raise ValueError("Weights must be nonnegative")
|
|
weight_sum = weights.sum(dtype=torch.float64)
|
|
if not bool(torch.isfinite(weight_sum)) or float(weight_sum) <= 0:
|
|
raise ValueError("Weights must have a finite positive sum")
|
|
return target.reshape(-1, 1).to(Xfine.dtype), weights.reshape(-1, 1) / weight_sum
|
|
|
|
|
|
class _TechnicalStop(RuntimeError):
|
|
pass
|
|
|
|
|
|
def fit(Xfine, coarse, target, weights, arm="scene_features", *, chunk=8192):
|
|
"""Fit all supplied known pixels and return ``(head, diagnostics)``.
|
|
|
|
Objective: sum(w * BCE) / sum(w) + .5 * .01 * sum(residual_params**2).
|
|
Bias and inactive fine coefficients are penalized as well, making the finite
|
|
dimensional objective strongly convex. Weight scale and pixel duplication do
|
|
not alter its definition. Chunking bounds activation memory, not sample count.
|
|
|
|
All hyperparameters are frozen constants. At most 400 objective/gradient
|
|
evaluations include a reserved final evaluation at the optimizer's returned
|
|
parameters. A technical stop returns the last fully evaluated parameters, if
|
|
any, and cannot be interpreted as a negative learning result.
|
|
"""
|
|
import torch
|
|
from torch.nn import functional as F
|
|
|
|
started = time.monotonic()
|
|
y, normalized_weights = _validate(Xfine, coarse, target, weights, arm, chunk)
|
|
head = network(channels=Xfine.shape[1]).to(Xfine)
|
|
parameters = list(head.parameters())
|
|
optimizer = torch.optim.LBFGS(
|
|
parameters, lr=1.0, max_iter=MAX_ITER, max_eval=MAX_EVAL,
|
|
tolerance_grad=TOLERANCE_GRAD, tolerance_change=TOLERANCE_CHANGE,
|
|
history_size=100, line_search_fn="strong_wolfe",
|
|
)
|
|
evaluations = 0
|
|
completed_evaluations = 0
|
|
last_values = None
|
|
last_parameters = [p.detach().clone() for p in parameters]
|
|
stop_reason = None
|
|
runtime_error = None
|
|
|
|
def check_time(evaluation_started):
|
|
now = time.monotonic()
|
|
if now - started >= FIT_TIMEOUT_SECONDS:
|
|
raise _TechnicalStop("fit_timeout")
|
|
if now - evaluation_started >= EVALUATION_TIMEOUT_SECONDS:
|
|
raise _TechnicalStop("evaluation_timeout")
|
|
|
|
def evaluate(*, final=False):
|
|
nonlocal evaluations, completed_evaluations, last_values, last_parameters
|
|
# LBFGS line searches can otherwise exceed the nominal max_eval budget.
|
|
if evaluations >= MAX_EVAL - (0 if final else 1):
|
|
raise _TechnicalStop("evaluation_limit")
|
|
evaluation_started = time.monotonic()
|
|
check_time(evaluation_started)
|
|
evaluations += 1
|
|
optimizer.zero_grad(set_to_none=True)
|
|
data_loss = Xfine.new_zeros(())
|
|
for start in range(0, len(Xfine), chunk):
|
|
check_time(evaluation_started)
|
|
end = min(start + chunk, len(Xfine))
|
|
logits = head(Xfine[start:end], coarse[start:end], arm)
|
|
term = (
|
|
F.binary_cross_entropy_with_logits(logits, y[start:end], reduction="none")
|
|
* normalized_weights[start:end]
|
|
).sum()
|
|
if not bool(torch.isfinite(term)):
|
|
raise _TechnicalStop("nonfinite_objective")
|
|
term.backward()
|
|
data_loss += term.detach()
|
|
check_time(evaluation_started)
|
|
l2_loss = 0.5 * L2 * sum(p.square().sum() for p in parameters)
|
|
if not bool(torch.isfinite(l2_loss)):
|
|
raise _TechnicalStop("nonfinite_objective")
|
|
l2_loss.backward()
|
|
gradients = torch.cat([p.grad.reshape(-1) for p in parameters])
|
|
if not bool(torch.isfinite(gradients).all()):
|
|
raise _TechnicalStop("nonfinite_gradient")
|
|
objective = data_loss + l2_loss.detach()
|
|
if not bool(torch.isfinite(objective)):
|
|
raise _TechnicalStop("nonfinite_objective")
|
|
values = {
|
|
"loss": float(objective), "data_loss": float(data_loss),
|
|
"l2_loss": float(l2_loss.detach()),
|
|
"gradient_inf_norm": float(gradients.abs().max()),
|
|
}
|
|
check_time(evaluation_started)
|
|
last_values = values
|
|
last_parameters = [p.detach().clone() for p in parameters]
|
|
completed_evaluations += 1
|
|
return objective
|
|
|
|
try:
|
|
optimizer.step(evaluate)
|
|
evaluate(final=True)
|
|
except _TechnicalStop as exc:
|
|
stop_reason = str(exc)
|
|
except RuntimeError as exc:
|
|
stop_reason = "optimizer_runtime_error"
|
|
runtime_error = str(exc)
|
|
|
|
if stop_reason is not None:
|
|
with torch.no_grad():
|
|
for parameter, saved in zip(parameters, last_parameters, strict=True):
|
|
parameter.copy_(saved)
|
|
values = last_values or dict(
|
|
loss=None, data_loss=None, l2_loss=None, gradient_inf_norm=None,
|
|
)
|
|
stationarity = (
|
|
values["gradient_inf_norm"] is not None
|
|
and math.isfinite(values["gradient_inf_norm"])
|
|
and values["gradient_inf_norm"] <= STATIONARITY_LIMIT
|
|
)
|
|
if stop_reason is None and not stationarity:
|
|
stop_reason = "stationarity_not_met"
|
|
# A timeout remains a technical stop even if the last iterate was stationary.
|
|
converged = stop_reason is None and stationarity
|
|
head.zero_grad(set_to_none=True)
|
|
head.eval()
|
|
diagnostics = {
|
|
"status": "converged" if converged else "technical_stop",
|
|
"converged": converged, "stop_reason": stop_reason,
|
|
**values,
|
|
"stationarity": {"passed": stationarity, "limit": STATIONARITY_LIMIT},
|
|
"arm": arm, "points": len(Xfine),
|
|
"parameter_count": sum(p.numel() for p in parameters),
|
|
"parameters": {
|
|
"weight": head.weight.detach().cpu().tolist(),
|
|
"bias": head.bias.detach().cpu().tolist(),
|
|
},
|
|
"evaluations": evaluations, "completed_evaluations": completed_evaluations,
|
|
"iterations": optimizer.state.get(parameters[0], {}).get("n_iter", 0),
|
|
"seconds": time.monotonic() - started,
|
|
"configuration": {
|
|
"l2": L2, "max_iter": MAX_ITER, "max_eval": MAX_EVAL,
|
|
"tolerance_grad": TOLERANCE_GRAD, "tolerance_change": TOLERANCE_CHANGE,
|
|
"line_search_fn": "strong_wolfe", "chunk": chunk,
|
|
"fit_timeout_seconds": FIT_TIMEOUT_SECONDS,
|
|
"evaluation_timeout_seconds": EVALUATION_TIMEOUT_SECONDS,
|
|
},
|
|
"limitation": "Capacity and optimizer both differ from the MLP control.",
|
|
"production_eligible": False,
|
|
}
|
|
if runtime_error is not None:
|
|
diagnostics["runtime_error"] = runtime_error
|
|
return head, diagnostics
|