File size: 5,338 Bytes
0a3982f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//! Combinador algébrico do Pensamento: confiança (T-P1), projeção ridge
//! (T-P3 — minimizador global único da quadrática estritamente convexa) e
//! solução de sistemas simétricos.

use candle_core::{Result, Tensor};

// ---------------------------------------------------------------------------
// Confiança e gatilho (T-P1)
// ---------------------------------------------------------------------------

/// Confiança da distribuição preditiva: `conf = 1 − H(softmax(z))/log K`.
///
/// **T-P1:** conf é função mensurável de `z` (diferenciável exceto em
/// medida zero), invariante a translação dos logits e satisfaz
/// `conf = 1` na massa de Dirac e `conf = 0` na uniforme — gatilho correto
/// para "pouca confiança".
pub fn confianca_de_logits(logits: &Tensor) -> Result<f64> {
    let p = candle_nn::ops::softmax(logits, candle_core::D::Minus1)?;
    let logp = p.log()?;
    let entropia = (&p * &logp)?.sum_all()?.to_scalar::<f32>()? as f64 * -1.0;
    let k = logits.dim(candle_core::D::Minus1)? as f64;
    if k <= 1.0 {
        return Ok(1.0);
    }
    Ok(1.0 - entropia / k.ln())
}

// ---------------------------------------------------------------------------
// Combinador algébrico (T-P3 — projeção ridge, Teo V-1' portado)
// ---------------------------------------------------------------------------

/// Projeção ridge: `r* = (WᵀW + εI)^{−1} Wᵀ r_alvo` — minimizador de
/// `‖W r − r_alvo‖² + ε‖r‖²` (o montador algébrico do "re-encaixe de peças").
///
/// **Prova (T-P3):** a função é quadrática estritamente convexa (ε > 0);
/// o gradiente anula-se exatamente em `r*` acima; o resíduo mínimo é
/// `‖(I − W(WᵀW+εI)^{−1}Wᵀ) r_alvo‖` — análogo direto do Teo V-1'.
pub fn projetar_ridge(w: &Tensor, r_alvo: &Tensor, eps: f64) -> Result<Tensor> {
    // w: (m, n), r_alvo: (m, d) ⇒ r*: (n, d)
    let n = w.dim(1)?;
    let dev = w.device();
    let wt = w.transpose(0, 1)?;
    let wtw = wt.matmul(w)?;
    let ident = Tensor::eye(n, candle_core::DType::F32, &dev)?.affine(eps, 0.0)?;
    let m = (&wtw + &ident)?;
    let rhs = wt.matmul(r_alvo)?;
    resolver_simetrica(&m, &rhs)
}

/// Resolve `M x = B` para M simétrica (n, n) por eliminação de Gauss com
/// pivoteamento parcial (Cholesky não assumido — M pode ser só PSD+εI).
pub fn resolver_simetrica(m: &Tensor, b: &Tensor) -> Result<Tensor> {
    let n = m.dim(0)?;
    let d = b.dim(1)?;
    let dev = m.device();
    let mut a = m.to_vec2::<f32>()?;
    let mut rhs = b.to_vec2::<f32>()?;
    for col in 0..n {
        // pivoteamento parcial
        let (mut pivo, mut linha_p) = (a[col][col].abs(), col);
        for r in col + 1..n {
            if a[r][col].abs() > pivo {
                pivo = a[r][col].abs();
                linha_p = r;
            }
        }
        if pivo < 1e-12 {
            candle_core::bail!("matriz singular (pivo ~ 0 na coluna {col})");
        }
        a.swap(col, linha_p);
        rhs.swap(col, linha_p);
        for r in col + 1..n {
            let f = a[r][col] / a[col][col];
            for c in col..n {
                a[r][c] -= f * a[col][c];
            }
            for c in 0..d {
                rhs[r][c] -= f * rhs[col][c];
            }
        }
    }
    let mut x = vec![vec![0f32; d]; n];
    for r in (0..n).rev() {
        for c in 0..d {
            let mut s = rhs[r][c];
            for k in r + 1..n {
                s -= a[r][k] * x[k][c];
            }
            x[r][c] = s / a[r][r];
        }
    }
    let flat: Vec<f32> = x.into_iter().flatten().collect();
    Ok(Tensor::from_vec(flat, (n, d), &dev)?)
}

pub fn versao() -> &'static str {
    "pensamento-0.11.0"
}

#[cfg(test)]
mod testes {
    use super::*;
    use crate::rng::RngDeterministico;
    use candle_core::Device;

    #[test]
    fn teste_confianca_extremos() {
        // T-P1: Dirac ⇒ conf = 1; uniforme ⇒ conf = 0
        let dev = Device::Cpu;
        let dirac = Tensor::from_vec(vec![100.0f32, 0.0, 0.0, 0.0], (1, 4), &dev).unwrap();
        let uniforme = Tensor::from_vec(vec![0.0f32; 4], (1, 4), &dev).unwrap();
        let c1 = confianca_de_logits(&dirac).unwrap();
        let c0 = confianca_de_logits(&uniforme).unwrap();
        assert!(c1 > 0.999, "conf dirac = {c1}");
        assert!(c0 < 0.001, "conf uniforme = {c0}");
    }
    #[test]
    fn teste_tp3_projetar_ridge_minimiza() {
        // T-P3: r* da projeção ridge tem resíduo ≤ qualquer perturbação
        let dev = Device::Cpu;
        let w = Tensor::randn(0f32, 1.0, (8, 3), &dev).unwrap();
        let r_alvo = Tensor::randn(0f32, 1.0, (8, 5), &dev).unwrap();
        let r = projetar_ridge(&w, &r_alvo, 1e-6).unwrap();
        let residuo = |rr: &Tensor| {
            let d = (w.matmul(rr).unwrap() - &r_alvo).unwrap();
            d.sqr().unwrap().sum_all().unwrap().to_scalar::<f32>().unwrap() as f64
        };
        let f0 = residuo(&r);
        let mut rng = RngDeterministico::novo(1);
        for _ in 0..30 {
            let pert: Vec<f32> = (0..15).map(|_| rng.normal(0.0, 0.1) as f32).collect();
            let rp = (Tensor::from_vec(pert, (3, 5), &dev).unwrap() + &r).unwrap();
            let fp = residuo(&rp);
            assert!(f0 <= fp + 1e-6, "residuo r* = {f0} > perturbado {fp}");
        }
    }
}