{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Week 14 day 1: Static and Dynamic Computation Graphs\n",
"\n",
"## Objectives:\n",
"\n",
"* Quick note about Numpy temporaries\n",
"* Cover a couple of common ML frameworks\n",
"* Study automatic differentiation methods "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"While Google's TensorFlow and FaceBook's PyTorch are popular libraries, and (with some caveats) are available in the default Anaconda channel, they are not installed by default. Let's look at the many libraries briefly, then we will install and play with those two."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Install\n",
"\n",
"Let's set up a Conda environment with the necessary libraries. While Anaconda does have PyTorch, it only has it for Linux, so let's add the `pytorch` channel and install `pytorch` from there.\n",
"\n",
"```bash\n",
"conda create -n mlwork python==3.6 anaconda ipykernel tensorflow pytorch -c pytorch\n",
"```\n",
"\n",
"You can replace the metapackage `anaconda` with the list of packages you will be using. If you are on OSC, logging out then back in should be enough to set this up for Jupyter. On other systems using the latest Anaconda:\n",
"\n",
"```bash\n",
"conda activate mlwork\n",
"python -m ipykernel install --user --name \n",
"conda deactivate\n",
"```\n",
"\n",
"Or, an older Anaconda:\n",
"\n",
"```bash\n",
"source activate mlwork\n",
"python -m ipykernel install --user --name \n",
"source deactivate\n",
"```\n",
"\n",
"(Skip `source` on Windows)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## ML Libraries\n",
"\n",
"\n",
"* [**Theano**](http://deeplearning.net/software/theano/): A research project, one of the very first static graph systems. Killed by newer frameworks except for use in MC3.\n",
"* [**Tensorflow**](https://www.tensorflow.org): Powers Android's ML. Rapidly became most popular framework. Often used as a backend to a framework rather than directly (the popular Keras framework is now built in). Shifting from static graph to dynamic graph as default in 2.0 to look more like PyTorch (easier to learn and debug). Still no Python 3.7 support, so use Python 3.6.\n",
"* [**PyTorch**](https://pytorch.org): Comes from the old Lua-based Torch. Very easy to debug. Sort of similar but not quite to Numpy. Still heading to version 1.0, which will support production use (Facebook currently has Caffe, which is production ready). Very popular for such a young library. Has built-in ML framework. *Amazing* documentation. Best way to learn TensorFlow?!\n",
"* [**Chainer**](https://chainer.org): The original basis of PyTorch's design. Stays as close as possible to Numpy (and CuPy was developed to power the GPU side of this framework).\n",
"* [**CNTK**](https://www.microsoft.com/en-us/cognitive-toolkit/): Microsoft's offering, specializes in natural language processing.\n",
"\n",
"All the libraries have CPU/GPU support, decent performance, etc. There are lots more; these are just the most popular."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## ML libraries without ML?\n",
"\n",
"You may have noticed that I'm covering ML libraries *before* covering ML. That's because we have already covered fitting, and ML is mostly fitting. Let's review fitting:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"1. You have a sample of an underlying distribution\n",
"2. You build a model of that distribution\n",
"3. There are (many) parameters that describe the model\n",
"4. We select a metric that compares the model to the data\n",
"5. We want to minimize the parameters to give a good description of the data"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What's different in ML? We usually use a different metric instead of NLL, the models are larger but make of simpler parts. That's about it! So how can we improve fitting?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Automatic Differentiation\n",
"\n",
"Why use a framework instead of just writing plain Numpy? A few possible reasons:\n",
"\n",
"* **Avoid temporaries**: Numpy takes extra memory and time with temporaries. It would be nice to avoid them (note: Numba does this)\n",
"* **Performance**: Numpy runs separate bits of compiled code for each calculation. Some of these could be combined (note: Numba does this)\n",
"* **GPU**: Many systems have GPUs, and GPUs are great for massive but \"simple\" calculations. Numpy does not directly support GPUs (but CuPy, Numba, and others do).\n",
"* **Differentiation**: You can avoid a lot of calculations if you can get gradients easily! This is a big deal most ML frameworks."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Quick aside: Temporaries\n",
"\n",
"Numpy classically had issues with temporaries. It's much better now (at least on Numpy 1.13+ on Linux and macOS)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"np.random.seed(42)\n",
"N = 1_000_000\n",
"a = np.random.rand(N)\n",
"b = np.random.rand(N)\n",
"c = np.random.rand(N)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%%timeit\n",
"s = a + b + c # How many arrays are in memory? (classic: 5, 1.13+: 4 on some systems)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%%timeit\n",
"ab = a + b\n",
"s = ab + c # Right here, how many arrays are in memory? (5)\n",
"del ab"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%%timeit\n",
"s = a + b\n",
"s += c # (4)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Depending on your system, the first time should look like one of the other two times."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Fitting revisit\n",
"\n",
"Let's make a small sample of data to fit."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from scipy.optimize import minimize"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.random.seed(42)\n",
"dist = np.random.normal(loc=1, scale=2., size=100_000)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def gaussian(x, μ, σ):\n",
" return 1/np.sqrt(2*np.pi*σ**2) * np.exp(-(x-μ)**2/(2*σ**2))\n",
"\n",
"def nll(params, dist):\n",
" mean, sigma = params\n",
" return -np.sum(np.log(gaussian(dist, mean, sigma)))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"minimize(nll, (.5, 1.), args=(dist,))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Dynamic graphs: PyTorch\n",
"\n",
"When converting to Torch, let's notice a couple of quirks compared to Numpy:\n",
"\n",
"* The basic \"ndarray\" in ML frameworks is usually called a tensor. No, it is not a true mathematical tensor.\n",
"* Torch loves 32-bit floats. You'll need to request 64 for every tensor.\n",
"* Use the function `tensor` to make Tensors, not the constructor `Tensor`\n",
"* Use math functions from torch rather than Numpy. Numpy 1.13+ has the ability to call a custom library's functions, but Torch does not (yet?) use it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"\n",
"tdist = torch.tensor(dist, dtype=torch.float64)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tmean = torch.tensor([0.5], dtype=torch.float64, requires_grad=True)\n",
"tsigma = torch.tensor([0.5], dtype=torch.float64, requires_grad=True)\n",
" \n",
"def tgaussian(x, μ, σ):\n",
" return 1/torch.sqrt(2*np.pi*σ**2) * torch.exp(-(x-μ)**2/(2*σ**2))\n",
"\n",
"result = -torch.sum(torch.log(tgaussian(tdist, tmean, tsigma)))\n",
"print(result.item())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"result.backward()\n",
"print(tmean.grad.item(), tsigma.grad.item())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Unfortunately, this is not trivial to put into minimize, since the autograd requires \"result\", and is built once each time this runs."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Static Graphs: TensorFlow\n",
"\n",
"TensorFlow does not make any pretense about looking or acting like Numpy.\n",
"\n",
"* The basic \"ndarray\" is a Tensor again. Though you have customized tensors for different uses: placeholders, constants, and more.\n",
"* Use math functions from TensorFlow rather than Numpy. It's way too different; you are simply \"scheduling\" an operation, not making one.\n",
"* TensorFlow has an \"Eager Evaluation\" mode that acts like PyTorch, and will become the \"default\" in 2.0. We'll stay with static graphs at the moment, though."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import tensorflow as tf"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Make the distribution a constant Tensor; \n",
"# it does not change in iterations so TensorFlow can optimize for that.\n",
"x = tf.constant(dist)\n",
"\n",
"# Make placeholders for values we are going to \"feed\" in\n",
"# (0D tensor == scalar)\n",
"tf_mean = tf.placeholder(dtype=tf.float64)\n",
"tf_sigma = tf.placeholder(dtype=tf.float64)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# tf_gaussian is a Tensor graph (like a function) can can compute this expression!\n",
"tf_gaussian = 1/tf.sqrt(2*np.pi*tf_sigma**2) * tf.math.exp(-(x-tf_mean)**2/(2*tf_sigma**2))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# This is still just a \"description of what to do\", no computation has been done yet\n",
"tf_nll = -tf.reduce_sum(tf.math.log(tf_gaussian))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# We can compute symbolic derivatives with the graph, as well\n",
"tf_grads = tf.gradients(tf_nll, [tf_mean, tf_sigma])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with tf.Session() as sess:\n",
"\n",
" loss_value = sess.run(tf_nll,\n",
" feed_dict={tf_mean:0.5,\n",
" tf_sigma:0.5})\n",
" \n",
" grads = sess.run(tf_grads,\n",
" feed_dict={tf_mean:0.5,\n",
" tf_sigma:0.5})\n",
"\n",
" print(loss_value, grads)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notes:\n",
"\n",
"* You have to run inside a session. Sessions are slow to start/stop, so loops should be inside the session (`sess.run` is fast).\n",
"* The actual computation is quite fast, and can happen on the GPU.\n",
"* TensorFlow is a bit verbose and tricky to setup, but can be amazingly clear.\n",
"* (Not shown) TensorFlow has great graph visualization tools (TensorBoard) (using them is tricky)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "compclass",
"language": "python",
"name": "compclass"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.2"
}
},
"nbformat": 4,
"nbformat_minor": 4
}