sciel 0.23.2__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.
- sciel/__init__.py +1 -0
- sciel/campaign/__init__.py +0 -0
- sciel/campaign/budget.py +467 -0
- sciel/campaign/identity.py +97 -0
- sciel/campaign/memory.py +298 -0
- sciel/campaign/no_regression.py +118 -0
- sciel/candidate_modules/__init__.py +239 -0
- sciel/causal/__init__.py +4 -0
- sciel/causal/estimators.py +70 -0
- sciel/causal/ledger.py +134 -0
- sciel/causal/sequential.py +102 -0
- sciel/cli/__init__.py +0 -0
- sciel/cli/live.py +144 -0
- sciel/cli/main.py +335 -0
- sciel/cli/profile.py +65 -0
- sciel/cli/start.py +189 -0
- sciel/cli/supervise.py +202 -0
- sciel/components/__init__.py +0 -0
- sciel/components/bets/__init__.py +0 -0
- sciel/components/code_novelty.py +105 -0
- sciel/components/containers.py +374 -0
- sciel/components/policy/__init__.py +0 -0
- sciel/components/policy/base.py +52 -0
- sciel/components/policy/code_embed.py +472 -0
- sciel/components/policy/controller.py +166 -0
- sciel/components/policy/mode_bandit.py +93 -0
- sciel/components/policy/mode_features.py +30 -0
- sciel/components/policy/mode_policy_mlp.py +102 -0
- sciel/components/policy/pop_features.py +29 -0
- sciel/components/policy/preset_weights.py +127 -0
- sciel/components/policy/three_head.py +167 -0
- sciel/components/policy/tilt.py +40 -0
- sciel/components/selection/__init__.py +0 -0
- sciel/components/selection/kernels.py +206 -0
- sciel/components/selection/novelty_chain.py +82 -0
- sciel/config.py +155 -0
- sciel/config_validation.py +180 -0
- sciel/culture/__init__.py +3 -0
- sciel/culture/methods.py +52 -0
- sciel/culture/repertoire.py +90 -0
- sciel/demo/__init__.py +5 -0
- sciel/demo/circles.py +54 -0
- sciel/diagnostics/__init__.py +1 -0
- sciel/diagnostics/methods_observer.py +427 -0
- sciel/diagnostics/paired_eval.py +244 -0
- sciel/engine/__init__.py +0 -0
- sciel/engine/admission.py +358 -0
- sciel/engine/assay.py +81 -0
- sciel/engine/bootstrap.py +270 -0
- sciel/engine/capacity.py +425 -0
- sciel/engine/checkpoint.py +133 -0
- sciel/engine/checkpoint_identity.py +230 -0
- sciel/engine/checkpoint_restore.py +248 -0
- sciel/engine/container_db.py +212 -0
- sciel/engine/cooperative_io.py +420 -0
- sciel/engine/db.py +259 -0
- sciel/engine/decisions.py +85 -0
- sciel/engine/determinism.py +24 -0
- sciel/engine/evaluation.py +199 -0
- sciel/engine/evaluation_timing.py +114 -0
- sciel/engine/evaluator_fifo.py +209 -0
- sciel/engine/eviction_planner.py +22 -0
- sciel/engine/factory.py +104 -0
- sciel/engine/incubator.py +201 -0
- sciel/engine/initialization.py +354 -0
- sciel/engine/journal_anchor.py +26 -0
- sciel/engine/knockout.py +91 -0
- sciel/engine/lifecycle.py +251 -0
- sciel/engine/llm/__init__.py +0 -0
- sciel/engine/llm/anthropic_api.py +78 -0
- sciel/engine/llm/claude_code.py +149 -0
- sciel/engine/llm/client.py +443 -0
- sciel/engine/llm/codex.py +368 -0
- sciel/engine/llm/codex_protocol.py +252 -0
- sciel/engine/llm/errors.py +132 -0
- sciel/engine/llm/mock.py +109 -0
- sciel/engine/llm/trace.py +133 -0
- sciel/engine/loop.py +98 -0
- sciel/engine/loop_contracts.py +105 -0
- sciel/engine/novelty.py +376 -0
- sciel/engine/observed_changes.py +404 -0
- sciel/engine/observed_schema.py +189 -0
- sciel/engine/operators.py +107 -0
- sciel/engine/output_measurements.py +44 -0
- sciel/engine/output_novelty.py +256 -0
- sciel/engine/parallel.py +472 -0
- sciel/engine/parallel_calls.py +330 -0
- sciel/engine/parallel_control.py +51 -0
- sciel/engine/parallel_recovery.py +363 -0
- sciel/engine/parallel_schedule.py +215 -0
- sciel/engine/parallel_store.py +433 -0
- sciel/engine/population_view.py +113 -0
- sciel/engine/portfolio_allocation.py +74 -0
- sciel/engine/probe.py +75 -0
- sciel/engine/prompt/__init__.py +0 -0
- sciel/engine/prompt/budget.py +20 -0
- sciel/engine/prompt/build.py +202 -0
- sciel/engine/prompt/parse.py +54 -0
- sciel/engine/prompt/patch.py +101 -0
- sciel/engine/prompt/sources.py +10 -0
- sciel/engine/prompt/templates/cross.txt +26 -0
- sciel/engine/prompt/templates/diff.txt +24 -0
- sciel/engine/prompt/templates/error_repair.txt +23 -0
- sciel/engine/prompt/templates/fix.txt +8 -0
- sciel/engine/prompt/templates/full_rewrite.txt +24 -0
- sciel/engine/prompt/templates/idea.txt +27 -0
- sciel/engine/provider_abandonment.py +15 -0
- sciel/engine/recovery.py +85 -0
- sciel/engine/repeat_execution.py +177 -0
- sciel/engine/repeat_journal.py +91 -0
- sciel/engine/repeat_learning.py +20 -0
- sciel/engine/repeat_planning.py +128 -0
- sciel/engine/repeat_policy.py +131 -0
- sciel/engine/repeat_promotion.py +147 -0
- sciel/engine/repeat_state.py +253 -0
- sciel/engine/repeat_support.py +175 -0
- sciel/engine/research_artifacts.py +323 -0
- sciel/engine/research_candidate.py +84 -0
- sciel/engine/research_cells_context.py +168 -0
- sciel/engine/research_culture.py +119 -0
- sciel/engine/research_queue.py +129 -0
- sciel/engine/research_search_evidence.py +160 -0
- sciel/engine/research_targets.py +204 -0
- sciel/engine/research_tool_signals.py +57 -0
- sciel/engine/run_lock.py +37 -0
- sciel/engine/runtime.py +165 -0
- sciel/engine/schedule.py +179 -0
- sciel/engine/siblings.py +135 -0
- sciel/engine/source_identity.py +16 -0
- sciel/engine/step_cycle.py +217 -0
- sciel/engine/step_plan.py +405 -0
- sciel/engine/telemetry.py +168 -0
- sciel/engine/types.py +87 -0
- sciel/engine/validation.py +444 -0
- sciel/engine/viability.py +431 -0
- sciel/engine/warm_start.py +69 -0
- sciel/engine/worker.py +294 -0
- sciel/engine/worker_feedback.py +131 -0
- sciel/eval/__init__.py +0 -0
- sciel/eval/_candidate_worker.py +131 -0
- sciel/eval/_repeat_runner.py +229 -0
- sciel/eval/_runner.py +280 -0
- sciel/eval/_scorer_worker.py +24 -0
- sciel/eval/candidate_backend.py +209 -0
- sciel/eval/candidate_config.py +58 -0
- sciel/eval/candidate_evidence.py +52 -0
- sciel/eval/candidate_receipts.py +272 -0
- sciel/eval/candidate_registry.py +2 -0
- sciel/eval/cascade.py +55 -0
- sciel/eval/facade.py +153 -0
- sciel/eval/native_geometry.py +251 -0
- sciel/eval/near_output.py +147 -0
- sciel/eval/output_identity.py +308 -0
- sciel/eval/packing_geometry.py +185 -0
- sciel/eval/registry.py +251 -0
- sciel/eval/repeat_docker.py +187 -0
- sciel/eval/repeat_draw.py +466 -0
- sciel/eval/repeat_io.py +51 -0
- sciel/eval/sandbox.py +350 -0
- sciel/eval/scorer_container.py +186 -0
- sciel/eval/task_prompt.py +82 -0
- sciel/eval/trusted_scoring/__init__.py +1 -0
- sciel/eval/trusted_scoring/adapter.py +125 -0
- sciel/eval/trusted_scoring/beat.py +191 -0
- sciel/eval/trusted_scoring/circle.py +102 -0
- sciel/eval/trusted_scoring/heil.py +107 -0
- sciel/eval/trusted_scoring/transport.py +120 -0
- sciel/evidence/__init__.py +1 -0
- sciel/evidence/change_audit.py +243 -0
- sciel/evidence/eligibility.py +110 -0
- sciel/evidence/measurement.py +186 -0
- sciel/evidence/restart_optimizer_trace.py +189 -0
- sciel/evidence/restart_trace.py +54 -0
- sciel/evidence/restart_trace_recorder.py +253 -0
- sciel/evidence/restart_trace_source.py +31 -0
- sciel/evidence/restart_trace_validation.py +234 -0
- sciel/evidence/restart_trace_values.py +231 -0
- sciel/local_task.py +142 -0
- sciel/methods/__init__.py +11 -0
- sciel/methods/__main__.py +397 -0
- sciel/methods/_loader.py +99 -0
- sciel/methods/_runner.py +225 -0
- sciel/methods/budget.py +322 -0
- sciel/methods/campaign.py +372 -0
- sciel/methods/configuration.py +139 -0
- sciel/methods/coordinator.py +368 -0
- sciel/methods/coordinator_context.py +108 -0
- sciel/methods/coordinator_contracts.py +42 -0
- sciel/methods/coordinator_episode.py +251 -0
- sciel/methods/coordinator_exchange.py +156 -0
- sciel/methods/coordinator_execution.py +170 -0
- sciel/methods/coordinator_planning.py +156 -0
- sciel/methods/coordinator_policy.py +193 -0
- sciel/methods/engine_bridge.py +342 -0
- sciel/methods/evidence.py +384 -0
- sciel/methods/examples.py +255 -0
- sciel/methods/executor.py +519 -0
- sciel/methods/funding.py +119 -0
- sciel/methods/materialize.py +248 -0
- sciel/methods/models.py +242 -0
- sciel/methods/proposals.py +289 -0
- sciel/methods/provider_budget.py +71 -0
- sciel/methods/registry.py +500 -0
- sciel/methods/registry_records.py +117 -0
- sciel/methods/resource_values.py +129 -0
- sciel/methods/tasks.py +203 -0
- sciel/methods/technical.py +167 -0
- sciel/methods/transport.py +217 -0
- sciel/population.py +15 -0
- sciel/research_tools/__init__.py +2 -0
- sciel/research_tools/artifact_manifest.py +207 -0
- sciel/research_tools/artifact_reading.py +34 -0
- sciel/research_tools/canonical_diagnostics.py +241 -0
- sciel/research_tools/canonical_evidence.py +94 -0
- sciel/research_tools/cells.py +394 -0
- sciel/research_tools/comparison_assessment.py +89 -0
- sciel/research_tools/config.py +174 -0
- sciel/research_tools/continuations.py +289 -0
- sciel/research_tools/controller.py +236 -0
- sciel/research_tools/controller_jobs.py +315 -0
- sciel/research_tools/controller_state.py +204 -0
- sciel/research_tools/decision_projection.py +116 -0
- sciel/research_tools/episode_evidence.py +129 -0
- sciel/research_tools/episode_execution.py +249 -0
- sciel/research_tools/episode_results.py +224 -0
- sciel/research_tools/experiment_protocol.py +271 -0
- sciel/research_tools/followups.py +442 -0
- sciel/research_tools/job_worker.py +240 -0
- sciel/research_tools/jobs.py +364 -0
- sciel/research_tools/library.py +357 -0
- sciel/research_tools/lifecycle.py +377 -0
- sciel/research_tools/lifecycle_delivery.py +198 -0
- sciel/research_tools/lifecycle_evidence.py +324 -0
- sciel/research_tools/observation_cards.py +179 -0
- sciel/research_tools/planning.py +152 -0
- sciel/research_tools/projection_data.py +169 -0
- sciel/research_tools/projection_validation.py +133 -0
- sciel/research_tools/prompt_builder.py +393 -0
- sciel/research_tools/prompt_sections.py +377 -0
- sciel/research_tools/replay_feedback.py +153 -0
- sciel/research_tools/research_steps.py +222 -0
- sciel/research_tools/result_contract.py +73 -0
- sciel/research_tools/result_projection.py +319 -0
- sciel/research_tools/retained_observations.py +227 -0
- sciel/research_tools/sequential_research.py +371 -0
- sciel/research_tools/shared_evidence.py +408 -0
- sciel/research_tools/sharing.py +287 -0
- sciel/research_tools/stage_data.py +68 -0
- sciel/research_tools/tool_actions.py +241 -0
- sciel/research_tools/tool_artifacts.py +175 -0
- sciel/research_tools/tool_protocol.py +41 -0
- sciel/research_tools/transfer_jobs.py +190 -0
- sciel/reward.py +181 -0
- sciel/rl/__init__.py +3 -0
- sciel/rl/critic.py +104 -0
- sciel/rl/policy.py +235 -0
- sciel/rl/returns.py +56 -0
- sciel/rng.py +38 -0
- sciel/run_log.py +212 -0
- sciel/solvers/__init__.py +1 -0
- sciel/solvers/circle_anytime.py +257 -0
- sciel/solvers/circle_lp_initializer.py +132 -0
- sciel/solvers/circle_relocation.py +121 -0
- sciel/stats.py +217 -0
- sciel/swm/__init__.py +6 -0
- sciel/swm/archive.py +91 -0
- sciel/swm/diffusion.py +61 -0
- sciel/swm/embedding.py +94 -0
- sciel/swm/model.py +200 -0
- sciel/swm/niches.py +46 -0
- sciel/swm/sets.py +63 -0
- sciel/swm/tabular.py +66 -0
- sciel/swm/targets.py +63 -0
- sciel/swm/world.py +500 -0
- sciel/task.py +21 -0
- sciel/taskbuilder/__init__.py +118 -0
- sciel/taskbuilder/audit.py +92 -0
- sciel/taskbuilder/draft.py +69 -0
- sciel/taskbuilder/materials.py +88 -0
- sciel/theory/__init__.py +7 -0
- sciel/theory/assumptions.py +131 -0
- sciel/theory/claims.py +138 -0
- sciel/theory/experiments.py +106 -0
- sciel/theory/findings.py +148 -0
- sciel/theory/procedures.py +89 -0
- sciel/theory/schools.py +64 -0
- sciel/theory/strategies.py +85 -0
- sciel/theory/trials.py +107 -0
- sciel/tui/__init__.py +0 -0
- sciel/tui/board.py +52 -0
- sciel/ui/__init__.py +1 -0
- sciel/ui/activity.py +112 -0
- sciel/ui/engine.py +169 -0
- sciel/ui/render.py +165 -0
- sciel/ui/state.py +343 -0
- sciel/ui/static/engine.js +162 -0
- sciel/ui/static/index.html +397 -0
- sciel/ui/terminal.py +455 -0
- sciel/ui/views.py +307 -0
- sciel/ui/web.py +144 -0
- sciel-0.23.2.dist-info/METADATA +508 -0
- sciel-0.23.2.dist-info/RECORD +305 -0
- sciel-0.23.2.dist-info/WHEEL +5 -0
- sciel-0.23.2.dist-info/entry_points.txt +2 -0
- sciel-0.23.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Off-policy value of one decision type from logged propensities: self-normalized IPW and doubly robust."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from collections import defaultdict
|
|
7
|
+
|
|
8
|
+
Z = 1.96
|
|
9
|
+
PRIOR = 2.0
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _outcome_model(rows) -> dict:
|
|
13
|
+
by_action, by_cell = defaultdict(list), defaultdict(list)
|
|
14
|
+
for r in rows:
|
|
15
|
+
by_action[r.choice].append(r.outcome)
|
|
16
|
+
by_cell[(r.context, r.choice)].append(r.outcome)
|
|
17
|
+
mean = sum(r.outcome for r in rows) / len(rows)
|
|
18
|
+
action = {a: (sum(v) + PRIOR * mean) / (len(v) + PRIOR) for a, v in by_action.items()}
|
|
19
|
+
return {cell: (sum(v) + PRIOR * action[cell[1]]) / (len(v) + PRIOR) for cell, v in by_cell.items()} | {
|
|
20
|
+
("*", a): m for a, m in action.items()} | {("*", "*"): mean}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _q(model, context, action) -> float:
|
|
24
|
+
return model.get((context, action), model.get(("*", action), model[("*", "*")]))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _clustered(values, clusters) -> tuple:
|
|
28
|
+
n = len(values)
|
|
29
|
+
mean = sum(values) / n
|
|
30
|
+
totals = defaultdict(float)
|
|
31
|
+
for v, c in zip(values, clusters):
|
|
32
|
+
totals[c] += v - mean
|
|
33
|
+
clustered = sum(t * t for t in totals.values()) / (n * n)
|
|
34
|
+
independent = sum((v - mean) ** 2 for v in values) / (n * n)
|
|
35
|
+
return mean, math.sqrt(max(clustered, independent))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def evaluate(rows, target) -> dict:
|
|
39
|
+
"""Value of `target(row) -> distribution` against the logging policy that produced the rows."""
|
|
40
|
+
if not rows:
|
|
41
|
+
return {"n": 0}
|
|
42
|
+
model = _outcome_model(rows)
|
|
43
|
+
weights = [target(r).get(r.choice, 0.0) / r.propensity for r in rows]
|
|
44
|
+
total = sum(weights)
|
|
45
|
+
snipw = sum(w * r.outcome for w, r in zip(weights, rows)) / total if total > 0 else float("nan")
|
|
46
|
+
dr_terms = []
|
|
47
|
+
for w, r in zip(weights, rows):
|
|
48
|
+
policy = target(r)
|
|
49
|
+
direct = sum(p * _q(model, r.context, a) for a, p in policy.items())
|
|
50
|
+
dr_terms.append(direct + w * (r.outcome - _q(model, r.context, r.choice)))
|
|
51
|
+
dr, se = _clustered(dr_terms, [r.island for r in rows])
|
|
52
|
+
ess = total * total / sum(w * w for w in weights) if total > 0 else 0.0
|
|
53
|
+
return {"n": len(rows), "ess": ess, "snipw": snipw, "dr": dr, "low": dr - Z * se, "high": dr + Z * se}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def action_effect(rows, action: str, q=None) -> dict:
|
|
57
|
+
"""Effect of always taking `action` versus the logging policy, paired per row; `q` is an optional per-row outcome model."""
|
|
58
|
+
if not rows:
|
|
59
|
+
return {"n": 0}
|
|
60
|
+
model = _outcome_model(rows)
|
|
61
|
+
diffs = []
|
|
62
|
+
for r in rows:
|
|
63
|
+
learned = q(r, action) if q is not None else None
|
|
64
|
+
base = _q(model, r.context, action) if learned is None else learned
|
|
65
|
+
dr_action = base + ((r.outcome - base) / r.propensity if r.choice == action else 0.0)
|
|
66
|
+
diffs.append(dr_action - r.outcome)
|
|
67
|
+
effect, se = _clustered(diffs, [r.island for r in rows])
|
|
68
|
+
taken = sum(r.choice == action for r in rows)
|
|
69
|
+
return {"n": len(rows), "taken": taken, "effect": effect, "se": se,
|
|
70
|
+
"low": effect - Z * se, "high": effect + Z * se}
|
sciel/causal/ledger.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Journaled decisions joined to lineage outcomes: an island event by the child or its descendants within a horizon."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from dataclasses import asdict, dataclass, field
|
|
7
|
+
|
|
8
|
+
HORIZON = 20
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class Row:
|
|
13
|
+
decision: str
|
|
14
|
+
iteration: int
|
|
15
|
+
island: int
|
|
16
|
+
context: str
|
|
17
|
+
distribution: dict
|
|
18
|
+
choice: str
|
|
19
|
+
propensity: float
|
|
20
|
+
child: str | None
|
|
21
|
+
outcome: float | None = None
|
|
22
|
+
state: str | None = None
|
|
23
|
+
reward: float = 0.0
|
|
24
|
+
scope: str = "lineage"
|
|
25
|
+
population: list = field(default_factory=list)
|
|
26
|
+
gain: float = 0.0
|
|
27
|
+
standing: dict = field(default_factory=dict)
|
|
28
|
+
shaped: float = 0.0 # learning_reward of a step that gained nothing: a world-model target, never an outcome
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def context_of(decision_context: dict) -> str:
|
|
32
|
+
phase = decision_context.get("phase", 0)
|
|
33
|
+
progress = decision_context.get("progress") or 0.0
|
|
34
|
+
return f"phase={phase}|third={min(int(progress * 3), 2)}"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Ledger:
|
|
38
|
+
def __init__(self, horizon: int = HORIZON):
|
|
39
|
+
self.horizon = horizon
|
|
40
|
+
self.rows: list[Row] = []
|
|
41
|
+
self.parent: dict[str, str] = {}
|
|
42
|
+
self.now = 0
|
|
43
|
+
self.path_best: dict[str, float] = {}
|
|
44
|
+
self.scale: float | None = None
|
|
45
|
+
|
|
46
|
+
def path_gain(self, before: float, child: str | None, score: float | None, origin: float) -> float:
|
|
47
|
+
"""Rise of the best score above `before` (the parent's path best, or the population best for a step from
|
|
48
|
+
scratch), on a log scale above the starting program's score; it telescopes along every lineage, so a copy adds
|
|
49
|
+
nothing, siblings never take each other's credit and a restart earns only what it adds to the population.
|
|
50
|
+
A starting score of zero takes its scale from the first nonzero score."""
|
|
51
|
+
before = max(before, origin)
|
|
52
|
+
if child is None or score is None:
|
|
53
|
+
return 0.0
|
|
54
|
+
after = max(before, score)
|
|
55
|
+
self.path_best[child] = after
|
|
56
|
+
if self.scale is None and (origin != 0 or score != 0):
|
|
57
|
+
self.scale = abs(origin) if origin != 0 else abs(score)
|
|
58
|
+
if self.scale is None:
|
|
59
|
+
return 0.0
|
|
60
|
+
potential = lambda b: math.log1p(max(b - origin, 0.0) / self.scale)
|
|
61
|
+
return potential(after) - potential(before)
|
|
62
|
+
|
|
63
|
+
def path_start(self, parent: str, score: float | None) -> float | None:
|
|
64
|
+
"""The path best of a recorded program, else the program's own score (seeds, migrants, programme steps)."""
|
|
65
|
+
return self.path_best.get(parent, score)
|
|
66
|
+
|
|
67
|
+
def add(self, *, iteration: int, island: int, decision_context: dict, child: str | None,
|
|
68
|
+
parent: str | None, event: bool, gain: float = 0.0, shaped: float = 0.0) -> None:
|
|
69
|
+
self.now = max(self.now, iteration)
|
|
70
|
+
context = context_of(decision_context)
|
|
71
|
+
decided = int(decision_context.get("iteration_no", iteration))
|
|
72
|
+
for record in decision_context.get("decisions", []):
|
|
73
|
+
self.rows.append(Row(decision=record["decision"], iteration=decided, island=island,
|
|
74
|
+
context=context, distribution=dict(record["distribution"]),
|
|
75
|
+
choice=str(record["choice"]), propensity=float(record["propensity"]),
|
|
76
|
+
child=child, outcome=None if child is not None else 0.0,
|
|
77
|
+
state=decision_context.get("parent_id"), reward=float(event),
|
|
78
|
+
population=list(decision_context.get("population", [])), gain=gain,
|
|
79
|
+
standing=dict(record.get("standing", {})), shaped=shaped))
|
|
80
|
+
if child is not None and parent is not None:
|
|
81
|
+
self.parent[child] = parent
|
|
82
|
+
if event and child is not None:
|
|
83
|
+
self._credit(child, iteration)
|
|
84
|
+
if event:
|
|
85
|
+
for row in self.rows:
|
|
86
|
+
if (row.scope == "island" and row.outcome is None and row.island == island
|
|
87
|
+
and iteration - row.iteration <= self.horizon):
|
|
88
|
+
row.outcome = 1.0
|
|
89
|
+
self._expire(iteration)
|
|
90
|
+
|
|
91
|
+
def add_island(self, *, iteration: int, island: int, context: str, record: dict) -> None:
|
|
92
|
+
"""A decision whose outcome is any island event within the horizon, not a lineage event."""
|
|
93
|
+
self.now = max(self.now, iteration)
|
|
94
|
+
self.rows.append(Row(decision=record["decision"], iteration=iteration, island=island, context=context,
|
|
95
|
+
distribution=dict(record["distribution"]), choice=str(record["choice"]),
|
|
96
|
+
propensity=float(record["propensity"]), child=None, scope="island"))
|
|
97
|
+
|
|
98
|
+
def _lineage(self, program: str) -> set:
|
|
99
|
+
seen, node = set(), program
|
|
100
|
+
while node is not None and node not in seen and len(seen) <= self.horizon:
|
|
101
|
+
seen.add(node)
|
|
102
|
+
node = self.parent.get(node)
|
|
103
|
+
return seen
|
|
104
|
+
|
|
105
|
+
def _credit(self, child: str, iteration: int) -> None:
|
|
106
|
+
ancestors = self._lineage(child)
|
|
107
|
+
for row in self.rows:
|
|
108
|
+
if row.outcome is None and row.child in ancestors and iteration - row.iteration <= self.horizon:
|
|
109
|
+
row.outcome = 1.0
|
|
110
|
+
|
|
111
|
+
def _expire(self, iteration: int) -> None:
|
|
112
|
+
for row in self.rows:
|
|
113
|
+
if row.outcome is None and iteration - row.iteration > self.horizon:
|
|
114
|
+
row.outcome = 0.0
|
|
115
|
+
|
|
116
|
+
def settled(self, row: Row) -> bool:
|
|
117
|
+
"""A row enters inference only at the end of its horizon, when its outcome is fixed for good, whatever its
|
|
118
|
+
scope; so rows enter in decision order and no settled factor is ever revised."""
|
|
119
|
+
return row.outcome is not None and self.now - row.iteration > self.horizon
|
|
120
|
+
|
|
121
|
+
def labeled(self, decision: str) -> list[Row]:
|
|
122
|
+
return [r for r in self.rows if r.decision == decision and r.outcome is not None]
|
|
123
|
+
|
|
124
|
+
def state(self) -> dict:
|
|
125
|
+
return {"horizon": self.horizon, "rows": [asdict(r) for r in self.rows],
|
|
126
|
+
"parent": dict(self.parent), "now": self.now, "path_best": dict(self.path_best), "scale": self.scale}
|
|
127
|
+
|
|
128
|
+
def load_state(self, data: dict) -> None:
|
|
129
|
+
self.horizon = int(data["horizon"])
|
|
130
|
+
self.rows = [Row(**r) for r in data["rows"]]
|
|
131
|
+
self.parent = dict(data["parent"])
|
|
132
|
+
self.now = int(data["now"])
|
|
133
|
+
self.path_best = dict(data["path_best"])
|
|
134
|
+
self.scale = data["scale"]
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Anytime-valid inference: DR contrasts with predictable outcome models, mixture-of-bets e-processes and e-BH.
|
|
2
|
+
|
|
3
|
+
The contrast of an action is its value minus the uniform mixture of the other actions of the same decision when every
|
|
4
|
+
row offers the same alternatives, and minus one reference action offered in every row when the alternatives change, so
|
|
5
|
+
the target does not drift when the theory tilts the logging policy or arms enter and leave. Rows enter in decision order
|
|
6
|
+
once their outcomes are settled, so the order never depends on an outcome, and each row's outcome model uses only
|
|
7
|
+
earlier rows.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
from collections import defaultdict
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
GRID = np.linspace(-1.0, 1.0, 81)
|
|
18
|
+
PRIOR = 2.0
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def comparator(rows: list, action: str) -> tuple[bool, str | None]:
|
|
22
|
+
"""Whether `action` has a fixed comparison target in these rows: the shared alternatives or a reference action."""
|
|
23
|
+
others = [frozenset(r.distribution) - {action} for r in rows if action in r.distribution]
|
|
24
|
+
others = [o for o in others if o]
|
|
25
|
+
if not others or len(set(others)) == 1:
|
|
26
|
+
return True, None
|
|
27
|
+
common = frozenset.intersection(*others)
|
|
28
|
+
reference = next((a for r in rows if action in r.distribution for a in r.distribution if a in common), None)
|
|
29
|
+
return reference is not None, reference
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def contrasts(rows: list, action: str, reference: str | None = None) -> tuple[np.ndarray, np.ndarray]:
|
|
33
|
+
"""Doubly robust pseudo-outcomes of `action` against the other actions or a reference action, with known bounds."""
|
|
34
|
+
sums, counts = defaultdict(float), defaultdict(int)
|
|
35
|
+
total, seen = 0.0, 0
|
|
36
|
+
psi, bound = [], []
|
|
37
|
+
for row in rows:
|
|
38
|
+
others = [reference] if reference is not None else [b for b in row.distribution if b != action]
|
|
39
|
+
if action not in row.distribution or not others or any(b not in row.distribution for b in others):
|
|
40
|
+
continue
|
|
41
|
+
mean = (total + PRIOR * 0.5) / (seen + PRIOR)
|
|
42
|
+
|
|
43
|
+
def q(b):
|
|
44
|
+
return (sums[b] + PRIOR * mean) / (counts[b] + PRIOR)
|
|
45
|
+
|
|
46
|
+
y = row.reward if row.scope == "lineage" else row.outcome
|
|
47
|
+
value = q(action) + (row.choice == action) * (y - q(action)) / row.distribution[action]
|
|
48
|
+
rest = sum(q(b) + (row.choice == b) * (y - q(b)) / row.distribution[b] for b in others) / len(others)
|
|
49
|
+
psi.append(value - rest)
|
|
50
|
+
bound.append(1.0 + 1.0 / min(row.distribution.values()))
|
|
51
|
+
sums[row.choice] += y
|
|
52
|
+
counts[row.choice] += 1
|
|
53
|
+
total += y
|
|
54
|
+
seen += 1
|
|
55
|
+
return np.asarray(psi, dtype=float), np.asarray(bound, dtype=float)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
LAMBDAS = np.array([v for v in np.linspace(-0.9, 0.9, 19) if abs(v) > 1e-9])
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def mixture(psi: np.ndarray, bound, alpha: float) -> dict:
|
|
62
|
+
"""Equal-weight mixture of fixed bets on every grid value m: the current e-value at zero and the current
|
|
63
|
+
confidence set, both valid at any stopping time; the log wealth per (m, bet) lets a later run continue it."""
|
|
64
|
+
if len(psi) == 0:
|
|
65
|
+
return {"n": 0, "mean": 0.0, "se": 0.0, "low": -1.0, "high": 1.0, "e": 1.0, "empty": False,
|
|
66
|
+
"log_wealth": np.zeros((len(GRID), len(LAMBDAS)))}
|
|
67
|
+
bound = np.broadcast_to(np.asarray(bound, dtype=float), psi.shape)
|
|
68
|
+
x = psi[:, None, None] - GRID[None, :, None]
|
|
69
|
+
lam = LAMBDAS[None, None, :] / (bound[:, None, None] + np.abs(GRID)[None, :, None])
|
|
70
|
+
log_wealth = np.log1p(lam * x).sum(0)
|
|
71
|
+
return {**summary(psi, log_wealth, alpha), "log_wealth": log_wealth}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def summary(psi: np.ndarray, log_wealth: np.ndarray, alpha: float) -> dict:
|
|
75
|
+
capital = np.logaddexp.reduce(log_wealth, axis=1) - math.log(log_wealth.shape[1])
|
|
76
|
+
kept = GRID[capital < math.log(1.0 / alpha)]
|
|
77
|
+
zero = int(np.argmin(np.abs(GRID)))
|
|
78
|
+
step = GRID[1] - GRID[0]
|
|
79
|
+
se = float(psi.std(ddof=1) / math.sqrt(len(psi))) if len(psi) > 1 else 1.0
|
|
80
|
+
return {"n": len(psi), "mean": float(psi.mean()), "se": se,
|
|
81
|
+
"low": float(kept.min() - step) if len(kept) else 0.0,
|
|
82
|
+
"high": float(kept.max() + step) if len(kept) else 0.0,
|
|
83
|
+
"e": float(np.exp(capital[zero])), "empty": not len(kept)}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def continued(log_wealth: np.ndarray, prior: np.ndarray | None, psi: np.ndarray, alpha: float) -> dict:
|
|
87
|
+
"""The same betting martingale carried on from an earlier run's final wealth."""
|
|
88
|
+
total = log_wealth if prior is None else log_wealth + prior
|
|
89
|
+
return {**summary(psi if len(psi) else np.zeros(1), total, alpha), "log_wealth": total}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def e_bh(evalues: dict, alpha: float, weights: dict | None = None) -> set:
|
|
93
|
+
"""e-BH: reject the largest k with weighted e-value at least K/(alpha*k); valid under any dependence."""
|
|
94
|
+
keys = list(evalues)
|
|
95
|
+
k_total = len(keys)
|
|
96
|
+
weights = weights or {k: 1.0 for k in keys}
|
|
97
|
+
ranked = sorted(keys, key=lambda k: -weights[k] * evalues[k])
|
|
98
|
+
rejected = 0
|
|
99
|
+
for k in range(1, k_total + 1):
|
|
100
|
+
if weights[ranked[k - 1]] * evalues[ranked[k - 1]] >= k_total / (alpha * k):
|
|
101
|
+
rejected = k
|
|
102
|
+
return set(ranked[:rejected])
|
sciel/cli/__init__.py
ADDED
|
File without changes
|
sciel/cli/live.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Run the engine in its own process and follow it in the terminal, the browser, or both.
|
|
2
|
+
|
|
3
|
+
Closing a viewer never stops the run: the engine keeps going in the background and
|
|
4
|
+
`sciel watch`, `sciel web` or `sciel stop` reach it again by its directory.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from rich.console import Console
|
|
18
|
+
|
|
19
|
+
MODES = ("both", "terminal", "web", "none")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def log_path(run_dir: Path) -> Path:
|
|
23
|
+
return run_dir.parent / (run_dir.name + ".log")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def spawn(run_dir: Path, *, fresh_config=None, tasks_root=None, recover=False) -> subprocess.Popen:
|
|
27
|
+
"""Start the engine supervisor as a detached child that writes beside the run directory."""
|
|
28
|
+
command = [sys.executable, "-m", "sciel.cli.main", "_engine", str(run_dir)]
|
|
29
|
+
if fresh_config is not None:
|
|
30
|
+
command += ["--fresh-config", str(fresh_config)]
|
|
31
|
+
if tasks_root is not None:
|
|
32
|
+
command += ["--tasks-root", str(tasks_root)]
|
|
33
|
+
if recover:
|
|
34
|
+
command.append("--abandon-provider-failure")
|
|
35
|
+
run_dir.parent.mkdir(parents=True, exist_ok=True)
|
|
36
|
+
log = open(log_path(run_dir), "ab")
|
|
37
|
+
return subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT,
|
|
38
|
+
start_new_session=True, env=os.environ.copy())
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _reason(lines) -> str | None:
|
|
42
|
+
"""The exception line that ended the engine, without the traceback above it."""
|
|
43
|
+
found = [line.strip() for line in lines
|
|
44
|
+
if re.match(r"^[A-Za-z_][\w.]*(Error|Exception|Stopped|Interrupt|Exit)\b:?", line.strip())]
|
|
45
|
+
found = [re.sub(r"^SuperviseError:\s*", "", line) for line in found]
|
|
46
|
+
if found:
|
|
47
|
+
return found[-1]
|
|
48
|
+
rest = [line.strip() for line in lines if line.strip()]
|
|
49
|
+
return rest[-1] if rest else None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _tail(path: Path, lines=12) -> str:
|
|
53
|
+
try:
|
|
54
|
+
return "\n".join(path.read_text(errors="replace").splitlines()[-lines:])
|
|
55
|
+
except OSError:
|
|
56
|
+
return ""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def follow(run_dir: Path, child, mode: str) -> int:
|
|
60
|
+
"""Show the run in the chosen viewer; return the engine's exit code, or 0 if it is still running."""
|
|
61
|
+
from ..ui.web import request_pause, serve
|
|
62
|
+
console = Console()
|
|
63
|
+
web = {}
|
|
64
|
+
|
|
65
|
+
def engine():
|
|
66
|
+
code = child.poll() if child is not None else None
|
|
67
|
+
tail = _tail(log_path(run_dir), 30).splitlines() if code not in (None, 0) else []
|
|
68
|
+
return {"exit": code, "log": str(log_path(run_dir)), "tail": tail, "reason": _reason(tail)}
|
|
69
|
+
|
|
70
|
+
def open_web():
|
|
71
|
+
if "url" not in web:
|
|
72
|
+
web["url"], web["server"] = serve(run_dir, engine=engine)
|
|
73
|
+
else:
|
|
74
|
+
import webbrowser
|
|
75
|
+
webbrowser.open(web["url"])
|
|
76
|
+
return web["url"]
|
|
77
|
+
|
|
78
|
+
if mode in ("both", "web"):
|
|
79
|
+
open_web()
|
|
80
|
+
try:
|
|
81
|
+
if mode in ("both", "terminal") and sys.stdin.isatty() and sys.stdout.isatty():
|
|
82
|
+
from ..ui.terminal import watch
|
|
83
|
+
watch(run_dir, web_url=web.get("url"), open_web=open_web, pause=lambda: request_pause(run_dir),
|
|
84
|
+
engine=engine)
|
|
85
|
+
else:
|
|
86
|
+
console.print(f"[#8A8A8E]web[/] {web.get('url', '—')} [#8A8A8E]log[/] {log_path(run_dir)} "
|
|
87
|
+
"[#8A8A8E]Ctrl-C leaves the run going[/]")
|
|
88
|
+
while child is None or child.poll() is None:
|
|
89
|
+
time.sleep(1)
|
|
90
|
+
except KeyboardInterrupt:
|
|
91
|
+
pass
|
|
92
|
+
return _farewell(console, run_dir, child)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _farewell(console, run_dir: Path, child) -> int:
|
|
96
|
+
code = child.poll() if child is not None else None
|
|
97
|
+
summary = _summary(run_dir)
|
|
98
|
+
if child is None:
|
|
99
|
+
try:
|
|
100
|
+
status = json.loads((run_dir / "runtime.json").read_text()).get("status")
|
|
101
|
+
except (OSError, ValueError):
|
|
102
|
+
status = None
|
|
103
|
+
if status != "running":
|
|
104
|
+
console.print(f"The run is {status or 'not running'}. {summary}\n {run_dir}")
|
|
105
|
+
return 0
|
|
106
|
+
if code is None:
|
|
107
|
+
console.print(f"The run continues in the background.\n"
|
|
108
|
+
f" [#64D2FF]sciel watch[/] {run_dir} follow it again\n"
|
|
109
|
+
f" [#64D2FF]sciel web[/] {run_dir} open the page\n"
|
|
110
|
+
f" [#64D2FF]sciel stop[/] {run_dir} pause after the current step")
|
|
111
|
+
return 0
|
|
112
|
+
if code == 0:
|
|
113
|
+
console.print(f"Run finished. {summary}\n {run_dir}")
|
|
114
|
+
else:
|
|
115
|
+
reason = _reason(_tail(log_path(run_dir), 30).splitlines())
|
|
116
|
+
console.print(f"[#E5484D]The engine stopped with an error.[/] {summary}\n {reason or ''}\n"
|
|
117
|
+
f" full log: {log_path(run_dir)}")
|
|
118
|
+
return code
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _summary(run_dir: Path) -> str:
|
|
122
|
+
from ..ui.state import RunState
|
|
123
|
+
try:
|
|
124
|
+
snap = RunState(run_dir).refresh()
|
|
125
|
+
except (OSError, ValueError):
|
|
126
|
+
return ""
|
|
127
|
+
run = snap["run"]
|
|
128
|
+
if run.get("best") is None:
|
|
129
|
+
return ""
|
|
130
|
+
seed = run.get("seed_score")
|
|
131
|
+
gain = f" (+{run['best'] - seed:.3f} over seed)" if seed is not None else ""
|
|
132
|
+
return f"Best {run['best']:.4f}{gain} after {run['B_evals']} evaluations, ${run.get('cost') or 0:.2f}."
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def default_mode() -> str:
|
|
136
|
+
return "both" if sys.stdout.isatty() else "none"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def write_config(cfg: dict, run_dir: Path) -> Path:
|
|
140
|
+
"""Keep the exact starting configuration beside the run, where a fresh start can read it."""
|
|
141
|
+
path = run_dir.parent / (run_dir.name + ".config.json")
|
|
142
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
143
|
+
path.write_text(json.dumps(cfg, indent=1))
|
|
144
|
+
return path
|