Celestis-RL / docs /API.md
PureOne's picture
Release Celestis-RL v2.0.0: audited research reference
f95cbd4 verified
|
Raw
History Blame Contribute Delete
8.93 kB

API contracts

Import namespace: celestis_rl. Version: 2.0.0. The annotated source is the complete API specification; this guide gives shape and validity contracts. Tests are executable examples.

Exact moment replay

FeatureBank(features, bias=None) takes fixed finite floating tensors [V,R] and [V], owns detached copies, and fingerprints their bytes. It refuses trainable inputs unless the caller intentionally detaches them. The immutable feature basis is not the same as the effective output head: x_theta = A_theta h_theta + c_theta may train freely inside the fixed vocabulary span. Arbitrary new feature directions, moving tied embeddings and nonlinear post-projection logits are not supported by this identity.

capture_moments(q, actions, mask, bank, sampler_version=..., context_id=...) requires actual historical sampling probabilities [B,T,V], int64 actions [B,T] in historical support, and a boolean mask. It records feature mean [B,T,R], bias mean, sampled-action log q, mean log q, actions and mask, plus identifiers. Historical q is detached. Small rounding-scale normalization is allowed; smoothing/truncating a different distribution is forbidden. Capture costs a vocabulary pass and a matrix-moment reduction.

MomentBatch.verify(bank, context_id=None, full=False) validates dimensions, support metadata, finite values, bank identity and mutation counters. full=True hashes bytes too. A context label is not independently authenticated: the caller must retain and bind the exact original context and reward. save/load uses numeric NPZ, never pickle. .to(device) verifies the source record's digest before copying.

moment_sequence_loss(latent, record, bank, rewards, beta=0.1, temperature=1.0, outer_weights=None, normalizer=None) requires latent [B,T,R], terminal rewards [B], beta > 0, fixed positive temperature and complete-response masks. It returns (loss, diagnostics). It evaluates a genuine squared sequence-regression objective, not the numerically equal value of the older stop-gradient surrogate: gradients, not those two displayed scalars, are the equivalence target. There is no vocabulary-sized replay-head operation or normalizer pass. Backbone, input-embedding gradients and optimizer work remain.

moment_token_loss(...) preserves the exact full token sample-gradient but still computes the current action probability with a chunked forward normalizer. Do not call it normalization-free training.

moment_dimension(features) reports a numerical affine-rank diagnostic. The paper's exact-rank theorem concerns linear summaries preserving all feature expectations; it is not a claim that the whole replay record is information-theoretically minimal among arbitrary encodings.

Checked feature-bank transport

AffineBankTransport(source, target, matrix, offset, bias_direction=None, bias_offset=0) checks the entire bank relation once: phi_new = phi_old @ matrix + offset, b_new = b_old + phi_old @ bias_direction + bias_offset. Shapes are [R_old,R_new], [R_new], [R_old], scalar. Banks must share token identity, vocabulary size and device. The equality test is exact on the computed floating arrays, with ordinary subsequent arithmetic roundoff. Approximate relations are not silently accepted.

transport.apply(record) then transforms only the stored moments; it needs no full historical q. It returns a new bank-tagged record with unchanged actual historical action log q, entropy statistic, actions and context label. Target directions outside the certified affine image require retained full q or fresh collection. This map preserves the target objective, not the old policy or every possible downstream task.

Correction samplers

draw_correction(q, mask, budget, mode, generator=...) retains IID, safe and logit-trace head/tail comparators. exact_correction(q, mask) enumerates all positive probability entries.

stratified_correction(q, mask, budget=32, head='safe', generator=...) retains the same head and uses independent equal-mass inverse-CDF tail strata. Its Correction contains IDs, weights, historical log q and mask. Weighted masses equal one per active token in real arithmetic. Fresh auxiliary draws must be conditionally independent of the already collected action and of one another at separate score sites. Positive CDF-interval collapse triggers an IID tail fallback. The safe covariance chain is conditional, not an end-to-end superiority theorem. The trace head is chosen using the old IID-tail trace, not a reoptimized stratified trace.

