gam-sae 0.3.153

Sparse-autoencoder latent-manifold terms for the gam penalized-likelihood engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! SAEBench-facing and manifold-native evaluation metrics.
//!
//! This module is deliberately data-only: external SAEBench runners can own the
//! model calls, LLM descriptions, and behavioral measurements, then hand their
//! typed observations to these Rust routines.  Keeping the scoring here makes
//! chart-coordinate interpretability and output-Fisher dose calibration share a
//! single audited definition with the steering code instead of reimplementing
//! math in Python notebooks.

use crate::null_battery::{NullKind, NullSummary, Tail, summarize_null_distribution};

/// One row in the chart-interpretability evaluation: a recovered coordinate,
/// its ground-truth cyclic label, and the posterior/evidence weight assigned to
/// that row.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ChartInterpObservation {
    /// Recovered chart coordinate in turns.  Values are wrapped modulo one.
    pub recovered_turns: f64,
    /// Ground-truth cyclic label in turns.  Values are wrapped modulo one.
    pub label_turns: f64,
    /// Non-negative posterior/evidence weight for this row.
    pub weight: f64,
}

/// Exact statistic calibrated by every chart-interpretability report.
///
/// Naming this in the type and persisted artifact prevents an empirical p-value
/// for a different chart claim (for example, an EV gap or cyclic adjacency)
/// from being paired with this score (#2250).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ChartInterpStatistic {
    OrientationQuotientedWeightedPhaseLock,
}

impl ChartInterpStatistic {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::OrientationQuotientedWeightedPhaseLock => {
                "orientation_quotiented_weighted_phase_lock_v1"
            }
        }
    }
}

/// Coordinate readout applied identically to the observed data and every null
/// surrogate before the phase-lock statistic is evaluated.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ChartInterpReadout {
    /// Angle in the leading two-PC plane of cyclic-label mean activations.
    TokenMeanPcaPlaneV1,
    /// Coordinate returned by a fitted chart model.
    FittedChartCoordinateV1,
}

impl ChartInterpReadout {
    pub fn parse(value: &str) -> Result<Self, String> {
        match value {
            "token_mean_pca_plane_v1" => Ok(Self::TokenMeanPcaPlaneV1),
            "fitted_chart_coordinate_v1" => Ok(Self::FittedChartCoordinateV1),
            other => Err(format!(
                "chart_interp: unsupported readout {other:?}; expected token_mean_pca_plane_v1 or fitted_chart_coordinate_v1"
            )),
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::TokenMeanPcaPlaneV1 => "token_mean_pca_plane_v1",
            Self::FittedChartCoordinateV1 => "fitted_chart_coordinate_v1",
        }
    }
}

/// How one complete null observation ledger is produced.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ChartInterpNullDrawPolicy {
    /// Regenerate the declared surrogate and repeat the explicitly declared
    /// coordinate readout before evaluating the statistic.
    RegenerateSurrogateAndRepeatReadout,
}

impl ChartInterpNullDrawPolicy {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::RegenerateSurrogateAndRepeatReadout => {
                "regenerate_surrogate_and_repeat_declared_readout_each_draw"
            }
        }
    }
}

/// Closed chart-null protocols understood by the scorer.
///
/// A protocol owns its native [`NullKind`] and draw policy. Callers therefore
/// cannot label arbitrary rows "matched spectrum" while separately selecting a
/// contradictory policy.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ChartInterpNullProtocol {
    MatchedSpectrumGaussianV1,
}

impl ChartInterpNullProtocol {
    pub fn parse(value: &str) -> Result<Self, String> {
        match value {
            "matched_spectrum_gaussian_v1" => Ok(Self::MatchedSpectrumGaussianV1),
            other => Err(format!(
                "chart_interp: unsupported null protocol {other:?}; expected matched_spectrum_gaussian_v1"
            )),
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::MatchedSpectrumGaussianV1 => "matched_spectrum_gaussian_v1",
        }
    }

    pub fn null_kind(self) -> NullKind {
        match self {
            Self::MatchedSpectrumGaussianV1 => NullKind::MatchedSpectrumGaussian,
        }
    }

    pub fn draw_policy(self) -> ChartInterpNullDrawPolicy {
        match self {
            Self::MatchedSpectrumGaussianV1 => {
                ChartInterpNullDrawPolicy::RegenerateSurrogateAndRepeatReadout
            }
        }
    }
}

