Datasets:
Modalities:
Text
Formats:
json
Languages:
English
Size:
< 1K
Tags:
reinforcement-learning
policy-optimization
klpo
exact-moment-replay
score-centering
stratified-sampling
License:
Download src/celestis_rl/state.py from PureOne/Celestis-RL: direct link, hf CLI and curl.
- Browser
- Download file 5.37 kB
-
https://huggingface.co/datasets/PureOne/Celestis-RL/resolve/main/src/celestis_rl/state.py
- Command line
-
hf download hf://datasets/PureOne/Celestis-RL/src/celestis_rl/state.py
-
curl -L -o state.py https://huggingface.co/datasets/PureOne/Celestis-RL/resolve/main/src/celestis_rl/state.py
5.37 kB
| """Finite-state observability checks and tamper-evident event persistence. | |
| Inspired by the user's PIPS/RCCD/SPWSE design goals. These are independently | |
| specified finite constructions, not assertions that neural summaries preserve | |
| all causally relevant information. | |
| """ | |
| from dataclasses import dataclass, asdict | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| from .replay import canonical_json | |
| from .certificates import compaction_value_bound | |
| class QuotientCertificate: | |
| reward_error: float | |
| transition_tv: float | |
| exact: bool | |
| states: int | |
| quotient_states: int | |
| horizon: int | |
| value_error_bound: float | |
| kernel_digest: str | |
| scope: str = "enumerated finite MDP; policies constant on quotient fibers" | |
| def certify_quotient(reward, transition, mapping, *, horizon: int) -> tuple[QuotientCertificate, np.ndarray, np.ndarray]: | |
| """Construct a representative quotient and check every (state,action). | |
| reward[S,A], transition[S,A,S], mapping[S] with contiguous labels. | |
| No statistical/generalization claim follows when these arrays are merely | |
| fitted models instead of trusted exact transition tables. | |
| """ | |
| r, p, f = np.asarray(reward, dtype=float), np.asarray(transition, dtype=float), np.asarray(mapping) | |
| if r.ndim != 2 or p.shape != (*r.shape, r.shape[0]) or f.shape != (len(r),): | |
| raise ValueError("invalid finite MDP shapes") | |
| if f.dtype.kind not in "iu" or (f < 0).any() or not np.array_equal(np.unique(f), np.arange(f.max()+1)): | |
| raise ValueError("mapping must use contiguous nonnegative integer labels") | |
| if not np.isfinite(r).all() or not np.isfinite(p).all() or (p < 0).any() or not np.allclose(p.sum(-1), 1, atol=1e-12, rtol=0): | |
| raise ValueError("invalid finite MDP values") | |
| z = int(f.max()+1) | |
| agg = np.stack([p[..., f == j].sum(-1) for j in range(z)], -1) | |
| representatives = [int(np.flatnonzero(f == j)[0]) for j in range(z)] | |
| rq, pq = r[representatives], agg[representatives] | |
| er = float(np.abs(r-rq[f]).max()) | |
| ep = float((0.5*np.abs(agg-pq[f]).sum(-1)).max()) | |
| span = float(np.max(r)-np.min(r)) | |
| bound = compaction_value_bound(horizon, er, ep, span) | |
| h = hashlib.sha256() | |
| for a in (r, p, f.astype(np.int64)): | |
| h.update(canonical_json({"shape": a.shape, "dtype": a.dtype.str})) | |
| h.update(np.ascontiguousarray(a).tobytes()) | |
| cert = QuotientCertificate(er, ep, er == 0 and ep == 0, len(r), z, horizon, bound, h.hexdigest()) | |
| return cert, rq, pq | |
| class EventLog: | |
| """Append-only in-memory hash chain. No arbitrary tool execution capability.""" | |
| def __init__(self): | |
| self.events: list[dict] = [] | |
| def append(self, kind: str, payload: dict, *, capability_hash: str) -> str: | |
| if not kind or not capability_hash or not isinstance(payload, dict): | |
| raise ValueError("event kind, dict payload and capability hash required") | |
| # JSON roundtrip isolates future caller mutation and excludes NaN/objects. | |
| payload = json.loads(canonical_json(payload)) | |
| parent = self.events[-1]["digest"] if self.events else "0"*64 | |
| body = {"index": len(self.events), "kind": kind, "payload": payload, | |
| "capability_hash": capability_hash, "parent": parent} | |
| digest = hashlib.sha256(canonical_json(body)).hexdigest() | |
| self.events.append(dict(body, digest=digest)) | |
| return digest | |
| def verify(self) -> None: | |
| parent = "0"*64 | |
| for i, event in enumerate(self.events): | |
| body = {k: v for k, v in event.items() if k != "digest"} | |
| if body.get("index") != i or body.get("parent") != parent: | |
| raise ValueError("event ordering/parent mismatch") | |
| digest = hashlib.sha256(canonical_json(body)).hexdigest() | |
| if digest != event.get("digest"): | |
| raise ValueError("event digest mismatch") | |
| parent = digest | |
| def save(self, path: str | Path): | |
| self.verify() | |
| Path(path).write_text("\n".join(canonical_json(e).decode() for e in self.events)+"\n", encoding="utf-8") | |
| def load(cls, path: str | Path) -> "EventLog": | |
| obj = cls() | |
| obj.events = [json.loads(s) for s in Path(path).read_text(encoding="utf-8").splitlines() if s] | |
| obj.verify() | |
| return obj | |
| def potential_returns(rewards, potentials, *, gamma: float = 1.): | |
| """Return shaped rewards and return-to-go; requires zero terminal potential. | |
| Potentials are prefix-predictable. For gamma=1 and terminal-only rewards, | |
| the result is R - Phi_t: an action-independent baseline, not free new | |
| reward information. Adversarial/action-dependent potentials can bias it. | |
| """ | |
| r, phi = np.asarray(rewards, dtype=float), np.asarray(potentials, dtype=float) | |
| if r.ndim != 1 or phi.shape != (len(r)+1,) or not np.isfinite(r).all() or not np.isfinite(phi).all(): | |
| raise ValueError("finite rewards[T] and potentials[T+1] required") | |
| if not 0 <= gamma <= 1 or not np.isfinite(gamma) or phi[-1] != 0: | |
| raise ValueError("gamma in [0,1] and exactly zero terminal potential required") | |
| shaped = r + gamma*phi[1:] - phi[:-1] | |
| rtg = np.empty_like(r) | |
| carry = 0. | |
| for t in range(len(r)-1, -1, -1): | |
| carry = shaped[t] + gamma*carry | |
| rtg[t] = carry | |
| return shaped, rtg | |