{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "46d0dd15",
   "metadata": {},
   "source": [
    "<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/39/VU_logo.png/800px-VU_logo.png?20161029201021\" width=\"350\">\n",
    "\n",
    "### Programming large-scale parallel systems\n",
    "\n",
    "# Gaussian elimination"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff0fbd76",
   "metadata": {},
   "source": [
    "## Contents\n",
    "\n",
    "In this notebook, we will learn\n",
    "\n",
    "- How to parallelize Gaussian elimination\n",
    "- What is load imbalance, and how to fix it in this algorithm"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "480af594",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Note:</b> Do not forget to execute the cell below before starting this notebook! \n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7e93809a",
   "metadata": {},
   "outputs": [],
   "source": [
    "using Printf\n",
    "function answer_checker(answer,solution)\n",
    "    if answer == solution\n",
    "        \"🥳 Well done!\"\n",
    "    else\n",
    "        \"It's not correct. Keep trying! 💪\"\n",
    "    end |> println\n",
    "end\n",
    "function ge_par_why()\n",
    "    msg = \"The outer loop of the algorithm is not parallelizable, since the iterations depend on the results of the previous iterations. However, we can extract parallelism from the inner loops.\"\n",
    "    println(msg)\n",
    "end\n",
    "ge_par_check(answer) = answer_checker(answer, \"a\")\n",
    "ge_dep_check(answer) = answer_checker(answer, \"b\")\n",
    "function ge_lb_answer()\n",
    "    msg = \"It is a form of static load balancing. We know in advance the load distribution and the partition strategy does not depend on the actual values of the input matrix\"\n",
    "    println(msg)\n",
    "end\n",
    "println(\"🥳 Well done!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ad95aa5",
   "metadata": {},
   "source": [
    "## Gaussian elimination\n",
    "\n",
    "\n",
    "[Gaussian elimination](https://en.wikipedia.org/wiki/Gaussian_elimination) is a method to solve systems of linear equations, like this one:\n",
    "\n",
    "$$\n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "1 & 3 & 1 \\\\\n",
    "1 & 2 & -1 \\\\\n",
    "3 & 11 & 5 \\\\\n",
    "\\end{matrix}\n",
    "\\right]\n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "x \\\\\n",
    "y \\\\\n",
    "z  \\\\\n",
    "\\end{matrix}\n",
    "\\right]\n",
    "=\n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "9 \\\\\n",
    "1 \\\\\n",
    "35  \\\\\n",
    "\\end{matrix}\n",
    "\\right].\n",
    "$$\n",
    "\n",
    "This is just a small example with three unknowns, but practical applications need to solve linear equations with large number of unknowns. Parallel processing is needed in these cases.\n",
    "\n",
    "### Problem statement\n",
    "\n",
    "Let us consider a system of linear equations written in matrix form $Ax=b$, where $A$ is a nonsingular square matrix, and $x$ and $b$ are vectors. $A$ and $b$ are given, and $x$ is unknown. The goal of Gaussian elimination is to transform the system $Ax=b$, into a new system $Ux=c$ such that\n",
    "- both system have the same solution vector $x$,\n",
    "- the matrix $U$ of the new system is *upper triangular* with unit diagonal, namely $U_{ii} = 1$ and $U_{ij} = 0$ for $i>j$.\n",
    "\n",
    "\n",
    "For the particular system shown above, the transformed one is the following:\n",
    "\n",
    "$$\n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "1 & 3 & 1 \\\\\n",
    "1 & 2 & -1 \\\\\n",
    "3 & 11 & 5 \\\\\n",
    "\\end{matrix}\n",
    "\\right]\n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "x \\\\\n",
    "y \\\\\n",
    "z  \\\\\n",
    "\\end{matrix}\n",
    "\\right]\n",
    "=\n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "9 \\\\\n",
    "1 \\\\\n",
    "35  \\\\\n",
    "\\end{matrix}\n",
    "\\right]\n",
    "\\longrightarrow\n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "1 & 3 & 1 \\\\\n",
    "0 & 1 & 2 \\\\\n",
    "0 & 0 & 1 \\\\\n",
    "\\end{matrix}\n",
    "\\right]\n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "x \\\\\n",
    "y \\\\\n",
    "z  \\\\\n",
    "\\end{matrix}\n",
    "\\right]\n",
    "=\n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "9 \\\\\n",
    "8 \\\\\n",
    "4  \\\\\n",
    "\\end{matrix}\n",
    "\\right]\n",
    "$$\n",
    "\n",
    "The most challenging part of solving a system of linear equations is to transform it to upper triangular form. Afterwards, the solution vector can be obtained easily with a backward substitution. For this reason, we will study here the triangulation step only."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "980cb36f",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "### Augmented system matrix\n",
    "\n",
    "In practice, vector $b$ is added as an additional column to A forming the so-called *augmented* matrix $A^* = [A  b]$. The augmented matrix in the example above is\n",
    "\n",
    "$$\n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "1 & 3 & 1 \\\\\n",
    "1 & 2 & -1 \\\\\n",
    "3 & 11 & 5 \\\\\n",
    "\\end{matrix}\n",
    "\\right]\n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "x \\\\\n",
    "y \\\\\n",
    "z  \\\\\n",
    "\\end{matrix}\n",
    "\\right]\n",
    "=\n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "9 \\\\\n",
    "1 \\\\\n",
    "35  \\\\\n",
    "\\end{matrix}\n",
    "\\right]\\longrightarrow\n",
    "A^*=\n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "1 & 3 & 1 & 9  \\\\\n",
    "1 & 2 & -1 & 1 \\\\\n",
    "3 & 11 & 5 & 35\\\\\n",
    "\\end{matrix}\n",
    "\\right].\n",
    "$$\n",
    "\n",
    "With this new notation, the goal of Gaussian elimination is to find the augmented matrix containing $U$ and $c$, namely $U^*= [U  c]$, given the augmented matrix $A^* = [A  b]$. These are $A^*$ and $U^*$ in our example:\n",
    "\n",
    "$$\n",
    "A^*=\n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "1 & 3 & 1 & 9  \\\\\n",
    "1 & 2 & -1 & 1 \\\\\n",
    "3 & 11 & 5 & 35\\\\\n",
    "\\end{matrix}\n",
    "\\right]\\longrightarrow\n",
    "U^*=\n",
    "\\left[\n",
    "\\begin{matrix}\n",
    "1 & 3 & 1 & 9 \\\\\n",
    "0 & 1 & 2 & 8\\\\\n",
    "0 & 0 & 1 & 4\\\\\n",
    "\\end{matrix}\n",
    "\\right].\n",
    "$$\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "94c10106",
   "metadata": {},
   "source": [
    "### Serial implementation\n",
    "\n",
    "\n",
    "The following algorithm computes the Gaussian elimination on a given augmented matrix `B`, representing a system of linear equations. The result is given by overwriting `B`, avoiding the allocation of an additional matrix.\n",
    "\n",
    "- The outer loop is a loop over rows.\n",
    "- The first inner loop in line 4 divides the current row by the value of the diagonal entry, thus transforming the diagonal to contain only ones. Note that we skip the first entries in the row, as we know that these values are zero at this point. The cells updated in this loop at iteration $k$ are depicted in red in the figure below.\n",
    "- The second inner loop beginning in line 8 subtracts the rows from one another such that all entries below the diagonal become zero. The entries updated in this loop are depicted in blue in the figure below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e4070214",
   "metadata": {},
   "outputs": [],
   "source": [
    "function gaussian_elimination!(B)\n",
    "    n,m = size(B)\n",
    "    @inbounds for k in 1:n\n",
    "        for t in (k+1):m\n",
    "            B[k,t] =  B[k,t]/B[k,k]\n",
    "        end\n",
    "        B[k,k] = 1\n",
    "        for i in (k+1):n \n",
    "            for j in (k+1):m\n",
    "                B[i,j] = B[i,j] - B[i,k]*B[k,j]\n",
    "            end\n",
    "            B[i,k] = 0\n",
    "        end\n",
    "    end\n",
    "    B\n",
    "end"
   ]
  },
  {
   "attachments": {
    "g27851.png": {
     "image/png": "[encoded data, 33560 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "cc6ce65e",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 33560 characters]\"  align=\"left\" width=\"300\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3763b000",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Note:</b> This algorithm is not correct for all nonsingular matrices: if any diagonal element <code>B[k,k]</code> is zero, the computation in the first inner loop fails. To get around this problem, another step can be added to the algorithm that swaps the rows until the diagonal entry of the current row is not zero. This process of finding a nonzero value is called <b>pivoting</b>. We are not going to consider pivoting here for simplicity.  \n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fbb3d1eb",
   "metadata": {},
   "source": [
    "You can verify that the algorithm computes the upper triangular matrix correctly for the example in the introduction by running the following code cell. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb30df0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "A = Float64[1 3 1; 1 2 -1; 3 11 5]\n",
    "b = Float64[9,1,35]\n",
    "B = [A b]\n",
    "gaussian_elimination!(B)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a7d6f90a",
   "metadata": {},
   "source": [
    "### Complexity of the algorithm\n",
    "\n",
    "The number of operations of the algorithm is $O(N^3)$, where $N$ is the number of unknowns in the system. Intuitively, this makes sense as there are three nested loops. However, the length of the loops is not equal to $N$. In any case, it can be proven that the total number of operations is still $O(N^3)$. The actual proof is a bit challenging and it is not discussed here."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39f2e8ef",
   "metadata": {},
   "source": [
    "## Parallelization\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b1a6469",
   "metadata": {},
   "source": [
    "### Where can we extract parallelism?\n",
    "\n",
    "```julia\n",
    "n,m = size(B)\n",
    "for t in (k+1):m\n",
    "    B[k,t] =  B[k,t]/B[k,k]\n",
    "end\n",
    "B[k,k] = 1\n",
    "for i in (k+1):n \n",
    "    for j in (k+1):m\n",
    "        B[i,j] = B[i,j] - B[i,k]*B[k,j]\n",
    "    end\n",
    "    B[i,k] = 0\n",
    "end\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e52c4b38",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>Question:</b>  Which of the loops can be parallelized?\n",
    "</div>\n",
    "\n",
    "    a) the inner loops, but not the outer loop\n",
    "    b) the outer loop, but not the inner loops\n",
    "    c) all loops\n",
    "    d) only the first inner loop"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "078e974e",
   "metadata": {},
   "outputs": [],
   "source": [
    "answer = \"x\" # replace x with a, b, c, or d \n",
    "ge_par_check(answer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1169c86e",
   "metadata": {},
   "outputs": [],
   "source": [
    "ge_par_why()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74491f64",
   "metadata": {},
   "source": [
    "### Data partition\n",
    "\n",
    "Let start considering a row-wise block partition, as we did in previous algorithms.\n",
    "\n",
    "In the figure below, we use different colors to illustrate which entries are assigned to a CPU. All entries with the same color are assigned to the same CPU."
   ]
  },
  {
   "attachments": {
    "g31767.png": {
     "image/png": "[encoded data, 21664 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "7460b0af",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 21664 characters]\"  align=\"left\" width=\"250\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ebddda1",
   "metadata": {},
   "source": [
    "### Load imbalance\n",
    "\n",
    "Each CPU will be on charge of updating the entries stored locally. However, this algorithm is a bit different than the previous ones. At iteration $k$ only a subset of the entries in the matrix `B` are updated, i.e. only the entries in the bottom right block  `B[k:end,k:end]` are updated. This block is illustrated in a darker color in the next figure for $k=6$. "
   ]
  },
  {
   "attachments": {
    "fig-asp-data-updated-2.png": {
     "image/png": "[encoded data, 36992 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "d083cd53",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 36992 characters]\"  align=\"left\" width=\"250\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e341fda6",
   "metadata": {},
   "source": [
    "In this particular example CPU 1 will not have any work to do at iteration $k=6$ and it will be waiting, while other CPUs are computing. In general, CPUs containing rows previous to row $k$ will have less work to do than CPUs containing rows after row $k$. This will worsen as the value of $k$ increases. At some point, only the last CPU will have work to do and the others will idle. \n",
    "\n",
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Definition:</b> *Load imbalance*: is the problem when work is not equally distributed over all processes and consequently some processes do more work than others.\n",
    "</div>\n",
    "\n",
    "Having processors waiting for others is a waist of computational resources and affects negatively parallel speedups. The optimal speedup (speedup equal to the number of processors) assumes that the work is perfectly parallel and that it is evenly distributed. If there is load imbalance, the last assumption is not true anymore and the speedup will be suboptimal.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "51498a44",
   "metadata": {},
   "source": [
    "### Fixing load imbalance\n",
    "\n",
    "In this application, is relatively easy to fix the load imbalance problem. We know in advance which data is going to be processes at each CPU and we can design a more clever data partition.\n",
    "\n",
    "We can consider row-wise cyclic partition to fix the problem. See figure below. In this case, the CPUs will have less work as the value of $k$ increases, but amount of work will be better distributed than with the previous row block partition."
   ]
  },
  {
   "attachments": {
    "fig-asp-data-updated-cyclic.png": {
     "image/png": "[encoded data, 50160 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "b90252f1",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 50160 characters]\"  align=\"left\" width=\"250\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c9e4c8a",
   "metadata": {},
   "source": [
    "### Static vs dynamic load balancing\n",
    "\n",
    "Load balancing is the process of distributing work to processors uniformly with the aim to efficiently exploit a parallel system. There are two key forms of load balancing: Static and dynamic load balancing.\n",
    "\n",
    "- **Static load balancing**  the work distribution strategy is based on prior information of the algorithm and it does not depend on runtime values.\n",
    "- **Dynamic load balancing** the work distribution strategy is based on runtime values.\n",
    "\n",
    "Static load balancing is often used in algorithms for which the load distribution is known in advance and it does not depend on runtime values. On the other hand, dynamic load balancing is often needed in problems in which the work distribution cannot be predicted in advance and depends on runtime values.\n",
    "\n",
    "\n",
    "\n",
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>Question:</b>  Using a cyclic partition for Gaussian elimination, is a form of static or dynamic load balancing?\n",
    "</div>\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a6741a25",
   "metadata": {},
   "outputs": [],
   "source": [
    "ge_lb_answer()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e151fb8d",
   "metadata": {},
   "source": [
    "### Data dependencies\n",
    "\n",
    "Using a cyclic partition, we managed to distribute the work uniformly. But we still need to study the data dependencies in order to implement this algorithm in parallel efficiently.\n",
    "\n",
    "Look again to the algorithm\n",
    "\n",
    "```julia\n",
    "n,m = size(B)\n",
    "for t in (k+1):m\n",
    "    B[k,t] =  B[k,t]/B[k,k]\n",
    "end\n",
    "B[k,k] = 1\n",
    "for i in (k+1):n \n",
    "    for j in (k+1):m\n",
    "        B[i,j] = B[i,j] - B[i,k]*B[k,j]\n",
    "    end\n",
    "    B[i,k] = 0\n",
    "end\n",
    "```\n",
    "\n",
    "Note that all updates on the loop over i and j we do the following: \n",
    "\n",
    "```julia\n",
    "B[i,j] = B[i,j] - B[i,k]*B[k,j]\n",
    "```\n",
    "\n",
    "As we are using row-wise partitions, the CPU that updates `B[i,j]` will also have entry `B[i,k]` in memory (both are in the same row). However, `B[k,j]` is in another row and it might be located on another processor. We might need to communicate `B[k,j]` for `j=(k+1):m`. This corresponds to the cells marked in red in the figure below.  These red entries are the data dependencies of this algorithm. The owner of these entries has to send them to the other processors. This is very similar to the communication pattern seen in previous notebook for Floyd's algorithm. There is a key difference however. In the current case, we do not need to send the full row, only the entries beyond column $k$ (the red cells in the figure).\n"
   ]
  },
  {
   "attachments": {
    "g27851.png": {
     "image/png": "[encoded data, 33560 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "0050b6c4",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 33560 characters]\"  align=\"left\" width=\"300\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf189776",
   "metadata": {},
   "source": [
    "### Parallel implementation\n",
    "\n",
    "\n",
    "At iteration $k$,\n",
    "\n",
    "1. The CPU owning row $k$ does the loop over $t$ to update row $k$.\n",
    "2. The CPU owning row $k$ sets $B_{kk} = 1$.\n",
    "2. This CPU sends the red cells in figure above to the other processors.\n",
    "3. All processors receive the updated values in row $k$ and do the loop over i and j locally (blue cells).\n",
    "\n",
    "\n",
    "As you probably see, the parallel implementation of this method is closely related to Floyd's algorithm. But there are some differences. \n",
    "\n",
    "1. The process that owns row $k$ updates its values before sending them.\n",
    "2. We do not send the full row $k$, only the entries beyond column $k$.\n",
    "3. We need a cyclic partition to balance the load properly.\n",
    "\n",
    "A key similarity between the two algorithms, however, is that they both suffer from synchronization problems. We need to make sure that the rows arrive in the right order. The strategies discussed for Floyd's algorithm also apply in this current case.\n",
    "\n",
    "The actual implementation of the parallel algorithm is left as an open exercise."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "866824c6",
   "metadata": {},
   "source": [
    "## Conclusion\n",
    "\n",
    "\n",
    "We studied the parallelization of an algorithm that leads to load imbalance. We fixed the problem using a cyclic partition. This is a form of static load balancing since we were able to distribute the load in advance without using runtime values. This is opposed to dynamic load balancing which can schedule loads flexibly during runtime. Note however that cyclic partitioning is not suitable for all communication patterns. For example, it can lead to a large communication overhead in the parallel Jacobi method, since the computation of each value depends on its neighboring elements.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f60d9ea0",
   "metadata": {},
   "source": [
    "# License\n",
    "\n",
    "\n",
    "\n",
    "This notebook is part of the course [Programming Large Scale Parallel Systems](https://www.francescverdugo.com/XM_40017) at Vrije Universiteit Amsterdam and may be used under a [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) license."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Julia 1.9.0",
   "language": "julia",
   "name": "julia-1.9"
  },
  "language_info": {
   "file_extension": ".jl",
   "mimetype": "application/julia",
   "name": "julia",
   "version": "1.9.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
