The neural notebook
← All chapters

IV-57 / Part XIV · Fine-Tuning and Alignment

Preference Data and Optimization Objectives

Build a reference-relative preference loss from one authored response pair, derive all five sensitivities, and distinguish a ranking objective from probability mass, training and safety evidence.

Review the ideas this chapter uses

Suppose two answers to the same prompt are both reasonable, but an example labels one as preferred. How can we express that comparison as a numerical objective? We will calculate a loss that asks whether a policy favors the labeled answer more strongly than a reference does. The label supplies the preference; the calculation does not discover which answer is objectively better.

Learning objective: Define scored and ranked pairs and derive a transparent pairwise logistic objective. Review IV-55 — Pretraining, Fine-Tuning and Transfer for what changes during adaptation, and VII.1 — Logarithms and log probabilities in computation for natural logarithms and log-probabilities.

Our fixed, author-written prompt is “Suggest a short break”. Response A is “Stretch your arms for a moment”; response B is “Look away from your screen for a moment”. The default label chooses A. These texts, labels and numerical inputs are teaching examples, not model generations or measured human preferences. Neither response is declared better or safer.

Start with four log-probabilities equal to −2-2, label A, and comparison scale 11. The policy and reference then have equal chosen-versus-rejected log-probability gaps. Their relative margin is zero, the pairwise preference probability is 1/21/2, and the exact real loss is ln⁡2\ln 2. The policy’s probability of A is instead exp⁡(−2)\exp(-2). Understanding why those two probabilities differ is our first goal.

Source checkpoint: The lab below consumes the actual IV57 calculation, and the two Python panels later display its complete canonical reference files. The source panels are not evidence of import, numerical-check or rendered-interaction results.

Compute it yourself

Preference Data and Optimization Objectives

Compare two authored responses with a reference-relative pairwise objective. Edit four log-probabilities, the strict preference label and beta to recompute the complete saved calculation. Default log-probabilities are all -2, A is chosen, and beta is 1.

The five numeric fields accept finite values in their stated ranges; beta also accepts -0. Invalid or unfinished drafts withhold results and graded questions until every field is valid. Reset restores the default. Changing an input or the trace step clears answers. No model is trained or updated.

preferenceLoss0.6931471805599453
relativeMargin0
pairwisePreferenceProbability0.5
policyChosenGradient-0.5
Exact starting inputs for this saved calculation

preferenceLoss 0.6931471805599453. relativeMargin 0. pairwisePreferenceProbability 0.5. policyChosenGradient -0.5. Set up one authored preference pair and a fixed reference comparison. The prompt and both responses are authored examples. Four independent log-probability inputs represent policy and reference scores for A and B; a discrete label chooses their comparison order. Evaluate the objective and sensitivities without updating any model or renormalizing this pair.

Set up one authored preference pair and a fixed reference comparison

raw=[policyA,policyB,referenceA,referenceB,preferred,beta]; mask=[1,1,0,0,0]; optimizerSteps=0

The prompt and both responses are authored examples. Four independent log-probability inputs represent policy and reference scores for A and B; a discrete label chooses their comparison order. Evaluate the objective and sensitivities without updating any model or renormalizing this pair.

Saved inputs

policyA
-2
policyB
-2
referenceA
-2
referenceB
-2
preferred
0
beta
1

Saved outputs

policyA
-2
policyB
-2
referenceA
-2
referenceB
-2
preferred
0
beta
1
pairCount
1
responseCount
2
differentiableCoordinates
5
policyCoordinates
2
frozenCoordinates
3
optimizerSteps
0

One authored pair, two different model distributions

Prompt: Suggest a short break

Authored responses and the current strict preference
ResponseExact authored textLabel role
AStretch your arms for a momentchosen
BLook away from your screen for a momentrejected

Preferred zero chooses A and one chooses B. These are author-written responses and an illustrative editable ranking, not model outputs, measured human-study preferences, objective truth or a safety judgment. Numeric ranking scores and ties are outside this strict-label example.

Self-authored fixed prompt, two benign responses, log-probability defaults and editable strict ranking. This chapter evaluates a transparent pairwise objective without training a model, measuring human preferences or certifying alignment. Runtime validation remains deferred under the FluxGeo hold.

A log-probability is the natural logarithm of a response probability. A policy is the distribution being compared; the reference is a separate comparison distribution. Chosen and rejected identify the authored ranking within this pair. No token model or annotator runs here.

Whole current root: six saved raw inputs
Raw fieldSaved numberMeaning and domain
policyA-2Natural-log probability; finite [-8,-1]; WORD
policyB-2Natural-log probability; finite [-8,-1]; WORD
referenceA-2Natural-log probability; finite [-8,-1]; WORD
referenceB-2Natural-log probability; finite [-8,-1]; WORD
preferred00 chooses A, 1 chooses B; discrete VALUE
beta1Comparison scale; finite [0,2], including -0; WORD

One prompt-response pair has scalar log-probabilities, margin, logistic probabilities and loss. Raw log-probabilities form [Model=2,Response=2] in policy/reference then A/B order. The five derivative coordinates are policyA,policyB,referenceA,referenceB,beta. There is no token, batch, hidden mean or parameter axis; preferred has no derivative.

Raw probability and mass outside the pair

Both models: raw response probabilities, pair sums and remaining masses
Modellog P(A)log P(B)Raw P(A)Raw P(B)Saved pair sumSaved remaining mass
policy-2-20.13533528323661270.13533528323661270.27067056647322540.7293294335267746
reference-2-20.13533528323661270.13533528323661270.27067056647322540.7293294335267746

Exponentiate each of the four raw log-probabilities separately. Add the policy pair and reference pair, then compute each remaining mass as1-sum. Positive remaining mass belongs to unspecified other outcomes. Never divide by the two-response sum: the pair is not a complete modeled distribution.

At the default, raw P(A)=exp(-2), while pairwise p=1/2. The raw probabilities come from four separate exp calls, and the remaining mass is saved as 1 minus each saved pair sum. A common allowed shift of both policy log-probabilities changes these probabilities and remaining mass while preserving the policy log gap and the real preference loss.

Copy chosen and rejected scores, then subtract the reference gap

Chosen and rejected log-probability copies for both models
ModelChosen responseChosen log-probabilityRejected responseRejected log-probability
policyA-2B-2
referenceA-2B-2

Copy chosen and rejected log-probabilities by the label. Compute dPolicy=chosenPolicy-rejectedPolicy, dReference=chosenReference-rejectedReference, delta=dPolicy-dReference and margin=beta*delta, in that order. The reference subtracts its own preference rather than supplying a target probability.

Saved relative gaps and scaled margin
FieldActual saved value
dPolicy0
dReference0
delta0
margin0

A difference of natural log-probabilities is a log probability ratio. Delta subtracts the reference’s chosen-to-rejected log ratio from the policy’s. A positive policy gap can still give negative delta if the reference gap is larger. Beta multiplies delta; beta is a comparison scale rather than a learning rate.

Chosen/rejected copy and reference-relative subtraction operands

pair_selection: Use the label to select chosen and rejected log-probabilities

chosenPolicy=preferred==0?policyA:policyB; rejectedPolicy=preferred==0?policyB:policyA; chosenReference=preferred==0?referenceA:referenceB; rejectedReference=preferred==0?referenceB:referenceA

Label zero chooses A; label one chooses B. These are copies of the actual raw log-probabilities. The authored label is a ranking for this example, not evidence of truth or safety.

Saved inputs
preferred
0
policyA
-2
policyB
-2
referenceA
-2
referenceB
-2
Saved outputs
chosenPolicy
-2
rejectedPolicy
-2
chosenReference
-2
rejectedReference
-2

pair_relative: Compare the policy preference against the reference preference

dPolicy=chosenPolicy-rejectedPolicy; dReference=chosenReference-rejectedReference; delta=dPolicy-dReference; margin=beta*delta

Each difference is in natural-log units. Delta measures the change in the labeled preference relative to the reference; beta scales that comparison. These are separate saved subtractions and one multiplication, including beta zero.

Saved inputs
chosenPolicy
-2
rejectedPolicy
-2
chosenReference
-2
rejectedReference
-2
beta
1
Saved outputs
dPolicy
0
dReference
0
delta
0
margin
0

One stable exponential feeds direct p, direct q and the loss

Compute negMargin=-margin, absMargin=abs(margin), expArgument=-absMargin, t=exp(expArgument), denominator=1+t. If margin>=0, probability=1/denominator then complement=t/denominator; otherwise probability=t/denominator then complement=1/denominator. Next compute logPart=log1p(t), positivePart=max(+0,negMargin), loss=positivePart+logPart. Complement is never1-probability.

Every saved stable-objective intermediate
Stable field in dependency orderActual saved value
negMargin-0
absMargin0
expArgument-0
t1
denominator2
probability0.5
complement0.5
logPart0.6931471805599453
positivePart0
loss0.6931471805599453

The saved margin is 0. This evaluation used the nonnegative branch: p=1/denominator and q=t/denominator. Both signed zeros use the nonnegative branch. p is the logistic preference probability; q is its directly evaluated counterpart, never a UI subtraction of p from one.

The mathematical loss is L=log(1+exp(-m)), where m is the relative margin. Numerically it is max(+0,-m)+log1p(exp(-abs(m))). The real function is smooth at zero even though this stable evaluation uses abs and max. Each margin and loss is a scalar for one pair, with no batch mean. The argument -abs(m) stays between -28 and zero; log1p computes the small logarithmic part without first rounding 1+t in this producer.

All stable branches, divisions and loss operands as saved text

pair_stability: Prepare one bounded exponential argument

negMargin=-margin; absMargin=abs(margin); expArgument=-absMargin

The stable exponential argument is between -28 and zero. At either signed margin zero, abs returns positive zero and its negation is negative zero. The same exponential will feed both probabilities and the loss.

Saved inputs
margin
0
Saved outputs
negMargin
-0
absMargin
0
expArgument
-0

pair_stable_exp: Evaluate this actual exponential occurrence

value=exp(argument)

Record this call separately even when another argument is equal. Raw response probabilities and the stable loss term have distinct occurrences.

Saved inputs
argument
-0
Saved outputs
value
1

pair_denominator: Add the shared stable denominator

denominator=1+t

Keep this actual rounded addition for both direct ratios. No second exponential is evaluated for a negative margin.

Saved inputs
one
1
t
1
Saved outputs
denominator
2

pair_sigmoids: Compute both logistic probabilities by direct division

if margin>=0: probability=1/denominator; complement=t/denominator; else: probability=t/denominator; complement=1/denominator

Probability is sigmoid(margin), not the raw policy probability of the chosen response. Complement is sigmoid(-margin), computed directly rather than by subtracting probability from one. Either signed zero uses the nonnegative branch.

Saved inputs
margin
0
t
1
denominator
2
one
1
Saved outputs
probability
0.5
complement
0.5

pair_log1p: Evaluate the actual stable logarithm occurrence

value=log1p(argument)

Reuse the actual stable exponential as the argument. log1p evaluates log(1+argument) without first rounding that addition in this producer.

Saved inputs
argument
1
Saved outputs
value
0.6931471805599453

pair_loss: Add the two stable parts of the pairwise logistic loss

positivePart=max(+0,negMargin); loss=positivePart+logPart

This equals log(1+exp(-margin)) in real arithmetic. The maximum chooses positive zero at either zero tie. There is one pair, no hidden batch average and no optimizer update.

Saved inputs
positiveZero
0
negMargin
-0
logPart
0.6931471805599453
Saved outputs
positivePart
0
loss
0.6931471805599453

All six actual elementary occurrences

Native calls: identity, kind, equation, actual argument and returned result
Call ID in orderKindSaved equationActual argumentActual returned value
pair_policyA_expexpvalue=exp(argument)-20.1353352832366127
pair_policyB_expexpvalue=exp(argument)-20.1353352832366127
pair_referenceA_expexpvalue=exp(argument)-20.1353352832366127
pair_referenceB_expexpvalue=exp(argument)-20.1353352832366127
pair_stable_expexpvalue=exp(argument)-01
pair_log1plog1pvalue=log1p(argument)10.6931471805599453

Equal arguments do not merge occurrences. Four raw exp calls recover response probabilities; a fifth exp supplies the shared stable t; log1p consumes that saved t. The table reads the saved Elementary tensor, IDs, kinds and actual call frames. Moving the trace cursor only selects evidence from the same completed calculation.

Each stated arithmetic primitive is a separate finite binary64 operation with round-to-nearest ties-to-even, no contraction or reassociation. Save the actual native exp/log1p arguments and results in six distinct frames before independent assessment. Display precision never feeds computation; formal gradients evaluate the smooth real chain rule at stored values, not derivatives of the rounding map.

Five formal sensitivities, then five effective selections

The chain rule gives dL/dm=-q. A partial derivative changes one numeric coordinate while holding the other inputs fixed. For chosen policy the sensitivity is -beta×q; for rejected policy it is +beta×q. Reference chosen/rejected sensitivities copy the opposite products. Beta’s formal sensitivity is -delta×q. The discrete preferred label has no derivative.

Saved chain-rule signs and three gradient products
Product fieldActual saved value
negativeBeta-1
negativeDelta-0
minus-0.5
plus0.5
betaFormal-0

The smooth real loss has margin derivative -complement. Compute negativeBeta=-beta, negativeDelta=-delta, minus=negativeBeta*complement, plus=beta*complement and betaFormal=negativeDelta*complement. For label0 map [minus,plus,plus,minus,betaFormal]; for label1 map [plus,minus,minus,plus,betaFormal]. Reference components are exact copies of the actual policy products.

All five derivative coordinates: formal partial, mask and effective selection
CoordinateFormal sensitivityMask (integer VALUE)Effective sensitivity
policyA-0.51-0.5
policyB0.510.5
referenceA0.500
referenceB-0.500
beta-000

All five formal partials describe independently varied coordinates with the other inputs held fixed. Select mask[1,1,0,0,0]: policy entries copy their formal values; frozen reference and beta entries are explicit floating positive zeros. Frozen does not mean a zero formal derivative or reset reference scores. No update or optimizer is run.

At beta zero the real loss is ln2 and policy/reference gradient magnitudes are zero, but formal beta sensitivity is -delta/2 and can be nonzero. Increasing beta decreases real loss when delta>0 and increases it when delta<0. A smaller objective value alone does not establish better response quality.

Beta positive or negative zero still evaluates all five exp calls, the log1p call and every declared arithmetic operation. Both signed margin zeros use the nonnegative branch; abs gives positive zero, expArgument negative zero, and max(+0,negMargin) positive zero. Preserve every raw/arithmetic/copy word; at default delta positive zero gives betaFormal negative zero. Frozen effective zeros are positive zero.

For example, policyA=-1, policyB=-2, referenceA=referenceB=-2, preferred=0, beta=+0 gives delta=1 and formal beta=-1/2, although all four formal log-probability sensitivities have zero magnitudes. With beta=-0 those zero signs differ. At the default, formal beta is -0; its effective frozen entry is +0. This display preserves stored -0 instead of replacing it with 0.

All gradient products, coordinate copies and frozen-zero operands

pair_gradient_products: Apply the chain rule to the saved direct complement

negativeBeta=-beta; negativeDelta=-delta; minus=negativeBeta*complement; plus=beta*complement; betaFormal=negativeDelta*complement

The real derivative of loss with respect to margin is -complement. Compute both signed beta products separately and retain beta sensitivity even when beta is frozen or zero. These are rounded evaluations of real partial derivatives, not derivatives of rounding.

Saved inputs
beta
1
delta
0
complement
0.5
Saved outputs
negativeBeta
-1
negativeDelta
-0
minus
-0.5
plus
0.5
betaFormal
-0

pair_formal: Map all five formal partials back to raw coordinate order

preferred==0?[minus,plus,plus,minus,betaFormal]:[plus,minus,minus,plus,betaFormal]

Coordinate order is policyA, policyB, referenceA, referenceB, beta. Reference derivatives copy the actual opposite policy products. Preferred is discrete and has no derivative; holding the other inputs fixed still defines formal reference and beta sensitivities.

Saved inputs
preferred
0
minus
-0.5
plus
0.5
betaFormal
-0
Saved outputs
policyA
-0.5
policyB
0.5
referenceA
0.5
referenceB
-0.5
beta
-0

pair_mask: Select policy sensitivities and explicit frozen positive zeros

effective_i=enabled_i==1?formal_i:+0; mask=[1,1,0,0,0]

Enabled policy entries copy their formal words, including signed zeros. Frozen reference and beta entries are explicit positive zeros, not products with zero. Freezing does not reset reference scores, erase formal derivatives or perform an update.

Saved inputs
positiveZero
0
formal0
-0.5
enabled0
1
formal1
0.5
enabled1
1
formal2
0.5
enabled2
0
formal3
-0.5
enabled3
0
formal4
-0
enabled4
0
Saved outputs
effective0
-0.5
effective1
0.5
effective2
0
effective3
0
effective4
0

Count the actual declared work, without inferring training or speed

Saved setup counts and complete work counts from finish
Saved counterActual integer value
setup.pairCount1
setup.responseCount2
setup.differentiableCoordinates5
setup.policyCoordinates2
setup.frozenCoordinates3
setup.optimizerSteps0
finish.rawExponentialCalls4
finish.stableExponentialCalls1
finish.exponentialCalls5
finish.log1pCalls1
finish.pairSumAdditions2
finish.remainingMassSubtractions2
finish.logDifferenceSubtractions2
finish.relativeSubtractions1
finish.marginMultiplications1
finish.marginNegations1
finish.absoluteValues1
finish.stableArgumentNegations1
finish.denominatorAdditions1
finish.probabilityDivisions2
finish.lossMaxSelections1
finish.lossAdditions1
finish.gradientNegations2
finish.gradientMultiplications3
finish.chosenRejectedCopies4
finish.formalCoordinateCopies5
finish.effectiveCoordinateSelections5
finish.enabledGradientCopies2
finish.frozenPositiveZeros3
finish.elementaryOccurrences6
finish.frames18
finish.tensorCount11

Work counts describe one evaluation of the declared graph, including all four raw probability displays, one shared stable exponential, one log1p, all formal coordinates and all five effective selections. Copy counts cover the named selection/mapping stages, not serialization or snapshot storage. Frames include setup and finish; tensorCount includes every helper tensor. Counts are source bookkeeping, not timings or hardware evidence.