/// Complete null calibration input. There is intentionally no constructor from
/// scalar statistics: the scorer accepts full per-draw observation ledgers and
/// recomputes [`ChartInterpStatistic`] itself.
#[derive(Clone, Debug, PartialEq)]
pub struct ChartInterpNullCalibration {
    protocol: ChartInterpNullProtocol,
    readout: ChartInterpReadout,
    seed: u64,
    expected_draws: usize,
    observation_draws: Vec<Vec<ChartInterpObservation>>,
}

impl ChartInterpNullCalibration {
    pub fn new(
        protocol: ChartInterpNullProtocol,
        readout: ChartInterpReadout,
        seed: u64,
        expected_draws: usize,
        observation_draws: Vec<Vec<ChartInterpObservation>>,
    ) -> Result<Self, String> {
        // TWO draws is the floor, and it is a theorem about the statistic this
        // type feeds, not a style preference. [`chart_interp_score`] always
        // summarizes the calibration through
        // [`crate::null_battery::summarize_null_distribution`], whose standard
        // deviation carries `n - 1` degrees of freedom: at `n == 1` that `sd` is
        // `0.0` BY CONSTRUCTION, so the null z-score is undefined unless the
        // single draw coincides exactly with the observation. The only one-draw
        // calibration that can be scored at all is therefore one whose "null" IS
        // the observation, which calibrates nothing -- and three fixtures were
        // passing on exactly that degenerate branch (#2699). Declaring the floor
        // here names the reason at the seam that declares the draw count,
        // instead of surfacing later as an undefined-z-score error whose cause
        // is the declaration two frames up.
        if expected_draws < 2 {
            return Err(format!(
                "chart_interp: null calibration requires at least two draws; {expected_draws} cannot supply the null spread the z-score is denominated in (sd carries n-1 degrees of freedom, so a one-draw null has sd == 0 by construction)"
            ));
        }
        if observation_draws.len() != expected_draws {
            return Err(format!(
                "chart_interp: null protocol declares {expected_draws} draws but artifact contains {} complete observation ledgers",
                observation_draws.len()
            ));
        }
        Ok(Self {
            protocol,
            readout,
            seed,
            expected_draws,
            observation_draws,
        })
    }

    pub fn protocol(&self) -> ChartInterpNullProtocol {
        self.protocol
    }

    pub fn readout(&self) -> ChartInterpReadout {
        self.readout
    }

    pub fn seed(&self) -> u64 {
        self.seed
    }

    pub fn expected_draws(&self) -> usize {
        self.expected_draws
    }

    pub fn observation_draws(&self) -> &[Vec<ChartInterpObservation>] {
        &self.observation_draws
    }
}

/// Observed value of [`ChartInterpStatistic`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ChartInterpStatisticValue {
    /// Orientation-quotiented weighted cyclic phase-lock score in `[0, 1]`.
    pub circular_correlation: f64,
    /// Signed correlation before orientation is quotiented out.
    pub signed_circular_correlation: f64,
    /// Sum of accepted observation weights.
    pub effective_weight: f64,
}

/// Provenance and native null-battery distribution for a chart statistic.
#[derive(Clone, Debug, PartialEq)]
pub struct ChartInterpNullCalibrationReport {
    /// The statistic recomputed for the observation and every null draw.
    pub statistic: ChartInterpStatistic,
    /// Closed surrogate-generation protocol.
    pub protocol: ChartInterpNullProtocol,
    /// Coordinate readout repeated for observed and null data.
    pub readout: ChartInterpReadout,
    /// Native null kind fixed by [`Self::protocol`].
    pub null_kind: NullKind,
    /// Per-draw generation/readout policy fixed by [`Self::protocol`].
    pub draw_policy: ChartInterpNullDrawPolicy,
    /// Seed from which draw-index-specific surrogates were generated.
    pub seed: u64,
    /// Native null distribution, including kind, tail, summary, Monte Carlo
    /// uncertainty, extreme count, and every statistic sample in draw order.
    pub null_distribution: NullSummary,
}

/// Evidential decision after null calibration.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ChartInterpVerdict {
    Pass,
    NullCompatible,
}

impl ChartInterpVerdict {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Pass => "pass",
            Self::NullCompatible => "null_compatible",
        }
    }
}

/// Null-calibrated chart-interpretability artifact.
#[derive(Clone, Debug, PartialEq)]
pub struct ChartInterpReport {
    pub statistic: ChartInterpStatistic,
    pub observed: ChartInterpStatisticValue,
    pub calibration: ChartInterpNullCalibrationReport,
    /// Significance level used for the evidential verdict.
    pub significance_level: f64,
    pub verdict: ChartInterpVerdict,
}

