permutation

package
v0.3.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const DualMirrorLetterWarning = "--dual-mirror on lettered choice questions: the forward and reversed slots share letters (A, B, C...) " +
	"that mean different options, and the model can copy the letter across slots, changing the forward answer (EXP-14). " +
	"Research use only; see docs/experiments/exp-14-idc-rerun.md."

DualMirrorLetterWarning is the message emitted when --dual-mirror mirrors a lettered choice question.

Variables

View Source
var MirrorAliasNames = true

InjectDualMirrorSchema transforms a dgem JSON schema by adding a companion reversed-option slot (`<id>` + MirrorSlotSuffix, default `<id>__rev`) for every choice/boolean slot so both forward and reversed option orderings are evaluated simultaneously on the SAME bidirectional diffusion canvas (reads=1). MirrorAliasNames controls how the reversed mirror slot names its options. When true (the historical default), options are renamed item_1..item_K with "name: description" text. When false, the reversed slot keeps the real option names and descriptions, matching the EXP-13 bench-permutation setup.

View Source
var MirrorMode = "reversed"

MirrorMode selects how the second slot is built (PROP-11):

reversed        reversed options, lettered choice (historical default; letters collide)
copy            identical copy of the question in the same order (letters mean the same options)
reversed-digits reversed options sent as a score question, so the server labels them 1, 2, 3...
reversed-first  reversed lettered choice placed before the forward question
View Source
var MirrorSlotSuffix = "__rev"

MirrorSlotSuffix is appended to a question id to name its reversed mirror slot. Slot ids are visible to the model: the historical suffix "__mirror_rev" measurably degraded both the mirror and the forward readings on the Vertex endpoint (EXP-14), while neutral suffixes such as "__rev" did not. Kept configurable so older receipts can be reproduced with --mirror-slot-suffix=__mirror_rev.

View Source
var (

	// WarnWriter receives the one-time dual-mirror warning (stderr by default; set to io.Discard to silence).
	WarnWriter io.Writer = os.Stderr
)

Functions

func ApplyPriorDeBiasing

func ApplyPriorDeBiasing(rawProbs map[string]float64, orderedOpts []OptionItem, np *NullPrior, alpha float64) (map[string]float64, string)

ApplyPriorDeBiasing removes the positional letter prior p_0(pos_i) from a permutation pass's probabilities: p_debiased(o_{pi(i)}) \propto p_raw(o_{pi(i)}) / (p_0(i))^alpha.

func ComputeBALDDecomposition

func ComputeBALDDecomposition(dists []map[string]float64, keys []string) (map[string]float64, string, float64, float64, float64)

ComputeBALDDecomposition takes R probability distributions over the same semantic keys and returns:

  • ensembleProbs: bar_p(o_k) = (1/R) sum_r p_r(o_k)
  • ensembleWinner: argmax_k bar_p(o_k)
  • meanH: (1/R) sum_r H(p_r) (Aleatoric / Within-Pass Entropy)
  • totalH: H(bar_p) (Total Predictive Uncertainty)
  • jsd: H(bar_p) - meanH (Jensen-Shannon Divergence = Mutual Information I(Y; Pi | X))

func ComputeBrier

func ComputeBrier(probs map[string]float64, keys []string, gold string) float64

ComputeBrier computes the multi-class Brier score sum_{k} (p_k - y_k)^2.

func ComputeShannonEntropy

func ComputeShannonEntropy(probs map[string]float64, k int) (float64, float64)

ComputeShannonEntropy computes H(p) = -sum p_k ln(p_k) in nats and normalized H / ln(K).

func ComputeTVD

func ComputeTVD(p, q map[string]float64, keys []string) float64

ComputeTVD computes Total Variation Distance 0.5 * sum_k |p_k - q_k|.

func DualMirrorLetterCollisionSeen

func DualMirrorLetterCollisionSeen() bool

DualMirrorLetterCollisionSeen reports whether any schema in this process mirrored a lettered choice question.

