Skip to content
Snippets Groups Projects
tf4pi.html 1.38 KiB
Newer Older
  • Learn to ignore specific revisions
  • Neil Gershenfeld's avatar
    wip
    Neil Gershenfeld committed
    <html>
    <body>
    <script src=tf.min.js></script>
    <script>
    //
    // tf4pi.html
    // Neil Gershenfeld 11/18/18
    // Ann Yuan 12/4/18
    // TensorFlow.js pi calculation benchmark
    // pi = 3.14159265358979323846
    //
    
    const points = 1e10;
    const a = tf.scalar(0.5)
    const b = tf.scalar(0.75)
    const c = tf.scalar(0.25)
    
    const indicesPerTexel = 1000;
    const outputSize = points / indicesPerTexel;
    
    const divMulIndexSubProgram = {
      variableNames: ['X', 'Y', 'Z'],
      outputShape: [outputSize],
      userCode: `
        float compute(float i) {
          return 0.5 / ((i - 0.75) * (i - 0.25));
        }
    
        void main() {
          float i = float(getOutputCoords());
          float sum = 0.;
          for(int index=0; index<${indicesPerTexel}; index++) {
            sum += compute(float(i * ${indicesPerTexel}. + float(index)));
          }
          setOutput(sum);
        }
      `
    }
    
    function divMulIndexSub(x, y, z) {
      return tf.ENV.backend.compileAndRun(divMulIndexSubProgram, [x, y, z]);
    }
    
    function f() {
      const product = divMulIndexSub(b, c, a);
    
      return tf.sum(product).dataSync();
    }
    
    // Warmup
    f();
    
    const tstart = performance.now() / 1000
    const sum = f();
    const tend = performance.now() / 1000
    const mflops = outputSize * 5.0 * indicesPerTexel * 1e-6 / (tend - tstart);
    document.write('pi: ' + sum.toString())
    document.write('<br>')
    document.write('time: ' + (tend - tstart) + 's')
    document.write('<br>')
    document.write('estimated MFlops: ' + mflops)
    
    </script>