The real margin stays in [-28,28]. The stable exponential cannot overflow or underflow in that interval, while other small-beta products may round to signed zero. Log-probability coordinates are editable sensitivities, not already network-logit or neural-parameter gradients; normalized model constraints need an additional chain rule.

Small loss measures agreement with this reference-relative authored ranking. It supplies no factual or safety judgment, annotator agreement, normalized model update or population evaluation. Increasing beta helps this real objective only for positive delta; a negative delta reverses that effect. At very favorable margins the logistic sensitivity becomes small, which is saturation rather than proof of response quality.

Numerical admission and the narrowly conditional default derivative diagnostic

A separate authority may admit each producer own native words within four ordered finite binary64 word steps of an independently proved correctly rounded reference. Exp at either signed zero requires the exact positive-one word. Then exact-RN replay binds all arithmetic and copies. This per-call policy is not a whole-gradient tolerance, cross-language word equality or physical runtime provenance proof; unresolved reference enclosures fail closed.

The exact-zero centered-difference proof is restricted to all four raw log-probabilities WORD-2, preferred VALUE0, beta WORD+1, policy coordinate0or1 and h WORD2^-10. Verify the complete actual central record, both complete actual endpoint helpers, every native occurrence, paired stable-exp/log1p argument and result words, the common-logPart binade and all exact loss-difference/quotient/gradient words before any zero verdict. Any failed premise fails closed; no other state or coordinate inherits this claim.

No native call, complete record or finite-difference packet has been verified by this view. The UI reads the producer’s saved records; it does not issue an authority verdict.

Complete saved operation text fallback: every frame in trace order

setup: Set up one authored preference pair and a fixed reference comparison

raw=[policyA,policyB,referenceA,referenceB,preferred,beta]; mask=[1,1,0,0,0]; optimizerSteps=0

The prompt and both responses are authored examples. Four independent log-probability inputs represent policy and reference scores for A and B; a discrete label chooses their comparison order. Evaluate the objective and sensitivities without updating any model or renormalizing this pair.

Saved inputs
policyA
-2
policyB
-2
referenceA
-2
referenceB
-2
preferred
0
beta
1
Saved outputs
policyA
-2
policyB
-2
referenceA
-2
referenceB
-2
preferred
0
beta
1
pairCount
1
responseCount
2
differentiableCoordinates
5
policyCoordinates
2
frozenCoordinates
3
optimizerSteps
0

pair_policyA_exp: Evaluate this actual exponential occurrence

value=exp(argument)

Record this call separately even when another argument is equal. Raw response probabilities and the stable loss term have distinct occurrences.

Saved inputs
argument
-2
Saved outputs
value
0.1353352832366127

pair_policyB_exp: Evaluate this actual exponential occurrence

value=exp(argument)

Record this call separately even when another argument is equal. Raw response probabilities and the stable loss term have distinct occurrences.

Saved inputs
argument
-2
Saved outputs
value
0.1353352832366127

pair_referenceA_exp: Evaluate this actual exponential occurrence

value=exp(argument)

Record this call separately even when another argument is equal. Raw response probabilities and the stable loss term have distinct occurrences.

Saved inputs
argument
-2
Saved outputs
value
0.1353352832366127

pair_referenceB_exp: Evaluate this actual exponential occurrence

value=exp(argument)

Record this call separately even when another argument is equal. Raw response probabilities and the stable loss term have distinct occurrences.

Saved inputs
argument
-2
Saved outputs
value
0.1353352832366127

pair_masses: Keep the probability mass outside the two authored responses

policySum=policyProbabilityA+policyProbabilityB; referenceSum=referenceProbabilityA+referenceProbabilityB; policyRemaining=1-policySum; referenceRemaining=1-referenceSum

These are probabilities from log-probabilities, not a softmax over A and B. Their sums are below one in the admitted range; the rest belongs to unspecified other outcomes. Do not renormalize the pair.

Saved inputs
policyProbabilityA
0.1353352832366127
policyProbabilityB
0.1353352832366127
referenceProbabilityA
0.1353352832366127
referenceProbabilityB
0.1353352832366127
one
1
Saved outputs
policySum
0.2706705664732254
referenceSum
0.2706705664732254
policyRemaining
0.7293294335267746
referenceRemaining
0.7293294335267746

pair_selection: Use the label to select chosen and rejected log-probabilities

chosenPolicy=preferred==0?policyA:policyB; rejectedPolicy=preferred==0?policyB:policyA; chosenReference=preferred==0?referenceA:referenceB; rejectedReference=preferred==0?referenceB:referenceA

Label zero chooses A; label one chooses B. These are copies of the actual raw log-probabilities. The authored label is a ranking for this example, not evidence of truth or safety.

Saved inputs
preferred
0
policyA
-2
policyB
-2
referenceA
-2
referenceB
-2
Saved outputs
chosenPolicy
-2
rejectedPolicy
-2
chosenReference
-2
rejectedReference
-2

pair_relative: Compare the policy preference against the reference preference

dPolicy=chosenPolicy-rejectedPolicy; dReference=chosenReference-rejectedReference; delta=dPolicy-dReference; margin=beta*delta

Each difference is in natural-log units. Delta measures the change in the labeled preference relative to the reference; beta scales that comparison. These are separate saved subtractions and one multiplication, including beta zero.

Saved inputs
chosenPolicy
-2
rejectedPolicy
-2
chosenReference
-2
rejectedReference
-2
beta
1
Saved outputs
dPolicy
0
dReference
0
delta
0
margin
0

pair_stability: Prepare one bounded exponential argument

negMargin=-margin; absMargin=abs(margin); expArgument=-absMargin

The stable exponential argument is between -28 and zero. At either signed margin zero, abs returns positive zero and its negation is negative zero. The same exponential will feed both probabilities and the loss.

Saved inputs
margin
0
Saved outputs
negMargin
-0
absMargin
0
expArgument
-0

pair_stable_exp: Evaluate this actual exponential occurrence

value=exp(argument)

Record this call separately even when another argument is equal. Raw response probabilities and the stable loss term have distinct occurrences.

Saved inputs
argument
-0
Saved outputs
value
1

pair_denominator: Add the shared stable denominator

denominator=1+t

Keep this actual rounded addition for both direct ratios. No second exponential is evaluated for a negative margin.

Saved inputs
one
1
t
1
Saved outputs
denominator
2

pair_sigmoids: Compute both logistic probabilities by direct division

if margin>=0: probability=1/denominator; complement=t/denominator; else: probability=t/denominator; complement=1/denominator

Probability is sigmoid(margin), not the raw policy probability of the chosen response. Complement is sigmoid(-margin), computed directly rather than by subtracting probability from one. Either signed zero uses the nonnegative branch.

Saved inputs
margin
0
t
1
denominator
2
one
1
Saved outputs
probability
0.5
complement
0.5

pair_log1p: Evaluate the actual stable logarithm occurrence

value=log1p(argument)

Reuse the actual stable exponential as the argument. log1p evaluates log(1+argument) without first rounding that addition in this producer.

Saved inputs
argument
1
Saved outputs
value
0.6931471805599453

pair_loss: Add the two stable parts of the pairwise logistic loss

positivePart=max(+0,negMargin); loss=positivePart+logPart

This equals log(1+exp(-margin)) in real arithmetic. The maximum chooses positive zero at either zero tie. There is one pair, no hidden batch average and no optimizer update.

Saved inputs
positiveZero
0
negMargin
-0
logPart
0.6931471805599453
Saved outputs
positivePart
0
loss
0.6931471805599453

pair_gradient_products: Apply the chain rule to the saved direct complement

negativeBeta=-beta; negativeDelta=-delta; minus=negativeBeta*complement; plus=beta*complement; betaFormal=negativeDelta*complement

The real derivative of loss with respect to margin is -complement. Compute both signed beta products separately and retain beta sensitivity even when beta is frozen or zero. These are rounded evaluations of real partial derivatives, not derivatives of rounding.

Saved inputs
beta
1
delta
0
complement
0.5
Saved outputs
negativeBeta
-1
negativeDelta
-0
minus
-0.5
plus
0.5
betaFormal
-0

pair_formal: Map all five formal partials back to raw coordinate order

preferred==0?[minus,plus,plus,minus,betaFormal]:[plus,minus,minus,plus,betaFormal]

Coordinate order is policyA, policyB, referenceA, referenceB, beta. Reference derivatives copy the actual opposite policy products. Preferred is discrete and has no derivative; holding the other inputs fixed still defines formal reference and beta sensitivities.

Saved inputs
preferred
0
minus
-0.5
plus
0.5
betaFormal
-0
Saved outputs
policyA
-0.5
policyB
0.5
referenceA
0.5
referenceB
-0.5
beta
-0

pair_mask: Select policy sensitivities and explicit frozen positive zeros

effective_i=enabled_i==1?formal_i:+0; mask=[1,1,0,0,0]

Enabled policy entries copy their formal words, including signed zeros. Frozen reference and beta entries are explicit positive zeros, not products with zero. Freezing does not reset reference scores, erase formal derivatives or perform an update.

Saved inputs
positiveZero
0
formal0
-0.5
enabled0
1
formal1
0.5
enabled1
1
formal2
0.5
enabled2
0
formal3
-0.5
enabled3
0
formal4
-0
enabled4
0
Saved outputs
effective0
-0.5
effective1
0.5
effective2
0
effective3
0
effective4
0

finish: Report the same saved loss, relative margin and chosen-policy sensitivity

preferenceLoss=pair.loss; relativeMargin=pair.margin; pairwisePreferenceProbability=pair.probability; policyChosenGradient=pair.formalGradient[preferred==0?0:1]

These four summaries copy the complete evaluated pair. A lower loss means a more favorable labeled policy-versus-reference comparison under this objective. It establishes neither factual correctness nor safety. Counts describe the declared source operations, not measured time, memory, training or backend accuracy.

Saved inputs
loss
0.6931471805599453
margin
0
probability
0.5
preferred
0
chosenGradient
-0.5
Saved outputs
preferenceLoss
0.6931471805599453
relativeMargin
0
pairwisePreferenceProbability
0.5
policyChosenGradient
-0.5
rawExponentialCalls
4
stableExponentialCalls
1
exponentialCalls
5
log1pCalls
1
pairSumAdditions
2
remainingMassSubtractions
2
logDifferenceSubtractions
2
relativeSubtractions
1
marginMultiplications
1
marginNegations
1
absoluteValues
1
stableArgumentNegations
1
denominatorAdditions
1
probabilityDivisions
2
lossMaxSelections
1
lossAdditions
1
gradientNegations
2
gradientMultiplications
3
chosenRejectedCopies
4
formalCoordinateCopies
5
effectiveCoordinateSelections
5
enabledGradientCopies
2
frozenPositiveZeros
3
elementaryOccurrences
6
frames
18
tensorCount
11

All numbers above are saved round-trip decimal presentations, with negative zero shown as -0. Arithmetic values and floating copies retain WORD roles; labels, masks, indices and counts use VALUE roles. Display text never feeds computation. The house inspector below exposes all scalar aliases, full text metadata and all eleven tensors with axes, dtype, precision, provenance and storage indices from this same root.

IV-58 next considers alignment, safety and evaluation limits: the preference objective here supplies a training signal’s definition, while observed behavior needs separate evidence.

Inspect all stored values, text metadata and tensor storage

Every scalar output, including flattened operation outputs

Exact text evidence from the same record

These are the stored values, shown without display rounding. Each tensor names its axes, dtype and display precision. Empty arrays are omitted rather than padded.

pair_Raw

RawField=6 · float64 · precision 8 · Actual raw fields policyA,policyB,referenceA,referenceB,preferred,beta; preferred is an integer VALUE selector, all other entries preserve floating WORDs.

Zero-based storage indexStored value
0-2
1-2
2-2
3-2
40
51

pair_Probabilities

Model=2 × Response=2 · float64 · precision 8 · Actual four native raw exp results in policy then reference, A then B order; no pair renormalization.

Zero-based storage indexStored value
00.1353352832366127
10.1353352832366127
20.1353352832366127
30.1353352832366127

pair_Masses

Model=2 × MassField=2 · float64 · precision 8 · Actual saved pair sum and remaining mass for policy then reference; remaining=1-sum from each actual sum.

Zero-based storage indexStored value
00.2706705664732254
10.7293294335267746
20.2706705664732254
30.7293294335267746

pair_Selected

Model=2 × PreferenceRole=2 · float64 · precision 8 · Exact chosen then rejected raw log-probability copies, policy then reference; selection uses the discrete authored label.

Zero-based storage indexStored value
0-2
1-2
2-2
3-2

pair_Relative

RelativeField=4 · float64 · precision 8 · Actual saved dPolicy,dReference,delta,margin in dependency order; margin=beta*delta even for signed-zero beta.

Zero-based storage indexStored value
00
10
20
30

pair_Stable

StableField=10 · float64 · precision 8 · Actual negMargin,absMargin,expArgument,t,denominator,probability,complement,logPart,positivePart,loss; one shared stable exp and one log1p.

Zero-based storage indexStored value
0-0
10
2-0
31
42
50.5
60.5
70.6931471805599453
80
90.6931471805599453

pair_GradientProducts

GradientProductField=5 · float64 · precision 8 · Actual saved negativeBeta,negativeDelta,minus,plus,betaFormal; reference formal partials later copy the actual plus/minus words.

Zero-based storage indexStored value
0-1
1-0
2-0.5
30.5
4-0

pair_FormalGradient

Coordinate=5 · float64 · precision 8 · Actual five formal partials in policyA,policyB,referenceA,referenceB,beta order, including signed-zero words and frozen-coordinate sensitivities.

Zero-based storage indexStored value
0-0.5
10.5
20.5
3-0.5
4-0

pair_EffectiveGradient

Coordinate=5 · float64 · precision 8 · Actual selected formal policy copies followed by three explicit floating positive zeros; no optimizer or parameter update is performed.

Zero-based storage indexStored value
0-0.5
10.5
20
30
40

pair_Mask

Coordinate=5 · int32 · precision 0 · Actual selectors [1,1,0,0,0] in policyA,policyB,referenceA,referenceB,beta order; all entries are integer VALUE roles.

Zero-based storage indexStored value
01
11
20
30
40

pair_Elementary

NativeCall=6 × NativeField=2 · float64 · precision 8 · Actual native argument and returned value for each distinct raw policyA,policyB,referenceA,referenceB exp, then stable exp and log1p occurrence; IDs and kinds accompany this table in root texts.

Zero-based storage indexStored value
0-2
10.1353352832366127
2-2
30.1353352832366127
4-2
50.1353352832366127
6-2
70.1353352832366127
8-0
91
101
110.6931471805599453

Check your understanding

Use the inputs stated in each question. Live questions use the current calculation. Each option pairs a value or conclusion with its mechanism. Editing a raw input, resetting or selecting a trace step clears graded answers; local inspection selectors preserve them.

1. Fixed default: policyA=-2, policyB=-2, referenceA=-2, referenceB=-2, preferred=0, beta=1. What does pairwise p=1/2 mean?
2. Fixed nondefault: policyA=-1, policyB=-2, referenceA=-2, referenceB=-2, preferred=0, beta=1. Which dPolicy, dReference, delta, margin and stable loss are correct?
3. Compare two complete cases in coordinate order [policyA,policyB,referenceA,referenceB,beta]. D: (-2,-2,-2,-2,0,1). Z: (-1,-2,-2,-2,0,+0). Each tuple is [policyA,policyB,referenceA,referenceB,preferred,beta]. Which formal/effective vectors and shape are correct?
4. Current whole saved root: policyA=-2, policyB=-2, referenceA=-2, referenceB=-2, preferred=0, beta=1. dPolicy=0, dReference=0, delta=0, margin=0, p=0.5, q=0.5, loss=0.6931471805599453. With the four log-probabilities and label fixed, use this saved delta as the coefficient in the smooth real function L(beta)=log(1+exp(-beta×delta)). What does a sufficiently small allowed increase in beta do to the real objective? Read the whole root, independently of the selected trace step.
5. Fixed counterexample: policyA=-2, policyB=-3, referenceA=-1, referenceB=-3, preferred=0, beta=1. The policy ranks chosen A above B. Which conclusion respects the reference and the objective’s limits?

Exactly five graded questions use complete stated cases or the current whole root. There are no extra raw fields or local inspection selectors. The full saved-operation fallback and house tensor inspector can be opened with the keyboard; opening evidence does not change inputs or answers.

Read and edit one complete calculation

The four summaries are preferenceLoss, relativeMargin, pairwisePreferenceProbability and policyChosenGradient. They always describe the complete current calculation. Selecting an earlier trace frame changes which saved operation you inspect; it does not turn the summaries or fourth exercise into an earlier or partial calculation. The chosen-policy sensitivity is the formal derivative for whichever response the label chooses, rather than always the A coordinate.

There are exactly six controls, in raw input order. Policy log-probability of A (policyA), Policy log-probability of B (policyB), Reference log-probability of A (referenceA) and Reference log-probability of B (referenceB) are number inputs from -8 through -1. Authored preference label (preferred) is a dropdown: 0 — choose A; reject B or 1 — choose B; reject A. Comparison scale β (beta; includes -0) is a number input from 0 through 2. The five number inputs allow arbitrary steps; there is no training button or local coordinate selector.

Try changing only policy A from -2 to -1. Keep the other three scores at -2, choose A and leave beta at 1. Follow the saved policy gap, reference gap, delta and margin before reading the loss. Then change only the label to choose B and compare the direct probability divisions and the positive loss part. The complete hand calculation below explains both cases without presenting invented native decimal results.

Reset example restores all four scores to -2, label 0, beta 1, the first trace frame and unanswered exercises. Draft text is kept separately from admitted numerical state. An empty, nonfinite or out-of-range draft produces an alert and withholds summaries, trace, numerical evidence, inspector and questions until all six inputs are valid. Inputs are not clipped into range and an old successful calculation is not shown as though it belonged to an invalid draft. Valid number text is converted at this UI boundary; the numerical model itself rejects strings and booleans.

Use Previous step, Next step or Calculation step to inspect saved operands and results. Raw edits, reset and valid trace seeks clear graded answers; opening an evidence disclosure preserves them. The trace cursor is bounded to an integer index within the saved frames. All six native calls and all five derivative coordinates are shown together, so there is no separate local index that could select a different calculation. The display explicitly retains negative zero as -0.