func EvaluateSinglePermutation

func EvaluateSinglePermutation(ctx context.Context, cli *client.Client, c PermutationCase, orderedOpts []OptionItem) (map[string]float64, string, float64, error)

EvaluateSinglePermutation runs 1 forward pass with options in the specified order `orderedOpts`.

func ExtractSchemaSlotOptions

func ExtractSchemaSlotOptions(schemaJSON string) map[string][]OptionItem

ExtractSchemaSlotOptions parses a dgem JSON schema and returns the ordered option items for each choice/boolean slot.

func InjectDualMirrorSchema

func InjectDualMirrorSchema(schemaJSON string) (string, map[string][]OptionItem, bool)

func PostProcessDecisionResponse

func PostProcessDecisionResponse(
	resp *client.StructuredDecisionResponse,
	slotOpts map[string][]OptionItem,
	enableDualMirror bool,
	enableNullPrior bool,
	alpha float64,
) (map[string]float64, map[string]float64)

PostProcessDecisionResponse applies EXP-13B Null-Prior De-Biasing and/or EXP-13C O(1) Dual-Mirror Canvas distribution merging in-place on a StructuredDecisionResponse, returning per-slot Mirror TVD and Mirror JSD.

func PostProcessDecisionResponseDetailed

func PostProcessDecisionResponseDetailed(
	resp *client.StructuredDecisionResponse,
	slotOpts map[string][]OptionItem,
	enableDualMirror bool,
	enableNullPrior bool,
	alpha float64,
) map[string]SlotIDCDetail

PostProcessDecisionResponseDetailed is PostProcessDecisionResponse plus per-slot raw/processed distributions.

func SaveSuite

func SaveSuite(path string, cases []PermutationCase) error

SaveSuite writes the slice of PermutationCase to a JSONL file.

Types

type CasePermutationResult

type CasePermutationResult struct {
	ID                   string  `json:"id"`
	Regime               string  `json:"regime"`
	Title                string  `json:"title"`
	Cardinality          int     `json:"cardinality"`
	Expected             string  `json:"expected"`
	CanonicalWinner      string  `json:"canonical_winner"`
	CanonicalAccurate    bool    `json:"canonical_accurate"`
	CanonicalConfidence  float64 `json:"canonical_confidence"`
	CanonicalEntropy     float64 `json:"canonical_entropy"`
	CanonicalNormalizedH float64 `json:"canonical_normalized_h"`
	CanonicalBrier       float64 `json:"canonical_brier"`
	// Cyclic K-permutation metrics (Raw)
	CyclicPasses         []PermPassTelemetry `json:"cyclic_passes"`
	RawFlipOccurred      bool                `json:"raw_flip_occurred"` // Did argmax change across any cyclic shift?
	RawDistinctWinners   int                 `json:"raw_distinct_winners"`
	RawMajorityAgreement float64             `json:"raw_majority_agreement"` // Fraction of K shifts agreeing with mode
	RawMeanEntropy       float64             `json:"raw_mean_entropy"`       // E_pi[H(p_pi)] (Aleatoric / Within-pass)
	RawEntropyStdDev     float64             `json:"raw_entropy_stddev"`
	RawTotalEntropy      float64             `json:"raw_total_entropy"`      // H(E_pi[p_pi]) (Total uncertainty)
	RawJSDivergence      float64             `json:"raw_js_divergence_nats"` // I(Y; Pi | X) = H(bar_p) - bar_H (Epistemic)
	RawMaxTVD            float64             `json:"raw_max_tvd"`
	RawEnsembleWinner    string              `json:"raw_ensemble_winner"`
	RawEnsembleAccurate  bool                `json:"raw_ensemble_accurate"`
	RawEnsembleBrier     float64             `json:"raw_ensemble_brier"`
	// Content-Free Prior De-Biased metrics (13B)
	DebiasedFlipOccurred   bool    `json:"debiased_flip_occurred"`
	DebiasedJSDivergence   float64 `json:"debiased_js_divergence_nats"`
	DebiasedCanonicalAcc   bool    `json:"debiased_canonical_accurate"`
	DebiasedCanonicalBrier float64 `json:"debiased_canonical_brier"`
	// O(1) Single-Pass Dual-Mirror Canvas metrics (13C)
	DualMirror DualMirrorResult `json:"dual_mirror"`
}

