From 0f944d367627a1491fcb1bf14cbbe96964ecaffb Mon Sep 17 00:00:00 2001 From: Alexander Novikov Date: Mon, 10 Apr 2017 11:49:28 +0300 Subject: [PATCH] init --- LICENSE | 7 + speed up einsum.ipynb | 296 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 303 insertions(+) create mode 100644 LICENSE create mode 100644 speed up einsum.ipynb diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..89ac2c5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright 2017 Alexander Novikov + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/speed up einsum.ipynb b/speed up einsum.ipynb new file mode 100644 index 0000000..7e43d32 --- /dev/null +++ b/speed up einsum.ipynb @@ -0,0 +1,296 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "from inspect import getframeinfo, stack\n", + "import tensorflow as tf\n", + "import timeit\n", + "import numpy as np\n", + "import itertools\n", + "import t3f" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "sess = tf.Session()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [ + "\n", + "def my_timeit(tens, sess):\n", + " timings = []\n", + " for rep in range(20):\n", + " best_of_three = np.inf\n", + " for i in range(3):\n", + " start = timeit.default_timer()\n", + " sess.run(tens)\n", + " end = timeit.default_timer()\n", + " best_of_three = min(best_of_three, end - start)\n", + " timings.append(best_of_three)\n", + " return np.mean(timings)\n", + " \n", + "\n", + "def freeze_args(argument_list, sess):\n", + " cheap_args = []\n", + " for argument in argument_list:\n", + " shape = sess.run(tf.shape(argument))\n", + " cheap_args.append(tf.constant(np.random.rand(*shape)))\n", + " return cheap_args\n", + "\n", + "\n", + "def optimize_einsum(struct, sess):\n", + " subscripts = struct['subscripts']\n", + " pos = subscripts.find('->')\n", + " if pos != -1:\n", + " output_str = subscripts[pos:]\n", + " subscripts = subscripts[:pos]\n", + " else:\n", + " output_str = ''\n", + " argument_strings = np.array(subscripts.split(','))\n", + " \n", + " cheap_args = np.array(struct['cheap_args'])\n", + " num_args = len(cheap_args[0])\n", + " perm_idx = 0\n", + " orders = np.array(list(itertools.permutations(range(num_args))))\n", + " num_orders = orders.shape[0]\n", + " timings_table = np.zeros((num_orders, len(cheap_args)))\n", + " for order_idx in range(num_orders):\n", + " curr_order = orders[order_idx, :]\n", + " curr_einsum_string = ','.join(argument_strings[curr_order])\n", + " curr_einsum_string += output_str\n", + " for i in range(len(cheap_args)):\n", + " curr_tens = tf.einsum(curr_einsum_string, *cheap_args[i][curr_order])\n", + " timings_table[order_idx, i] = my_timeit(curr_tens, sess)\n", + " \n", + " return timings_table, orders\n", + " \n", + "def optimizer(f, sess, *args):\n", + " cache = {}\n", + " original_einsum = tf.einsum\n", + " def my_einsum(subscripts, *args):\n", + " caller = getframeinfo(stack()[1][0])\n", + " caller_str = \"%s:%d\" % (caller.filename, caller.lineno)\n", + " if caller_str in cache:\n", + " if cache[caller_str]['subscripts'] != subscripts:\n", + " raise ValueError('Calling different types of einsum from the same line of code '\n", + " 'is not supported, %s sometimes calls einsum with argumens \"%s\"'\n", + " 'and sometimes with \"%s\"' % (caller_str, cache[caller_str]['subscripts'],\n", + " subscripts))\n", + " cache[caller_str]['arguments'].append(args)\n", + " else:\n", + " cache[caller_str] = {'subscripts': subscripts, 'arguments': [args]}\n", + " return original_einsum(subscripts, *args)\n", + " tf.einsum = my_einsum\n", + " f_out = f(*args)\n", + " tf.einsum = original_einsum\n", + " print('Found %d einsums.' % len(cache))\n", + " vanilla_whole_runtime = my_timeit(f_out, sess)\n", + " print('The running time of the whole function is %f s' % vanilla_whole_runtime)\n", + " for caller_str in cache:\n", + " subscripts = cache[caller_str]['subscripts']\n", + " arguments = cache[caller_str]['arguments']\n", + " cache[caller_str]['cheap_args'] = []\n", + " cur_timings = np.zeros(len(arguments))\n", + " for i in range(len(arguments)):\n", + " cheap_args = freeze_args(arguments[i], sess)\n", + " cache[caller_str]['cheap_args'].append(cheap_args)\n", + " curr_tens = original_einsum(subscripts, *cheap_args)\n", + " cur_timings[i] = my_timeit(curr_tens, sess)\n", + " cache[caller_str]['timings'] = cur_timings\n", + " vanilla_einsum_runtime = [np.sum(cache[s]['timings']) for s in cache]\n", + " print('Einsums constitue %0.1f %% of the running time of the whole function (%f s).' %\n", + " (100 * np.sum(vanilla_einsum_runtime) / vanilla_whole_runtime, np.sum(vanilla_einsum_runtime)))\n", + " \n", + " worst_einsum_idx = np.argmax([np.max(cache[s]['timings']) for s in cache])\n", + " worst_einsum = list(cache)[worst_einsum_idx]\n", + " vanilla_wors_timings = cache[worst_einsum]['timings']\n", + " print('The slowest einsum (on which we gonna focus) is located in %s and it '\n", + " 'constitues %0.1f %% of the running time of the whole function (%f s).' %\n", + " (worst_einsum, 100 * np.sum(vanilla_wors_timings) / vanilla_whole_runtime, np.sum(vanilla_wors_timings)))\n", + " \n", + " print(cache)\n", + " timings_table, orders = optimize_einsum(cache[worst_einsum], sess)\n", + " print(vanilla_wors_timings, timings_table, np.sum(vanilla_wors_timings - timings_table, axis=1))\n", + " absolute_savings = np.sum(vanilla_wors_timings - timings_table, axis=1)\n", + " global_rel_savings = (absolute_savings) / float(vanilla_whole_runtime)\n", + " best_order_idx = np.argmax(global_rel_savings, axis=1)\n", + " best_order = orders[best_order_idx]\n", + " best_improovement = 100 * global_rel_savings[best_order_idx]\n", + " if best_improovement >= 20:\n", + " print('By changing the order of einsum in \"%s\" to %s you program will run %0.1f %% faster.' % \n", + " (worst_einsum, best_order, best_improovement))\n", + " else:\n", + " print('Einsum improovements haven\\'t found, good work!')\n" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found 2 einsums.\n", + "The running time of the whole function is 0.000381 s\n", + "Einsums constitue 68.7 % of the running time of the whole function (0.000262 s).\n", + "The slowest einsum (on which we gonna focus) is located in :2 and it constitues 35.4 % of the running time of the whole function (0.000135 s).\n", + "{':3': {'subscripts': 'iab,kb->iak', 'cheap_args': [[, ]], 'arguments': [(, )], 'timings': array([ 0.00012703])}, ':2': {'subscripts': 'ijk,ja,kb->iab', 'cheap_args': [[, , ]], 'arguments': [(, , )], 'timings': array([ 0.00013497])}}\n", + "Einsum improovements haven't found, good work!\n" + ] + } + ], + "source": [ + "def func(a, b, c):\n", + " res = tf.einsum('ijk,ja,kb->iab', a, b, c) + 1\n", + " res = tf.einsum('iab,kb->iak', res, c)\n", + " return res\n", + "a = tf.random_normal((10, 11, 12))\n", + "b = tf.random_normal((11, 13))\n", + "c = tf.random_normal((12, 14))\n", + "# res = func(a, b, c)\n", + "optimizer(func, sess, a, b, c)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false, + "deletable": true, + "editable": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Found 6 einsums.\n", + "The running time of the whole function is 0.148120 s\n", + "Einsums constitue 3.2 % of the running time of the whole function (0.004702 s).\n", + "The slowest einsum (on which we gonna focus) is located in /Users/alex/projects/t3f/t3f/riemannian.py:435 and it constitues 0.7 % of the running time of the whole function (0.001085 s).\n", + "{'/Users/alex/projects/t3f/t3f/riemannian.py:438': {'subscripts': 'saikcb,sbcd->saikd', 'cheap_args': [[, ], [, ], [, ], [, ], [, ], [, ]], 'arguments': [(, ), (, ), (, ), (, ), (, ), (, )], 'timings': array([ 0.00017605, 0.00012864, 0.00012822, 0.00016164, 0.00011204,\n", + " 0.00013613])}, '/Users/alex/projects/t3f/t3f/riemannian.py:445': {'subscripts': 'sabc,bijd,scjke->saike', 'cheap_args': [[, , ]], 'arguments': [(, , )], 'timings': array([ 0.00012475])}, '/Users/alex/projects/t3f/t3f/riemannian.py:423': {'subscripts': 'bije,aikd,sabc,scjkf->sdef', 'cheap_args': [[, , , ], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ]], 'arguments': [(, , , ), (, , , ), (, , , ), (, , , ), (, , , ), (, , , )], 'timings': array([ 0.00012592, 0.00013083, 0.00013722, 0.00013331, 0.00012629,\n", + " 0.00014398])}, '/Users/alex/projects/t3f/t3f/riemannian.py:411': {'subscripts': 'bije,cikf,sdef,sajkd->sabc', 'cheap_args': [[, , , ], [, , , ], [, , , ], [, , , ], [, , , ], [, , , ]], 'arguments': [(, , , ), (, , , ), (, , , ), (, , , ), (, , , ), (, , , )], 'timings': array([ 0.00016844, 0.00012118, 0.00015308, 0.00013359, 0.00014083,\n", + " 0.00011501])}, '/Users/alex/projects/t3f/t3f/riemannian.py:435': {'subscripts': 'sabc,bijd,scjke->saikde', 'cheap_args': [[, , ], [, , ], [, , ], [, , ], [, , ], [, , ]], 'arguments': [(, , ), (, , ), (, , ), (, , ), (, , ), (, , )], 'timings': array([ 0.00012825, 0.00015975, 0.00018233, 0.00021538, 0.00018234,\n", + " 0.00021745])}, '/Users/alex/projects/t3f/t3f/riemannian.py:437': {'subscripts': 'aikb,sbcd->saikcd', 'cheap_args': [[, ], [, ], [, ], [, ], [, ], [, ]], 'arguments': [(, ), (, ), (, ), (, ), (, ), (, )], 'timings': array([ 0.00014957, 0.00017437, 0.00017155, 0.00017079, 0.00017611,\n", + " 0.0001771 ])}}\n", + "Einsum improovements haven't found, good work!\n" + ] + } + ], + "source": [ + "shape = 7 * np.ones(7)\n", + "mat_rank = 10\n", + "vec_rank = 10\n", + "B = 10\n", + "mat = t3f.random_matrix((shape, shape), mat_rank)\n", + "what = t3f.random_matrix_batch((shape, None), vec_rank, batch_size=B)\n", + "where = t3f.random_matrix((shape, None), vec_rank)\n", + "\n", + "func = lambda what, where, mat: t3f.project_matmul(what, where, mat).op\n", + "optimizer(func, sess, what, where, mat)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true, + "deletable": true, + "editable": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 2", + "language": "python", + "name": "python2" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 2 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython2", + "version": "2.7.13" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +}