{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "bea76753",
   "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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "038e5442",
   "metadata": {},
   "source": [
    "# Matrix-matrix multiplication"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f70e2f35",
   "metadata": {},
   "source": [
    "## Contents\n",
    "\n",
    "In this notebook, we will:\n",
    "\n",
    "- Parallelize a simple algorithm\n",
    "- Study the performance of different parallelization strategies\n",
    "- Learn the importance of \"grain size\" in a parallel algorithm\n",
    "- Implement and measure the performance of parallel algorithms"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "480af594",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Note:</b> Do not forget to execute the cells below before starting this notebook! \n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4d5f1a1",
   "metadata": {},
   "outputs": [],
   "source": [
    "] add BenchmarkTools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f8ba040",
   "metadata": {},
   "outputs": [],
   "source": [
    "using Distributed\n",
    "using BenchmarkTools\n",
    "using Printf\n",
    "if procs() == workers()\n",
    "    addprocs(4)\n",
    "end\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",
    "alg_0_comp_check(answer) = answer_checker(answer, \"d\")\n",
    "alg_1_deps_check(answer) = answer_checker(answer,\"b\")\n",
    "alg_1_comm_overhead_check(answer) = answer_checker(answer, \"b\")\n",
    "alg_1_comp_check(answer) = answer_checker(answer, \"b\")\n",
    "alg_2_complex_check(answer) = answer_checker(answer, \"b\")\n",
    "alg_2_deps_check(answer) = answer_checker(answer,\"d\")\n",
    "alg_3_deps_check(answer) = answer_checker(answer, \"c\")\n",
    "alg_3_complex_check(answer) = answer_checker(answer, \"b\")\n",
    "println(\"🥳 Well done! \")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96d2693d",
   "metadata": {},
   "source": [
    "## Problem Statement\n",
    "\n",
    "We consider matrix-matrix multiplication as our first algorithm to parallelize. The problem we want so solve is defined as follows.\n",
    "\n",
    "Given $A$ and $B$ two $N$-by-$N$ matrices, compute the matrix-matrix product $C=AB$. Compute it in parallel and efficiently."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "88bc2633",
   "metadata": {},
   "source": [
    " <div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 43364 characters]\" align=\"left\" width=\"450\"/>\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a358ee60",
   "metadata": {},
   "source": [
    "### Goals\n",
    "\n",
    "We want to\n",
    "\n",
    "- compute the product in parallel using more than one process (distributed implementation)\n",
    "- study the performance of different parallelization alternatives\n",
    "- implement the algorithms using Julia's task-based programming model\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "495ef679",
   "metadata": {},
   "source": [
    "### Assumptions\n",
    "\n",
    "- All matrices `A`,`B`, and `C` are initially stored in the master process\n",
    "- The result will be overwritten in `C` (in the master process)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5828e243",
   "metadata": {},
   "source": [
    " <div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 189312 characters]\" align=\"left\" width=\"450\"/>\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c57f340c",
   "metadata": {},
   "source": [
    "### Steps\n",
    "\n",
    "To develop and study the parallel implementation, we will follow these steps:\n",
    "\n",
    "- Identify the parts of the sequential algorithm that can be parallelized\n",
    "- Consider different parallelization strategies\n",
    "- Discuss the (theoretical) performance of these implementations\n",
    "- Measure the actual performance of these implementations\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca56a7fe",
   "metadata": {},
   "source": [
    "## Serial implementation\n",
    "\n",
    "We start by considering the (naive) sequential algorithm, which is based on the math definition of the matrix-matrix product $C_{ij} = \\sum_k A_{ik} B_{kj}$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af8dfb37",
   "metadata": {},
   "outputs": [],
   "source": [
    "@everywhere function matmul_seq!(C,A,B)\n",
    "    m = size(C,1)\n",
    "    n = size(C,2)\n",
    "    l = size(A,2)\n",
    "    @assert size(A,1) == m\n",
    "    @assert size(B,2) == n\n",
    "    @assert size(B,1) == l\n",
    "    z = zero(eltype(C))\n",
    "    for j in 1:n\n",
    "        for i in 1:m\n",
    "            Cij = z\n",
    "            for k in 1:l\n",
    "                @inbounds Cij += A[i,k]*B[k,j]\n",
    "            end\n",
    "            C[i,j] = Cij\n",
    "        end\n",
    "    end\n",
    "    C\n",
    "end"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3b86457",
   "metadata": {},
   "source": [
    "Run next cell to test the implementation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c5caf799",
   "metadata": {},
   "outputs": [],
   "source": [
    "using Test\n",
    "N = 10\n",
    "A = rand(N,N)\n",
    "B = rand(N,N)\n",
    "C = similar(A)\n",
    "matmul_seq!(C,A,B)\n",
    "@test C ≈ A*B"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f967d2ea",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Note:</b> The matrix-matrix multiplication naively implemented with 3 nested loops as above is known to be very inefficient (memory bound). Libraries such as BLAS provide much more efficient implementations, which are the ones used in practice (e.g., by the `*` operator in Julia). We consider our hand-written implementation as a simple way of expressing the algorithm we are interested in.\n",
    "</div>\n",
    "\n",
    "Just to satisfy your curiosity, run the following cell to compare the performance of our hand-written function with respect to the built in function `mul!`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "725387f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "using LinearAlgebra\n",
    "N = 1000\n",
    "A = rand(N,N)\n",
    "B = rand(N,N)\n",
    "C = rand(N,N)\n",
    "@btime matmul_seq!(C,A,B)\n",
    "@btime mul!(C,A,B);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0ca2fbd4",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>Question:</b>  Which is the complexity (number of operations) of the serial algorithm? Assume that all matrices are $N$-by-$N$ matrices.    \n",
    "</div>\n",
    "\n",
    "```julia\n",
    "for j in 1:N\n",
    "    for i in 1:N\n",
    "        Cij = z\n",
    "        for k in 1:N\n",
    "            @inbounds Cij += A[i,k]*B[k,j]\n",
    "        end\n",
    "        C[i,j] = Cij\n",
    "    end\n",
    "end\n",
    "```\n",
    "\n",
    "\n",
    "    a) O(1)\n",
    "    b) O(N)\n",
    "    c) O(N²)\n",
    "    d) O(N³)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "078e974e",
   "metadata": {},
   "outputs": [],
   "source": [
    "answer = \"x\" # replace x with a, b, c, or d \n",
    "alg_0_comp_check(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0eedd28a",
   "metadata": {},
   "source": [
    "## Where can we exploit parallelism?\n",
    "\n",
    "\n",
    "The matrix-matrix multiplication is an example of [embarrassingly parallel algorithm](https://en.wikipedia.org/wiki/Embarrassingly_parallel). An embarrassingly parallel (also known as trivially parallel) algorithm is an algorithm that can be split in parallel tasks with no (or very few) dependences between them. Such algorithms are typically easy to parallelize.\n",
    "\n",
    "Which parts of an algorithm are completely independent and thus trivially parallel? To answer this question, it is useful to inspect the for loops, which are potential sources of parallelism. If the iterations are independent of each other, then they are trivial to parallelize. An easy check to find out if the iterations are dependent or not is to change their order (for instance changing `for j in 1:n` by `for j in n:-1:1`, i.e. doing the loop in reverse). If the result changes, then the iterations are not independent.\n",
    "\n",
    "Look at the three nested loops in the sequential implementation of the matrix-matrix product:\n",
    "\n",
    "```julia\n",
    "for j in 1:n\n",
    "    for i in 1:m\n",
    "        Cij = z\n",
    "        for k in 1:l\n",
    "            @inbounds Cij +=  A[i,k]*B[k,j]\n",
    "        end\n",
    "        C[i,j] = Cij\n",
    "    end\n",
    "end\n",
    "```\n",
    "\n",
    "Note that:\n",
    "\n",
    "- Loops over `i` and `j` are trivially parallel.\n",
    "- The loop over `k` is not trivially parallel. The accumulation into the reduction variable `Cij` introduces extra dependences. In addition, remember that the addition of floating point numbers is not strictly associative due to rounding errors. Thus, the result of this loop may change with the loop order when using floating point numbers. In any case, this loop can also be parallelized, but it requires a parallel *fold* or a parallel *reduction*.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b50aecff",
   "metadata": {},
   "source": [
    "### Parallel algorithms\n",
    "\n",
    "The loops over `i` and `j` are trivially parallel, implying that all the entries of matrix C can be potentially computed in parallel. However, *which is the most efficient solution to solve all these entries in parallel in a distributed system?* To find this we will consider different parallelization strategies:\n",
    "\n",
    "- Algorithm 1: each worker computes a single entry of C\n",
    "- Algorithm 2: each worker computes a single row of C\n",
    "- Algorithm 3: each worker computes N/P rows of C"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6a706283",
   "metadata": {},
   "source": [
    " <div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 70440 characters]\" align=\"left\" width=\"450\"/>\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd759cb2",
   "metadata": {},
   "source": [
    "## Parallel algorithm 1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bdae0a02",
   "metadata": {},
   "source": [
    "### Data dependencies\n",
    "\n",
    "Moving data through the network is expensive and reducing data movement is one of the key points to design efficient distributed algorithms. To this end, we need to determine which is the minimum data needed by a worker to perform its computations. These are called the *data dependencies*. This will give us later information about the performance of the parallel algorithm.\n",
    "\n",
    "In algorithm 1, each worker computes only an entry of the result matrix C."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "acfb354b",
   "metadata": {},
   "source": [
    " <div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 49660 characters]\" align=\"left\" width=\"450\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be3c4a01",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>Question:</b>  Which are the data dependencies of the computations done by the worker in charge of computing entry C[i,j] ?    \n",
    "</div>\n",
    "\n",
    "    a) column A[:,i] and row B[j,:]\n",
    "    b) row A[i,:] and column B[:,j]\n",
    "    c) the whole matrices A and B\n",
    "    d) row A[i,:] and the whole matrix B"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a8b7d1e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "answer = \"x\" # replace x with a, b, c, or d \n",
    "alg_1_deps_check(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06e1977a",
   "metadata": {},
   "source": [
    "### Implementation\n",
    "\n",
    "Taking into account the data dependencies, the parallel algorithm 1 can be efficiently implemented following these steps from the worker perspective:\n",
    "\n",
    "1. The worker receives the data dependencies, i.e., the corresponding row A[i,:] and column B[:,j] from the master process\n",
    "2. The worker computes the dot product of A[i,:] and B[:,j] locally\n",
    "3. The worker sends back the result of C[i,j] to the master process"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70087bce",
   "metadata": {},
   "source": [
    " <div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 159628 characters]\" align=\"left\" width=\"450\"/>\n",
    "</div>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d22ccea",
   "metadata": {},
   "source": [
    "A possible implementation of this algorithm in Julia is as follows. Try to understand why `@sync` and `@async` are needed here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e4697fda",
   "metadata": {},
   "outputs": [],
   "source": [
    "function matmul_dist_1!(C, A, B)\n",
    "    m = size(C,1)\n",
    "    n = size(C,2)\n",
    "    l = size(A,2)\n",
    "    @assert size(A,1) == m\n",
    "    @assert size(B,2) == n\n",
    "    @assert size(B,1) == l\n",
    "    z = zero(eltype(C))\n",
    "    @assert nworkers() == m*n\n",
    "    iw = 0    \n",
    "    @sync for j in 1:n\n",
    "        for i in 1:m\n",
    "            Ai = A[i,:]\n",
    "            Bj = B[:,j]\n",
    "            iw += 1\n",
    "            w = workers()[iw]\n",
    "            ftr = @spawnat w begin\n",
    "                Cij = z\n",
    "                for k in 1:l\n",
    "                    @inbounds Cij += Ai[k]*Bj[k]\n",
    "                end\n",
    "                Cij\n",
    "            end\n",
    "            @async C[i,j] = fetch(ftr)\n",
    "        end\n",
    "    end\n",
    "    C\n",
    "end"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0e5a38b",
   "metadata": {},
   "source": [
    "You can execute the following cells to test this implementation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13920a31",
   "metadata": {},
   "outputs": [],
   "source": [
    "using Test\n",
    "N = 2\n",
    "A = rand(N,N)\n",
    "B = rand(N,N)\n",
    "C = similar(A)\n",
    "matmul_dist_1!(C,A,B)\n",
    "@test  C ≈ A*B"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f69d3333",
   "metadata": {},
   "source": [
    "### Performance\n",
    "\n",
    "We have a first parallel algorithm, but how efficient is this algorithm? Let us study its performance. To this end we need to consider a performance baseline as reference. In this case, we will use the so-called optimal parallel *speedup*. The parallel speedup on $P$ processes is defined as  \n",
    "\n",
    "$$\n",
    "S_P = \\frac{T_1}{T_P},\n",
    "$$\n",
    "\n",
    "where $T_1$ denotes the runtime of the sequential algorithm and $T_P$ denotes the runtime of the parallel algorithm on $P$ processes. If we run an optimal parallel algorithm with $P$ processes we expect it to run $p$ times faster than the sequential implementation. I.e., the *optimal* speedup of a parallel algorithm on $p$ processes is equal to $P$:\n",
    "\n",
    "$$\n",
    "S^{*}_p = P.\n",
    "$$\n",
    "\n",
    "The ratio of the actual speedup over the optimal one is called the parallel efficiency (the closer to one the better).\n",
    "\n",
    "$$\n",
    "E_p = \\frac{S_p}{S^{*}_p} = \\frac{T_1/T_P}{P}.\n",
    "$$\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8eb224d",
   "metadata": {},
   "source": [
    "### Experimental speedup\n",
    "\n",
    "The following cell measures the speedup of parallel algorithm 1. Do we achieve the optimal speedup?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cc698aa8",
   "metadata": {},
   "outputs": [],
   "source": [
    "N = 2\n",
    "A = rand(N,N)\n",
    "B = rand(N,N)\n",
    "C = similar(A)\n",
    "T1 = @belapsed matmul_seq!(C,A,B)\n",
    "C = similar(A)\n",
    "TP = @belapsed matmul_dist_1!(C,A,B)\n",
    "P = nworkers()\n",
    "println(\"Speedup = \", T1/TP)\n",
    "println(\"Optimal speedup = \", P)\n",
    "println(\"Efficiency = \", 100*(T1/TP)/P, \"%\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "501d4008",
   "metadata": {},
   "source": [
    "### Communication overhead\n",
    "\n",
    "Since communication is usually the main bottleneck in a distributed algorithm, we want to reduce the amount of communication per unit of computation in a worker. Let us compute the (theoretical) communication overhead for algorithm 1. This will help us understand why the speedup of this algorithm was so bad.\n",
    "\n",
    "Remember, algorithm 1 consisted of these main steps:\n",
    "\n",
    "1. The worker receives the corresponding row A[i,:] and column B[:,j] from the master process\n",
    "2. The worker computes the dot product of A[i,:] and B[:,j]\n",
    "3. The worker sends back the result of C[i,j] to the master process\n",
    "\n",
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>Question:</b>  How many scalars are communicated from and to a worker?  Assume that matrices A, B, and C are N by N matrices.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45f44171",
   "metadata": {},
   "source": [
    " <div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 159628 characters]\" align=\"left\" width=\"450\"/>\n",
    "</div>\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dac6a50b",
   "metadata": {},
   "source": [
    "    a) O(1)\n",
    "    b) O(N)\n",
    "    c) O(N²)\n",
    "    d) O(N³)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e78cbc7b",
   "metadata": {},
   "outputs": [],
   "source": [
    "answer = \"x\" # replace x with a, b, c, or d \n",
    "alg_1_comm_overhead_check(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b27a4d3f",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>Question:</b>  How many operations are done in a worker?    \n",
    "</div>\n",
    "\n",
    "    a) O(1)\n",
    "    b) O(N)\n",
    "    c) O(N²)\n",
    "    d) O(N³)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fcc9b903",
   "metadata": {},
   "outputs": [],
   "source": [
    "answer = \"x\" # replace x with a, b, or c\n",
    "alg_1_comp_check(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4c301de",
   "metadata": {},
   "source": [
    "From these results we can conclude:\n",
    "\n",
    "- The communication complexity is O(N)\n",
    "- The computation complexity is O(N)\n",
    "- The ratio communication over computation (the communication overhead) is O(1)\n",
    "\n",
    "In other words, the communication cost is of the same order of magnitude as the computation cost. Since, communication is orders of magnitude slower in real systems, the runtime in the worker will be dominated by communication. This explains why we obtained such a bad speedup.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b15cbaf4",
   "metadata": {},
   "source": [
    "## Parallel algorithm 2\n",
    "\n",
    "Let us study the next algorithm to see if we can improve the efficiency by augmenting the granularity (i.e. the amount of work) in each parallel task. In parallel algorithm 2, each worker computes an entire row of C.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62e5c637",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 50700 characters]\" align=\"left\" width=\"450\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa6cad0e",
   "metadata": {},
   "source": [
    "### Data dependencies"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4312f2c",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>Question:</b>  Which are the data dependencies of the computations done by the worker in charge of computing row C[i,:] ?    \n",
    "</div>\n",
    "\n",
    "    a) column A[:,i] and row B[j,:]\n",
    "    b) row A[i,:] and column B[:,j]\n",
    "    c) the whole matrices A and B\n",
    "    d) row A[i,:] and the whole matrix B"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cdb46cd8",
   "metadata": {},
   "outputs": [],
   "source": [
    "answer = \"x\" # replace x with a, b, c, or d \n",
    "alg_2_deps_check(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a9d84ac2",
   "metadata": {},
   "source": [
    "### Implementation\n",
    "\n",
    "These are the main steps of the implementation of algorithm 2:\n",
    "\n",
    "1. The worker receives the corresponding row A[i,:] and matrix B from the master process\n",
    "2. The worker computes the product of row A[i,:] times B\n",
    "3. The worker sends back the result of row C[i,:] to the master process\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb6b572b",
   "metadata": {},
   "source": [
    "\n",
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 185680 characters]\" align=\"left\" width=\"450\"/>\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a662afa4",
   "metadata": {},
   "source": [
    "A possible implementation of this algorithm in Julia is as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "365dc58e",
   "metadata": {},
   "outputs": [],
   "source": [
    "function matmul_dist_2!(C, A, B)\n",
    "    m = size(C,1)\n",
    "    n = size(C,2)\n",
    "    l = size(A,2)\n",
    "    @assert size(A,1) == m\n",
    "    @assert size(B,2) == n\n",
    "    @assert size(B,1) == l\n",
    "    z = zero(eltype(C))\n",
    "    @assert nworkers() == m\n",
    "    iw = 0\n",
    "    @sync for i in 1:m\n",
    "        Ai = A[i,:]\n",
    "        iw += 1\n",
    "        w = workers()[iw]\n",
    "        ftr = @spawnat w begin\n",
    "            Ci = fill(z,n)\n",
    "            for j in 1:n\n",
    "                for k in 1:l\n",
    "                    @inbounds Ci[j] += Ai[k]*B[k,j]\n",
    "                end\n",
    "            end\n",
    "            Ci\n",
    "        end\n",
    "        @async C[i,:] = fetch(ftr)\n",
    "    end\n",
    "    C\n",
    "    end"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8de835b9",
   "metadata": {},
   "source": [
    "Test it using next cell"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "267ac8b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "using Test\n",
    "N = 4\n",
    "A = rand(N,N)\n",
    "B = rand(N,N)\n",
    "C = similar(A)\n",
    "@test matmul_dist_2!(C,A,B) ≈ A*B"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f1f30faf",
   "metadata": {},
   "source": [
    "### Experimental speedup\n",
    "\n",
    "Measure the speedup with the following cell. Is this time better?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fe42f069",
   "metadata": {},
   "outputs": [],
   "source": [
    "N = 4\n",
    "A = rand(N,N)\n",
    "B = rand(N,N)\n",
    "C = similar(A)\n",
    "T1 = @belapsed matmul_seq!(C,A,B)\n",
    "C = similar(A)\n",
    "TP = @belapsed matmul_dist_2!(C,A,B)\n",
    "P = nworkers()\n",
    "println(\"Speedup = \", T1/TP)\n",
    "println(\"Optimal speedup = \", P)\n",
    "println(\"Efficiency = \", 100*(T1/TP)/P, \"%\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b1e3b24",
   "metadata": {},
   "source": [
    "### Complexity\n",
    "\n",
    "The speedup is still far from the optimal one. Let us study the communication overhead for this algorithm. Remember, algorithm 2 consists in these main steps:\n",
    "\n",
    "1. The worker receives the corresponding row A[i,:] and matrix B from the master process\n",
    "2. The worker computes the product of row A[i,:] times B\n",
    "3. The worker sends back the result of row C[i,:] to the master process\n",
    "\n",
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>Question:</b>  Which is the complexity of the communication and computations done by a worker in algorithm 2?\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77808863",
   "metadata": {},
   "source": [
    "\n",
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 185680 characters]\" align=\"left\" width=\"450\"/>\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2c6f60a",
   "metadata": {},
   "source": [
    "    a) O(N) communication and O(N^2) computation\n",
    "    b) O(N^2) communication and O(N^2) computation\n",
    "    c) O(N^3) communication and O(N^3) computation\n",
    "    d) O(N) communication and O(N) computation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1bf8feff",
   "metadata": {},
   "outputs": [],
   "source": [
    "answer = \"x\" # replace x with a, b, c, or d \n",
    "alg_2_complex_check(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a2038e04",
   "metadata": {},
   "source": [
    "The communication and computation cost are still of the same order of magnitude even though we have increased the grain size. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71088fb9",
   "metadata": {},
   "source": [
    "## Parallel algorithm 3\n",
    "\n",
    "Let us increase even more the granularity of the parallel tasks by computing several rows of C in a worker.  Each worker computes N/P consecutive rows of C, where P is the number of workers.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f1b8c712",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 52532 characters]\" align=\"left\" width=\"450\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d456fed",
   "metadata": {},
   "source": [
    "### Data dependencies"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "67b65ea6",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>Question:</b>  Which are the data dependencies of the computations done by the worker in charge of computing the range of rows C[rows,:] ?  \n",
    "</div>\n",
    "\n",
    "\n",
    "    a) A[rows,:] and B[:,rows] \n",
    "    b) the whole matrix A and B[:,rows]\n",
    "    c) A[rows,:] and the whole matrix B\n",
    "    d) the whole matrices A and B"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2825385a",
   "metadata": {},
   "outputs": [],
   "source": [
    "answer = \"x\" # replace x with a, b, c, or d \n",
    "alg_3_deps_check(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "429faa32",
   "metadata": {},
   "source": [
    "### Implementation\n",
    "\n",
    "These are the main steps of the implementation of algorithm 3:\n",
    "\n",
    "1. The worker receives the corresponding rows A[rows,:] and matrix B from the master process\n",
    "2. The worker computes the product of A[rows,:] times B\n",
    "3. The worker sends back the result of C[rows,:] to the master process"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c14ebcb3",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 198504 characters]\" align=\"left\" width=\"450\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d7952c1",
   "metadata": {},
   "source": [
    "The implementation of this variant is let as an exercise (see below)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0323d6d8",
   "metadata": {},
   "source": [
    "### Communication overhead\n",
    "\n",
    "Let us analyze the (theoretical) communication overhead for algorithm 3.\n",
    "\n",
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>Question:</b>  Which is the complexity of the communication and computations done by a worker in algorithm 3?\n",
    "</div>\n",
    "\n",
    "    a) O(N²) communication and O(N³) computation\n",
    "    b) O(N²) communication and O(N³/P) computation\n",
    "    c) O(N²) communication and O(N²) computation\n",
    "    d) O(N²/P) communication and O(N³/P) computation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50b8bf53",
   "metadata": {},
   "outputs": [],
   "source": [
    "answer = \"x\" # replace x with a, b, c, or d \n",
    "alg_3_complex_check(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3f0d99e6",
   "metadata": {},
   "source": [
    "In this case, the ratio between communication and computation is O(P/N). If the matrix size N is much larger than the number of workers P, then the communication overhead O(P/N) would be negligible. This opens the door to an scalable implementation."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7bb65f2e",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "The table below compares the three parallel algorithms. \n",
    "\n",
    "<div id = \"div1\"></div>\n",
    "\n",
    "| Algorithm | Parallelism <br>(#workers) | Communication <br>per worker | Computation <br>per worker | Ratio communication/<br>computation |\n",
    "|---|---|---|---|---|\n",
    "| 1 | N² | O(N) | O(N) | O(1) |\n",
    "| 2 | N | O(N²) | O(N²) | O(1) |\n",
    "| 3 | P | O(N²) | O(N³/P) | O(P/N) |\n",
    "\n",
    "\n",
    "- Matrix-matrix multiplication is trivially parallelizable (all entries in the result matrix can be computed in parallel, at least in theory)\n",
    "- However, we cannot exploit all the potential parallelism in a distributed system due to communication overhead\n",
    "- We need a sufficiently large grain size to obtain a near optimal speedup\n",
    "- We measured the theoretical parallel performance by computing the complexity of communication over computation\n",
    "- We measured the actual performance using the parallel speedup and parallel efficiency\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b83e744",
   "metadata": {},
   "source": [
    "## Exercises"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a628a1df",
   "metadata": {},
   "source": [
    "### Exercise 1\n",
    "\n",
    "Implement algorithm 3 in the function below. For simplicity, assume that the number of rows of C is a multiple of the number of workers.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8e50b923",
   "metadata": {},
   "outputs": [],
   "source": [
    "function matmul_dist_3!(C,A,B)\n",
    "    m = size(C,1)\n",
    "    n = size(C,2)\n",
    "    l = size(A,2)\n",
    "    @assert size(A,1) == m\n",
    "    @assert size(B,2) == n\n",
    "    @assert size(B,1) == l\n",
    "    @assert mod(m,nworkers()) == 0\n",
    "    # Implement here\n",
    "end"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4506dcfb",
   "metadata": {},
   "source": [
    "Use test-driven development to implement the algorithm. Use this test:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28cde36a",
   "metadata": {},
   "outputs": [],
   "source": [
    "using Test\n",
    "P = nworkers()\n",
    "load = 100\n",
    "N = load*P\n",
    "A = rand(N,N)\n",
    "B = rand(N,N)\n",
    "C = similar(A)\n",
    "@test matmul_dist_3!(C,A,B) ≈ A*B"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "03952b0b",
   "metadata": {},
   "source": [
    "Measure the performance of your implementation by running next cell. Do you get close to the optimal speedup?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3aa2b7c",
   "metadata": {},
   "outputs": [],
   "source": [
    "P = nworkers()\n",
    "load = 50 # try with 50, 100, and 200\n",
    "N = load*P\n",
    "A = rand(N,N)\n",
    "B = rand(N,N)\n",
    "C = similar(A)\n",
    "T1 = @belapsed matmul_seq!(C,A,B)\n",
    "C = similar(A)\n",
    "TP = @belapsed matmul_dist_3!(C,A,B)\n",
    "println(\"Speedup = \", T1/TP)\n",
    "println(\"Optimal speedup = \", P)\n",
    "println(\"Efficiency = \", 100*(T1/TP)/P, \"%\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e171362",
   "metadata": {},
   "source": [
    "# License\n",
    "\n",
    "\n",
    "This notebook is part of the course [Programming Large Scale Parallel Systems](https://www.francescverdugo.com/XM_40017/dev/) 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.10.0",
   "language": "julia",
   "name": "julia-1.10"
  },
  "language_info": {
   "file_extension": ".jl",
   "mimetype": "application/julia",
   "name": "julia",
   "version": "1.10.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