Scores, rankings and log-probabilities have different jobs

A score is a number used to compare responses. Larger scores may mean stronger preference under a chosen scoring rule. A ranking gives an order: A preferred to B, or B preferred to A. For example, scores 5 and 3 rank A first; scores 100 and 0 give the same order but a different numerical gap. This lesson retains only the strict order as its preference label. A tie is outside this two-label example.

A probability assigns mass to an outcome. A log-probability is its natural logarithm: if the log-probability is aa, the probability is exp⁡(a)\exp(a). The natural logarithm, written ln⁡\ln, is the inverse of the exponential exp⁡\exp. These are probabilities of the complete authored responses for the fixed prompt. They are supplied numbers; no token model computes them here. An arbitrary rating gap such as 5−35-3 is not automatically a log-probability gap.

The policy is the distribution whose relative preference we inspect. The reference supplies a comparison distribution. “Chosen” means the response selected by the label; “rejected” means the other response in this pair. Rejected does not mean harmful or universally undesirable.

A loss is a numerical penalty: smaller values mean better agreement with this objective. A pairwise logistic probability describes the objective’s comparison of the two responses. It is neither the policy’s raw probability of the chosen response nor an empirically calibrated probability that a person will agree.

Six inputs, five differentiable coordinates

All inputs are dimensionless scalars: each is one number, with mathematical shape []. Log-probabilities and the loss use natural-log units, often called nats. There is one pair and no batch average.

Raw inputSymbolMeaningAdmitted valuesDefault
policyAaaPolicy log-probability of AFinite number in [−8,−1][-8,-1]−2-2
policyBbbPolicy log-probability of BFinite number in [−8,−1][-8,-1]−2-2
referenceAccReference log-probability of AFinite number in [−8,−1][-8,-1]−2-2
referenceBddReference log-probability of BFinite number in [−8,−1][-8,-1]−2-2
preferredyyWhich response is chosenNumeric 00 for A, 11 for B00
betaβ\betaNonnegative comparison scaleFinite number in [0,2][0,2], including negative zero11

The label yy is discrete: it selects an order and has no derivative. The five differentiable coordinates are (a,b,c,d,β)(a,b,c,d,\beta) in that order. A gradient collects a scalar loss’s partial derivatives with respect to these coordinates. A partial derivative measures the local effect of varying one coordinate while holding the others fixed.

Two response values form a length-two array in A, B order. The four log-probabilities can be arranged as a two-by-two explanatory table with model rows policy, reference and response columns A, B. A formal gradient and its selection mask each have five entries. A tensor is an array with named axes; these conceptual layouts do not invent an extra sample axis or matrix multiplication. The actual inspector stores margin and loss as scalar fields; it adds no singleton tensor.

An input record must contain exactly the six own data fields, on an ordinary or null-prototype object. Accessors, missing or extra fields, and inherited substitutes are rejected. After that structural stage, all six values must be actual finite numbers before any range is checked. Thus an out-of-range aa together with infinite β\beta is a finite-number failure first. Strings and booleans do not become valid through conversion. Inputs are neither clamped nor completed with partial defaults. Numeric label negative zero selects A by value; beta’s negative-zero word is preserved.

First keep the raw probability mass

Recover the four probabilities in input order:

PA=exp⁡(a),PB=exp⁡(b),RA=exp⁡(c),RB=exp⁡(d).P_A=\exp(a),\quad P_B=\exp(b),\quad R_A=\exp(c),\quad R_B=\exp(d).

Here PP names policy probabilities and RR reference probabilities. Next form the policy sum SP=PA+PBS_P=P_A+P_B and reference sum SR=RA+RBS_R=R_A+R_B, then their remaining masses 1−SP1-S_P and 1−SR1-S_R. These remaining masses belong to outcomes outside the selected pair.

Every raw probability is at most exp⁡(−1)\exp(-1). Since exp⁡(1)>2\exp(1)>2, each pair sum is strictly below one in exact real arithmetic. The two selected responses can therefore coexist with other outcomes in a full distribution. We do not specify those other outcomes or divide the two displayed probabilities by their sum. Such division would produce probabilities conditioned on belonging to this pair and hide its unmodeled mass.

At the default, all four raw probabilities are exp⁡(−2)\exp(-2). Both pair sums are 2exp⁡(−2)2\exp(-2), and both remaining masses are 1−2exp⁡(−2)1-2\exp(-2). These symbolic expressions are exact real hand calculations, not reported floating-point outputs.

Subtract the reference’s existing preference

Select chosen and rejected copies from each model using the label. Write ℓπ,c\ell_{\pi,c} and ℓπ,r\ell_{\pi,r} for chosen and rejected policy log-probabilities, and ℓR,c\ell_{R,c} and ℓR,r\ell_{R,r} for the reference copies. The subscript π\pi names the policy; here the subscript cc means chosen, distinct from raw input cc above.

Compute, in order,

dpolicy=ℓπ,c−ℓπ,r,dreference=ℓR,c−ℓR,r,d_{\mathrm{policy}}=\ell_{\pi,c}-\ell_{\pi,r},\qquad d_{\mathrm{reference}}=\ell_{R,c}-\ell_{R,r}, δ=dpolicy−dreference,m=βδ.\delta=d_{\mathrm{policy}}-d_{\mathrm{reference}},\qquad m=\beta\delta.

The symbol δ\delta names the reference-relative gap; mm is the scaled margin. Subtracting log-probabilities gives the logarithm of a probability ratio. Thus δ\delta compares the policy’s chosen-to-rejected ratio with the reference’s chosen-to-rejected ratio. It does not ask only whether the policy ranks the chosen response first.

For example, choose A with (a,b,c,d)=(−2,−3,−1,−3)(a,b,c,d)=(-2,-3,-1,-3) and β=1\beta=1. The policy favors A: its gap is 11. But the reference favors A more strongly: its gap is 22. Hence δ=1−2=−1\delta=1-2=-1 and m=−1m=-1. A policy ranking that agrees with the label can still have an unfavorable relative margin.

A stable route from margin to loss

The real objective is

p=11+exp⁡(−m),q=11+exp⁡(m),L=−ln⁡p=ln⁡(1+exp⁡(−m)).p=\frac{1}{1+\exp(-m)},\qquad q=\frac{1}{1+\exp(m)},\qquad L=-\ln p=\ln(1+\exp(-m)).

The sigmoid function maps a margin to a number between zero and one; pp is the pairwise preference probability and qq its mathematical complement. These equations explain the objective. The numerical evaluation uses a shared stable exponential instead of evaluating the equations separately.

After the four raw exponentials, pair sums, residual masses, selected copies and margins, the prescribed operations are:

  1. Compute negMargin as −m-m, absMargin as ∣m∣|m|, then expArgument as −∣m∣-|m|.
  2. Evaluate one shared t=exp⁡(−∣m∣)t=\exp(-|m|), then D=1+tD=1+t.
  3. If m≥0m\geq0, compute p=1/Dp=1/D and then q=t/Dq=t/D. Otherwise compute p=t/Dp=t/D and then q=1/Dq=1/D.
  4. Evaluate logPart as u=log1p⁡(t)u=\operatorname{log1p}(t), meaning a numerically specialized evaluation of ln⁡(1+t)\ln(1+t).
  5. Compute positivePart as max⁡(+0,−m)\max(+0,-m), with positive zero at the tie, then L=max⁡(+0,−m)+uL=\max(+0,-m)+u.

Absolute value ∣m∣|m| removes the sign; max selects the larger argument. The stable argument is nonpositive, so its exponential never becomes enormous. The input ranges give each log gap in [−7,7][-7,7], δ\delta in [−14,14][-14,14], and mm in [−28,28][-28,28]. Thus tt lies between exp⁡(−28)\exp(-28) and 11 in real arithmetic. log1p preserves the small logarithmic contribution when adding tt to one first would lose precision.

Compute qq directly from the branch formula. Subtracting a rounded pp from one can lose relative accuracy in a small complement; algebraically equivalent expressions need not preserve the same stored numbers. There are exactly five exponential occurrences and one log1p occurrence: four raw probabilities, one stable exponential, and one logarithm. Repeated arguments still represent separate calls. Beta zero does not skip any of them or any subsequent stated arithmetic.

The stable formula uses abs and max, but its composed real function is smooth at m=0m=0. The branches join to the same smooth logistic loss; there is no loss kink requiring a ReLU-style derivative choice.

Work the default all the way through

With (a,b,c,d,y,β)=(−2,−2,−2,−2,0,1)(a,b,c,d,y,\beta)=(-2,-2,-2,-2,0,1), chosen and rejected copies are all −2-2. After the raw probability and mass calculations above,

dpolicy=(−2)−(−2)=0,dreference=0,δ=0−0=0,m=1⋅0=0.d_{\mathrm{policy}}=(-2)-(-2)=0,\quad d_{\mathrm{reference}}=0,\quad\delta=0-0=0,\quad m=1\cdot0=0.

Then −m=0-m=0, ∣m∣=0|m|=0, t=exp⁡(0)=1t=\exp(0)=1 and D=1+1=2D=1+1=2. The nonnegative branch gives p=1/2p=1/2 and q=1/2q=1/2. Finally u=log1p⁡(1)=ln⁡2u=\operatorname{log1p}(1)=\ln2, the positive part is zero, and L=0+ln⁡2L=0+\ln2.

This is equality of relative gaps, not evidence of indifference between all possible responses. No optimizer or new model state follows from this evaluation. Exact real expressions such as ln⁡2\ln2 are distinguished from a native library’s eventual rounded result throughout this lesson.

Derive all five partial derivatives

The chain rule multiplies the sensitivity of the loss to the margin by the sensitivity of the margin to an input. First,

dLdm=−exp⁡(−m)1+exp⁡(−m)=−q.\frac{dL}{dm}=\frac{-\exp(-m)}{1+\exp(-m)}=-q.

For a compact derivation only, let s=1−2ys=1-2y: s=+1s=+1 for A chosen and s=−1s=-1 for B chosen. Then

δ=s[(a−b)−(c−d)],m=βδ.\delta=s[(a-b)-(c-d)],\qquad m=\beta\delta.

The margin partials in (a,b,c,d,β)(a,b,c,d,\beta) order are (sβ,−sβ,−sβ,sβ,δ)(s\beta,-s\beta,-s\beta,s\beta,\delta). Multiplying each by −q-q gives every formal partial:

CoordinateMargin sensitivityFormal loss sensitivity
aa — policy Asβs\beta−sβq-s\beta q
bb — policy B−sβ-s\beta+sβq+s\beta q
cc — reference A−sβ-s\beta+sβq+s\beta q
dd — reference Bsβs\beta−sβq-s\beta q
β\beta — scaleδ\delta−δq-\delta q

For A chosen and β>0\beta>0, raising policy A locally lowers the loss, while raising reference A locally raises it: the comparison becomes harder. A reference partial deliberately varies that reference coordinate while holding all others fixed. Keeping the reference fixed during a policy partial does not erase its separate formal sensitivity.

These are derivatives of the smooth real objective, evaluated numerically with saved intermediates. They are not derivatives of the discrete rounding map between stored binary64 words.

The specified numerical order first negates beta and delta, then computes minus as (−β)q(-\beta)q, plus as βq\beta q, and betaFormal as (−δ)q(-\delta)q. Chosen and rejected policy derivatives use minus and plus; chosen and rejected reference derivatives copy plus and minus. Map those saved values back to raw A, B order. The ss equations prove the mathematics; they do not replace that copy-and-map schedule with a differently rounded computation.

At the default, negate beta to get −1-1 and multiply by q=1/2q=1/2 to get minus =−1/2=-1/2. Plus is 1⋅(1/2)=1/21\cdot(1/2)=1/2. The five real formal derivatives are (−1/2,+1/2,+1/2,−1/2,0)(-1/2,+1/2,+1/2,-1/2,0). Beta’s real-zero derivative has the stored sign discussed below.

A policy-only mask selects sensitivities; it does not perform training

The five selectors are (1,1,0,0,0)(1,1,0,0,0) in (a,b,c,d,β)(a,b,c,d,\beta) order. A one enables a policy coordinate; a zero freezes a reference or beta coordinate. Enabled effective entries copy their formal values. Frozen effective entries are explicit floating positive zero, even when their formal sensitivities are nonzero or negative zero. This is a selection rule, not a multiplication that might accidentally preserve a frozen zero’s negative sign.

The default effective vector is (−1/2,+1/2,+0,+0,+0)(-1/2,+1/2,+0,+0,+0). Freezing reference and beta does not reset their input scores, erase their formal partials, or remove their role in the objective. There is no sixth gradient for the label and no parameter update here.

Nor can five independent input sensitivities be used directly as a neural network’s gradients. A complete model couples log-probabilities through normalization and shared parameters. Differentiating with respect to its underlying scores or weights requires another chain rule. Changing one log-probability while holding the others fixed is a coordinate calculation, not a demonstrated normalized policy update.

Make one comparison favorable, then reverse the label

Set (a,b,c,d,y,β)=(−1,−2,−2,−2,0,1)(a,b,c,d,y,\beta)=(-1,-2,-2,-2,0,1), and write e=exp⁡(1)e=\exp(1). The four raw probabilities are (1/e,1/e2,1/e2,1/e2)(1/e,1/e^2,1/e^2,1/e^2). Their policy sum is 1/e+1/e21/e+1/e^2, reference sum 2/e22/e^2, and remaining masses are one minus those respective sums.

Chosen policy −1-1 minus rejected −2-2 gives 11; the reference gap is 00. Thus δ=1\delta=1 and m=1m=1. Negating the margin gives −1-1, absolute value gives 11, and the stable argument is −1-1. Hence

t=1/e,D=1+1/e,p=ee+1,q=1e+1,u=ln⁡(1+1/e),L=0+ln⁡(1+1/e).t=1/e,\quad D=1+1/e,\quad p=\frac{e}{e+1},\quad q=\frac{1}{e+1},\quad u=\ln(1+1/e),\quad L=0+\ln(1+1/e).

Negating beta gives −1-1 and negating delta gives −1-1. The three products are minus =−q=-q, plus =q=q, betaFormal =−q=-q. Formal raw order is (−q,+q,+q,−q,−q)(-q,+q,+q,-q,-q), while effective order is (−q,+q,+0,+0,+0)(-q,+q,+0,+0,+0).

Now change only yy to 11. All raw probabilities, sums and remaining masses stay the same. Chosen policy is −2-2, rejected policy −1-1, so dpolicy=−1d_{\mathrm{policy}}=-1, δ=−1\delta=-1 and m=−1m=-1. The stable tt and DD are unchanged, but the negative branch gives p=1/(e+1)p=1/(e+1), q=e/(e+1)q=e/(e+1), and L=1+ln⁡(1+1/e)L=1+\ln(1+1/e). Formal raw order is (+q,−q,−q,+q,+q)(+q,-q,-q,+q,+q) and effective order (+q,−q,+0,+0,+0)(+q,-q,+0,+0,+0) with this new qq.

In exact real arithmetic, L(−m)=L(m)+mL(-m)=L(m)+m. Reversing a nonzero-margin label reverses derivative directions but also changes their magnitudes. It does not merely negate the old gradient vector.

Beta zero, signed zero and saturation

Return to the favorable case with δ=1\delta=1, then set β=+0\beta=+0. The margin is +0+0, t=1t=1, D=2D=2, p=q=1/2p=q=1/2, positive part +0+0, and real loss ln⁡2\ln2. Minus is −0-0, plus is +0+0, and betaFormal is (−1)(1/2)=−1/2(-1)(1/2)=-1/2. The formal raw vector is (−0,+0,+0,−0,−1/2)(-0,+0,+0,-0,-1/2); the effective vector is (−0,+0,+0,+0,+0)(-0,+0,+0,+0,+0).

With β=−0\beta=-0 instead, the margin is −0-0. Both zero signs satisfy m≥0m\geq0. Absolute value gives +0+0, the stable argument is −0-0, and its exponential must be exactly positive one. The positive-part tie emits +0+0. Negative beta is now +0+0, so minus is +0+0 and plus is −0-0. Formal raw order is (+0,−0,−0,+0,−1/2)(+0,-0,-0,+0,-1/2), effective order (+0,−0,+0,+0,+0)(+0,-0,+0,+0,+0). The loss is the same real value, but saved zero words differ.

These beta derivatives are derivatives of the smooth extension of the objective; at beta zero they agree with the allowed right derivative. A central perturbation into negative beta is outside the input domain. At the original default, δ=+0\delta=+0 instead, so negativeDelta is −0-0 and betaFormal is −0-0; its frozen effective copy remains explicit +0+0.

For fixed δ>0\delta>0, increasing beta lowers the real loss; for δ<0\delta<0 it raises it; for δ=0\delta=0 the loss stays ln⁡2\ln2. Beta is a comparison scale, not a learning rate or a universal quality improvement. Tiny positive beta can also produce rounded or underflowed zero arithmetic, despite a well-behaved stable exponential.

At the admitted extreme (a,b,c,d,y,β)=(−1,−8,−8,−1,0,2)(a,b,c,d,y,\beta)=(-1,-8,-8,-1,0,2), the gaps are 77 and −7-7, so δ=14\delta=14 and m=28m=28. Then t=exp⁡(−28)t=\exp(-28), q=t/(1+t)q=t/(1+t), p=1/(1+t)p=1/(1+t) and L=log1p⁡(t)L=\operatorname{log1p}(t). Formal derivatives are (−2q,+2q,+2q,−2q,−14q)(-2q,+2q,+2q,-2q,-14q). Reversing only the label gives m=−28m=-28, q=1/(1+t)q=1/(1+t), loss 28+log1p⁡(t)28+\operatorname{log1p}(t) and formal derivatives (+2q,−2q,−2q,+2q,+14q)(+2q,-2q,-2q,+2q,+14q) using that new qq.

The favorable side saturates: loss and margin sensitivity become small. In real arithmetic qq stays positive at every admitted margin. Small loss means strong agreement with this relative labeled comparison; it supplies no evidence about factual accuracy or safety.

What exact numerical verification would mean

Binary64 stores a number in 64 bits. WORD equality means the identical stored pattern, including zero’s sign. VALUE equality compares an integer role such as a label, index, count or mask selector. Arithmetic values, copied log-probabilities, beta and native inputs/results retain WORD identity. Prose, axis names and occurrence order require their own exact structural comparisons.

