|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +// Compares `A.transpose().mmul(B)` (materializes the transpose) with the fused |
| 4 | +// `A.transposeMultiply(B)` (streams rows, never materializes the transpose). |
| 5 | +// Run after `npm run compile`: node benchmark/transposeMultiply.js |
| 6 | + |
| 7 | +let benchmark = require('benchmark'); |
| 8 | + |
| 9 | +let { Matrix } = require('..'); |
| 10 | +let { SparseMatrix } = require('ml-sparse-matrix'); |
| 11 | + |
| 12 | +// (m x n)ᵀ · (m x p) -> (n x p) |
| 13 | +const cases = [ |
| 14 | + { m: 256, n: 256, p: 256, label: 'dense 256' }, |
| 15 | + { m: 512, n: 512, p: 512, label: 'dense 512' }, |
| 16 | + { m: 252, n: 252, p: 210, label: 'dense 252x210 (NMR block)' }, |
| 17 | +]; |
| 18 | + |
| 19 | +for (const { m, n, p, label } of cases) { |
| 20 | + const A = Matrix.rand(m, n); |
| 21 | + const B = Matrix.rand(m, p); |
| 22 | + |
| 23 | + const reference = A.transpose().mmul(B); |
| 24 | + const fused = A.transposeMultiply(B); |
| 25 | + if (!reference.to2DArray().flat().every((v, i) => v === fused.to2DArray().flat()[i])) { |
| 26 | + throw new Error('transposeMultiply result differs from transpose().mmul()'); |
| 27 | + } |
| 28 | + |
| 29 | + new benchmark.Suite(label) |
| 30 | + .add(`${label}: transpose().mmul()`, () => { |
| 31 | + A.transpose().mmul(B); |
| 32 | + }) |
| 33 | + .add(`${label}: transposeMultiply()`, () => { |
| 34 | + A.transposeMultiply(B); |
| 35 | + }) |
| 36 | + .on('cycle', (event) => { |
| 37 | + console.log(String(event.target)); |
| 38 | + }) |
| 39 | + .on('complete', function onComplete() { |
| 40 | + console.log(` fastest: ${this.filter('fastest').map('name')}\n`); |
| 41 | + }) |
| 42 | + .run(); |
| 43 | +} |
| 44 | + |
| 45 | +// Sparse `this`: the zero-skip in transposeMultiply avoids most of the work. |
| 46 | +// Build the sparse operand with the real ml-sparse-matrix package (a few |
| 47 | +// non-zeros per row, as in the NMR spin-simulation operators) and densify it, |
| 48 | +// the path such callers take before multiplying. |
| 49 | +const builder = new SparseMatrix(512, 512); |
| 50 | +for (let i = 0; i < 512; i++) { |
| 51 | + for (let k = 0; k < 9; k++) builder.set(i, (i * 31 + k * 101) % 512, k + 1); |
| 52 | +} |
| 53 | +const sparse = new Matrix(builder.to2DArray()); |
| 54 | +const dense = Matrix.rand(512, 256); |
| 55 | +new benchmark.Suite('sparse') |
| 56 | + .add('sparse 512x512 (9 nnz/row): transpose().mmul()', () => { |
| 57 | + sparse.transpose().mmul(dense); |
| 58 | + }) |
| 59 | + .add('sparse 512x512 (9 nnz/row): transposeMultiply()', () => { |
| 60 | + sparse.transposeMultiply(dense); |
| 61 | + }) |
| 62 | + .on('cycle', (event) => { |
| 63 | + console.log(String(event.target)); |
| 64 | + }) |
| 65 | + .on('complete', function onComplete() { |
| 66 | + console.log(` fastest: ${this.filter('fastest').map('name')}`); |
| 67 | + }) |
| 68 | + .run(); |
0 commit comments