Skip to content

Commit dc20a18

Browse files
authored
Search the whole box when the starting values are guesses (#221)
A fit that moves one parameter at a time from the agent's guesses can settle in a compensating basin. Seed 1 of the Domino round fixes_r4 fit domino spinning friction 0.01 with mass 0.6 and restitution 0.43, while the world's materials (spinning friction 0.5) scored better on the same level-1 recording (replay error 4.456 against 4.480). Its belief, traced along lines through that point, put spinning friction at 0 to 0.003, and the rehearsal of its 47-degree turn said 97% where the world stalled. Under guessed starting values (code_sim_learning_prior_spans_bounds) a scrambled Sobol design over the whole box is scored in one batch, and the rollout LM runs from its best points beside the fit from the guesses; the result with the lowest posterior cost is the point estimate. Every distinct result within twice the model's own misfit (the SSE the best fit leaves above the declared noise, or the likelihood floor) is a basin: recordings the model fits no closer cannot prefer one of them. The parameter belief mixes the basins, weighted by exp(-dSSE / (2 misfit)): a draw picks a basin and samples it jointly, and the report's factors are the mixtures. On seed 1's recording a 128-point design found three points better than the world's materials, and every LM run from the design settled at spinning friction 0.4 to 0.75, near the world's 0.5.
1 parent 2d91142 commit dc20a18

10 files changed

Lines changed: 580 additions & 61 deletions

File tree

‎docs/uncertainty/principled-belief.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ There is no added model-error allowance and no between-segment term; both were m
3434
4. Draws: an independent sample from each line (inverse CDF), discrete parameters included.
3535
`K = belief_joint_draws` draws are made once per fit with a seed derived from `CFG.seed` and the fit identity, so a cached fit reuses them.
3636
5. Before any fit of the current program (and in the no-fitting ablation), `prior_belief` draws from the same Gaussian prior, restricted to the bounds.
37+
6. Basins: when the starting values are guesses (`code_sim_learning_prior_spans_bounds`), the fit also scores a scrambled Sobol design of `code_sim_learning_rollout_global_design_points` points over the whole box and runs the LM from the best `code_sim_learning_rollout_global_starts` of them.
38+
The result cheapest on the fit's own cost, the guesses' fit included, is the MAP.
39+
Every distinct result whose SSE lies within `2 m` of the MAP's is a basin, where the misfit `m` is the SSE the MAP leaves above the declared noise channel's expected SSE, or the likelihood floor when that is larger.
40+
`q(theta)` is then a mixture with one factor per basin, built as in steps 1 to 4 around that basin's point and weighted by `exp(-dSSE / (2 m))`.
41+
A draw picks a basin by weight and samples its factor, so it never pairs one basin's value of a parameter with another basin's value of the next.
3742

3843
The fit's consistency loop drops explainable segments that disagree; under the posterior view they are pooled (`code_sim_learning_rollout_consistency_factor = 0`), and their disagreement raises the estimated noise level.
3944
A segment is unexplainable when its own best replay over the parameter grid leaves a root-mean-square standardized error above `code_sim_learning_rollout_trim_rms_factor` (2); it stays excluded and is reported as evidence of a missing mechanism.

‎predicators/code_sim_learning/config.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,10 @@ class SysIdConfig:
110110
# The fit's starting values are the agent's guesses
111111
# (code_sim_learning_prior_spans_bounds), not calibrated baselines.
112112
anchors_are_guesses: bool = False
113+
# The global multi-start under guessed starting values (settings
114+
# code_sim_learning_rollout_global_design_points / _global_starts).
115+
global_design_points: int = 0
116+
global_starts: int = 0
113117

114118
@property
115119
def flat_band_frac(self) -> float:
@@ -182,4 +186,7 @@ def from_cfg(cls) -> SysIdConfig:
182186
track_frame_xy=tuple(CFG.code_sim_learning_track_frame_xy),
183187
observation_noise=_declared_observation_noise(),
184188
anchors_are_guesses=CFG.code_sim_learning_prior_spans_bounds,
189+
global_design_points=(
190+
CFG.code_sim_learning_rollout_global_design_points),
191+
global_starts=CFG.code_sim_learning_rollout_global_starts,
185192
)

‎predicators/code_sim_learning/fit_space.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,12 @@ class FitResult:
117117
# verdict reports it as anchored rather than identified. None =
118118
# ablation not run or nothing reverted.
119119
anchor_ablation: Optional[Dict[str, Dict[str, float]]] = None
120+
# Distinct local optima the global multi-start found that fit the
121+
# data within the model's own misfit of the point estimate, best
122+
# first, each as (parameter values in external units, its SSE, its
123+
# mixture weight); the first is the point estimate. The parameter
124+
# belief mixes them. None = no multi-start ran.
125+
basins: Optional[List[Tuple[Dict[str, float], float, float]]] = None
120126