A native exp or log1p call uses a runtime’s elementary-function library. Its output is checked independently against the correctly rounded exact-function reference. The admission cap is four ordered finite binary64 word steps from that reference word. It is per call; it is not a whole-loss or whole-gradient tolerance. Exp at either signed zero is the exact special case positive one, rather than a four-step allowance around one.

The independent reference uses exact binary64-to-decimal conversion and local 120-significant-digit standard-library _pydecimal contexts. Correctly nearest-rounded exp or ln values are expanded to outward decimal neighbors. For log1p, directed lower and upper additions first enclose the actual 1+t1+t; monotonic ln and outward neighbors then enclose its logarithm. Merely requesting directed transcendental rounding is not the proof. Both exact rational endpoints must round to the same binary64 reference word. Otherwise the reference is inconclusive and verification fails closed.

All six actual occurrences must be captured with their argument and result, bound to the complete computation, and admitted separately. Exact round-to-nearest, ties-to-even replay then checks every subsequent operation and copy using that producer’s own admitted leaves. Python and TypeScript need not return identical native words. A coherent alternate in-cap native result with all dependencies correctly updated may be admissible. A packet cannot authenticate where a result physically executed, and one successful scalar comparison cannot verify the whole record.

Why one very narrow centered difference can be exact

A centered finite difference estimates a derivative by evaluating above and below an input: [L(x+h)−L(x−h)]/(2h)[L(x+h)-L(x-h)]/(2h). Here the special scope is only all four log-probabilities word-equal to −2-2, label value 00, beta word-equal to +1+1, policy A or policy B coordinate, and h=2−10=1/1024h=2^{-10}=1/1024. Every endpoint stays in range; no clipping is allowed.

For policy A the endpoint margins are +h,−h+h,-h. Set g(h)=log1p⁡(exp⁡(−h))g(h)=\operatorname{log1p}(\exp(-h)). In exact real arithmetic,

L(+h)=g(h),L(−h)=h+g(h),L(+h)−L(−h)2h=−h2h=−12.L(+h)=g(h),\quad L(-h)=h+g(h),\quad \frac{L(+h)-L(-h)}{2h}=\frac{-h}{2h}=-\frac12.

Policy B reverses the margin order and yields +1/2+1/2. This nonlinear function’s common even contribution cancels; the function itself is not linear.

A floating-point zero-error claim requires more. Verify the whole central record first, then complete actual endpoint records with every raw display, helper field and operation. Admit every native occurrence independently. Within each producer’s endpoint pair, require WORD-identical actual stable-exp arguments and outputs, and WORD-identical log1p arguments and outputs. Call the common stored log part uu and prove 1/2<u<7/81/2<u<7/8 as well as u+h<1u+h<1.

In the interval [1/2,1)[1/2,1), binary64 numbers lie on a grid of spacing 2−532^{-53}. Since h=2432−53h=2^{43}2^{-53}, u+hu+h is exactly representable on that same grid. The favorable loss is uu, the unfavorable loss u+hu+h, their difference is exactly the appropriate signed hh, and division by positive 2h2h gives exactly the appropriate signed half. At the center the exact exp-zero special case gives t=1t=1, D=2D=2, q=1/2q=1/2 and the actual policy gradient word −1/2-1/2 or +1/2+1/2.

Only after all those premises hold may truncation, rounding and residual be reported zero for this restricted check. If pair equality, enclosure or any complete-record condition fails, the strict check fails closed. The explanatory nonpaired bound 17⋅2−4417\cdot2^{-44} is not a fallback tolerance. No zero-error claim extends to other states, reference or beta coordinates, or unobserved cross-language parity. The derivation alone does not establish these runtime premises.

Find every number in the saved record

The lab is a projection of deriveIV57, rather than a second implementation of the equations. Its tables read saved tensor cells, frame inputs and outputs, and text metadata. In particular, displaying the native table does not evaluate another exponential, and displaying a remaining mass does not recompute its sum. The four summaries, trace, full evidence and exercises share the same successful root.

The source declares 18 frames, 11 tensors containing 64 scalar cells, 87 scalar outputs and 32 text entries. These are manually read source inventories, not observed execution counts or verification results. The sixteen helper frames occur between setup and finish, in this exact order:

PositionSaved frame IDRole
1setupSix raw copies and six setup counts
2pair_policyA_expActual policy A exponential
3pair_policyB_expActual policy B exponential
4pair_referenceA_expActual reference A exponential
5pair_referenceB_expActual reference B exponential
6pair_massesBoth pair sums, then both remaining masses
7pair_selectionFour chosen/rejected copies
8pair_relativePolicy gap, reference gap, delta and margin
9pair_stabilityNegative margin, absolute margin and stable argument
10pair_stable_expActual shared stable exponential
11pair_denominatorSaved addition of one and t
12pair_sigmoidsDirect p division, then direct q division
13pair_log1pActual log1p at saved t
14pair_lossPositive part and final loss
15pair_gradient_productsTwo negations and three products
16pair_formalFive formal coordinate copies
17pair_maskTwo enabled copies and three explicit frozen +0 values
18finishFour summary copies and all 26 work counts

Every frame carries id, label, equation, explanation, inputs and outputs. Open Complete saved operation text fallback: every frame in trace order for the actual equations, explanations and all operand maps, including setup and finish. The shorter disclosures show selection/relative, stable-objective, and gradient/mask operations from those same frames. Plain text supplies the complete explanation without an animation. The current frame is marked inside that fallback.

The six native rows have their own IDs above, kinds exp, exp, exp, exp, exp, log1p, and actual argument/result pairs. pair_Elementary stores those pairs; elementaryIds and elementaryKinds in root texts identify them. There is no extra root-level elementary list. Identical arguments do not merge raw calls. The helper does have a six-record elementary list, whose records each contain exactly id,kind,input,output.

A tensor’s shape gives each axis length; its axes explain what an index selects. Storage is row-major: finish a row before moving to the next model or native call. Here is the complete stored layout; scalar loss and probability stay scalar fields rather than gaining invented singleton tensors.

Tensor IDShapeNamed axesStored order or meaning
pair_Raw[6]RawFieldpolicyA, policyB, referenceA, referenceB, preferred, beta
pair_Probabilities[2,2]Model, ResponsePolicy then reference; A then B
pair_Masses[2,2]Model, MassFieldPolicy then reference; pair sum then remaining mass
pair_Selected[2,2]Model, PreferenceRolePolicy then reference; chosen then rejected
pair_Relative[4]RelativeFielddPolicy, dReference, delta, margin
pair_Stable[10]StableFieldnegMargin, absMargin, expArgument, t, denominator, probability, complement, logPart, positivePart, loss
pair_GradientProducts[5]GradientProductFieldnegativeBeta, negativeDelta, minus, plus, betaFormal
pair_FormalGradient[5]CoordinatepolicyA, policyB, referenceA, referenceB, beta
pair_EffectiveGradient[5]CoordinateSame coordinates, selected formal copies or explicit +0
pair_Mask[5]CoordinateInteger selectors 1, 1, 0, 0, 0
pair_Elementary[6,2]NativeCall, NativeFieldSix actual occurrences; input then output

Each tensor has exactly id,shape,axes,dtype,values,provenance,precision. Mask alone is int32 with precision 0; the other ten are float64 with precision 8 metadata. In the mixed Raw table, preferred at zero-based index 4 has a VALUE role; the other five entries retain WORD roles. All true arithmetic and copy entries retain WORD identity, including frozen floating +0. Precision metadata never rounds computation. The custom tables and house inspector present stored round-trip number text with explicit -0, rather than feeding formatted numbers back into calculation.

The 87 outputs consist of four leading summaries and 83 once-only aliases named from a frame ID and its output key, such as pair_relative_delta. Setup contributes 12 aliases, helper frames 41, and finish 30: 12+41+30+4=8712+41+30+4=87. A repeated mathematical value can appear in a tensor, summary and alias; “once-only” means one occurrence of each alias name. The 32 text entries retain the fixed prompt/responses, policies, coordinate/field names and actual native IDs/kinds. Open Inspect all stored values, text metadata and tensor storage to read every scalar alias, every text entry and each tensor’s exact axes, dtype, precision, provenance and flat index.

The named table regions include Whole current root: six saved raw inputs, Both models: raw response probabilities, pair sums and remaining masses, Every saved stable-objective intermediate, Native calls: identity, kind, equation, actual argument and returned result, and All five derivative coordinates: formal partial, mask and effective selection. Each custom table has a caption, row/column headings and a focusable horizontal scroll region. Together with the complete operation fallback and metadata inspector, these preserve numerical evidence as text. Responsive wrapping and reduced-motion rules are authored in the UI; keyboard, viewport, theme and accessibility behavior require rendering evidence.

Saved setup counts and complete work counts from finish exposes the six setup counts and all 26 work counts. For example, it records five exp calls, one log1p call, two probability divisions, three gradient multiplications, five formal coordinate copies, five effective selections and zero optimizer steps. These counts describe the declared graph, including the raw probability displays. They do not measure time, hardware cost, snapshot storage or training.

Follow both complete Python files

The next two panels import the actual repository files as raw source text, in dependency order: preference_reference.py, then iv57.py. Both files are complete, including comments, guards, metadata, CLI and explicit check declarations. There is no copied numerical substitute, abbreviated implementation or omitted branch. Keep the two files adjacent. They are the entire canonical project-source closure; Python’s standard library and NumPy are external dependencies. Neither file imports the independent authority, a TypeScript parser or an older chapter mechanism. Displaying these source files does not establish an import or rendering result.

1. preference_reference.py: scalar mathematics before public storage

preference_state(value) accepts an exact plain Python dictionary with exactly the six string keys. It checks all six actual numeric types/finite float values before any domain. Booleans are excluded despite Python’s integer inheritance. Arbitrary-size Python integers reach bounded domain checks before conversion; admitted log-probabilities and beta become floats, while preferred becomes integer 0 or 1. Thus preferred negative zero selects A by VALUE, while beta negative zero retains its floating word. Python’s exact dictionary boundary corresponds to the TS own-data boundary without pretending that the two languages have identical object representations.

_evaluate_preference_mechanics(value, trace, prefix) owns the independent scalar calculation. Its native function calls actual math.exp four times for raw probabilities, once for the stable term, and actual math.log1p once. Python float arithmetic performs each subtraction, addition, negation, absolute value, max, product and division. save retains their operands; no NumPy expression computes a loss or gradient. The raw guard precedes re.fullmatch of the ASCII prefix grammar, so a trailing line terminator rejects as well as an invalid first character.

Read the local variables in dependency order: raw_probabilities, the two sums and rests, chosen/rejected copies, d_policy, d_reference, delta, margin, neg_margin, abs_margin, exp_argument, t, denominator, probability, complement, log_part, positive_part, loss, then negative_beta, negative_delta, minus, plus, beta_formal, formal, mask and effective. These are the names behind the equations already derived. p_numerator and q_numerator choose the two direct ratios; neither q nor a reference partial is reconstructed from an algebraic shortcut. The first operand in max(0.0, neg_margin) makes either zero tie positive.

The private result retains operands and storage for its independently authored evidence. np.array and reshape store already-computed numbers as float64 arrays, with an int32 mask. _public_evaluation(captured, trace, prefix) then copies those saved values into the adopted sixteen frames and eleven tensors; it does not call the native functions or redo scalar primitives. _tensor validates the bounded shapes/axes/storage and converts storage to lists for serialization. Shape-size multiplication is metadata bookkeeping, not another numerical objective.

Public preference_trace() supplies steps and add(id,label,equation,explanation,inputs,outputs). Its PreferenceTrace guards duplicate/nonempty IDs first, captured inputs then outputs, and the 512-frame limit last. It saves the same validated detached maps, and failed appends do not consume IDs. Python requires exact dictionary operand carriers; TS captures each side once with Object.entries and saves those captured numeric values, avoiding a second read of changing accessors. Unknown observer/programmer failures propagate. The observer is structurally trusted, rather than authenticated by a factory identity.

evaluate_preference(value, trace, prefix) first completes private scalar capture with _operand_trace(), then delivers public frames through _public_evaluation. Public callback delivery therefore follows that capture; no claim of identical callback timing with TS is needed. Its exact ten public fields are state,loss,margin,probability,complement,formalGradient,effectiveGradient,mask,elementary,tensors. Private operands/storage are not extra public fields. deepcopy detaches Python containers; the TS representation additionally freezes snapshots. Both retain the declared signed values.

Complete preference_reference.py

Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""IV57 independent scalar mechanics and adopted public helper — UNRUN.