CasePermutationResult aggregates all K cyclic permutations + Prior De-biasing + O(1) Dual-Mirror readout for one case.

func EvaluateFullCase

func EvaluateFullCase(ctx context.Context, cli *client.Client, c PermutationCase, np *NullPrior, alpha, gateNormH float64) (CasePermutationResult, error)

EvaluateFullCase runs all K cyclic shifts + Prior De-biasing + O(1) Dual-Mirror Canvas for one PermutationCase.

type DualMirrorResult

type DualMirrorResult struct {
	FwdProbs          map[string]float64 `json:"fwd_probs"`
	RevProbs          map[string]float64 `json:"rev_probs"`
	EnsembleProbs     map[string]float64 `json:"ensemble_probs"`
	FwdWinner         string             `json:"fwd_winner"`
	RevWinner         string             `json:"rev_winner"`
	EnsembleWinner    string             `json:"ensemble_winner"`
	MirrorDisagreed   bool               `json:"mirror_disagreed"` // True if FwdWinner != RevWinner
	MeanPassEntropy   float64            `json:"mean_pass_entropy"`
	TotalEntropy      float64            `json:"total_entropy"`      // H(EnsembleProbs) = MeanPassEntropy + JSDivergence
	NormalizedTotalH  float64            `json:"normalized_total_h"` // H(EnsembleProbs) / ln(K)
	JSDivergence      float64            `json:"js_divergence_nats"` // Epistemic permutation disagreement I(Y; Pi | X)
	NormalizedJSD     float64            `json:"normalized_jsd"`     // JSD / ln(2) in [0, 1]
	TVD               float64            `json:"tvd"`                // 0.5 * sum |p_fwd - p_rev|
	Accurate          bool               `json:"accurate"`
	EscalatedBySingle bool               `json:"escalated_by_single"` // H_norm(fwd) >= threshold
	EscalatedByMirror bool               `json:"escalated_by_mirror"` // MirrorDisagreed || NormalizedTotalH >= threshold || NormalizedJSD >= 0.08
	WallTimeMs        float64            `json:"wall_time_ms"`
}

DualMirrorResult records the O(1) Single-Pass Dual-Mirror Canvas readout (slot_fwd + slot_rev in 1 pass).

func EvaluateDualMirrorSinglePass

func EvaluateDualMirrorSinglePass(ctx context.Context, cli *client.Client, c PermutationCase, gateNormH float64) (DualMirrorResult, error)

EvaluateDualMirrorSinglePass places BOTH `decision_fwd` ([o_1..o_K]) and `decision_rev` ([o_K..o_1]) onto the SAME diffusion canvas in a SINGLE O(1) forward pass (reads=1)!

type NullPrior

type NullPrior struct {
	ByCardinality  map[int][]float64 `json:"by_cardinality"`
	EntropyByK     map[int]float64   `json:"entropy_by_k"`
	UniformEntropy map[int]float64   `json:"uniform_entropy_by_k"`
	MaxBiasRatio   map[int]float64   `json:"max_bias_ratio_by_k"` // max(p_0) / (1/K)
}

NullPrior holds the measured content-free positional probability distribution p_0(pos_0 .. pos_{K-1}) for each cardinality K (e.g. K=2, 3, 4).

func DefaultCalibratedNullPriors

func DefaultCalibratedNullPriors() NullPrior

DefaultCalibratedNullPriors returns the empirically measured content-free positional null priors p_0(k) from EXP-13B on Cloud Run DiffusionGemma (plus analytical primacy-recency interpolation for K >= 5).

