gemm caching bug, incorrect gradient

Aperta
#3,908 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
43/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
c, cpp, rust

Direzione di ricerca

Start by compiling and running the Rust reproducer in the issue, which calls cblas_sgemm and checks gradients against closed-form results. Compare the overwrite cases for A and B with the no-overwrite case across both layouts and dimensions. The issue is resolved when the reported gradients match the expected values within the stated tolerance.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

@wsmoses nothing urgent + haven't looked closely, but should be straightforward.

// Reverse-mode std::autodiff through one cblas_sgemm call whose input is overwritten afterwards,
// so Enzyme has to cache that input for the reverse pass.
//   C (m x n) = A (m x k) * B^T,  B stored row major as (n x k);  loss = sum_ij W_ij C_ij
// argv: m n k which layout   (which: 0 = no overwrite, 1 = A overwritten, 2 = B overwritten; layout: 101 row major, 102 column major)
#![feature(autodiff)]
use std::autodiff::autodiff_reverse;
unsafe extern "C" {
    fn cblas_sgemm(layout: i32, ta: i32, tb: i32, m: i32, n: i32, k: i32, alpha: f32, a: *const f32, lda: i32,
                   b: *const f32, ldb: i32, beta: f32, c: *mut f32, ldc: i32);
}
#[autodiff_reverse(d_f, Duplicated, Duplicated, Duplicated, Const, Const, Const, Const, Const, Active)]
#[inline(never)]
fn f(a: &mut [f32], b: &mut [f32], c: &mut [f32], m: usize, n: usize, k: usize, which: usize, layout: i32) -> f32 {
    assert!(a.len() >= m * k && b.len() >= n * k && c.len() >= m * n);
    let (lda, ldb, ldc) = if layout == 101 { (k, k, n) } else { (m, n, m) };
    unsafe { cblas_sgemm(layout, 111, 112, m as i32, n as i32, k as i32, 1.0, a.as_ptr(), lda as i32, b.as_ptr(), ldb as i32, 0.0, c.as_mut_ptr(), ldc as i32) }
    let mut s = 0.0;
    for i in 0..m * n { s += (1.0 + i as f32 * 0.25) * c[i]; }
    if which == 1 { for x in a.iter_mut() { *x = 0.0; } }
    if which == 2 { for x in b.iter_mut() { *x = 0.0; } }
    s
}
fn main() {
    let arg = |i: usize, d: usize| std::env::args().nth(i).and_then(|v| v.parse().ok()).unwrap_or(d);
    let (m, n, k, which) = (arg(1, 3), arg(2, 4), arg(3, 5), arg(4, 1));
    let layout = arg(5, 101) as i32;
    let row = layout == 101;
    let a0: Vec<f32> = (0..m * k).map(|i| 0.1 + 0.07 * i as f32).collect();
    let b0: Vec<f32> = (0..n * k).map(|i| -0.3 + 0.05 * i as f32).collect();
    let (mut a, mut b) = (a0.clone(), b0.clone());
    let (mut da, mut db) = (vec![0.0f32; m * k], vec![0.0f32; n * k]);
    let (mut c, mut dc) = (vec![0.0f32; m * n], vec![0.0f32; m * n]);
    d_f(&mut a, &mut da, &mut b, &mut db, &mut c, &mut dc, m, n, k, which, layout, 1.0);
    // closed form: dA = W B, dB = W^T A (both in the row-major layouts above)
    let ia = |i: usize, kk: usize| if row { i * k + kk } else { i + kk * m };
    let ib = |j: usize, kk: usize| if row { j * k + kk } else { j + kk * n };
    let w = |i: usize, j: usize| 1.0 + (if row { i * n + j } else { i + j * m }) as f32 * 0.25;
    let (mut ea, mut eb) = (0.0f32, 0.0f32);
    for i in 0..m { for kk in 0..k {
        let mut s = 0.0; for j in 0..n { s += w(i, j) * b0[ib(j, kk)]; }
        ea = ea.max((s - da[ia(i, kk)]).abs());
    } }
    for kk in 0..k { for j in 0..n {
        let mut s = 0.0; for i in 0..m { s += a0[ia(i, kk)] * w(i, j); }
        eb = eb.max((s - db[ib(j, kk)]).abs());
    } }
    let (sa, sb): (f32, f32) = (da.iter().map(|v| v.abs()).sum(), db.iter().map(|v| v.abs()).sum());
    let what = ["nothing", "A", "B"][which];
    let lay = if row { "row-major" } else { "col-major" };
    println!("{lay} m={m} n={n} k={k}, {what} overwritten: dA abssum {sa:.3} max err {ea:.1e} | dB abssum {sb:.3} max err {eb:.1e}  {}",
             if ea < 1e-2 && eb < 1e-2 { "OK" } else { "WRONG" });
}
Lingua principale
LLVM
Stelle
1.7k
Fork
204
Merge medio
18h 36m
PR unite (30g)
136

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di EnzymeAD/Enzyme

Tutte le issue di EnzymeAD/Enzyme

Issue simili

Altre issue su Compilers

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.