Python floats perform every scalar operation; math supplies exactly five exp
calls and one log1p call per evaluation. NumPy only stores detached arrays.
Private operands retain the independent FIRST. Public serialization copies those
operands without repeating arithmetic or native calls. Project dependencies: none.
"""
from copy import deepcopy
import math
import re
import struct
import sys
from types import MappingProxyType

import numpy as np

RAW_KEYS = ("policyA", "policyB", "referenceA", "referenceB", "preferred", "beta")
DEFAULT_IV57 = MappingProxyType(dict(policyA=-2.0, policyB=-2.0,
                                    referenceA=-2.0, referenceB=-2.0,
                                    preferred=0, beta=1.0))


class NumericalFault(ValueError):
    """Only this known semantic fault may become an unavailable record."""

    def __init__(self, code, reason):
        super().__init__(reason)
        self.code = code


def _number(value, label):
    # Like IV55/56, finite Python integers reach domain checks before conversion.
    if type(value) not in (int, float) or (type(value) is float and not math.isfinite(value)):
        raise NumericalFault("NONFINITE", f"{label} must be an actual finite number.")
    return value


def _finite(value, label):
    _number(value, label)
    if not -sys.float_info.max <= value <= sys.float_info.max:
        raise NumericalFault("NONFINITE", f"{label} requires a finite binary64 value.")
    return float(value)


def _word(value):
    return struct.pack(">d", value)


def _computed(value, label):
    if type(value) is not float or not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


def preference_state(value):
    """Exact plain dict, ALL six finite types, THEN domains; no partial defaults."""
    if type(value) is not dict:
        raise NumericalFault("INVALID_INPUT", "state must be a plain object.")
    if len(value) != 6 or any(type(key) is not str for key in value) or set(value) != set(RAW_KEYS):
        raise NumericalFault("INVALID_INPUT", "state must have exactly policyA, policyB, referenceA, referenceB, preferred, beta as own fields.")
    saved = {key: value[key] for key in RAW_KEYS}
    for key in RAW_KEYS:
        _number(saved[key], key)
    for key in RAW_KEYS[:4]:
        if not -8.0 <= saved[key] <= -1.0:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between -8 and -1.")
    if saved["preferred"] not in (0, 1):
        raise NumericalFault("INVALID_INPUT", "preferred must be numeric 0 or 1.")
    if not 0.0 <= saved["beta"] <= 2.0:
        raise NumericalFault("INVALID_INPUT", "beta must be between 0 and 2.")
    return {key: int(saved[key]) if key == "preferred" else float(saved[key]) for key in RAW_KEYS}


def _numeric_record(value, label):
    if type(value) is not dict or any(type(key) is not str for key in value):
        raise NumericalFault("INVALID_INPUT", f"{label} must be a plain numeric record.")
    saved = value.copy()
    for key, number in saved.items():
        _number(number, f"{label}.{key}")
    for key, number in saved.items():
        _finite(number, f"{label}.{key}")
    return saved


class _OperandTrace:
    """Private independent FIRST frames; never included in the public helper."""

    def __init__(self):
        self.steps = []

    def add(self, identifier, inputs, outputs):
        if type(identifier) is not str or not identifier:
            raise NumericalFault("INVALID_INPUT", "trace id must be a nonempty string.")
        # Both sides clear numeric validation before any frame is appended.
        captured_inputs = _numeric_record(inputs, "trace inputs")
        captured_outputs = _numeric_record(outputs, "trace outputs")
        if len(self.steps) >= 512:
            raise NumericalFault("INVALID_INPUT", "trace cannot exceed 512 frames.")
        if any(step["id"] == identifier for step in self.steps):
            raise NumericalFault("INVALID_INPUT", "trace ids must be unique.")
        self.steps.append(deepcopy(dict(id=identifier, inputs=captured_inputs,
                                        outputs=captured_outputs)))


def _operand_trace():
    return _OperandTrace()


def _evaluate_preference_mechanics(value, trace, prefix):
    """Full scalar graph, six ACTUAL native occurrences, and detached evidence.

    A structural trusted observer needs only add(id, inputs, outputs). Observer
    and programmer exceptions propagate. FIRST frame IDs are internal names;
    the adopted public view copies this completed graph in a separate phase.
    """
    state = preference_state(value)
    if type(prefix) is not str or re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", prefix) is None:
        raise NumericalFault("INVALID_INPUT", "prefix must start with an ASCII letter and contain only ASCII letters, digits or underscores.")
    elementary, operands = [], {}

    def save(name, inputs, outputs):
        for key, number in inputs.items():
            _finite(number, f"{name} input {key}")
        for key, number in outputs.items():
            _finite(number, f"{name} output {key}")
        operands[name] = deepcopy(dict(inputs=inputs, outputs=outputs))
        trace.add(f"{prefix}_{name}", inputs, outputs)

    def native(name, kind, argument):
        suffix = dict(rawExp0="policyA_exp", rawExp1="policyB_exp", rawExp2="referenceA_exp",
                      rawExp3="referenceB_exp", stableExp="stable_exp", logPart="log1p")[name]
        identifier = f"{prefix}_{suffix}"
        argument = _finite(argument, f"{identifier} argument")
        # No native re-evaluation for display, recording, p, q, or loss.
        result = math.exp(argument) if kind == "exp" else math.log1p(argument)
        result = _finite(result, f"{identifier} value")
        elementary.append(dict(id=identifier, kind=kind, input=argument, output=result))
        save(name, dict(argument=argument), dict(value=result))
        return result

    # Four separately observed raw exps precede all pair arithmetic.
    raw_probabilities = [native(f"rawExp{i}", "exp", state[key])
                         for i, key in enumerate(RAW_KEYS[:4])]
    policy_sum = _computed(raw_probabilities[0] + raw_probabilities[1], "policy pair sum")
    save("policySum", dict(left=raw_probabilities[0], right=raw_probabilities[1]), dict(value=policy_sum))
    reference_sum = _computed(raw_probabilities[2] + raw_probabilities[3], "reference pair sum")
    save("referenceSum", dict(left=raw_probabilities[2], right=raw_probabilities[3]), dict(value=reference_sum))
    policy_rest = _computed(1.0 - policy_sum, "policy remaining mass")
    save("policyRest", dict(one=1.0, pairSum=policy_sum), dict(value=policy_rest))
    reference_rest = _computed(1.0 - reference_sum, "reference remaining mass")
    save("referenceRest", dict(one=1.0, pairSum=reference_sum), dict(value=reference_rest))

    chosen = state["preferred"]
    rejected = 1 if chosen == 0 else 0
    policy = [state["policyA"], state["policyB"]]
    reference = [state["referenceA"], state["referenceB"]]
    chosen_policy, rejected_policy = policy[chosen], policy[rejected]
    chosen_reference, rejected_reference = reference[chosen], reference[rejected]
    save("selection", dict(policyA=policy[0], policyB=policy[1],
                           referenceA=reference[0], referenceB=reference[1], preferred=chosen),
         dict(chosenPolicy=chosen_policy, rejectedPolicy=rejected_policy,
              chosenReference=chosen_reference, rejectedReference=rejected_reference))
    d_policy = _computed(chosen_policy - rejected_policy, "policy log-probability difference")
    save("dPolicy", dict(chosen=chosen_policy, rejected=rejected_policy), dict(value=d_policy))
    d_reference = _computed(chosen_reference - rejected_reference, "reference log-probability difference")
    save("dReference", dict(chosen=chosen_reference, rejected=rejected_reference), dict(value=d_reference))
    delta = _computed(d_policy - d_reference, "reference-relative difference")
    save("delta", dict(policy=d_policy, reference=d_reference), dict(value=delta))
    beta = state["beta"]
    margin = _computed(beta * delta, "relative margin")
    save("margin", dict(beta=beta, delta=delta), dict(value=margin))
    neg_margin = _computed(-margin, "negative margin")
    save("negMargin", dict(margin=margin), dict(value=neg_margin))
    abs_margin = _computed(abs(margin), "absolute margin")
    save("absMargin", dict(margin=margin), dict(value=abs_margin))
    exp_argument = _computed(-abs_margin, "stable exponential argument")
    save("expArgument", dict(absolute=abs_margin), dict(value=exp_argument))
    t = native("stableExp", "exp", exp_argument)
    denominator = _computed(1.0 + t, "stable denominator")
    save("denominator", dict(one=1.0, t=t), dict(value=denominator))
    # Both signs of margin zero take this branch; q NEVER uses 1-p.
    p_numerator, q_numerator = (1.0, t) if margin >= 0.0 else (t, 1.0)
    probability = _computed(p_numerator / denominator, "pairwise preference probability")
    save("probability", dict(margin=margin, numerator=p_numerator, denominator=denominator), dict(value=probability))
    complement = _computed(q_numerator / denominator, "direct complement probability")
    save("complement", dict(margin=margin, numerator=q_numerator, denominator=denominator), dict(value=complement))
    log_part = native("logPart", "log1p", t)
    # The first max operand ensures a positive-zero tie for either margin sign.
    positive_part = _computed(max(0.0, neg_margin), "nonnegative loss part")
    save("positivePart", dict(zero=0.0, negMargin=neg_margin), dict(value=positive_part))
    loss = _computed(positive_part + log_part, "preference loss")
    save("loss", dict(positivePart=positive_part, logPart=log_part), dict(value=loss))

    negative_beta = _computed(-beta, "negative beta")
    save("negativeBeta", dict(beta=beta), dict(value=negative_beta))
    negative_delta = _computed(-delta, "negative delta")
    save("negativeDelta", dict(delta=delta), dict(value=negative_delta))
    minus = _computed(negative_beta * complement, "chosen policy formal gradient")
    save("minus", dict(negativeBeta=negative_beta, q=complement), dict(value=minus))
    plus = _computed(beta * complement, "rejected policy formal gradient")
    save("plus", dict(beta=beta, q=complement), dict(value=plus))
    beta_formal = _computed(negative_delta * complement, "beta formal gradient")
    save("betaFormal", dict(negativeDelta=negative_delta, q=complement), dict(value=beta_formal))
    formal = ([minus, plus, plus, minus, beta_formal] if chosen == 0
              else [plus, minus, minus, plus, beta_formal])
    coordinates = ("policyA", "policyB", "referenceA", "referenceB", "beta")
    save("formalMapping", dict(preferred=chosen, minus=minus, plus=plus, betaFormal=beta_formal),
         dict(zip(coordinates, formal)))
    mask = [1, 1, 0, 0, 0]
    effective = []
    for i, coordinate in enumerate(coordinates):
        enabled = mask[i]
        selected = formal[i] if enabled else 0.0
        effective.append(selected)
        save(f"effective{i}", dict(formal=formal[i], enabled=enabled, frozenZero=0.0),
             dict(value=selected))

    # Storage only: no NumPy arithmetic, reductions, exp, or gradient machinery.
    storage = dict(rawLogProbabilities=np.array(policy + reference, dtype=np.float64).reshape((2, 2)),
                   rawProbabilities=np.array(raw_probabilities, dtype=np.float64).reshape((2, 2)),
                   pairSums=np.array([policy_sum, reference_sum], dtype=np.float64),
                   remainingMasses=np.array([policy_rest, reference_rest], dtype=np.float64),
                   formalGradient=np.array(formal, dtype=np.float64),
                   effectiveGradient=np.array(effective, dtype=np.float64),
                   mask=np.array(mask, dtype=np.int32))
    return deepcopy(dict(state=state, loss=loss, margin=margin, probability=probability,
                         complement=complement, formalGradient=formal,
                         effectiveGradient=effective, mask=mask, elementary=elementary,
                         operands=operands, storage=storage))


class PreferenceTrace:
    """Trusted structural observer; capture both numeric maps exactly once."""

    def __init__(self):
        self.steps = []
        self._ids = set()

    def add(self, identifier, label, equation, explanation, inputs, outputs):
        if type(identifier) is not str or not identifier or identifier in self._ids:
            raise NumericalFault("INVALID_INPUT", "Trace IDs must be nonempty and unique.")
        # Exact dictionaries have no getters; validate the copies that we save.
        captured_inputs = _numeric_record(inputs, f"{identifier}.inputs")
        captured_outputs = _numeric_record(outputs, f"{identifier}.outputs")
        if len(self.steps) >= 512:
            raise NumericalFault("UNSUPPORTED_SIZE", "At most 512 operations are supported.")
        frame = deepcopy(dict(id=identifier, label=label, equation=equation,
                              explanation=explanation, inputs=captured_inputs, outputs=captured_outputs))
        self.steps.append(frame)
        self._ids.add(identifier)


def preference_trace():
    return PreferenceTrace()


def _tensor(identifier, shape, axes, values, provenance, integer=False):
    """Bounded authored layouts; NumPy stores values, never computes the graph."""
    if not 1 <= len(shape) <= 4 or len(shape) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name each of 1–4 axes uniquely.")
    if len(set(axes)) != len(axes) or any(type(axis) is not str or not axis for axis in axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: each axis needs a unique name.")
    cells = 1
    for dimension in shape:
        if type(dimension) is not int or not 1 <= dimension <= 64:
            raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions 1–64 and at most 4096 elements required.")
        cells *= dimension
    if cells > 4096:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: dimensions 1–64 and at most 4096 elements required.")
    if len(values) != cells:
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage does not match dimensions.")
    for i, value in enumerate(values):
        _finite(value, f"{identifier}[{i}]")
    stored = np.array(values, dtype=np.int32 if integer else np.float64)
    return dict(id=identifier, shape=shape.copy(), axes=axes.copy(),
                dtype="int32" if integer else "float64", values=stored.tolist(),
                provenance=provenance, precision=0 if integer else 8)


def _public_evaluation(captured, trace, prefix):
    """Copy the retained FIRST graph into the adopted record; no math replay."""
    state, op = captured["state"], captured["operands"]
    def saved(name):
        return op[name]["outputs"]["value"]
    def add(suffix, label, equation, explanation, inputs, outputs):
        trace.add(f"{prefix}_{suffix}", label, equation, explanation, inputs, outputs)
    elementary = captured["elementary"]
    def native(index):
        leaf = elementary[index]
        exponential = leaf["kind"] == "exp"
        trace.add(leaf["id"],
                  "Evaluate this actual exponential occurrence" if exponential else "Evaluate the actual stable logarithm occurrence",
                  "value=exp(argument)" if exponential else "value=log1p(argument)",
                  "Record this call separately even when another argument is equal. Raw response probabilities and the stable loss term have distinct occurrences." if exponential else "Reuse the actual stable exponential as the argument. log1p evaluates log(1+argument) without first rounding that addition in this producer.",
                  dict(argument=leaf["input"]), dict(value=leaf["output"]))
    probabilities = [saved(f"rawExp{i}") for i in range(4)]
    for i in range(4):
        native(i)
    policy_sum, reference_sum = saved("policySum"), saved("referenceSum")
    policy_rest, reference_rest = saved("policyRest"), saved("referenceRest")
    add("masses", "Keep the probability mass outside the two authored responses",
        "policySum=policyProbabilityA+policyProbabilityB; referenceSum=referenceProbabilityA+referenceProbabilityB; policyRemaining=1-policySum; referenceRemaining=1-referenceSum",
        "These are probabilities from log-probabilities, not a softmax over A and B. Their sums are below one in the admitted range; the rest belongs to unspecified other outcomes. Do not renormalize the pair.",
        dict(policyProbabilityA=probabilities[0], policyProbabilityB=probabilities[1], referenceProbabilityA=probabilities[2], referenceProbabilityB=probabilities[3], one=1.0),
        dict(policySum=policy_sum, referenceSum=reference_sum, policyRemaining=policy_rest, referenceRemaining=reference_rest))
    selected = op["selection"]["outputs"]
    add("selection", "Use the label to select chosen and rejected log-probabilities",
        "chosenPolicy=preferred==0?policyA:policyB; rejectedPolicy=preferred==0?policyB:policyA; chosenReference=preferred==0?referenceA:referenceB; rejectedReference=preferred==0?referenceB:referenceA",
        "Label zero chooses A; label one chooses B. These are copies of the actual raw log-probabilities. The authored label is a ranking for this example, not evidence of truth or safety.",
        dict(preferred=state["preferred"], **{key: state[key] for key in RAW_KEYS[:4]}), selected.copy())
    relative = dict(dPolicy=saved("dPolicy"), dReference=saved("dReference"), delta=saved("delta"), margin=saved("margin"))
    add("relative", "Compare the policy preference against the reference preference",
        "dPolicy=chosenPolicy-rejectedPolicy; dReference=chosenReference-rejectedReference; delta=dPolicy-dReference; margin=beta*delta",
        "Each difference is in natural-log units. Delta measures the change in the labeled preference relative to the reference; beta scales that comparison. These are separate saved subtractions and one multiplication, including beta zero.",
        dict(**selected, beta=state["beta"]), relative.copy())
    stability = dict(negMargin=saved("negMargin"), absMargin=saved("absMargin"), expArgument=saved("expArgument"))
    add("stability", "Prepare one bounded exponential argument",
        "negMargin=-margin; absMargin=abs(margin); expArgument=-absMargin",
        "The stable exponential argument is between -28 and zero. At either signed margin zero, abs returns positive zero and its negation is negative zero. The same exponential will feed both probabilities and the loss.",
        dict(margin=captured["margin"]), stability.copy())
    native(4)
    t, denominator = saved("stableExp"), saved("denominator")
    add("denominator", "Add the shared stable denominator", "denominator=1+t",
        "Keep this actual rounded addition for both direct ratios. No second exponential is evaluated for a negative margin.",
        dict(one=1.0, t=t), dict(denominator=denominator))
    add("sigmoids", "Compute both logistic probabilities by direct division",
        "if margin>=0: probability=1/denominator; complement=t/denominator; else: probability=t/denominator; complement=1/denominator",
        "Probability is sigmoid(margin), not the raw policy probability of the chosen response. Complement is sigmoid(-margin), computed directly rather than by subtracting probability from one. Either signed zero uses the nonnegative branch.",
        dict(margin=captured["margin"], t=t, denominator=denominator, one=1.0),
        dict(probability=captured["probability"], complement=captured["complement"]))
    native(5)
    log_part, positive_part = saved("logPart"), saved("positivePart")
    add("loss", "Add the two stable parts of the pairwise logistic loss", "positivePart=max(+0,negMargin); loss=positivePart+logPart",
        "This equals log(1+exp(-margin)) in real arithmetic. The maximum chooses positive zero at either zero tie. There is one pair, no hidden batch average and no optimizer update.",
        dict(positiveZero=0.0, negMargin=stability["negMargin"], logPart=log_part), dict(positivePart=positive_part, loss=captured["loss"]))
    products = {key: saved(key) for key in ("negativeBeta", "negativeDelta", "minus", "plus", "betaFormal")}
    add("gradient_products", "Apply the chain rule to the saved direct complement",
        "negativeBeta=-beta; negativeDelta=-delta; minus=negativeBeta*complement; plus=beta*complement; betaFormal=negativeDelta*complement",
        "The real derivative of loss with respect to margin is -complement. Compute both signed beta products separately and retain beta sensitivity even when beta is frozen or zero. These are rounded evaluations of real partial derivatives, not derivatives of rounding.",
        dict(beta=state["beta"], delta=relative["delta"], complement=captured["complement"]), products.copy())
    add("formal", "Map all five formal partials back to raw coordinate order",
        "preferred==0?[minus,plus,plus,minus,betaFormal]:[plus,minus,minus,plus,betaFormal]",
        "Coordinate order is policyA, policyB, referenceA, referenceB, beta. Reference derivatives copy the actual opposite policy products. Preferred is discrete and has no derivative; holding the other inputs fixed still defines formal reference and beta sensitivities.",
        dict(preferred=state["preferred"], minus=products["minus"], plus=products["plus"], betaFormal=products["betaFormal"]),
        op["formalMapping"]["outputs"].copy())
    mask_inputs, mask_outputs = dict(positiveZero=0.0), {}
    for i in range(5):
        mask_inputs[f"formal{i}"] = captured["formalGradient"][i]
        mask_inputs[f"enabled{i}"] = captured["mask"][i]
        mask_outputs[f"effective{i}"] = captured["effectiveGradient"][i]
    add("mask", "Select policy sensitivities and explicit frozen positive zeros", "effective_i=enabled_i==1?formal_i:+0; mask=[1,1,0,0,0]",
        "Enabled policy entries copy their formal words, including signed zeros. Frozen reference and beta entries are explicit positive zeros, not products with zero. Freezing does not reset reference scores, erase formal derivatives or perform an update.",
        mask_inputs, mask_outputs)
    def table(suffix, shape, axes, values, provenance, integer=False):
        return _tensor(f"{prefix}_{suffix}", shape, axes, values, provenance, integer)
    tensors = [
        table("Raw", [6], ["RawField"], list(state.values()), "Actual raw fields policyA,policyB,referenceA,referenceB,preferred,beta; preferred is an integer VALUE selector, all other entries preserve floating WORDs."),
        table("Probabilities", [2, 2], ["Model", "Response"], probabilities, "Actual four native raw exp results in policy then reference, A then B order; no pair renormalization."),
        table("Masses", [2, 2], ["Model", "MassField"], [policy_sum, policy_rest, reference_sum, reference_rest], "Actual saved pair sum and remaining mass for policy then reference; remaining=1-sum from each actual sum."),
        table("Selected", [2, 2], ["Model", "PreferenceRole"], list(selected.values()), "Exact chosen then rejected raw log-probability copies, policy then reference; selection uses the discrete authored label."),
        table("Relative", [4], ["RelativeField"], list(relative.values()), "Actual saved dPolicy,dReference,delta,margin in dependency order; margin=beta*delta even for signed-zero beta."),
        table("Stable", [10], ["StableField"], [*stability.values(), t, denominator, captured["probability"], captured["complement"], log_part, positive_part, captured["loss"]], "Actual negMargin,absMargin,expArgument,t,denominator,probability,complement,logPart,positivePart,loss; one shared stable exp and one log1p."),
        table("GradientProducts", [5], ["GradientProductField"], list(products.values()), "Actual saved negativeBeta,negativeDelta,minus,plus,betaFormal; reference formal partials later copy the actual plus/minus words."),
        table("FormalGradient", [5], ["Coordinate"], captured["formalGradient"], "Actual five formal partials in policyA,policyB,referenceA,referenceB,beta order, including signed-zero words and frozen-coordinate sensitivities."),
        table("EffectiveGradient", [5], ["Coordinate"], captured["effectiveGradient"], "Actual selected formal policy copies followed by three explicit floating positive zeros; no optimizer or parameter update is performed."),
        table("Mask", [5], ["Coordinate"], captured["mask"], "Actual selectors [1,1,0,0,0] in policyA,policyB,referenceA,referenceB,beta order; all entries are integer VALUE roles.", True),
        table("Elementary", [6, 2], ["NativeCall", "NativeField"], [number for leaf in elementary for number in (leaf["input"], leaf["output"])], "Actual native argument and returned value for each distinct raw policyA,policyB,referenceA,referenceB exp, then stable exp and log1p occurrence; IDs and kinds accompany this table in root texts."),
    ]
    return deepcopy(dict(state=state, loss=captured["loss"], margin=captured["margin"],
                         probability=captured["probability"], complement=captured["complement"],
                         formalGradient=captured["formalGradient"], effectiveGradient=captured["effectiveGradient"],
                         mask=captured["mask"], elementary=elementary, tensors=tensors))


def evaluate_preference(value, trace, prefix):
    """Public ten-field helper; caller supplies a trusted six-argument observer.

    Complete independent scalar capture precedes public serialization. Only the
    private graph owns arithmetic/native calls; serialization copies its words.
    """
    captured = _evaluate_preference_mechanics(value, _operand_trace(), prefix)
    return _public_evaluation(captured, trace, prefix)

2. iv57.py: complete root, strict CLI and explicit checks

iv57.py loads exactly its adjacent preference_reference.py using Path(__file__).resolve().with_name(...), with the standard-library importlib.util loader. It does not guess a path from the current working directory. DEFAULT_IV57, NumericalFault, preference_state, preference_trace and evaluate_preference refer to that loaded module’s objects, preserving known-fault identity. dict(DEFAULT_IV57) makes a complete mutable default copy from the immutable mapping.

derive_iv57(value) adds setup, calls the full helper with prefix pair, copies four summaries, adds finish, creates _texts(evaluated) and emits every ordered alias once. Its successful root is exactly status,outputs,steps,tensors,texts; known NumericalFault instances alone become status,code,reason. Unknown semantic, observer, native, programmer, resource and serialization exceptions escape. An empty dictionary is an invalid replacement, not a request for defaults.

strict_json(source) rejects duplicate keys, malformed/trailing JSON and nonstandard NaN/Infinity constants. Its integer parser preserves literal -0 as a floating negative zero. A syntactically valid overflow such as 1e999 reaches the finite-number guard. Zero-argument run() reads command-line arguments itself: no argument evaluates the complete default; one JSON argument or - stdin supplies a complete replacement. Known parse or semantic faults print unavailable JSON and return exit 0. Unknown switches or multiple arguments return usage exit 2. Only JSON parsing sits in the narrow ValueError catch; semantic evaluation and JSON serialization sit outside it.

The explicit --self-check branch occurs before parser/fault catches and calls source_self_check(), which requires assertions enabled. Ordinary import, helper evaluation and default/JSON/stdin queries call no self-checks. All eight terminal checks are declared in this wrapper, in this dispatcher order:

  1. check_raw_guards() covers structure, actual numeric types, finite-before-domain, raw-before-prefix, domains and zero roles.
  2. check_trace_guards() covers both captured operand sides, detachment, duplicate/cap precedence, structural observers and unknown failures.
  3. check_hand_cases_and_signed_zero() covers the hand cases, default halves, beta +/-0, formal beta sensitivity and frozen +0.
  4. check_native_schedule_and_trace() covers the private scalar order and six actual native argument/result bindings.
  5. check_public_helper_and_serialization() covers every public helper field, sixteen frames and eleven tensors, while forbidding native/scalar re-evaluation during serialization.
  6. check_public_root_and_native_schedule() covers full root, summaries, aliases, counts, text arrays and native-frame/tensor copies.
  7. check_public_faults_and_unknown_errors() covers complete known fault roots and identity-preserving unknown errors.
  8. check_cli_boundary_and_check_isolation() covers complete queries, parsing, misuse, signed zero and isolation of explicit checks.

The CLI check substitutes a local self-check callable before invoking run(), so it does not recursively enter the dispatcher. Its temporary patches and streams are restored in finally. The support functions _same_words, _same_numeric_map, _expect_fault and _evaluate belong to explicit checking, not ordinary queries. The numerical helper file has no check dispatcher. These declarations are meaningful check source; they do not replace independent native admission, exact-RN authority or the restricted whole-record finite-difference proof. Source declarations alone do not establish a self-check or CLI result.

Complete iv57.py

Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""IV57 canonical public record, strict CLI and explicit checks — ALL UNRUN.

Project closure is exactly this file plus adjacent preference_reference.py.
Public metadata follows the owner-adopted actual A inventory. Ordinary imports
and queries call no checks. Scalar mechanics remain independently authored.
"""
import importlib.util
from pathlib import Path