func MeasureNullPrior

func MeasureNullPrior(ctx context.Context, cli *client.Client) (*NullPrior, error)

MeasureNullPrior queries the model once with a content-free state containing K=2, K=3, and K=4 neutral slots in a single O(1) forward pass to measure the positional letter prior p_0(pos_0 .. pos_{K-1}).

type OptionItem

type OptionItem struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

OptionItem represents a single semantic option with a stable key and description.

func CyclicShift

func CyclicShift(opts []OptionItem, r int) []OptionItem

CyclicShift returns the r-th cyclic shift of options: out[i] = opts[(i+r)%len(opts)].

func ReverseOptions

func ReverseOptions(opts []OptionItem) []OptionItem

ReverseOptions returns the reversed slice of options: out[i] = opts[n-1-i].

type PermPassTelemetry

type PermPassTelemetry struct {
	PermIndex      int                `json:"perm_index"`
	OptionOrder    []string           `json:"option_order"` // Order of option keys bound to [A, B, C, ...]
	RawProbs       map[string]float64 `json:"raw_probs"`    // Keyed by semantic OptionItem.Name
	DebiasedProbs  map[string]float64 `json:"debiased_probs,omitempty"`
	RawWinner      string             `json:"raw_winner"`
	DebiasedWinner string             `json:"debiased_winner,omitempty"`
	RawEntropy     float64            `json:"raw_entropy"`
	NormalizedH    float64            `json:"normalized_entropy"`
	WallTimeMs     float64            `json:"wall_time_ms"`
}

PermPassTelemetry records the outcome of evaluating one specific permutation pi_r of a question.

type PermutationCase

type PermutationCase struct {
	ID           string       `json:"id"`
	Regime       string       `json:"regime"` // "consensus", "ambiguous_chaosnli", "adversarial_trap", "binary_ablation"
	Title        string       `json:"title"`
	State        string       `json:"state"`
	Instructions string       `json:"instructions"`
	Options      []OptionItem `json:"options"`
	Expected     string       `json:"expected"`
}

PermutationCase represents one evaluation item in the EXP-13 Permutation Sensitivity suite.

func DefaultPermutationSuite

func DefaultPermutationSuite() []PermutationCase

DefaultPermutationSuite returns 16 stratified evaluation cases across 4 epistemic regimes:

  1. "consensus" (4 cases): Unambiguous factual/policy cases where semantic signal s(o_k|X) >> beta(letter).
  2. "ambiguous_chaosnli" (4 cases): Genuine 50/50 or 33/33/34 ChaosNLI & policy splits where letter-position bias can induce false low entropy in a single pass, but flips when options are cyclically shifted or mirrored.
  3. "adversarial_trap" (4 cases): JevBench Hard / ANLI-R3 multi-clause precedence & distractor traps where the surface distractor is placed in slot 'A' (index 0) to test whether positional prior pulls the model into a false-confident error.
  4. "binary_ablation" (4 cases): Borderline 2-option decisions where 'A' vs 'B' ordering tests first-option bias.

func LoadOrSaveSuite

func LoadOrSaveSuite(path string) ([]PermutationCase, error)

LoadOrSaveSuite loads a JSONL file of PermutationCase items, or initializes DefaultPermutationSuite().

type PermutationReport