121127
@property
122128
def point_estimate(self) -> Dict[str, float]:

‎predicators/code_sim_learning/orchestrator.py‎

Lines changed: 50 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
import copy
2323
import logging
2424
import time
25-
from dataclasses import dataclass, field
25+
from dataclasses import dataclass, field, replace
2626
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
2727

2828
import numpy as np
@@ -38,7 +38,8 @@
3838
from predicators.code_sim_learning.inference_result import \
3939
LegacyInferenceResult
4040
from predicators.code_sim_learning.parameter_belief import BeliefConfig, \
41-
ParameterBelief, build_parameter_belief, prior_belief, stable_seed
41+
ParameterBelief, build_parameter_belief, mix_beliefs, prior_belief, \
42+
stable_seed
4243
from predicators.code_sim_learning.physical_sysid import \
4344
_ROLLOUT_PRIOR_SIGMA_SCALE, _explainability_cache_key, \
4445
fit_params_rollout_trimmed
@@ -488,19 +489,50 @@ def _build_belief(
488489
if sigmas is None or len(sigmas) != len(all_specs):
489490
sigmas = _prior_widths_for(all_specs, centers)
490491
fitted = result.point_estimate
491-
return build_parameter_belief(
492-
list(all_specs),
493-
fitted,
494-
residuals_fn,
495-
noise_sigma=float(result.noise_sigma or DEFAULT_NOISE_SIGMA),
496-
prior_centers={
497-
s.name: scalar_to_fit_space(s, float(centers[s.name]))
498-
for s in all_specs
499-
},
500-
prior_sigmas={
501-
s.name: float(sigma)
502-
for s, sigma in zip(all_specs, sigmas)
503-
},
504-
config=belief_config,
505-
seed=stable_seed(CFG.seed, sorted(fitted.items()), num_survivors),
506-
batch_residuals=batch_residuals_fn)
492+
493+
def around(point: Dict[str, float], config: BeliefConfig,
494+
*seed_parts: Any) -> ParameterBelief:
495+
return build_parameter_belief(
496+
list(all_specs),
497+
point,
498+
residuals_fn,
499+
noise_sigma=float(result.noise_sigma or DEFAULT_NOISE_SIGMA),
500+
prior_centers={
501+
s.name: scalar_to_fit_space(s, float(centers[s.name]))
502+
for s in all_specs
503+
},
504+
prior_sigmas={
505+
s.name: float(sigma)
506+
for s, sigma in zip(all_specs, sigmas)
507+
},
508+
config=config,
509+
seed=stable_seed(CFG.seed, sorted(point.items()), num_survivors,
510+
*seed_parts),
511+
batch_residuals=batch_residuals_fn)
512+
513+
basins = list(result.basins or [])
514+
if len(basins) <= 1:
515+
return around(fitted, belief_config)
516+
shares = _draw_shares(belief_config.num_draws,
517+
[weight for _point, _sse, weight in basins])
518+
return mix_beliefs([
519+
around(point, replace(belief_config, num_draws=share), index)
520+
for index, ((point, _sse, _weight),
521+
share) in enumerate(zip(basins, shares))
522+
], [weight for _point, _sse, weight in basins])
523+
524+
525+
def _draw_shares(total: int, weights: Sequence[float]) -> List[int]:
526+
"""``total`` draws split in proportion to ``weights`` (largest remainder),
527+
at least one each when there are enough."""
528+
raw = np.asarray(weights, dtype=float) / float(np.sum(weights)) * total
529+
shares = np.floor(raw).astype(int)
530+
if total >= len(shares):
531+
shares = np.maximum(shares, 1)
532+
while int(shares.sum()) > total:
533+
shares[int(np.argmax(shares))] -= 1
534+
for index in np.argsort(-(raw - np.floor(raw)), kind="stable"):
535+
if int(shares.sum()) >= total:
536+
break
537+
shares[int(index)] += 1
538+
return [int(s) for s in shares]

‎predicators/code_sim_learning/parameter_belief.py‎

Lines changed: 149 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,11 @@ class ParameterBelief:
268268
held: List[str] = field(default_factory=list)
269269
evaluations: int = 0
270270
discrete: Dict[str, DiscretePosterior] = field(default_factory=dict)
271+
# A mixture over basins (mix_beliefs): each draw comes from one
272+
# component, picked by weight, and the factors above are the
273+
# components' weighted mixtures. Empty for a single basin.
274+
components: List["ParameterBelief"] = field(default_factory=list)
275+
weights: List[float] = field(default_factory=list)
271276

272277
@property
273278
def num_draws(self) -> int:
@@ -284,8 +289,18 @@ def sample(self, rng: np.random.Generator,
284289
"""``num`` new joint draws (fresh, independent of ``draws``).
285290
286291
Used to re-estimate a plan chosen on the stored draws, where the
287-
selection biases the estimate on those same draws.
292+
selection biases the estimate on those same draws. A mixture
293+
picks a component per draw and samples it jointly.
288294
"""
295+
if self.components:
296+
picks = rng.choice(len(self.components), size=num, p=self.weights)
297+
mixed: List[Dict[str, float]] = [{} for _ in range(num)]
298+
for k, component in enumerate(self.components):
299+
chosen = np.flatnonzero(picks == k)
300+
for i, row in zip(chosen,
301+
component.sample(rng, int(chosen.size))):
302+
mixed[int(i)] = row
303+
return mixed
289304
rows: List[Dict[str, float]] = [{} for _ in range(num)]
290305
for j, name in enumerate(self.names):
291306
if name in self.held or (name not in self.lines
@@ -358,6 +373,12 @@ def describe(self) -> List[str]:
358373
interval.
359374
"""
360375
lines = []
376+
if len(self.components) > 1:
377+
lines.append(
378+
f"The recordings fit {len(self.components)} distinct "
379+
"parameter sets about as well as the model fits them at "
380+
"all; the belief mixes them, and each draw comes from one "
381+
"of them.")
361382
if self.noise_scale > 1.0:
362383
lines.append(
363384
f"The program misfits the recordings {self.noise_scale:.3g}x "
@@ -402,29 +423,115 @@ def to_dict(self) -> Dict[str, Any]:
402423
n: [d.values.tolist(), d.probs.tolist()]
403424
for n, d in self.discrete.items()
404425
},
426+
"components": [c.to_dict() for c in self.components],
427+
"weights": list(self.weights),
405428
}
406429

407430
@classmethod
408431
def from_dict(cls, data: Dict[str, Any]) -> ParameterBelief:
409432
"""Inverse of :meth:`to_dict`."""
410-
return cls(names=list(data["names"]),
411-
scales=list(data["scales"]),
412-
map_estimate=dict(data["map_estimate"]),
413-
lines={
414-
n: LinePosterior(np.asarray(g, dtype=float),
415-
np.asarray(d, dtype=float))
416-
for n, (g, d) in data["lines"].items()
417-
},
418-
noise_scale=float(data["noise_scale"]),
419-
draws=np.asarray(data["draws"], dtype=float).reshape(
420-
-1, len(data["names"])),
421-
held=list(data.get("held", [])),
422-
evaluations=int(data.get("evaluations", 0)),
423-
discrete={
424-
n: DiscretePosterior(np.asarray(v, dtype=float),
425-
np.asarray(p, dtype=float))
426-
for n, (v, p) in data.get("discrete", {}).items()
427-
})
433+
return cls(
434+
names=list(data["names"]),
435+
scales=list(data["scales"]),
436+
map_estimate=dict(data["map_estimate"]),
437+
lines={
438+
n: LinePosterior(np.asarray(g, dtype=float),
439+
np.asarray(d, dtype=float))
440+
for n, (g, d) in data["lines"].items()
441+
},
442+
noise_scale=float(data["noise_scale"]),
443+
draws=np.asarray(data["draws"],
444+
dtype=float).reshape(-1, len(data["names"])),
445+
held=list(data.get("held", [])),
446+
evaluations=int(data.get("evaluations", 0)),
447+
discrete={
448+
n: DiscretePosterior(np.asarray(v, dtype=float),
449+
np.asarray(p, dtype=float))
450+
for n, (v, p) in data.get("discrete", {}).items()
451+
},
452+
components=[cls.from_dict(c) for c in data.get("components", [])],
453+
weights=[float(w) for w in data.get("weights", [])])
454+
455+
456+
def _mix_lines(lines: Sequence[LinePosterior],
457+
weights: Sequence[float]) -> LinePosterior:
458+
"""The weighted mixture of line densities on the union of their grids; a
459+
point mass becomes a narrow triangle."""
460+
parts = []
461+
for line, weight in zip(lines, weights):
462+
if line.is_point:
463+
value = float(line.grid[0])
464+
eps = 1e-9 * max(1.0, abs(value))
465+
parts.append((np.array([value - eps, value, value + eps]),
466+
np.array([0.0, 1.0 / eps, 0.0]), weight))
467+
else:
468+
parts.append((line.grid, line.density, weight))
469+
grid = np.unique(np.concatenate([g for g, _d, _w in parts]))
470+
density = np.zeros_like(grid)
471+
for g, d, weight in parts:
472+
density += weight * np.interp(grid, g, d, left=0.0, right=0.0)
473+
mass = float(np.trapz(density, grid))
474+
if not np.isfinite(mass) or mass <= 0.0:
475+
return lines[0]
476+
return LinePosterior(grid, density / mass)
477+
478+
479+
def _mix_discrete(parts: Sequence[DiscretePosterior],
480+
weights: Sequence[float]) -> DiscretePosterior:
481+
"""The weighted mixture of discrete posteriors over their values."""
482+
values = np.unique(np.concatenate([p.values for p in parts]))
483+
probs = np.zeros_like(values)
484+
for part, weight in zip(parts, weights):
485+
for value, prob in zip(part.values, part.probs):
486+
probs[int(np.searchsorted(values, value))] += weight * prob
487+
return DiscretePosterior(values, probs / np.sum(probs))
488+
489+
490+
def mix_beliefs(components: Sequence[ParameterBelief],
491+
weights: Sequence[float]) -> ParameterBelief:
492+
"""The mixture of beliefs over the same parameters, one per basin.
493+
494+
A draw picks a component by weight and samples it jointly, so it
495+
never pairs one basin's value of a parameter with another basin's
496+
value of the next. Each parameter's factor, which the report reads,
497+
is the weighted mixture of the components' factors, and a parameter
498+
every component holds at different values becomes discrete over
499+
them. The stored draws are the components' own, and the point
500+
estimate is the first component's.
501+
"""
502+
first = components[0]
503+
total = float(sum(weights))
504+
shares = [float(w) / total for w in weights]
505+
lines = {
506+
name: _mix_lines([c.lines[name] for c in components], shares)
507+
for name in first.lines if all(name in c.lines for c in components)
508+
}
509+
discrete = {
510+
name: _mix_discrete([c.discrete[name] for c in components], shares)
511+
for name in first.discrete
512+
if all(name in c.discrete for c in components)
513+
}
514+
held = []
515+
for name in first.held:
516+
values = [float(c.map_estimate[name]) for c in components]
517+
if len(set(values)) == 1:
518+
held.append(name)
519+
else:
520+
discrete[name] = _mix_discrete([
521+
DiscretePosterior(np.array([v]), np.array([1.0]))
522+
for v in values
523+
], shares)
524+
return ParameterBelief(names=list(first.names),
525+
scales=list(first.scales),
526+
map_estimate=dict(first.map_estimate),
527+
lines=lines,
528+
noise_scale=first.noise_scale,
529+
draws=np.vstack([c.draws for c in components]),
530+
held=held,
531+
evaluations=sum(c.evaluations for c in components),
532+
discrete=discrete,
533+
components=list(components),
534+
weights=shares)
428535

429536

430537
def join_beliefs(first: ParameterBelief,
@@ -441,24 +548,29 @@ def join_beliefs(first: ParameterBelief,
441548
if second.num_draws < num:
442549
raise ValueError(f"Joining {num} draws needs as many from each "
443550
f"factor; got {second.num_draws}.")
444-
return ParameterBelief(names=list(first.names) + list(second.names),
445-
scales=list(first.scales) + list(second.scales),
446-
map_estimate={
447-
**first.map_estimate,
448-
**second.map_estimate
449-
},
450-
lines={
451-
**first.lines,
452-
**second.lines
453-
},
454-
noise_scale=first.noise_scale,
455-
draws=np.hstack([first.draws, second.draws[:num]]),
456-
held=list(first.held) + list(second.held),
457-
evaluations=first.evaluations + second.evaluations,
458-
discrete={
459-
**first.discrete,
460-
**second.discrete
461-
})
551+
if second.components:
552+
raise ValueError("Only the first joined belief may be a mixture.")
553+
return ParameterBelief(
554+
names=list(first.names) + list(second.names),
555+
scales=list(first.scales) + list(second.scales),
556+
map_estimate={
557+
**first.map_estimate,
558+
**second.map_estimate
559+
},
560+
lines={
561+
**first.lines,
562+
**second.lines
563+
},
564+
noise_scale=first.noise_scale,
565+
draws=np.hstack([first.draws, second.draws[:num]]),
566+
held=list(first.held) + list(second.held),
567+
evaluations=first.evaluations + second.evaluations,
568+
discrete={
569+
**first.discrete,
570+
**second.discrete
571+
},
572+
components=[join_beliefs(c, second) for c in first.components],
573+
weights=list(first.weights))
462574

463575

464576
def stable_seed(*parts: Any) -> int:

0 commit comments

Comments
 (0)