_spec = importlib.util.spec_from_file_location(
    "_p14_iv57_preference_reference", Path(__file__).resolve().with_name("preference_reference.py"))
if _spec is None or _spec.loader is None:
    raise ImportError("Cannot load adjacent preference_reference.py")
_reference = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_reference)

DEFAULT_IV57 = _reference.DEFAULT_IV57
NumericalFault = _reference.NumericalFault
preference_state = _reference.preference_state
preference_trace = _reference.preference_trace
evaluate_preference = _reference.evaluate_preference
_evaluate_preference_mechanics = _reference._evaluate_preference_mechanics


def _same_words(actual, expected):
    assert len(actual) == len(expected)
    for left, right in zip(actual, expected):
        assert type(left) is float and type(right) is float
        assert _reference._word(left) == _reference._word(right)


def _expect_fault(code, operation, *args):
    try:
        operation(*args)
    except NumericalFault as fault:
        assert fault.code == code
        return str(fault)
    raise AssertionError(f"Expected {code}")


def _evaluate(value=None, prefix="check"):
    trace = _reference._operand_trace()
    evaluation = _evaluate_preference_mechanics(dict(DEFAULT_IV57) if value is None else value, trace, prefix)
    return evaluation, trace


def check_raw_guards():
    default = dict(DEFAULT_IV57)
    assert tuple(preference_state(default)) == _reference.RAW_KEYS
    for bad in (None, [], (), {}, {**default, "extra": 0},
                {key: value for key, value in default.items() if key != "beta"}):
        _expect_fault("INVALID_INPUT", preference_state, bad)
    class DictSubclass(dict):
        pass
    _expect_fault("INVALID_INPUT", preference_state, DictSubclass(default))
    _expect_fault("INVALID_INPUT", preference_state, {**default, 7: 0})
    for key in default:
        for bad in (True, False, None, "0", float("nan"), float("inf"), -float("inf")):
            _expect_fault("NONFINITE", preference_state, {**default, key: bad})
        _expect_fault("INVALID_INPUT", preference_state, {**default, key: 10 ** 400})
    for key in _reference.RAW_KEYS[:4]:
        for bad in (-8.0001, -0.9999):
            _expect_fault("INVALID_INPUT", preference_state, {**default, key: bad})
        for endpoint in (-8.0, -1.0):
            assert preference_state({**default, key: endpoint})[key] == endpoint
    for bad in (-1, 0.5, 2):
        _expect_fault("INVALID_INPUT", preference_state, {**default, "preferred": bad})
    for bad in (-0.01, 2.01):
        _expect_fault("INVALID_INPUT", preference_state, {**default, "beta": bad})
    for bad in (-9, 10 ** 400):
        reason = _expect_fault("NONFINITE", preference_state,
                               {**default, "policyA": bad, "beta": float("nan")})
        assert reason == "beta must be an actual finite number."
    raw = preference_state({**default, "preferred": -0.0, "beta": -0.0})
    assert type(raw["preferred"]) is int and raw["preferred"] == 0
    _same_words([raw["beta"]], [-0.0])
    for key, expected in (("policyA", "policyA must be between -8 and -1."),
                          ("preferred", "preferred must be numeric 0 or 1."),
                          ("beta", "beta must be between 0 and 2.")):
        assert _expect_fault("INVALID_INPUT", preference_state, {**default, key: 3}) == expected
    # All raw guards precede prefix validation, even when beta is inactive.
    reason = _expect_fault("NONFINITE", evaluate_preference,
                           {**default, "beta": True}, preference_trace(), "!")
    assert reason == "beta must be an actual finite number."
    for prefix in ("", "0pair", "é", "pair-x", "pair\n", "pair\r", "pair\r\n", "pair\u2028", "pair\u2029", None, True):
        trace = preference_trace()
        assert _expect_fault("INVALID_INPUT", evaluate_preference, default, trace, prefix) == "prefix must start with an ASCII letter and contain only ASCII letters, digits or underscores."
        assert trace.steps == []
    assert _evaluate(default, "Pair_2")[0]["state"] == default


def check_trace_guards():
    # Both sides validate and save the same detached numeric records.
    def append(trace, identifier, inputs, outputs):
        return trace.add(identifier, "label", "equation", "explanation", inputs, outputs)
    for side in ("inputs", "outputs"):
        for bad in (True, False, "0", None, float("nan"), float("inf"), 10 ** 400, -(10 ** 400)):
            trace = preference_trace()
            inputs, outputs = dict(value=1.0), dict(value=2.0)
            (inputs if side == "inputs" else outputs)["value"] = bad
            _expect_fault("NONFINITE", append, trace, "bad", inputs, outputs)
            assert trace.steps == []
        for bad in ([], (), {1: 0.0}):
            trace = preference_trace()
            _expect_fault("INVALID_INPUT", append, trace, "bad", bad if side == "inputs" else {},
                          bad if side == "outputs" else {})
            assert trace.steps == []
    trace = preference_trace()
    source, result = dict(value=-0.0), dict(value=2.0)
    append(trace, "first", source, result)
    source["value"], result["value"] = 99.0, 99.0
    _same_words([trace.steps[0]["inputs"]["value"], trace.steps[0]["outputs"]["value"]], [-0.0, 2.0])
    assert tuple(trace.steps[0]) == ("id", "label", "equation", "explanation", "inputs", "outputs")
    assert _expect_fault("INVALID_INPUT", append, trace, "first", {"bad": True}, {}) == "Trace IDs must be nonempty and unique."
    for identifier in ("", None, True):
        assert _expect_fault("INVALID_INPUT", append, trace, identifier, {}, {}) == "Trace IDs must be nonempty and unique."
    for side in ("inputs", "outputs"):
        args = [dict(value=1.0), dict(value=1.0)]
        args[0 if side == "inputs" else 1]["value"] = False
        assert _expect_fault("NONFINITE", append, trace, "bad", *args) == f"bad.{side}.value must be an actual finite number."
        # Reject carriers with custom reads; never execute a getter-like items().
        class Changing(dict):
            def items(self):
                raise AssertionError("Trace reread a custom carrier.")
        args[0 if side == "inputs" else 1] = Changing(value=1.0)
        _expect_fault("INVALID_INPUT", append, trace, "custom", *args)
    for i in range(1, 512):
        append(trace, f"frame{i}", {}, {})
    assert _expect_fault("NONFINITE", append, trace, "overflow", {}, {"bad": True}) == "overflow.outputs.bad must be an actual finite number."
    assert _expect_fault("INVALID_INPUT", append, trace, "first", {}, {}) == "Trace IDs must be nonempty and unique."
    assert _expect_fault("UNSUPPORTED_SIZE", append, trace, "overflow", {}, {}) == "At most 512 operations are supported."
    assert len(trace.steps) == 512
    # Structural observer accepted; no factory/issuance brand is consulted.
    class Observer:
        def __init__(self):
            self.steps = []
        def add(self, identifier, label, equation, explanation, inputs, outputs):
            self.steps.append(dict(id=identifier, label=label, equation=equation, explanation=explanation,
                                   inputs=inputs.copy(), outputs=outputs.copy()))
    observer = Observer()
    evaluate_preference(dict(DEFAULT_IV57), observer, "observer")
    assert observer.steps[0]["id"] == "observer_policyA_exp" and len(observer.steps) == 16
    sentinel = RuntimeError("observer sentinel")
    class BrokenObserver:
        def add(self, *_args):
            raise sentinel
    try:
        evaluate_preference(dict(DEFAULT_IV57), BrokenObserver(), "observer")
    except RuntimeError as fault:
        assert fault is sentinel
    else:
        raise AssertionError("Observer failure was swallowed.")


def check_hand_cases_and_signed_zero():
    default = dict(DEFAULT_IV57)
    center, trace = _evaluate(default)
    _same_words([center["margin"], center["probability"], center["complement"]], [0.0, 0.5, 0.5])
    _same_words(center["formalGradient"], [-0.5, 0.5, 0.5, -0.5, -0.0])
    _same_words(center["effectiveGradient"], [-0.5, 0.5, 0.0, 0.0, 0.0])
    _same_words([center["elementary"][4]["input"], center["elementary"][4]["output"]], [-0.0, 1.0])
    assert 0.69 < center["loss"] < 0.70  # Independent hand enclosure of ln(2).
    assert center["mask"] == [1, 1, 0, 0, 0]
    assert center["storage"]["mask"].dtype == _reference.np.dtype("int32")
    assert center["storage"]["rawProbabilities"].shape == (2, 2)
    for name, array in center["storage"].items():
        if name != "mask":
            assert array.dtype == _reference.np.dtype("float64")
    for beta, expected in ((0.0, [-0.0, 0.0, 0.0, -0.0, -0.5]),
                            (-0.0, [0.0, -0.0, -0.0, 0.0, -0.5])):
        result, _ = _evaluate({**default, "policyA": -1.0, "beta": beta})
        _same_words(result["formalGradient"], expected)
        _same_words(result["effectiveGradient"], expected[:2] + [0.0, 0.0, 0.0])
        _same_words([result["margin"]], [beta])
        _same_words([result["operands"]["positivePart"]["outputs"]["value"]], [0.0])
        assert len(result["elementary"]) == 6
    a, _ = _evaluate({**default, "policyA": -1.0})
    b, _ = _evaluate({**default, "policyA": -1.0, "preferred": 1})
    assert a["margin"] == 1.0 and b["margin"] == -1.0
    assert a["loss"] < center["loss"] < b["loss"]
    _same_words([a["probability"], a["complement"]], [b["complement"], b["probability"]])
    assert a["formalGradient"][0] < 0.0 < b["formalGradient"][0]
    assert a["formalGradient"][4] < 0.0 < b["formalGradient"][4]
    for label, expected_margin in ((0, 28.0), (1, -28.0)):
        extreme, _ = _evaluate(dict(policyA=-1.0, policyB=-8.0, referenceA=-8.0,
                                    referenceB=-1.0, preferred=label, beta=2.0))
        assert extreme["margin"] == expected_margin
        assert 0.0 < extreme["complement"] < 1.0
        assert 0.0 < extreme["probability"] < 1.0 and extreme["loss"] > 0.0
        if label == 0:
            assert extreme["complement"] < 0.000000000001
        for remaining in extreme["storage"]["remainingMasses"].tolist():
            assert 0.0 < remaining < 1.0
    # Evidence detaches the state, trace, arrays, and returned gradient lists.
    raw = dict(DEFAULT_IV57)
    captured, history = _evaluate(raw)
    raw["policyA"] = -8.0
    captured["formalGradient"][0] = 99.0
    captured["storage"]["rawProbabilities"][0, 0] = 99.0
    assert captured["state"]["policyA"] == -2.0
    assert captured["storage"]["formalGradient"][0] == -0.5
    assert history.steps[0]["outputs"]["value"] != 99.0
    assert captured["operands"]["formalMapping"]["outputs"]["policyA"] == -0.5


def check_native_schedule_and_trace():
    math = _reference.math
    original_exp, original_log1p = math.exp, math.log1p
    observed = []
    def exp(argument):
        result = original_exp(argument)
        observed.append(("exp", argument, result))
        return result
    def log1p(argument):
        result = original_log1p(argument)
        observed.append(("log1p", argument, result))
        return result
    try:
        math.exp, math.log1p = exp, log1p
        for beta in (0.0, -0.0, 1.0, 2.0):
            observed.clear()
            result, trace = _evaluate({**dict(DEFAULT_IV57), "policyA": -1.0, "beta": beta}, "native")
            assert [kind for kind, _, _ in observed] == ["exp"] * 5 + ["log1p"]
            leaves = result["elementary"]
            assert len(leaves) == len(observed) == 6
            assert [leaf["id"] for leaf in leaves] == [f"native_{suffix}" for suffix in ("policyA_exp", "policyB_exp", "referenceA_exp", "referenceB_exp", "stable_exp", "log1p")]
            by_id = {frame["id"]: frame for frame in trace.steps}
            internal_names = ("rawExp0", "rawExp1", "rawExp2", "rawExp3", "stableExp", "logPart")
            for name, leaf, (kind, argument, output) in zip(internal_names, leaves, observed):
                assert tuple(leaf) == ("id", "kind", "input", "output")
                assert leaf["kind"] == kind
                _same_words([leaf["input"], leaf["output"]], [argument, output])
                frame = by_id[f"native_{name}"]
                _same_words([frame["inputs"]["argument"], frame["outputs"]["value"]], [argument, output])
            _same_words([leaves[5]["input"]], [leaves[4]["output"]])
            order = [frame["id"].removeprefix("native_") for frame in trace.steps]
            assert order == ["rawExp0", "rawExp1", "rawExp2", "rawExp3", "policySum", "referenceSum",
                             "policyRest", "referenceRest", "selection", "dPolicy", "dReference", "delta", "margin",
                             "negMargin", "absMargin", "expArgument", "stableExp", "denominator", "probability",
                             "complement", "logPart", "positivePart", "loss", "negativeBeta", "negativeDelta",
                             "minus", "plus", "betaFormal", "formalMapping", "effective0", "effective1",
                             "effective2", "effective3", "effective4"]
    finally:
        math.exp, math.log1p = original_exp, original_log1p


def _same_numeric_map(actual, expected):
    assert tuple(actual) == tuple(expected)
    for key, value in expected.items():
        if type(value) is int:  # Declared VALUE selectors/counts only.
            assert type(actual[key]) in (int, float) and actual[key] == value
        else:
            _same_words([actual[key]], [value])