type PermutationReport struct {
	Timestamp              string                  `json:"timestamp"`
	Endpoint               string                  `json:"endpoint"`
	Model                  string                  `json:"model"`
	GateThresholdNormH     float64                 `json:"gate_threshold_normalized_h"`
	PriorDampingAlpha      float64                 `json:"prior_damping_alpha"`
	NullPrior              *NullPrior              `json:"null_prior"`
	TotalCases             int                     `json:"total_cases"`
	CanonicalAccuracyPct   float64                 `json:"canonical_accuracy_pct"`
	DebiasedAccuracyPct    float64                 `json:"debiased_accuracy_pct"`
	DualMirrorAccuracyPct  float64                 `json:"dual_mirror_accuracy_pct"`
	CyclicEnsembleAccPct   float64                 `json:"cyclic_ensemble_accuracy_pct"`
	RawFlipRatePct         float64                 `json:"raw_flip_rate_pct"`
	DebiasedFlipRatePct    float64                 `json:"debiased_flip_rate_pct"`
	FlipReductionRelPct    float64                 `json:"flip_reduction_relative_pct"`
	CanonicalBrier         float64                 `json:"canonical_brier"`
	DebiasedBrier          float64                 `json:"debiased_brier"`
	DualMirrorBrier        float64                 `json:"dual_mirror_brier"`
	MeanSinglePassNormH    float64                 `json:"mean_single_pass_normalized_h"`
	MeanCyclicJSD          float64                 `json:"mean_cyclic_jsd_nats"`
	MeanMirrorJSD          float64                 `json:"mean_mirror_jsd_nats"`
	FalseConfidentErrors   int                     `json:"false_confident_errors_single_pass"` // Wrong in pass 1 AND H_norm < threshold
	CaughtByDualMirror     int                     `json:"caught_by_dual_mirror_gate"`         // How many of those false-confident errors Dual-Mirror caught!
	SingleGateErrRecallPct float64                 `json:"single_gate_error_recall_pct"`
	MirrorGateErrRecallPct float64                 `json:"mirror_gate_error_recall_pct"`
	MeanSingleLatencyMs    float64                 `json:"mean_single_latency_ms"`
	MeanMirrorLatencyMs    float64                 `json:"mean_mirror_latency_ms"`
	Regimes                []RegimeSummary         `json:"regimes"`
	Cases                  []CasePermutationResult `json:"cases"`
}

PermutationReport is the top-level EXP-13 JSON receipt.

func BuildPermutationReport

func BuildPermutationReport(endpoint, model string, gateNormH, alpha float64, np *NullPrior, results []CasePermutationResult) *PermutationReport

BuildPermutationReport aggregates CasePermutationResults into the complete EXP-13 report.

type RegimeSummary

type RegimeSummary struct {
	Regime                string  `json:"regime"`
	Cases                 int     `json:"cases"`
	CanonicalAccuracyPct  float64 `json:"canonical_accuracy_pct"`
	DualMirrorAccuracyPct float64 `json:"dual_mirror_accuracy_pct"`
	RawFlipRatePct        float64 `json:"raw_flip_rate_pct"`
	DebiasedFlipRatePct   float64 `json:"debiased_flip_rate_pct"`
	MeanSingleNormalizedH float64 `json:"mean_single_normalized_h"`
	MeanCyclicJSD         float64 `json:"mean_cyclic_jsd_nats"`
	MeanMirrorJSD         float64 `json:"mean_mirror_jsd_nats"`
	MeanMirrorTVD         float64 `json:"mean_mirror_tvd"`
	SingleGateRecallOnErr float64 `json:"single_gate_recall_on_errors_pct"`
	MirrorGateRecallOnErr float64 `json:"mirror_gate_recall_on_errors_pct"`
}

RegimeSummary aggregates permutation stability and error-detection metrics for one regime.

type SlotIDCDetail

type SlotIDCDetail struct {
	RawFwdProbs map[string]float64 `json:"raw_fwd_probs,omitempty"`
	RawRevProbs map[string]float64 `json:"raw_rev_probs,omitempty"`
	FwdProbs    map[string]float64 `json:"fwd_probs,omitempty"`
	RevProbs    map[string]float64 `json:"rev_probs,omitempty"`
	MirrorTVD   float64            `json:"mirror_tvd"`
	MirrorJSD   float64            `json:"mirror_jsd"`
	HasMirror   bool               `json:"has_mirror"`
}

SlotIDCDetail records the raw and post-processed distributions for one slot so that receipts can be re-scored offline (merge rules, prior strength, mirror gates) without re-running the model.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL