mixle.reason package¶
mixle.reason – the cross-modal scientific-reasoning front door.
A scientific question is a query on a joint posterior over a shared latent that every modality is evidence about. This package wires that idea into one call:
answer = reason(prior, [evidence_from_modality_1, evidence_from_modality_2, …]) answer.mean, answer.interval(0.9) # posterior with calibrated intervals answer.attribution() # which modality sharpened the belief (nats) answer.predict(H, R).epistemic # split a prediction’s uncertainty (epi vs aleatoric)
The exact core here is linear-Gaussian: each modality contributes a linear-Gaussian observation
y = H z + noise(R) and the beliefs fuse by exact Kalman assimilation (a product of experts).
Learned encoders and application-specific forward models plug in by producing such evidence – a
linearized (H, y, R) or a Gaussian expert – so the front door stays stable while encoders vary
underneath it.
Built on mixle.inference.belief (the belief state) and
mixle.inference.uncertainty (the epistemic/aleatoric split).
- class AnchorHarnessReport(modalities, hop_names, coverage_by_hop, abstained_site_ids, abstain_rate, driller_projection_components, scout_projection_components, driller_readout, scout_readout, frontier_mae, walk_mae, frontier_is_calibrated, walk_is_calibrated, notes=<factory>)[source]
Bases:
objectMeasured report for the cross-modal geoscience harness.
- run_anchor_harness(*, n_train=2000, n_test=200, seed=0)[source]
Run the cross-modal harness and return the measured report.
Requires
torch(the transport fits do); raises the underlyingImportErrorif it is absent, same as other neural transport fitting paths.
- class Ontology(classes=<factory>, relations=<factory>, axioms=<factory>, disjoint=<factory>)[source]
Bases:
objectA typed schema over knowledge: class hierarchy + relation signatures + axioms + disjointness.
- Parameters:
- add_class(name, parent=None)[source]
Add an ontology class, optionally under a known parent.
- add_relation(name, domain, range_, *axioms)[source]
Add a relation with domain, range, and optional ontology axioms.
- add_disjoint(a, b)[source]
Declare two classes mutually exclusive.
- is_a(cls, ancestor)[source]
Whether
clsisancestoror a descendant of it (walks the parent chain).
- check_triple(h, r, t, types)[source]
Every named violation of
(h, r, t)given entitytypes({} means unconstrained).
- check_graph(triples, types)[source]
Audit a triple set: per-triple violations plus the cross-triple axioms (functional/asymmetric).
Returns
{consistent, n_triples, violations: [{triple, problems}]}– every problem named.
- class OntologyConstrainedKG(kg, ontology, *, entities, relations, types)[source]
Bases:
objectA fitted KG embedding, typed by an ontology: probability mass only on schema-consistent triples.
Wraps a
KnowledgeGraphDistribution(entities and relations as integer indices) together with the symbolic ontology and the index<->name maps. The tail posterior is masked to entities whose class conforms to the relation’s range and renormalized, so completion can never propose an ontology-violating tail –Graph(ontology)as a distribution.- Parameters:
- tail_posterior(head, relation)[source]
p(tail | head, relation)over ONLY the range-conforming entities (renormalized).
- constrained_decode(llm, prompt, ontology, types, *, n=None, floor=0.5, calibrator=None)[source]
Decode only schema-consistent facts above a confidence floor.
Samples
llm(aGraphLLM)ntimes, masks every sampled graph throughOntology.filter_triples()(violating triples are rejected with named reasons), then marginalizes the constrained graphs into aGraphDistributionand keeps only facts whose edge marginal clearsfloor– the calibrated confidence floor (pass a fittedcalibratorfromfit_fact_calibrator()to apply the floor on calibrated truth probability rather than the raw marginal). Consistent-but-underconfident facts are reported as withheld, never silently dropped: the decode says what it refused to assert and why.
- class ConstrainedDecode(facts, rejected, below_floor, n_samples)[source]
Bases:
objectThe result of ontology-constrained LLM decoding: what survived, what the schema rejected, and why.
- Parameters:
- asserted()[source]
Return facts that passed constraints and confidence floor.
- class NonlinearEvidence(h, y, R, jacobian=None, iterations=2, name='')[source]
Bases:
objectOne modality’s evidence through a nonlinear forward model.
Assimilated by (iterated) extended-Kalman linearization: at the current belief mean
mthe forward is replaced by its tangenth(z) ~ h(m) + J(m)(z - m)and the exact linear update runs on that tangent; withiterations > 1the linearization point is refined at the updated mean and the update repeats from the pre-update belief, which matters when the prior mean is far from the truth.jacobianis analytic when you have it; otherwise a central finite difference is used. This is a Gaussian approximation around the linearization point; for strongly multimodal posteriors it reports one mode’s belief, not the full mixture.
- class DiscreteAnswer(belief, attribution=<factory>)[source]
Bases:
objectThe posterior over hypotheses plus per-source attribution (nats of entropy removed).
- property probs: ndarray
Return posterior probabilities over hypotheses.
- top(k=3)[source]
Return the top
khypotheses and probabilities.
- decide(loss, actions=None, *, abstain_cost=None)[source]
The Bayes-optimal action under this posterior — EXACT over the finite hypothesis set.
- Parameters:
loss (Any) – an
(A, K)matrix (loss[a, k]= cost of actionawhen hypothesiskis true) or a callableloss(action, hypothesis) -> float.actions (Any) – action labels (defaults to the hypothesis labels — the “declare k” actions).
abstain_cost (float | None) – when given, an extra
"abstain"action with this flat cost — chosen whenever every committal action’s expected loss exceeds it (the escalate-don’t-guess decision, priced explicitly).
- Returns:
{action, expected_loss, alternatives}with the exact expected loss of every candidate.- Return type:
- model_evidence(name, models, x)[source]
Evidence from fitted mixle models: hypothesis
k<->models[k], scored on observationx.Returns
(name, log_lik)withlog_lik[k] = models[k].log_density(x).
- reason_discrete(prior, evidence)[source]
Fold evidence into a categorical belief and return the posterior with per-source attribution.
- reason(prior, evidence, *, query=None)[source]
Fuse
evidenceintopriorby exact Kalman assimilation; return the queried posterior.- Parameters:
prior (Any) – the latent’s prior belief (
GaussianBelief; build one withLatent).evidence (Any) – a sequence of
LinearGaussianEvidenceand/orNonlinearEvidence– one per modality / observation. Nonlinear items assimilate by iterated-EKF linearization (a Gaussian approximation; seeNonlinearEvidence). They are folded in one at a time (order does not affect the result), and the nats each removes are recorded forReasonedAnswer.attribution().query (Any) – optional latent coordinate indices to restrict the answer to.
- Returns:
A
ReasonedAnswer– the posterior belief plus attribution and prediction UQ.- Return type:
ReasonedAnswer
- class Latent[source]
Bases:
objectFactories for the shared latent prior used at the start of assimilation.
- static gaussian(mean, cov)[source]
A Gaussian prior
N(mean, cov)over the latent.
- static vector(dim, *, mean=0.0, var=1.0)[source]
An isotropic Gaussian prior over a
dim-vector latent:N(mean*1, var*I).
- static mechanistic(A, steps, *, x0_mean=None, x0_cov=None, process_cov=None)[source]
Return a linear-dynamics prior over
z_0 .. z_{steps-1}.The trajectory follows
z_{t+1} = A z_t + w_twithw_t ~ N(0, Q). The returned belief is the joint Gaussian over the stacked trajectory(steps * d,). Because the states are coupled, evidence at one time can inform other times through the dynamics, so fusing observations viareason()performs exact Kalman smoothing for this linear-Gaussian model.- Parameters:
A (Any) –
(d, d)linear state-transition operator (one discrete step).steps (int) – number of time steps
Tin the trajectory.x0_mean (Any) – mean of
z_0(default zeros).x0_cov (Any) – covariance of
z_0(default identity).process_cov (Any) – process-noise covariance
Q(default zeros – deterministic dynamics).
- Return type:
GaussianBelief
- Evidence
alias of
LinearGaussianEvidence
- class LinearGaussianEvidence(H, y, R, name='')[source]
Bases:
objectOne modality’s evidence about the latent
z:y = H z + noise,noise ~ N(0, R).His the (possibly linearized) forward operator mapping the latent to this modality’s measurement space,ythe observed data,Rits noise covariance (matrix, diagonal, or scalar). Application forward models (e.g.mixle_pdegeophysics operators) produce these.
- block_selector(step, n_blocks, block_dim, within=None)[source]
An observation matrix that reads time-block
stepof a stacked trajectory latent.For a latent built by
Latent.mechanistic()(shape(n_blocks * block_dim,)), returns theHselecting blockstep– use it to buildLinearGaussianEvidencefor an observation at that time.withinoptionally reads only part of the block (a(k, block_dim)local readout); by default the whole block is read (identity).
- class ReasonedAnswer(belief, prior_entropy, contributions)[source]
Bases:
objectA posterior belief about a query, with the UQ a scientific answer needs.
Beyond
mean/interval/entropy(delegated to the belief), it exposesattribution()– the nats of uncertainty each modality removed – andpredict(), which splits a prediction’s uncertainty into epistemic (from latent uncertainty) and aleatoric (observation noise) via the law of total variance.- property mean: ndarray
Return posterior mean from the underlying belief.
- interval(level=0.9)[source]
Per-coordinate central credible interval at
level(an(d, 2)array of[lo, hi]).
- information_gain()[source]
Total nats of uncertainty the evidence removed from the prior (
H[prior] - H[posterior]).- Return type:
- attribution(*, normalize=False)[source]
Per-modality information gain in nats – which modality sharpened the belief, and by how much.
With
normalize=True, values are the fraction of the total gain (they then sum to ~1).
- predict(H, R=0.0)[source]
Split the uncertainty of a new prediction
y* = H z + noise(R)(law of total variance).epistemic = diag(H P Hᵀ)(from the latent’s remaining uncertainty, reducible by more data) andaleatoric = diag(R)(irreducible observation noise). Exact for the Gaussian belief.
- class GaussianBelief(mean, cov)[source]
Bases:
BeliefStateA multivariate-Gaussian belief
N(mean, cov)over a continuous latent.Evidence is a linear-Gaussian observation
y = H z + noise,noise ~ N(0, R);update()applies the exact Kalman measurement update (Joseph form, so the covariance stays symmetric positive-definite).fuse()combines two beliefs about the same latent as a product of Gaussian experts.condition()does noiseless Gaussian conditioning on a coordinate subset.- Parameters:
mean (Any)
cov (Any)
- property dim: int
Return the latent dimensionality.
- interval(level=0.9)[source]
Return marginal central intervals for each coordinate.
- sample(n=1, rng=None)[source]
Draw samples from the Gaussian belief.
- update(H, y, R)[source]
Kalman measurement update: condition on
y = H z + noise,noise ~ N(0, R).
- fuse(other)[source]
Product-of-experts fusion of two beliefs about the same latent (cross-modal fusion).
Equivalent to conditioning
selfonothertreated as a direct Gaussian observation (H = I,R = other.cov), so it reuses the exact Kalman update.- Parameters:
other (GaussianBelief)
- Return type:
GaussianBelief
- condition(indices, values)[source]
Noiseless Gaussian conditioning: fix latent coordinates
indicestovalues.Returns the belief over the remaining coordinates. This is the exact
R -> 0limit of an observation that reads off those coordinates.
- class BeliefState[source]
Bases:
ABCA distribution over a latent, exposing a uniform query + update interface.
Realizations answer where they are defined:
mean(),cov(),var(),sd(),entropy(),interval(),sample(),marginal(), and – the point of a belief state –update(), which returns a new belief conditioned on fresh evidence.- abstractmethod entropy()[source]
The differential/Shannon entropy
H[q](nats) – watch it shrink as evidence arrives.- Return type:
- abstractmethod sample(n=1, rng=None)[source]
Draw
nlatent samples from the belief.
- abstractmethod update(*args, **kwargs)[source]
Return a new belief conditioned on fresh evidence (the assimilation step).
- interval(level=0.9)[source]
Per-coordinate central credible interval at
level– an(d, 2)array of[lo, hi].
- class AcquisitionPlan(items=<factory>, total_cost=0.0, total_gain=0.0, belief=None)[source]
Bases:
objectA budgeted evidence-acquisition plan: the chosen items, the nats they bought, and the final belief.
- Parameters:
- select_evidence_batch(store, belief, *, budget, query=None, fine_cost=1.0, coarse_cost=0.2, fidelities=('coarse', 'fine'), candidates=None, max_items=None, min_gain=1e-9)[source]
Greedily acquire the most-informative-per-cost
(item, fidelity)evidence under a totalbudget.At each step every remaining candidate is scored – at each allowed fidelity – by the entropy it would remove from the query given the belief so far, divided by its cost; the best affordable one is folded in. Adaptive re-scoring means a batch never double-counts overlapping evidence. Stops when nothing affordable helps.
- as_belief(obj, node=None)[source]
Adapt any object exposing
mean/cov(aFieldPosteriornode, a fitted Gaussian, aParameterPosterior) into aGaussianBelief.nodeis forwarded when the source is node-addressable (e.g.FieldPosterior.mean(node)/.cov(node)); otherwisemean/covare called with no argument.
- class CrossModalStore(keys, payloads, *, coarse, fine, metric='euclidean')[source]
Bases:
objectA corpus indexed by embedding keys, with raw payloads conditioned on when embeddings fall short.
- Parameters:
keys (Any) –
(N, d_key)embedding vectors used as the retrieval index.payloads (Sequence[Any]) – length-
Nsequence of raw items (arbitrary; passed tocoarse/fine).coarse (Callable[[Any], LinearGaussianEvidence]) –
payload -> LinearGaussianEvidenceat embedding fidelity (low-cost, lossy).fine (Callable[[Any], LinearGaussianEvidence]) –
payload -> LinearGaussianEvidenceat raw fidelity (precise, “expensive”).metric (str) –
"euclidean"(default) or"cosine"for retrieval.
- retrieve(query_key, k=8)[source]
Return indices of the nearest
kembedding keys toquery_key.
- assimilate(belief, query_key, *, k=8, query=None, epsilon=0.0)[source]
Retrieve neighbors and fold selected evidence into
belief.For each retrieved item the sufficiency test compares how much raw evidence would reduce query entropy relative to embedding evidence. If the surplus exceeds
epsilonthe raw payload is used, else the embedding evidence is. Returns the updated belief and a per-item provenance trail.
- next_evidence(belief, *, query=None, candidates=None, fidelity='fine')[source]
Active retrieval: the corpus item whose evidence most reduces the query entropy (EIG).
Returns
(index, expected_gain_nats).fidelityselects thefine(raw) orcoarse(embedding) evidence builder for the look-ahead.
- class RetrievalStep(index, fidelity, gain)[source]
Bases:
objectProvenance for one assimilated item: which corpus index, at what fidelity, and the nats it removed.
- class LLMUncertainty(generate, *, equivalent=None, n=10)[source]
Bases:
objectCalibrated uncertainty and selective prediction for any
generate(prompt) -> strLLM.- Parameters:
generate (Callable[[str], Any]) –
callable(prompt) -> str– one stochastic sample from the model.equivalent (Callable[[Any, Any], bool] | None) –
callable(a, b) -> booldeciding whether two answers mean the same thing (default exact match; pass a normalizer / embedding / entailment check for real text).n (int) – default number of samples per prompt.
- sample(prompt, n=None)[source]
Draw
nstochastic responses toprompt.generatemay return a plain string, or a(text, logprob)pair – the sequence log-probabilitylog P(s). When logprobs are provided they are used to marginalize the string distribution over meaning classes exactly (mixle.inference.marginalize_meaning()) rather than by sample counting.
- assess(prompt, n=None)[source]
Sample, marginalize the string distribution over meaning classes, and report the answer.
The reported
confidenceis the marginal probability of the top meaning (summed over its equivalence class of strings), andsemantic_entropythe entropy of that meaning marginal – not a per-string token probability.
- decompose(prompts, n=None)[source]
Epistemic/aleatoric split across member prompts (paraphrases of one question).
Each prompt is a member; all members’ samples are pooled to define shared meaning-clusters, then each member’s distribution over those clusters feeds
decompose_entropy(). Epistemic = disagreement across paraphrasings (prompt-sensitivity / model uncertainty); aleatoric = within-member spread.
- assess_claims(prompt, *, extract=None, corroborates=None, n=None, threshold=0.5)[source]
Score the reliability of each claim in the response by cross-sample corroboration.
Finer-grained than
assess(): a response can be internally consistent (low semantic entropy) yet contain one fabricated fact. This decomposes the response into claims and checks each unit of information separately – a claim the model knows recurs across independent resamples; a hallucinated one appears once. This is UQ on the information in what is said, not just on the answer as a whole.- Parameters:
prompt (str) – the query.
extract (Callable[[str], Sequence[str]] | None) –
response -> [claim, ...](defaultsentence_claims()).corroborates (Callable[[str, str], bool] | None) –
(other_sample, claim) -> bool– does a resample support the claim? (defaultcontent_overlap(); pass an entailment/NLI check for real text).n (int | None) – number of samples (the first is the response scored; the rest corroborate).
threshold (float) – support below which a claim is flagged as unreliable/fabricated.
- Return type:
InformationAssessment
- calibrate(examples, *, correct=None, alpha=0.1, n=None)[source]
Calibrate a confidence threshold for selective risk
<= alphaon labeled(prompt, gold).For each example, the model’s answer (majority meaning-cluster) and its confidence are computed;
correct(answer, gold)(default theequivalentrelation) marks it right or wrong. The threshold is the lowest confidence at which the selective error rate on the calibration set is<= alpha– soanswer()abstains below it and, when it answers, is right with probability about1 - alpha.
- answer(prompt, n=None)[source]
Answer
promptif confident enough, elseNone(abstain).Requires a prior
calibrate(). Returns theLLMAssessmentwhenconfidence >= threshold(so the answer meets the selective-risk guarantee), elseNone.
- fit_factuality(examples, *, signal=None, correct=None, method='isotonic', n=None)[source]
Learn a calibrated
P(answer is correct)from a raw signal, on labeled(prompt, gold).The model’s raw confidence (its self-consistency, or a token likelihood) is not a probability that the information is correct – it can be systematically over/under-confident, or unrelated to truth. This fits a
ProbabilityCalibratormapping the signal to the empirical correctness rate, so the output is a probability of the information being right.discrimination(AUC of signal vs correctness) reports how much the raw signal knew at all – ~0.5 means it was unrelated to truth, calibration or not.- Parameters:
examples (Sequence[tuple[str, Any]]) – labeled
(prompt, gold_answer)pairs.signal (Callable[[str], float] | None) –
prompt -> floatraw score (default: the self-consistency confidence fromassess()).correct (Callable[[Any, Any], bool] | None) –
(answer, gold) -> bool(default theequivalentrelation).method (str) – calibration map –
"isotonic"or"platt".n (int | None) – samples per prompt.
- Return type:
FactualityModel
- class LLMAssessment(answer, confidence, semantic_entropy, clusters, samples)[source]
Bases:
objectOne prompt’s assessed answer with uncertainty.
answeris the majority meaning-cluster’s representative;confidenceits cluster share in[0, 1];semantic_entropythe nats of meaning-uncertainty;clustersthe[(representative, probability), ...]distribution over meanings;samplesthe raw draws.
- class ClaimAssessment(claim, support, reliable)[source]
Bases:
objectReliability of one claim inside a response, by cross-sample corroboration.
supportis the fraction of independent resamples that corroborate the claim (in[0, 1]);reliableissupport >= threshold. A claim the model actually knows recurs across samples (high support); a fabricated one appears once and vanishes (low support).
- class InformationAssessment(claims, reliability)[source]
Bases:
objectUQ over the information content of a response: every claim scored, plus a summary.
claimsis the per-claim reliability;reliabilitythe mean support (how trustworthy the response’s information is overall);fabricatedthe claims below threshold (likely hallucinated).- property fabricated: list[ClaimAssessment]
Return claims assessed as unreliable.
- class FactualityModel(calibrator, signal, discrimination)[source]
Bases:
objectA fitted map from a per-prompt uncertainty signal to a calibrated
P(answer is correct).The signal (self-consistency, a token likelihood, …) is only a raw number; the calibrator turns it into a genuine probability of the information being correct, learned against labeled facts.
discrimination(held-out AUC on the fit set) reports how much the signal actually knew about correctness – ~0.5 means the signal was unrelated to truth, no matter how confident it looked.- Parameters:
- sentence_claims(text)[source]
Split a response into atomic claims (sentence-ish units) – the default claim extractor.
- content_overlap(sample, claim, *, threshold=0.6)[source]
Simple corroboration test: does
samplecover >=thresholdofclaim’s content words?Counts every content word equally, so boilerplate shared across responses (“the tower is located in …”) can mask that the informative word (the city) differs.
information_corroborator()fixes that by weighting words by their information content; it is the default inLLMUncertainty.assess_claims().
- class ModalityView(name, dist, symmetry_group='none', notes=<factory>)[source]
Bases:
objectOne modality as a typed structured belief: a real mixle distribution plus its symmetry group.
distis any fittedSequenceEncodableProbabilityDistribution: for example a categorical model over labels, a Gaussian or Student-t model over measurements, a neural density over an embedding-shaped field, or a Bayesian network over a structured record.symmetry_groupnames the invariance the modality declares, such as"none","translation","permutation", or"rotation".- score(x)[source]
Return
log p(x)under this modality’s structured belief.
- sample(n=1, *, seed=None)[source]
Draw from this modality’s own sampler.
- class ModalityGraph(views=<factory>)[source]
Bases:
objectA named collection of
ModalityViewfor one entity.Belief walks hop across this joint representation. A receiver reads named modalities and their own scores rather than an implicit shared vector.
- add(view)[source]
Add a modality view and return the graph for chaining.
- Parameters:
view (ModalityView)
- Return type:
ModalityGraph
- class TaskReadout(name, label)[source]
Bases:
objectTask readout used to decide which mixture components can be merged.
label(mean)maps a component mean to a discrete readout value. Components sharing a readout are indistinguishable for this task and may be merged; components with different readouts remain separate.
- task_sufficient_projection(mixture, task)[source]
pi_T(mixture): collapsemixture’s components into groups sharingtask.label.Components are grouped by
task.label(component_mean). Groups with more than one component are moment-matched bycollapse_mixture(); singleton groups pass through unchanged. The result never has more components than the input.- Parameters:
mixture (Any)
task (TaskReadout)
- Return type:
MixtureDistribution
- read_out(mixture, task, x)[source]
Return the task label of the component most responsible for
x.The same readout applies to a full or projected belief, so a projection can be evaluated by the task labels it preserves.
- cycle_inconsistency(sampler, given_value, *, n_draws=20, forward=None)[source]
Return disagreement among posterior target samples for one observation.
A well-determined posterior yields draws that agree closely. A collapsed observation region yields draws that disagree, without needing the true target at serving time. If
forwardis supplied, agreement is checked in observation space rather than raw target space.
- fit_cycle_transport(given, target, *, k=3, hidden=32, layers=2, max_its=30, m_steps=80, lr=3e-3, seed=0, delta=1.0e-9, reuse_estep_ll=True)[source]
Fit
p(target | given)via a mixture density network.given/targetare(n, d)arrays of paired observations.delta/reuse_estep_lldefault tooptimize()’s own early-stopping; passdelta=None, reuse_estep_ll=Falsefor a harder, more multimodal target.
- posterior_mean_estimate(sampler, given_value, *, n_draws=20)[source]
Return the posterior-sample mean of the target given
given_value.
- selective_error(errors, abstain_scores, keep_frac)[source]
Return mean error on examples kept by the lowest abstention scores.
Lower is better: a useful abstention signal keeps examples the policy can answer and escalates examples with higher expected error.
- class CrossModalJoint(names, joint)[source]
Bases:
objectA joint over named modalities sharing one latent regime (a mixture component index).
namesfixes the modality-name -> composite-field-index mapping;jointis aMixtureDistributionwhose components areCompositeDistributioninstances overlen(names)heterogeneous fields, innamesorder. The mixture weights are the shared latent’s priorp(regime); each component isp(modality_0, modality_1, ... | regime=k).- classmethod from_components(names, component_fields, weights)[source]
Build a shared-latent joint from per-regime per-modality distributions.
component_fields[k]is the sequence oflen(names)per-modality distributions for latent regimek(innamesorder);weights[k]isp(regime=k). Each regime is wrapped as oneCompositeDistributionover the (heterogeneous) modality fields and the regimes are mixed, so the resulting joint’s own component index is exactly the shared latent tying every modality together.
- infer(observed, target=None)[source]
Posterior over
targetmodalities given observed values for any OTHER subset.observedmaps modality name -> its observed value, for any subset (including the empty set, which returns the marginal/prior).targetnames the modalities to infer the joint posterior over; defaults to every modality not inobserved. Everytargetname must be absent fromobserved(you cannot condition on and infer the same modality).Returns a
MixtureDistributionover alen(target)-tuple, intargetorder (a 1-modality target is a mixture over a 1-tuple, matchingCompositeDistribution’s own convention for a single field).
- joint_cycle_consistency_receipt(joint, source, target, *, backward_joint=None, n_round_trip=300, n_kl_samples=500, seed=0)[source]
Cross-modal generalization (workstream L2) of this module’s round-trip closure signal.
cycle_inconsistencyabove measures round-trip closure (A -> B -> A) for a NEURAL transport, where the true target is unknown at serving time and self-AGREEMENT among repeated draws is the only available proxy. ACrossModalJointis a typed grammar object, not an opaque transport: its true marginalp(source)is available in closed form (CrossModalJoint.infer()with no observations), so the round-trip receipt here compares the round-trip estimate DIRECTLY against that true marginal, rather than against itself.Two ways to arrive at a belief about
sourcethrough the joint: (1) directly, its own marginalp(source); (2) via a round trip,p(source) -> infer p(target | source) -> infer p(source | target) back, averaged over many draws into one aggregate “round-trip” belief. This receipt is a Monte-Carlo KL-divergence estimate between (2) and (1); a well-specified joint recovers its own marginal on a round trip (the receipt is ~0 up to Monte-Carlo noise), while a deliberately mis-specified backward projection (backward_joint– e.g. a joint whosetarget-given-regime distributions have been shuffled relative tojoint’s, standing in for a broken/incompatible A<-B projection) breaks that identity and the receipt becomes clearly, measurably elevated.
- class HopTransport(name, fit, premise_passed=True)[source]
Bases:
objectOne edge of the belief walk and its own calibration verdict.
premise_passedrecords whether this transport was independently verified usable and calibrated on this edge.
- class WalkResult(hop_names, samples)[source]
Bases:
objectThe belief walk’s outcome: an empirical posterior over the final hop’s variable.
- property mean: ndarray
Return posterior sample mean for the final hop.
- property std: ndarray
Return posterior sample standard deviation for the final hop.
- belief_walk(hops, x0, *, n_draws=200, seed=0)[source]
Propagate a belief forward through a chain of hops, starting from a single value
x0.Each hop’s transport is applied by drawing
n_drawssamples of the current belief and pushing each through the hop’ssample_givenmethod. Raises if any hop’spremise_passedflag isFalse.
- coverage_by_hop_count(hops, x0_test, true_final, *, alpha=0.1, n_draws=150, seed=0)[source]
Return empirical calibration by hop count.
For
k = 1 .. len(hops), walks the firstkhops for every test point inx0_testand checks credible-interval coverage oftrue_final[k]against the nominal1 - alpharate with a two-sided binomial test.true_finalmust supply ground truth for each checked hop count.
- information_corroborator(samples, *, overlap=0.5)[source]
Build a corroboration test that weights each word by its information content over
samples.A word appearing in nearly every sample is boilerplate (low information, low weight); a rare word carries the actual claim (high weight). A sample corroborates a claim when it covers at least
overlapof the claim’s information-weighted words – so whether the distinctive fact (a city, a number, a name) matches drives the decision, not the shared filler. Inverse-document-frequency weighting:w(word) = log((N + 1) / (df + 0.5)).
- class GraphLLM(generate, parse, *, n=10)[source]
Bases:
objectTurn a
generate(prompt) -> strLLM into a distribution over knowledge graphs.- Parameters:
generate (Callable[[str], str]) –
callable(prompt) -> strfor one stochastic generation.parse (Callable[[str], Iterable[Any]]) –
callable(str) -> iterable[triple]to extract asserted facts. Generations that parse to the same triple set are treated as the same canonical graph.n (int) – default number of samples per prompt.
- sample_graphs(prompt, n=None)[source]
Sample
ngenerations and parse each into a canonical graph.
- distribution(prompt, n=None, *, log_probs=None, graphs=None)[source]
Sample, parse, and marginalize strings onto graphs.
Marginalization uses Monte-Carlo counting by default (
P(G)= fraction of samples that parse toG); passlog_probs(onelog P(string)per sample) to instead sum the sequence likelihoods within each graph. This lower-variance estimator does not assume every string realizing a graph is equiprobable.
- class GraphDistribution(graphs, probs)[source]
Bases:
objectA distribution over knowledge graphs.
graphsare the distinct canonical graphs observed;probs[i] = P(graphs[i])is the string distribution marginalized onto graphs (so it sums to 1 over distinct graphs). Every query is answered by marginalizing this distribution over the graphs that produce the queried outcome.- marginalize(outcome)[source]
Return
P(outcome = c) = sum_{G : outcome(G) = c} P(G).outcomemaps a graph to a hashable value (a fact’s object, a boolean property, an aggregate). Returns[(value, probability), ...]sorted by descending probability.
- entropy(outcome)[source]
Return entropy in nats of the marginal outcome distribution.
- edge_marginals()[source]
Return
P(triple in G)for every asserted triple.
- fact_probability(triple)[source]
P(triple in G)for one fact (0 if never asserted).
- calibrated_edge_marginals(calibrator)[source]
Map edge marginals through a fitted calibrator.
A raw edge marginal is the model’s internal assertion rate for a fact, not a probability that the fact is true – a confidently-hallucinated fact has a high marginal yet is false. Fit the calibrator with
fit_fact_calibrator()on labeled facts, then this reports, per fact, the empirical truth rate at that marginal. Confident hallucinations that look exactly like known facts still require an external check.
- query(*prefix)[source]
Answer-completion posterior:
P(object | prefix)over triples whose leading fields match.query("eiffel", "city")marginalizes over graphs, collecting the objects of every triple starting("eiffel", "city", ...)weighted byP(G), then renormalizes over the objects actually asserted. Returns[(object, probability), ...]best-first.
- canonical_graph(triples)[source]
Return an order-independent, deduplicated graph representation.
- fit_fact_calibrator(distributions, truth, *, method='isotonic')[source]
Fit
edge marginal -> P(fact is true)over the facts asserted across many graph distributions.Turn the model’s internal assertion rate (the edge marginal) into a calibrated probability of truth, learned against ground-truth labels. Collect every
(triple, marginal)the model asserts, label it withtruth(triple), and fit aProbabilityCalibrator.This does not by itself identify confident hallucinations: a false fact the model reliably emits can have a high marginal. Calibration can improve the aggregate reliability curve, but separating those cases requires an external signal such as retrieval or a checker.
- class EdgeTransportVerdict(edge_name, usable, coverage_rates=<factory>, p_values=<factory>, reason='')[source]
Bases:
objectPremise decision for one real modality edge, computed on that edge.
- coverage_consistent_with_nominal(covered_flags)[source]
(observed_rate, p_value)for a two-sided binomial test of coverage against1 - ALPHA.
- fit_conditional_transport(data, *, x_dim, y_dim, k=3, max_its=30, m_steps=80, lr=3e-3, seed=0, delta=1.0e-9, reuse_estep_ll=True)[source]
Fit
p(cond | target)and return a sampler withsample_given.Uses
mixle.models.mixture_density.build_mdn()andNeuralConditionalDensity, fit throughoptimize(). Passdelta=None, reuse_estep_ll=Falsefor an edge whose relationship needs the full iteration budget rather than early stopping.
- marginal_coverage(sampler, x_test, y_test, *, n_draws=200)[source]
Return per-dimension credible-interval coverage flags.
- Parameters:
n_draws (int)
- verify_edge_transport(edge_name, sampler, x_test, y_test, *, n_draws=200)[source]
Check one fitted edge sampler against held-out calibration data.
Submodules¶
- mixle.reason.adapter module
- mixle.reason.anchor_harness module
- mixle.reason.belief_walk module
- mixle.reason.core module
- mixle.reason.cross_modal module
- mixle.reason.cycle_consistency module
- mixle.reason.design module
- mixle.reason.discrete module
- mixle.reason.embedding module
- mixle.reason.encoder module
- mixle.reason.fusion module
- mixle.reason.graph_llm module
- mixle.reason.inference_program module
- mixle.reason.language_bridge module
- mixle.reason.llm module
- mixle.reason.modality module
- mixle.reason.model module
- mixle.reason.ontology module
- mixle.reason.store module
- mixle.reason.task_projection module
- mixle.reason.transport_edge module
- mixle.reason.zero_shot_bootstrap module