def check_public_helper_and_serialization():
    """Bind every helper field, frame operand and tensor cell to saved FIRST."""
    layouts = [
        ("policyA_exp", "argument", "value"), ("policyB_exp", "argument", "value"),
        ("referenceA_exp", "argument", "value"), ("referenceB_exp", "argument", "value"),
        ("masses", "policyProbabilityA policyProbabilityB referenceProbabilityA referenceProbabilityB one", "policySum referenceSum policyRemaining referenceRemaining"),
        ("selection", "preferred policyA policyB referenceA referenceB", "chosenPolicy rejectedPolicy chosenReference rejectedReference"),
        ("relative", "chosenPolicy rejectedPolicy chosenReference rejectedReference beta", "dPolicy dReference delta margin"),
        ("stability", "margin", "negMargin absMargin expArgument"), ("stable_exp", "argument", "value"),
        ("denominator", "one t", "denominator"), ("sigmoids", "margin t denominator one", "probability complement"),
        ("log1p", "argument", "value"), ("loss", "positiveZero negMargin logPart", "positivePart loss"),
        ("gradient_products", "beta delta complement", "negativeBeta negativeDelta minus plus betaFormal"),
        ("formal", "preferred minus plus betaFormal", "policyA policyB referenceA referenceB beta"),
        ("mask", "positiveZero formal0 enabled0 formal1 enabled1 formal2 enabled2 formal3 enabled3 formal4 enabled4", "effective0 effective1 effective2 effective3 effective4"),
    ]
    tensor_layouts = [
        ("Raw", [6], ["RawField"]), ("Probabilities", [2, 2], ["Model", "Response"]),
        ("Masses", [2, 2], ["Model", "MassField"]), ("Selected", [2, 2], ["Model", "PreferenceRole"]),
        ("Relative", [4], ["RelativeField"]), ("Stable", [10], ["StableField"]),
        ("GradientProducts", [5], ["GradientProductField"]), ("FormalGradient", [5], ["Coordinate"]),
        ("EffectiveGradient", [5], ["Coordinate"]), ("Mask", [5], ["Coordinate"]),
        ("Elementary", [6, 2], ["NativeCall", "NativeField"]),
    ]
    cases = [{}, {"preferred": 1}, {"preferred": -0.0, "beta": -0.0}, {"beta": 0.0, "policyA": -1.0},
             {"beta": -0.0, "policyA": -1.0}, {"beta": float.fromhex("0x0.0000000000001p-1022")},
             dict(policyA=-1.0, policyB=-8.0, referenceA=-8.0, referenceB=-1.0, beta=2.0),
             dict(policyA=-8.0, policyB=-1.0, referenceA=-1.0, referenceB=-8.0, beta=2.0, preferred=1)]
    for prefix in ("pair", "v3Plus", "v3Minus"):
        for patch in cases:
            captured, _ = _evaluate({**dict(DEFAULT_IV57), **patch}, prefix)
            op, state = captured["operands"], captured["state"]
            def value(name):
                return op[name]["outputs"]["value"]
            # Serialization must not execute ANY graph/native primitive again.
            math = _reference.math
            original_exp, original_log1p, original_computed = math.exp, math.log1p, _reference._computed
            def forbidden(*_args):
                raise AssertionError("Public serialization repeated a numerical primitive.")
            trace = preference_trace()
            try:
                math.exp = math.log1p = _reference._computed = forbidden
                helper = _reference._public_evaluation(captured, trace, prefix)
            finally:
                math.exp, math.log1p, _reference._computed = original_exp, original_log1p, original_computed
            assert tuple(helper) == ("state", "loss", "margin", "probability", "complement", "formalGradient", "effectiveGradient", "mask", "elementary", "tensors")
            _same_numeric_map(helper["state"], state)
            for key in ("loss", "margin", "probability", "complement"):
                _same_words([helper[key]], [captured[key]])
            for key in ("formalGradient", "effectiveGradient"):
                _same_words(helper[key], captured[key])
            assert helper["mask"] == [1, 1, 0, 0, 0]
            assert len(helper["elementary"]) == 6 and len(trace.steps) == 16
            for frame, (suffix, inputs, outputs) in zip(trace.steps, layouts):
                assert tuple(frame) == ("id", "label", "equation", "explanation", "inputs", "outputs")
                assert frame["id"] == f"{prefix}_{suffix}"
                assert tuple(frame["inputs"]) == tuple(inputs.split()) and tuple(frame["outputs"]) == tuple(outputs.split())
                assert all(type(frame[key]) is str and frame[key] for key in ("label", "equation", "explanation"))
            frames = {frame["id"].removeprefix(prefix + "_"): frame for frame in trace.steps}
            for actual, original in zip(helper["elementary"], captured["elementary"]):
                assert tuple(actual) == ("id", "kind", "input", "output")
                assert actual["id"] == original["id"] and actual["kind"] == original["kind"]
                _same_words([actual["input"], actual["output"]], [original["input"], original["output"]])
                frame = next(frame for frame in trace.steps if frame["id"] == actual["id"])
                _same_numeric_map(frame["inputs"], dict(argument=actual["input"]))
                _same_numeric_map(frame["outputs"], dict(value=actual["output"]))
                assert frame["equation"] == f'value={actual["kind"]}(argument)'
            probabilities = [value(f"rawExp{i}") for i in range(4)]
            selected = op["selection"]["outputs"]
            relative = dict(dPolicy=value("dPolicy"), dReference=value("dReference"), delta=value("delta"), margin=value("margin"))
            stability = {key: value(key) for key in ("negMargin", "absMargin", "expArgument")}
            products = {key: value(key) for key in ("negativeBeta", "negativeDelta", "minus", "plus", "betaFormal")}
            expected = {
                "masses": (dict(policyProbabilityA=probabilities[0], policyProbabilityB=probabilities[1], referenceProbabilityA=probabilities[2], referenceProbabilityB=probabilities[3], one=1.0), dict(policySum=value("policySum"), referenceSum=value("referenceSum"), policyRemaining=value("policyRest"), referenceRemaining=value("referenceRest"))),
                "selection": (dict(preferred=state["preferred"], **{key: state[key] for key in _reference.RAW_KEYS[:4]}), selected),
                "relative": (dict(**selected, beta=state["beta"]), relative),
                "stability": (dict(margin=captured["margin"]), stability),
                "denominator": (dict(one=1.0, t=value("stableExp")), dict(denominator=value("denominator"))),
                "sigmoids": (dict(margin=captured["margin"], t=value("stableExp"), denominator=value("denominator"), one=1.0), dict(probability=captured["probability"], complement=captured["complement"])),
                "loss": (dict(positiveZero=0.0, negMargin=value("negMargin"), logPart=value("logPart")), dict(positivePart=value("positivePart"), loss=captured["loss"])),
                "gradient_products": (dict(beta=state["beta"], delta=value("delta"), complement=captured["complement"]), products),
                "formal": (dict(preferred=state["preferred"], minus=value("minus"), plus=value("plus"), betaFormal=value("betaFormal")), op["formalMapping"]["outputs"]),
            }
            mask_inputs, mask_outputs = dict(positiveZero=0.0), {}
            for i in range(5):
                mask_inputs[f"formal{i}"] = captured["formalGradient"][i]
                mask_inputs[f"enabled{i}"] = captured["mask"][i]
                mask_outputs[f"effective{i}"] = captured["effectiveGradient"][i]
            expected["mask"] = (mask_inputs, mask_outputs)
            for suffix, (inputs, outputs) in expected.items():
                _same_numeric_map(frames[suffix]["inputs"], inputs)
                _same_numeric_map(frames[suffix]["outputs"], outputs)
            tensor_values = [list(state.values()), probabilities,
                             [value("policySum"), value("policyRest"), value("referenceSum"), value("referenceRest")],
                             list(selected.values()), list(relative.values()),
                             [*stability.values(), value("stableExp"), value("denominator"), captured["probability"], captured["complement"], value("logPart"), value("positivePart"), captured["loss"]],
                             list(products.values()), captured["formalGradient"], captured["effectiveGradient"], captured["mask"],
                             [number for leaf in captured["elementary"] for number in (leaf["input"], leaf["output"])]]
            assert len(helper["tensors"]) == 11 and sum(len(t["values"]) for t in helper["tensors"]) == 64
            for tensor, (suffix, shape, axes), values in zip(helper["tensors"], tensor_layouts, tensor_values):
                assert tuple(tensor) == ("id", "shape", "axes", "dtype", "values", "provenance", "precision")
                assert tensor["id"] == f"{prefix}_{suffix}" and tensor["shape"] == shape and tensor["axes"] == axes
                assert tensor["dtype"] == ("int32" if suffix == "Mask" else "float64")
                assert tensor["precision"] == (0 if suffix == "Mask" else 8)
                assert len(tensor["values"]) == len(values)
                assert type(tensor["provenance"]) is str
                assert tensor["provenance"].startswith("Exact " if suffix == "Selected" else "Actual ")
                for actual, expected_value in zip(tensor["values"], values):
                    if type(expected_value) is int:
                        assert actual == expected_value and type(actual) in (int, float)
                    else:
                        _same_words([actual], [expected_value])
            # Mutate every returned container family; retained FIRST/frame words survive.
            helper["state"]["policyA"] = 99.0
            helper["formalGradient"][0] = helper["effectiveGradient"][0] = 99.0
            helper["mask"][0] = 0
            helper["elementary"][0]["output"] = helper["tensors"][1]["values"][0] = 99.0
            _same_words([state["policyA"]], [op["selection"]["inputs"]["policyA"]])
            _same_words([frames["formal"]["outputs"]["policyA"]], [captured["formalGradient"][0]])
            _same_words([trace.steps[0]["outputs"]["value"]], [captured["elementary"][0]["output"]])
            assert captured["mask"][0] == 1


def check_public_root_and_native_schedule():
    """Whole root/alias/copy contract, with exactly six real native calls."""
    import json
    math = _reference.math
    original_exp, original_log1p = math.exp, math.log1p
    observed = []
    def exp(argument):
        result = original_exp(argument)
        observed.append(("exp", argument, result))
        return result
    def log1p(argument):
        result = original_log1p(argument)
        observed.append(("log1p", argument, result))
        return result
    try:
        math.exp, math.log1p = exp, log1p
        for beta in (0.0, -0.0, 1.0, 2.0):
            for preferred in (0, 1):
                observed.clear()
                raw = {**dict(DEFAULT_IV57), "beta": beta, "preferred": preferred}
                root = derive_iv57(raw)
                assert tuple(root) == ("status", "outputs", "steps", "tensors", "texts") and root["status"] == "defined"
                assert [kind for kind, _, _ in observed] == ["exp"] * 5 + ["log1p"]
                assert len(root["steps"]) == 18 and len(root["outputs"]) == 87 and len(root["tensors"]) == 11
                assert [s["id"] for s in root["steps"]] == ["setup", *[f"pair_{name}" for name in ("policyA_exp", "policyB_exp", "referenceA_exp", "referenceB_exp", "masses", "selection", "relative", "stability", "stable_exp", "denominator", "sigmoids", "log1p", "loss", "gradient_products", "formal", "mask")], "finish"]
                steps = {step["id"]: step for step in root["steps"]}
                outputs = root["outputs"]
                aliases = [f'{s["id"]}_{key}' for s in root["steps"] for key in s["outputs"]]
                assert tuple(outputs) == ("preferenceLoss", "relativeMargin", "pairwisePreferenceProbability", "policyChosenGradient", *aliases)
                assert len(set(aliases)) == 83
                for step in root["steps"]:
                    assert tuple(step) == ("id", "label", "equation", "explanation", "inputs", "outputs")
                    for key, number in step["outputs"].items():
                        _same_numeric_map({key: outputs[f'{step["id"]}_{key}']}, {key: number})
                _same_numeric_map(steps["setup"]["inputs"], preference_state(raw))
                _same_numeric_map(steps["setup"]["outputs"], dict(**preference_state(raw), pairCount=1, responseCount=2, differentiableCoordinates=5, policyCoordinates=2, frozenCoordinates=3, optimizerSteps=0))
                counts = dict(rawExponentialCalls=4, stableExponentialCalls=1, exponentialCalls=5, log1pCalls=1,
                              pairSumAdditions=2, remainingMassSubtractions=2, logDifferenceSubtractions=2,
                              relativeSubtractions=1, marginMultiplications=1, marginNegations=1, absoluteValues=1,
                              stableArgumentNegations=1, denominatorAdditions=1, probabilityDivisions=2,
                              lossMaxSelections=1, lossAdditions=1, gradientNegations=2, gradientMultiplications=3,
                              chosenRejectedCopies=4, formalCoordinateCopies=5, effectiveCoordinateSelections=5,
                              enabledGradientCopies=2, frozenPositiveZeros=3, elementaryOccurrences=6, frames=18, tensorCount=11)
                summaries = {key: outputs[key] for key in ("preferenceLoss", "relativeMargin", "pairwisePreferenceProbability", "policyChosenGradient")}
                _same_numeric_map(steps["finish"]["outputs"], dict(**summaries, **counts))
                _same_numeric_map(steps["finish"]["inputs"], dict(loss=summaries["preferenceLoss"], margin=summaries["relativeMargin"], probability=summaries["pairwisePreferenceProbability"], preferred=preferred, chosenGradient=summaries["policyChosenGradient"]))
                _same_words([outputs["preferenceLoss"], outputs["relativeMargin"], outputs["pairwisePreferenceProbability"], outputs["policyChosenGradient"]],
                            [steps["pair_loss"]["outputs"]["loss"], steps["pair_relative"]["outputs"]["margin"], steps["pair_sigmoids"]["outputs"]["probability"], steps["pair_formal"]["outputs"]["policyA" if preferred == 0 else "policyB"]])
                texts = root["texts"]
                assert tuple(texts) == tuple("prompt responseLabels responseTexts labelPolicy inputPolicy shapePolicy probabilityPolicy relativePolicy objectivePolicy gradientPolicy effectivePolicy zeroPolicy betaPolicy limitsPolicy numericPolicy admissionPolicy diagnosticPolicy computePolicy provenance rawFields modelKeys responseKeys preferenceRoles coordinateKeys massFields relativeFields stableFields gradientProductFields elementaryFields elementaryIds elementaryKinds integerValuePolicy".split())
                assert texts["prompt"] == "Suggest a short break" and texts["responseLabels"] == ["A", "B"]
                assert texts["responseTexts"] == ["Stretch your arms for a moment", "Look away from your screen for a moment"]
                assert texts["rawFields"] == list(_reference.RAW_KEYS) and texts["coordinateKeys"] == ["policyA", "policyB", "referenceA", "referenceB", "beta"]
                arrays = dict(modelKeys=["policy", "reference"], responseKeys=["A", "B"], preferenceRoles=["chosen", "rejected"],
                              massFields=["sum", "remaining"], relativeFields=["dPolicy", "dReference", "delta", "margin"],
                              stableFields=["negMargin", "absMargin", "expArgument", "t", "denominator", "probability", "complement", "logPart", "positivePart", "loss"],
                              gradientProductFields=["negativeBeta", "negativeDelta", "minus", "plus", "betaFormal"], elementaryFields=["input", "output"])
                for key, expected in arrays.items():
                    assert texts[key] == expected
                assert texts["elementaryIds"] == [f"pair_{suffix}" for suffix in ("policyA_exp", "policyB_exp", "referenceA_exp", "referenceB_exp", "stable_exp", "log1p")]
                assert texts["elementaryKinds"] == ["exp"] * 5 + ["log1p"]
                for identifier, (kind, argument, result) in zip(texts["elementaryIds"], observed):
                    frame = steps[identifier]
                    assert frame["equation"] == f"value={kind}(argument)"
                    _same_words([frame["inputs"]["argument"], frame["outputs"]["value"]], [argument, result])
                _same_words(root["tensors"][-1]["values"], [number for _, argument, result in observed for number in (argument, result)])
                # Complete finite JSON serialization retains float negative zeros.
                decoded = json.loads(json.dumps(root, allow_nan=False))
                _same_words([decoded["steps"][0]["inputs"]["beta"]], [beta])
                assert decoded["texts"] == texts
                saved_word = _reference._word(outputs["preferenceLoss"])
                raw["policyA"] = 99.0
                root["tensors"][5]["values"][-1] = root["steps"][-1]["outputs"]["preferenceLoss"] = 99.0
                assert _reference._word(outputs["preferenceLoss"]) == saved_word
    finally:
        math.exp, math.log1p = original_exp, original_log1p


def check_public_faults_and_unknown_errors():
    """Complete fault roots, native failure reasons and unknown identity escape."""
    default = dict(DEFAULT_IV57)
    for raw, code, reason in (
        (None, "INVALID_INPUT", "state must be a plain object."),
        ({}, "INVALID_INPUT", "state must have exactly policyA, policyB, referenceA, referenceB, preferred, beta as own fields."),
        ({**default, "policyA": -9, "beta": float("nan")}, "NONFINITE", "beta must be an actual finite number."),
        ({**default, "policyA": -9}, "INVALID_INPUT", "policyA must be between -8 and -1."),
        ({**default, "preferred": 2}, "INVALID_INPUT", "preferred must be numeric 0 or 1."),
        ({**default, "beta": 3}, "INVALID_INPUT", "beta must be between 0 and 2."),
    ):
        root = derive_iv57(raw)
        assert tuple(root) == ("status", "code", "reason")
        assert root == dict(status="unavailable", code=code, reason=reason)
    original_evaluate = evaluate_preference
    for sentinel in (ValueError("semantic sentinel"), TypeError("programmer sentinel"), MemoryError("resource sentinel")):
        def broken(*_args):
            raise sentinel
        try:
            globals()["evaluate_preference"] = broken
            try:
                derive_iv57(default)
            except type(sentinel) as fault:
                assert fault is sentinel
            else:
                raise AssertionError("Public root swallowed an unknown exception.")
        finally:
            globals()["evaluate_preference"] = original_evaluate
    math = _reference.math
    original_exp, original_log1p = math.exp, math.log1p
    try:
        for bad in (True, float("nan"), float("inf")):
            math.exp = lambda _argument: bad
            assert derive_iv57(default) == dict(status="unavailable", code="NONFINITE", reason="pair_policyA_exp value must be an actual finite number.")
        math.exp = original_exp
        math.log1p = lambda _argument: float("nan")
        assert derive_iv57(default) == dict(status="unavailable", code="NONFINITE", reason="pair_log1p value must be an actual finite number.")
        sentinel = RuntimeError("native sentinel")
        def broken_native(_argument):
            raise sentinel
        math.exp = broken_native
        try:
            derive_iv57(default)
        except RuntimeError as fault:
            assert fault is sentinel
        else:
            raise AssertionError("Native exception identity was lost.")
    finally:
        math.exp, math.log1p = original_exp, original_log1p


def strict_json(source):
    """Full replacement JSON: no duplicate keys, nonfinite constants, or -0 loss."""
    import json
    def pairs(entries):
        result = {}
        for key, value in entries:
            if key in result:
                raise ValueError("Duplicate JSON object key.")
            result[key] = value
        return result
    def constant(_token):
        raise ValueError("Nonfinite JSON constant.")
    def integer(token):
        return -0.0 if token == "-0" else int(token)
    return json.loads(source, object_pairs_hook=pairs, parse_constant=constant, parse_int=integer)


def _texts(evaluated):
    """Exact adopted public strings; array IDs/kinds copy this actual evaluation."""
    return dict(
        prompt="Suggest a short break",
        responseLabels=["A", "B"],
        responseTexts=["Stretch your arms for a moment", "Look away from your screen for a moment"],
        labelPolicy="Preferred zero chooses A and one chooses B. These are author-written responses and an illustrative editable ranking, not model outputs, measured human-study preferences, objective truth or a safety judgment. Numeric ranking scores and ties are outside this strict-label example.",
        inputPolicy="Provide exactly six own data fields on an ordinary or null-prototype object. Check all descriptors, then all six actual finite numbers, then domains in raw order. Four log-probabilities lie in [-8,-1], preferred is numeric0or1, beta lies in [0,2] including negative zero. No coercion, clipping, getters or partial default filling.",
        shapePolicy="One prompt-response pair has scalar log-probabilities, margin, logistic probabilities and loss. Raw log-probabilities form [Model=2,Response=2] in policy/reference then A/B order. The five derivative coordinates are policyA,policyB,referenceA,referenceB,beta. There is no token, batch, hidden mean or parameter axis; preferred has no derivative.",
        probabilityPolicy="Exponentiate each of the four raw log-probabilities separately. Add the policy pair and reference pair, then compute each remaining mass as1-sum. Positive remaining mass belongs to unspecified other outcomes. Never divide by the two-response sum: the pair is not a complete modeled distribution.",
        relativePolicy="Copy chosen and rejected log-probabilities by the label. Compute dPolicy=chosenPolicy-rejectedPolicy, dReference=chosenReference-rejectedReference, delta=dPolicy-dReference and margin=beta*delta, in that order. The reference subtracts its own preference rather than supplying a target probability.",
        objectivePolicy="Compute negMargin=-margin, absMargin=abs(margin), expArgument=-absMargin, t=exp(expArgument), denominator=1+t. If margin>=0, probability=1/denominator then complement=t/denominator; otherwise probability=t/denominator then complement=1/denominator. Next compute logPart=log1p(t), positivePart=max(+0,negMargin), loss=positivePart+logPart. Complement is never1-probability.",
        gradientPolicy="The smooth real loss has margin derivative -complement. Compute negativeBeta=-beta, negativeDelta=-delta, minus=negativeBeta*complement, plus=beta*complement and betaFormal=negativeDelta*complement. For label0 map [minus,plus,plus,minus,betaFormal]; for label1 map [plus,minus,minus,plus,betaFormal]. Reference components are exact copies of the actual policy products.",
        effectivePolicy="All five formal partials describe independently varied coordinates with the other inputs held fixed. Select mask[1,1,0,0,0]: policy entries copy their formal values; frozen reference and beta entries are explicit floating positive zeros. Frozen does not mean a zero formal derivative or reset reference scores. No update or optimizer is run.",
        zeroPolicy="Beta positive or negative zero still evaluates all five exp calls, the log1p call and every declared arithmetic operation. Both signed margin zeros use the nonnegative branch; abs gives positive zero, expArgument negative zero, and max(+0,negMargin) positive zero. Preserve every raw/arithmetic/copy word; at default delta positive zero gives betaFormal negative zero. Frozen effective zeros are positive zero.",
        betaPolicy="At beta zero the real loss is ln2 and policy/reference gradient magnitudes are zero, but formal beta sensitivity is -delta/2 and can be nonzero. Increasing beta decreases real loss when delta>0 and increases it when delta<0. A smaller objective value alone does not establish better response quality.",
        limitsPolicy="The real margin stays in [-28,28]. The stable exponential cannot overflow or underflow in that interval, while other small-beta products may round to signed zero. Log-probability coordinates are editable sensitivities, not already network-logit or neural-parameter gradients; normalized model constraints need an additional chain rule.",
        numericPolicy="Each stated arithmetic primitive is a separate finite binary64 operation with round-to-nearest ties-to-even, no contraction or reassociation. Save the actual native exp/log1p arguments and results in six distinct frames before independent assessment. Display precision never feeds computation; formal gradients evaluate the smooth real chain rule at stored values, not derivatives of the rounding map.",
        admissionPolicy="A separate authority may admit each producer own native words within four ordered finite binary64 word steps of an independently proved correctly rounded reference. Exp at either signed zero requires the exact positive-one word. Then exact-RN replay binds all arithmetic and copies. This per-call policy is not a whole-gradient tolerance, cross-language word equality or physical runtime provenance proof; unresolved reference enclosures fail closed.",
        diagnosticPolicy="The exact-zero centered-difference proof is restricted to all four raw log-probabilities WORD-2, preferred VALUE0, beta WORD+1, policy coordinate0or1 and h WORD2^-10. Verify the complete actual central record, both complete actual endpoint helpers, every native occurrence, paired stable-exp/log1p argument and result words, the common-logPart binade and all exact loss-difference/quotient/gradient words before any zero verdict. Any failed premise fails closed; no other state or coordinate inherits this claim.",
        computePolicy="Work counts describe one evaluation of the declared graph, including all four raw probability displays, one shared stable exponential, one log1p, all formal coordinates and all five effective selections. Copy counts cover the named selection/mapping stages, not serialization or snapshot storage. Frames include setup and finish; tensorCount includes every helper tensor. Counts are source bookkeeping, not timings or hardware evidence.",
        provenance="Self-authored fixed prompt, two benign responses, log-probability defaults and editable strict ranking. This chapter evaluates a transparent pairwise objective without training a model, measuring human preferences or certifying alignment. Runtime validation remains deferred under the FluxGeo hold.",
        rawFields=["policyA", "policyB", "referenceA", "referenceB", "preferred", "beta"],
        modelKeys=["policy", "reference"], responseKeys=["A", "B"], preferenceRoles=["chosen", "rejected"],
        coordinateKeys=["policyA", "policyB", "referenceA", "referenceB", "beta"], massFields=["sum", "remaining"],
        relativeFields=["dPolicy", "dReference", "delta", "margin"],
        stableFields=["negMargin", "absMargin", "expArgument", "t", "denominator", "probability", "complement", "logPart", "positivePart", "loss"],
        gradientProductFields=["negativeBeta", "negativeDelta", "minus", "plus", "betaFormal"], elementaryFields=["input", "output"],
        elementaryIds=[leaf["id"] for leaf in evaluated["elementary"]],
        elementaryKinds=[leaf["kind"] for leaf in evaluated["elementary"]],
        integerValuePolicy="Preferred, masks, coordinate selectors, shapes, indices and work counts use VALUE comparison. In pair_Raw only preferred at index4 is VALUE; all other mixed-table entries are WORD. pair_Mask is int32 precision0. All other tensors are float64 precision8, with their true arithmetic/copy entries compared by WORD including signed zeros. Text, field order, IDs, kinds, axes and provenance require exact structured/string comparison.")


def derive_iv57(value):
    """Complete root; catch known numerical faults only, preserving their reason."""
    try:
        raw, trace = preference_state(value), preference_trace()
        trace.add("setup", "Set up one authored preference pair and a fixed reference comparison",
                  "raw=[policyA,policyB,referenceA,referenceB,preferred,beta]; mask=[1,1,0,0,0]; optimizerSteps=0",
                  "The prompt and both responses are authored examples. Four independent log-probability inputs represent policy and reference scores for A and B; a discrete label chooses their comparison order. Evaluate the objective and sensitivities without updating any model or renormalizing this pair.",
                  raw.copy(), dict(**raw, pairCount=1, responseCount=2, differentiableCoordinates=5, policyCoordinates=2, frozenCoordinates=3, optimizerSteps=0))
        evaluated = evaluate_preference(raw, trace, "pair")
        tensors = evaluated["tensors"]
        summaries = dict(preferenceLoss=evaluated["loss"], relativeMargin=evaluated["margin"],
                         pairwisePreferenceProbability=evaluated["probability"],
                         policyChosenGradient=evaluated["formalGradient"][0 if raw["preferred"] == 0 else 1])
        work = dict(rawExponentialCalls=4, stableExponentialCalls=1, exponentialCalls=5, log1pCalls=1,
                    pairSumAdditions=2, remainingMassSubtractions=2, logDifferenceSubtractions=2,
                    relativeSubtractions=1, marginMultiplications=1, marginNegations=1, absoluteValues=1,
                    stableArgumentNegations=1, denominatorAdditions=1, probabilityDivisions=2,
                    lossMaxSelections=1, lossAdditions=1, gradientNegations=2, gradientMultiplications=3,
                    chosenRejectedCopies=4, formalCoordinateCopies=5, effectiveCoordinateSelections=5,
                    enabledGradientCopies=2, frozenPositiveZeros=3, elementaryOccurrences=len(evaluated["elementary"]),
                    frames=len(trace.steps) + 1, tensorCount=len(tensors))
        trace.add("finish", "Report the same saved loss, relative margin and chosen-policy sensitivity",
                  "preferenceLoss=pair.loss; relativeMargin=pair.margin; pairwisePreferenceProbability=pair.probability; policyChosenGradient=pair.formalGradient[preferred==0?0:1]",
                  "These four summaries copy the complete evaluated pair. A lower loss means a more favorable labeled policy-versus-reference comparison under this objective. It establishes neither factual correctness nor safety. Counts describe the declared source operations, not measured time, memory, training or backend accuracy.",
                  dict(loss=evaluated["loss"], margin=evaluated["margin"], probability=evaluated["probability"], preferred=raw["preferred"], chosenGradient=summaries["policyChosenGradient"]),
                  dict(**summaries, **work))
        texts = _texts(evaluated)
        outputs = summaries.copy()
        for step in trace.steps:
            for key, entry in step["outputs"].items():
                alias = f'{step["id"]}_{key}'
                if alias in outputs:
                    raise RuntimeError("IV57 output aliases must be unique.")
                outputs[alias] = entry
        return _reference.deepcopy(dict(status="defined", outputs=outputs, steps=trace.steps, tensors=tensors, texts=texts))
    except NumericalFault as fault:
        return dict(status="unavailable", code=fault.code, reason=str(fault))


def run():
    """Strict zero-argument entrypoint; explicit checks OUTSIDE all fault catches."""
    import json
    import sys
    args = sys.argv[1:]
    if args == ["--self-check"]:
        source_self_check()
        print("IV57 explicit source self-checks completed.")
        return 0
    if len(args) > 1 or (args and args[0].startswith("--")):
        print("Usage: iv57.py [JSON|-|--self-check]", file=sys.stderr)
        return 2
    if not args:
        value = dict(DEFAULT_IV57)
    else:
        source = sys.stdin.read() if args[0] == "-" else args[0]
        try:
            value = strict_json(source)
        except ValueError as fault:
            print(json.dumps(dict(status="unavailable", code="INVALID_INPUT", reason=str(fault)), allow_nan=False))
            return 0
    print(json.dumps(derive_iv57(value), allow_nan=False))
    return 0


def check_cli_boundary_and_check_isolation():
    """In-process CLI checks are explicit source, never ordinary-query work."""
    import contextlib
    import io
    import json
    import sys
    saved_argv, saved_stdin = sys.argv, sys.stdin
    original_derive, original_check, original_parser = derive_iv57, source_self_check, strict_json
    def invoke(args, source=""):
        sys.argv, sys.stdin = ["iv57.py", *args], io.StringIO(source)
        out, err = io.StringIO(), io.StringIO()
        with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
            status = run()
        return status, out.getvalue(), err.getvalue()
    def forbidden_check():
        raise AssertionError("Ordinary query called a self-check.")
    try:
        globals()["source_self_check"] = forbidden_check
        for source in ("{", "{} {}", '{"beta":0,"beta":1}', "NaN", "Infinity", "-Infinity",
                       "1" * 5000, "null", "[]", "true", "{}"):
            code, output, error = invoke([source])
            assert code == 0 and not error
            assert tuple(json.loads(output)) == ("status", "code", "reason")
            assert json.loads(output)["status"] == "unavailable"
        code, output, error = invoke(["-"], '{"policyA":-9,"policyB":-2,"referenceA":-2,"referenceB":-2,"preferred":0,"beta":1e999}')
        assert code == 0 and not error
        assert json.loads(output) == dict(status="unavailable", code="NONFINITE", reason="beta must be an actual finite number.")
        for args in (["{}", "{}"], ["--unknown"], ["--self-check", "{}"]):
            code, output, error = invoke(args)
            assert code == 2 and not output and "Usage:" in error
        # Valid default/replacement/stdin return complete roots without checks.
        for args, source in (([], ""), ([json.dumps(dict(DEFAULT_IV57))], ""),
                             (["-"], '{"policyA":-2,"policyB":-2,"referenceA":-2,"referenceB":-2,"preferred":-0,"beta":-0}')):
            code, output, error = invoke(args, source)
            record = json.loads(output)
            assert code == 0 and not error and record["status"] == "defined"
            assert tuple(record) == ("status", "outputs", "steps", "tensors", "texts")
            assert len(record["steps"]) == 18 and len(record["outputs"]) == 87
        parsed = strict_json('{"beta":-0}')
        _same_words([parsed["beta"]], [-0.0])
        seen = []
        def capture(value):
            seen.append(value)
            return dict(status="unavailable", code="INVALID_INPUT", reason="capture only")
        globals()["derive_iv57"] = capture
        invoke([])
        invoke(["-"], '{"beta":-0}')
        assert seen[0] == dict(DEFAULT_IV57) and tuple(seen[1]) == ("beta",)
        _same_words([seen[1]["beta"]], [-0.0])
        for sentinel in (ValueError("semantic sentinel"), json.JSONDecodeError("semantic JSON class", "", 0),
                         MemoryError("resource sentinel")):
            def broken(_value):
                raise sentinel
            globals()["derive_iv57"] = broken
            try:
                invoke([])
            except type(sentinel) as fault:
                assert fault is sentinel
            else:
                raise AssertionError("Unknown semantic/resource exception was swallowed.")
        for sentinel in (TypeError("parser programmer sentinel"), MemoryError("parser resource sentinel")):
            def broken_parser(_source):
                raise sentinel
            globals()["strict_json"] = broken_parser
            try:
                invoke(["{}"])
            except type(sentinel) as fault:
                assert fault is sentinel
            else:
                raise AssertionError("Unknown parser exception was swallowed.")
        # Even a KNOWN fault injected into the explicit check must escape run().
        for sentinel in (NumericalFault("NONFINITE", "check sentinel"), AssertionError("check assertion")):
            def broken_check():
                raise sentinel
            globals()["source_self_check"] = broken_check
            try:
                invoke(["--self-check"])
            except type(sentinel) as fault:
                assert fault is sentinel
            else:
                raise AssertionError("Explicit self-check failure was swallowed.")
    finally:
        globals()["derive_iv57"], globals()["source_self_check"], globals()["strict_json"] = original_derive, original_check, original_parser
        sys.argv, sys.stdin = saved_argv, saved_stdin


def source_self_check():
    """Only explicit dispatch reaches these checks; no public acceptance claim."""
    if not __debug__:
        raise RuntimeError("Explicit source checks require assertions enabled.")
    check_raw_guards()
    check_trace_guards()
    check_hand_cases_and_signed_zero()
    check_native_schedule_and_trace()
    check_public_helper_and_serialization()
    check_public_root_and_native_schedule()
    check_public_faults_and_unknown_errors()
    check_cli_boundary_and_check_isolation()


if __name__ == "__main__":
    raise SystemExit(run())

Use the five corrective questions in the lab

There is exactly one graded set, inside the lab above. Its first question separates raw probability from the logistic comparison; the second works the complete favorable nondefault case; the third compares five-entry formal/effective vectors at the default and at beta zero. The fifth uses the case where policy A outranks B but the reference favors A more strongly. Its feedback explains why freezing the reference does not erase its gap or certify truth/safety. Choosing an answer immediately displays corrective reasoning; changing the choice changes the feedback. There is no second grader in this chapter text.

The fourth question uses the current whole saved root, including all six raw values, both gaps, saved delta, margin, p, q and loss. It interprets the smooth real function with that saved delta as its fixed coefficient. This matters when the saved subtractions have rounded: the question does not silently recompute a different exact-real coefficient from the original inputs. It asks about a sufficiently small beta increase below 2, or an allowed decrease when beta equals 2.

Saved deltaBeta below 2: small increaseBeta at 2: small decrease
PositiveLowers the real lossRaises the real loss
NegativeRaises the real lossLowers the real loss
Either signed zeroLeaves real loss ln(2) unchangedLeaves real loss ln(2) unchanged

The reason is the real derivative −δq-\delta q, with positive real qq. At beta +0 or -0, formal beta is −δ/2-\delta/2 and may be nonzero, despite zero-magnitude log-probability partials and an effective beta of +0. At delta zero, constant loss under beta changes does not erase policy/reference partials when beta is positive. A strict real direction need not produce visible binary64 movement for a particular tiny edit: products or changes can round away. Selecting a trace frame clears the answer but does not change this whole-root rule. Invalid drafts expose no numerical question or stale answer evidence.

What the objective leaves unresolved

Shift both policy log-probabilities from (−2,−2)(-2,-2) to (−3,−3)(-3,-3) while leaving the reference and label fixed. Both policy gaps are zero, so the real loss stays ln⁡2\ln2, but the selected policy mass falls from 2exp⁡(−2)2\exp(-2) to 2exp⁡(−3)2\exp(-3). The objective cannot identify absolute chosen-response probability from a gap alone. This is a counterexample to “equal preference loss means equal distributions.” A matching valid common shift in a model’s two log-probabilities likewise preserves that model’s gap.

Changing the label changes the target comparison without changing either response’s content. A biased or mistaken label can be optimized just as faithfully as a useful one. This authored pair supplies neither annotator agreement nor evidence of generalization to other prompts. A reference-relative loss also does not measure distance from the reference over the full outcome space or impose a complete normalization constraint.

These limits explain why we evaluated an objective rather than inventing a training run. Extending it to a learned policy needs data collection, a normalized model, parameter gradients, an optimizer and independent evaluation. None is supplied by lowering this one scalar.

Carry these distinctions forward

  • The label specifies a strict chosen/rejected order; arbitrary rating gaps are not log-probabilities.
  • The margin compares policy and reference log-probability gaps, while raw probabilities retain unmodeled mass.
  • One shared stable exponential feeds direct pp, direct qq and log1p loss after the four raw exponentials.
  • All five formal partials exist; the policy-only mask selects two without updating a model or erasing the others.
  • Native admission and exact centered-difference claims have explicit, narrow premises; preference fit establishes neither truth nor safety.

Revisit IV-55 — Pretraining, Fine-Tuning and Transfer to connect an objective with actual adaptation, and VII.1 — Logarithms and log probabilities in computation to review why subtracting log-probabilities compares probability ratios. IV-58, Alignment, Safety and Evaluation Limits, next separates training objectives, evaluation proxies and observed behavior. The unresolved questions here are exactly why that separation matters.