coalesce_correction(record) merges repeated IDs without changing the weighted integral, up to floating-point arithmetic; it adds sorting overhead. stratum_probabilities and stratified_trace_variance are analytic diagnostics, not empirical learning metrics.

Trainable linear output-head kernels

centered_linear_scores(hidden, weight, actions, q=... OR ids=..., coefficients=..., bias=None, chunk_size=4096, row_chunk_size=64, temperature=1.0) returns centered logits plus detached current action log probabilities. hidden is [N,D], weight [V,D], actions [N]; sampled IDs/zero-mass coefficients are [N,K]. It implements first-order vector–Jacobian products only. Exact mode streams q-weighted terms. Sampled mode recomputes selected activations in backward. Shared/tied output weights are tested for this general full-q route.

linear_token_loss(hidden[B,T,D], weight, actions, q, mask, returns, correction=None, ...) connects that kernel to the token objective. correction=None is exact streaming. Supplied correction records preserve the specified sample gradient. Full q, dense output-weight gradients, optimizer state and full-vocabulary normalization are not eliminated by these kernels.

The older selected_linear_scores, selected_token_loss, dense token_loss, and independent-view sequence_loss remain available. Sequence sampled views must be independent; reusing a view in residual and score creates a bias term. Outer weights represent fixed finite-buffer sampling corrections, not self-normalized weights. Default reduction is sum over valid tokens per response and mean over responses, not a mean over tokens. A supplied fixed normalizer supports microbatch accumulation.

Audits, replay and transactional updates

MetricSpec(name, minimum=0, maximum=1, direction=1, min_gain=0, penalty=0) defines a bounded return, its improvement direction, a required signed gain, and any separately justified error allowance. A lower-is-better cost uses direction=-1; tolerating a small cost increase requires an explicitly negative min_gain.

SequentialParetoAudit(metrics, ledger, candidate_id=..., looks=(...), method='hybrid', ledger_path=None) consumes confidence at construction. .add(candidate[N,M], baseline[N,M], candidate_id=...) uses fresh IID paired evaluations of a proposal held fixed during that audit. It stops at registered looks, accepts only if all lower bounds exceed margins, or remains inconclusive. Hybrid selection splits its confidence allocation between the two candidate inequalities. Candidate IDs are caller-maintained identities, not an independent proof that model bytes were held fixed. save/load resumes the same audit; never rewind consumed evidence or the global ledger. Concurrent writers require external locking.

transactional_step(model, optimizer, closure, audit) snapshots parameters, buffers, optimizer state, parameter gradients and training-mode flags. Rejection or exception restores them. Randomness, external systems and confidence spending are not rolled back. Do not use it to undo real-world external actions. The original single-look Hoeffding paired_gain_audit remains available.

Historical full-q ReplayRecord, ReplayBuffer, collate, finite-state quotient checks, bounded beta control and potential-baseline helpers remain. Their integrity digests do not prove truth, causal validity or future environment stability.

Runnable models and checkpoint loading

FixedSpanCausalLM is a tiny synthetic model whose forward includes the trainable span adapter. run_moment_lm trains it with default moment replay; dense_oracle=True keeps q only for the reference comparison. load_moment_model validates numeric-only weights, expected parameter names/shapes/dtypes, the feature bank and output projection, and returns (model, bank) for inference. The checkpoint contains no pretrained natural-language ability and no complete optimizer/RNG resume state.

TinyCausalLM, run_tiny_lm and load_tiny_weights cover the unrestricted-head token route. The optional Hugging Face adapter uses generic dense logits; its protocol is locally tested with an initialized model, not a downloaded pretrained model. Architecture-specific extraction of pretrained hidden states for optimized kernels must be integrated and validated separately.