/// One dose-response calibration point along a steered arc.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DoseResponseObservation {
    /// Arc-length coordinate or any unit-speed path coordinate used for the move.
    pub arc_length: f64,
    /// Local output-Fisher prediction from `steer_delta`, in nats.
    pub predicted_nats: f64,
    /// Measured KL / behavior change in nats.
    pub measured_nats: f64,
    /// Non-negative posterior/evidence weight for this row or intervention.
    pub weight: f64,
}

/// Weighted calibration fit of measured nats on predicted output-Fisher nats.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DoseResponseCalibrationReport {
    /// Slope of the no-intercept weighted least-squares fit
    /// `measured_nats = slope * predicted_nats`.
    pub slope_through_origin: f64,
    /// Weighted R² of that no-intercept calibration fit.
    pub r2_through_origin: f64,
    /// Weighted mean of `measured_nats / arc_length²` for non-zero arcs.
    pub mean_measured_nats_per_arc_squared: f64,
    /// Weighted coefficient of variation of `measured_nats / arc_length²`.
    pub cv_measured_nats_per_arc_squared: f64,
    /// Sum of accepted observation weights.
    pub effective_weight: f64,
}

/// Gaussian posterior summary for one token/chart coordinate block from an
/// already-factorized row-Hessian precision block.
#[derive(Clone, Debug, PartialEq)]
pub struct CoordinatePosterior {
    /// Posterior mean coordinate supplied by the fit/encoder.
    pub mean: Vec<f64>,
    /// Diagonal of the covariance matrix, i.e. the inverse row-Hessian diagonal.
    pub covariance_diag: Vec<f64>,
    /// Trace of the covariance matrix, used as an uncertainty weight source.
    pub covariance_trace: f64,
    /// Precision-weighted evidence mass `1 / trace(covariance)`.
    pub precision_weight: f64,
}

/// Score chart-coordinate interpretability against cyclic labels and an explicit
/// matched-spectrum null distribution.
///
/// Every null draw is a complete observation ledger produced by the same chart
/// fit/readout protocol on one matched-spectrum surrogate. The exact
/// orientation-quotiented statistic used for the observed ledger is recomputed
/// for every null ledger. Requiring the draws here makes it impossible for the
/// public scorer to present a large circular correlation as evidence without
/// calibrating that same number against its matched null (#2250).
pub fn chart_interp_score(
    observations: &[ChartInterpObservation],
    null_calibration: &ChartInterpNullCalibration,
    significance_level: f64,
) -> Result<ChartInterpReport, String> {
    if !(significance_level.is_finite() && significance_level > 0.0 && significance_level < 1.0) {
        return Err(format!(
            "chart_interp: significance_level must be finite and in (0, 1), got {significance_level}"
        ));
    }
    let (circular_correlation, signed_circular_correlation, weight_sum) =
        chart_correlation(observations, "chart_interp observed")?;
    let mut null_statistics = Vec::with_capacity(null_calibration.expected_draws());
    for (draw_idx, draw) in null_calibration.observation_draws().iter().enumerate() {
        validate_null_ledger_alignment(observations, draw, draw_idx)?;
        let (null_statistic, _, _) =
            chart_correlation(draw, &format!("chart_interp null draw {draw_idx}"))?;
        null_statistics.push(null_statistic);
    }
    let statistic = ChartInterpStatistic::OrientationQuotientedWeightedPhaseLock;
    let protocol = null_calibration.protocol();
    let null_distribution = summarize_null_distribution(
        protocol.null_kind(),
        circular_correlation,
        null_statistics,
        Tail::Larger,
    )?;
    let verdict = if null_distribution.p_value <= significance_level {
        ChartInterpVerdict::Pass
    } else {
        ChartInterpVerdict::NullCompatible
    };
    Ok(ChartInterpReport {
        statistic,
        observed: ChartInterpStatisticValue {
            circular_correlation,
            signed_circular_correlation,
            effective_weight: weight_sum,
        },
        calibration: ChartInterpNullCalibrationReport {
            statistic,
            protocol,
            readout: null_calibration.readout(),
            null_kind: protocol.null_kind(),
            draw_policy: protocol.draw_policy(),
            seed: null_calibration.seed(),
            null_distribution,
        },
        significance_level,
        verdict,
    })
}

