Skip to main content

engine.solvers.fine_tuning

engine.solvers.fine_tuning

Fine-tuning solvers: what a serialized trajectory teaches, and what the update costs.

Domain implementations behind mlsysim.solvers (added 2026-10-20). Each model is arithmetic on stated counts: one serialized example’s positions under a target mask, one example per model call against one transcript, recorded transcripts split by role, a long trajectory’s weight under token and example averaging, padding against packing, one preference pair under the DPO loss, a distilled per-turn prefix against its bill, and a candidate policy’s release comparison. None models a trained network’s learning dynamics.

Classes

Name Description
LossNormalizationModel One long trajectory’s weight in a batch under token and example averaging.
PerInvocationSerializationModel One training example per model call against one stored transcript.
PreferencePairModel One preference pair under the DPO loss, against its value at a zero margin.
SequencePackingModel Variable-length examples padded to the longest against packed into fixed buffers.
TargetMaskModel One serialized example’s positions under two target masks.

LossNormalizationModel

engine.solvers.fine_tuning.LossNormalizationModel()

One long trajectory’s weight in a batch under token and example averaging.

The batch holds the trajectory, split into focus_pieces records that each select every turn’s response once, and other_examples examples of other_targets selected targets each. Token averaging weights each example by its target count, so splitting changes nothing; example averaging weights each record once, so the trajectory’s share rises from 1/B to k/(B - 1 + k).

Methods

Name Description
solve Compare target-token weighting with equal-record weighting.
solve
engine.solvers.fine_tuning.LossNormalizationModel.solve(
    focus_targets,
    other_examples,
    other_targets,
    focus_pieces=1,
)

Compare target-token weighting with equal-record weighting.

Parameters
Name Type Description Default
focus_targets int Positive selected-target count of the focus trajectory. required
other_examples int Positive count of other records. required
other_targets int Positive target count in each other record. required
focus_pieces int Positive number of focus records after splitting; default one. 1
Returns
Name Type Description
LossNormalizationResult Counts and dimensionless weighting shares.
Notes

Equation: focus_token_share = focus_targets / (focus_targets + other_examples * other_targets); focus_example_share = focus_pieces / (focus_pieces + other_examples).

Assumptions: Splitting preserves all focus targets; other records have equal target counts.

Excludes: Gradient magnitudes, optimization dynamics, and changes in training quality.

References

Derivation: Token averaging normalizes by target counts; equal-record averaging normalizes by the count of records.

Examples
>>> LossNormalizationModel().solve(20, 2, 10).focus_token_share
0.5

PerInvocationSerializationModel

engine.solvers.fine_tuning.PerInvocationSerializationModel()

One training example per model call against one stored transcript.

When each of H turns adds about a tokens, call t carries t a tokens, so separate examples store a H (H + 1) / 2 tokens against a H for one transcript: the append-only resend triangle (calc_append_only_context with s0 = delta = a), an expansion of (H + 1) / 2.

Methods

Name Description
solve Compare repeated call prefixes with one stored transcript.
solve
engine.solvers.fine_tuning.PerInvocationSerializationModel.solve(
    turns,
    tokens_per_turn,
)

Compare repeated call prefixes with one stored transcript.

Parameters
Name Type Description Default
turns int Positive number of turns. required
tokens_per_turn int Positive number of tokens appended per turn. required
Returns
Name Type Description
PerInvocationSerializationResult Token counts and a dimensionless storage expansion.
Notes

Equation: transcript = a H; per_invocation = a H (H + 1) / 2.

Assumptions: Every turn appends the same a tokens and stores its full prefix.

Excludes: Compression, deduplication, tokenization, and model execution.

References

Derivation: Summing prefix lengths a, 2a, …, Ha yields the arithmetic-series total.

Examples
>>> PerInvocationSerializationModel().solve(3, 10).expansion
2.0

PreferencePairModel

engine.solvers.fine_tuning.PreferencePairModel()

One preference pair under the DPO loss, against its value at a zero margin.

At initialization the policy equals the reference, so both scores are zero, the loss is ln 2, the saturation factor is 1/2, and the coefficient is beta / 2. The logistic score depends on beta, so it measures fit to this comparison, not a success probability.

Methods

Name Description
solve Evaluate one DPO preference margin and logistic loss.
solve
engine.solvers.fine_tuning.PreferencePairModel.solve(
    policy_preferred,
    reference_preferred,
    policy_dispreferred,
    reference_dispreferred,
    beta,
)

Evaluate one DPO preference margin and logistic loss.

Parameters
Name Type Description Default
policy_preferred float Log probability of the preferred response under the policy, dimensionless. required
reference_preferred float Log probability of the preferred response under the reference, dimensionless. required
policy_dispreferred float Log probability of the dispreferred response under the policy, dimensionless. required
reference_dispreferred float Log probability of the dispreferred response under the reference, dimensionless. required
beta float Positive dimensionless scale of the policy/reference log-ratio margin. required
Returns
Name Type Description
PreferencePairResult Dimensionless margin, logistic score, loss, saturation, and gradient coefficient.
Notes

Equation: margin = beta * ((policy_preferred - reference_preferred) - (policy_dispreferred - reference_dispreferred)); loss = -log(sigmoid(margin)).

Assumptions: The supplied log probabilities describe one preferred/dispreferred pair; initialization has zero log-ratio margin.

Excludes: Sequence generation, empirical success probability, and training dynamics.

References

Derivation: The negative log-sigmoid gives pairwise logistic loss; differentiating the margin yields the saturation factor and beta-scaled coefficient. This wrapper delegates the calculation to calc_preference_pair.

Examples
>>> PreferencePairModel().solve(0.0, 0.0, 0.0, 0.0, 0.2).preference_score
0.5

SequencePackingModel

engine.solvers.fine_tuning.SequencePackingModel()

Variable-length examples padded to the longest against packed into fixed buffers.

Padding allocates N rows of the longest length, so occupancy is the mean length over the maximum. Packing places examples longest first into the first capacity-token buffer with room (first-fit decreasing). Occupancy counts context and targets alike; it is not measured throughput.

Methods

Name Description
solve Compare padding with first-fit-decreasing sequence packing.
solve
engine.solvers.fine_tuning.SequencePackingModel.solve(lengths, capacity)

Compare padding with first-fit-decreasing sequence packing.

Parameters
Name Type Description Default
lengths sequence of int Nonempty sequence of positive token counts, each no larger than capacity. required
capacity int Positive token capacity of each packing buffer. required
Returns
Name Type Description
SequencePackingResult Token-position counts, buffer loads, and dimensionless occupancies.
Notes

Equation: padded = N * max(lengths); packed = number_of_buffers * capacity; occupancy = sum(lengths) / allocated_positions.

Assumptions: Examples remain whole; first-fit decreasing determines the buffer placement.

Excludes: Attention masking costs, runtime throughput, and optimal bin packing.

References

Derivation: Allocated positions count rectangular padding or fixed buffers; occupancy is occupied divided by allocated positions.

Examples
>>> SequencePackingModel().solve([2, 2], 4).packed_occupancy
1.0

TargetMaskModel

engine.solvers.fine_tuning.TargetMaskModel()

One serialized example’s positions under two target masks.

The example stores a prompt, a task, an optional rationale, the policy’s responses, and the observations. Targets are the responses minus the unselected ones (kept as context), with or without the rationale. The first stored position has no preceding position, so an unmasked token average divides by stored - 1 prediction terms; each target’s weight shrinks by (stored - 1) / targets.

Methods

Name Description
solve Count stored context and selected prediction targets.
solve
engine.solvers.fine_tuning.TargetMaskModel.solve(
    prompt,
    task,
    rationale,
    response,
    observation,
    unselected_response,
)

Count stored context and selected prediction targets.

Parameters
Name Type Description Default
prompt int Prompt token count, nonnegative. required
task int Task-description token count, nonnegative. required
rationale int Rationale token count, nonnegative. required
response int Response token count, positive. required
observation int Observation token count, nonnegative. required
unselected_response int Response tokens retained as context; from zero to response minus one. required
Returns
Name Type Description
TargetMaskResult Token counts and dimensionless target shares and dilution ratios.
Notes

Equation: stored = prompt + task + rationale + response + observation; selected = response - unselected_response; predicted = stored - 1.

Assumptions: Counts refer to a single serialized sequence; the first position has no preceding predictor.

Excludes: Tokenizer behavior, model quality, and loss values.

References

Derivation: Subtracting excluded responses counts targets; dividing by stored positions or prediction terms gives the reported shares and dilution.

Examples
>>> TargetMaskModel().solve(2, 1, 1, 4, 2, 1).selected_response
3
Back to top