fn validate_null_ledger_alignment(
    observed: &[ChartInterpObservation],
    null_draw: &[ChartInterpObservation],
    draw_idx: usize,
) -> Result<(), String> {
    if null_draw.len() != observed.len() {
        return Err(format!(
            "chart_interp null draw {draw_idx} has {} rows but observed ledger has {}; the generation/readout protocol requires the same labeled rows",
            null_draw.len(),
            observed.len()
        ));
    }
    for (row, (observed_row, null_row)) in observed.iter().zip(null_draw).enumerate() {
        if wrap_turns(observed_row.label_turns) != wrap_turns(null_row.label_turns) {
            return Err(format!(
                "chart_interp null draw {draw_idx} changes label_turns at row {row}; matched-spectrum draws must score the identical labeled ledger"
            ));
        }
    }
    Ok(())
}

fn chart_correlation(
    observations: &[ChartInterpObservation],
    context: &str,
) -> Result<(f64, f64, f64), String> {
    let weight_sum = validate_weights(observations.iter().map(|o| o.weight), context)?;
    for (row, observation) in observations.iter().enumerate() {
        if !(observation.recovered_turns.is_finite() && observation.label_turns.is_finite()) {
            return Err(format!(
                "{context}: recovered_turns and label_turns must be finite at row {row}"
            ));
        }
    }
    let same = weighted_phase_lock(
        observations.iter().map(|o| {
            (
                wrap_turns(o.label_turns) - wrap_turns(o.recovered_turns),
                o.weight,
            )
        }),
        weight_sum,
    );
    let reversed = weighted_phase_lock(
        observations.iter().map(|o| {
            (
                wrap_turns(o.label_turns) + wrap_turns(o.recovered_turns),
                o.weight,
            )
        }),
        weight_sum,
    );
    let signed = if same >= reversed { same } else { -reversed };
    Ok((
        same.max(reversed).min(1.0),
        signed.clamp(-1.0, 1.0),
        weight_sum,
    ))
}

/// Fit the dose-response calibration ledger.
pub fn dose_response_calibration(
    observations: &[DoseResponseObservation],
) -> Result<DoseResponseCalibrationReport, String> {
    let weight_sum = validate_weights(observations.iter().map(|o| o.weight), "dose_response")?;
    let mut x2 = 0.0;
    let mut xy = 0.0;
    let mut y2 = 0.0;
    let mut rate_w = 0.0;
    let mut rate_sum = 0.0;
    for obs in observations {
        if !(obs.arc_length.is_finite()
            && obs.predicted_nats.is_finite()
            && obs.measured_nats.is_finite())
        {
            return Err(
                "dose_response: arc_length, predicted_nats, and measured_nats must be finite"
                    .into(),
            );
        }
        if obs.predicted_nats < 0.0 || obs.measured_nats < 0.0 {
            return Err(
                "dose_response: predicted_nats and measured_nats must be non-negative".into(),
            );
        }
        x2 += obs.weight * obs.predicted_nats * obs.predicted_nats;
        xy += obs.weight * obs.predicted_nats * obs.measured_nats;
        y2 += obs.weight * obs.measured_nats * obs.measured_nats;
        if obs.arc_length > 0.0 {
            let rate = obs.measured_nats / (obs.arc_length * obs.arc_length);
            rate_w += obs.weight;
            rate_sum += obs.weight * rate;
        }
    }
    if x2 <= 0.0 || y2 <= 0.0 {
        return Err("dose_response: non-zero predicted and measured nats are required".into());
    }
    if rate_w <= 0.0 {
        return Err("dose_response: at least one positive arc_length is required".into());
    }
    let slope = xy / x2;
    let sse = observations.iter().fold(0.0, |acc, obs| {
        let residual = obs.measured_nats - slope * obs.predicted_nats;
        acc + obs.weight * residual * residual
    });
    let mean_rate = rate_sum / rate_w;
    let rate_var = observations.iter().fold(0.0, |acc, obs| {
        if obs.arc_length > 0.0 {
            let residual = obs.measured_nats / (obs.arc_length * obs.arc_length) - mean_rate;
            acc + obs.weight * residual * residual
        } else {
            acc
        }
    }) / rate_w;
    let cv = if mean_rate > 0.0 {
        rate_var.sqrt() / mean_rate
    } else {
        0.0
    };
    Ok(DoseResponseCalibrationReport {
        slope_through_origin: slope,
        r2_through_origin: (1.0 - sse / y2).clamp(0.0, 1.0),
        mean_measured_nats_per_arc_squared: mean_rate,
        cv_measured_nats_per_arc_squared: cv,
        effective_weight: weight_sum,
    })
}

/// Expose per-token coordinate posterior uncertainty from a row-Hessian block.
pub fn coordinate_posterior_from_precision(
    mean: &[f64],
    precision_row_major: &[f64],
) -> Result<CoordinatePosterior, String> {
    let d = mean.len();
    if d == 0 {
        return Err("coordinate_posterior: coordinate dimension must be positive".into());
    }
    if precision_row_major.len() != d * d {
        return Err(format!(
            "coordinate_posterior: precision block has length {} but mean dimension {d} requires {} entries",
            precision_row_major.len(),
            d * d
        ));
    }
    for (i, &m) in mean.iter().enumerate() {
        if !m.is_finite() {
            return Err(format!("coordinate_posterior: mean[{i}] is not finite"));
        }
    }
    let max_abs = precision_row_major
        .iter()
        .copied()
        .map(f64::abs)
        .fold(0.0_f64, f64::max);
    if !max_abs.is_finite() {
        return Err("coordinate_posterior: precision block contains a non-finite entry".into());
    }
    let symmetry_tol = f64::EPSILON * d.max(1) as f64 * max_abs.max(1.0);
    for row in 0..d {
        for col in 0..row {
            let lower = precision_row_major[row * d + col];
            let upper = precision_row_major[col * d + row];
            if (lower - upper).abs() > symmetry_tol {
                return Err(format!(
                    "coordinate_posterior: precision block is not symmetric at ({row}, {col}): \
                     {lower} versus {upper} (tolerance {symmetry_tol:e})"
                ));
            }
        }
    }
    let chol = cholesky_lower(precision_row_major, d)?;
    let mut diag = vec![0.0; d];
    for basis in 0..d {
        let mut e = vec![0.0; d];
        e[basis] = 1.0;
        let col = solve_cholesky(&chol, &e, d);
        diag[basis] = col[basis];
    }
    let trace: f64 = diag.iter().sum();
    if !(trace.is_finite() && trace > 0.0) {
        return Err(
            "coordinate_posterior: inverse precision trace must be finite and positive".into(),
        );
    }
    Ok(CoordinatePosterior {
        mean: mean.to_vec(),
        covariance_diag: diag,
        covariance_trace: trace,
        precision_weight: 1.0 / trace,
    })
}

fn validate_weights<I>(weights: I, context: &str) -> Result<f64, String>
where
    I: IntoIterator<Item = f64>,
{
    let mut sum = 0.0;
    let mut count = 0usize;
    for weight in weights {
        count += 1;
        if !(weight.is_finite() && weight >= 0.0) {
            return Err(format!(
                "{context}: weights must be finite and non-negative"
            ));
        }
        sum += weight;
    }
    if count == 0 || sum <= 0.0 {
        return Err(format!(
            "{context}: at least one positive-weight observation is required"
        ));
    }
    Ok(sum)
}

fn wrap_turns(x: f64) -> f64 {
    x.rem_euclid(1.0)
}

fn weighted_phase_lock<I>(values: I, weight_sum: f64) -> f64
where
    I: IntoIterator<Item = (f64, f64)>,
{
    let mut c = 0.0;
    let mut s = 0.0;
    for (turns, weight) in values {
        let angle = std::f64::consts::TAU * turns;
        c += weight * angle.cos();
        s += weight * angle.sin();
    }
    (c * c + s * s).sqrt() / weight_sum
}

fn cholesky_lower(a: &[f64], d: usize) -> Result<Vec<f64>, String> {
    let mut l = vec![0.0; d * d];
    for i in 0..d {
        for j in 0..=i {
            let mut sum = a[i * d + j];
            for k in 0..j {
                sum -= l[i * d + k] * l[j * d + k];
            }
            if i == j {
                if !(sum.is_finite() && sum > 0.0) {
                    return Err(
                        "coordinate_posterior: precision block must be symmetric positive definite"
                            .into(),
                    );
                }
                l[i * d + j] = sum.sqrt();
            } else {
                l[i * d + j] = sum / l[j * d + j];
            }
        }
    }
    Ok(l)
}

fn solve_cholesky(l: &[f64], b: &[f64], d: usize) -> Vec<f64> {
    let mut y = vec![0.0; d];
    for i in 0..d {
        let mut sum = b[i];
        for k in 0..i {
            sum -= l[i * d + k] * y[k];
        }
        y[i] = sum / l[i * d + i];
    }
    let mut x = vec![0.0; d];
    for i in (0..d).rev() {
        let mut sum = y[i];
        for k in i + 1..d {
            sum -= l[k * d + i] * x[k];
        }
        x[i] = sum / l[i * d + i];
    }
    x
}