Introduction

  • Motivation: Many of the previous cluster programming models are based on directed acyclic data flow from stable storage to stable storage, e.g. MapReduce, Dryad, Tez, SQL
  • Benefits of data flow: runtime can decide where to run tasks and can automatically recover from failures
  • However, although Acyclic data flow is a powerful abstraction, it is NOT efficient for applications that repeatedly reuse a Working-Set of data:

    • Iterative algorithms (machine learning)
    • Interactive data mining tools (R, Excel, Python)
  • Data Sharing:

    • MapReduce: Sharing via Disk I/O
    • Spark: In-memory Sharing (Fast Disk-based sharing as well)

Functional Programming

Functional programming is a good fit for Parallel, Concurrent, and Fault-Tolerant Computing because the states of every step are traceable due to the properties of functional programming; the function must provide the same output if giving the same input

  • The Root of The Problem
    • Non-determinism caused by the concurrent threads accessing shared mutable state
    • It helps to encapsulate state in actors or transactions but the fundamental problem stays the same
      1
      2
      3
      4
      5
      var x = 0
      async {x = x + 1}
      async {x = x * 2}

      // It can give 0, 1, 2
    • Functional programming can avoid the multable state

Scala

  1. Declaring Variables:

    1
    2
    3
    4
    5
    6
    // Constant
    var x: Int = 7;
    var x = 7 // type inferred

    // Variable
    val y = "hi" // read-only
  2. Functions:

    1
    2
    3
    4
    5
    6
    7
    8
    def square(x: Int): Int = x * x
    def square(x: Int): Int = {
    x * x
    }

    def announce(text: String) {
    println(text)
    }
  3. Generic Types and Indexing:

    1
    2
    3
    4
    5
    var arr = new Array[Int](8)
    var lst = List(1, 2, 3)

    arr(5) = 7
    println(lst(5))

Scala Closure Syntax

  • List Operations:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    val list = List(1, 2, 3)

    list.foreach(x => println(x)) // prints 1, 2, 3
    list.foreach(println) // same

    list.map(x => x + 2) // => List(3, 4, 5)
    list.map(_ + 2) // same, with placeholder notation

    list.filter(x => x % 2 == 1) // => List(1, 3)
    list.filter(_ % 2 == 1) // same

    list.reduce((x, y) => x + y) // => 6
    list.reduce(_ + _) // same
  • Add 2 Operations:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    (x: Int) => x + 2   // full version
    x => x + 2 // type inferred
    _ + 2 // when each argument is used exactly once
    x => { // when body is a block of code
    val numberToAdd = 2
    x + numberToAdd
    }
    // If the closure is too long, we can pass a function
    def addTwo(x: Int): Int = x + 2
    list.map(addTwo)
  • Other Scala Collection Methods:

Method Expanation
map(f: T => U): Seq[U] Pass each element through f
flatMap(f: T => Seq[U]): Seq[U] One-to-many map
filter(f: T => Boolean): Seq[T] Keep elements passing f
exists(f: T => Boolean): Boolean True if one element passes
forall(f: T => Boolean): Boolean True if all element pass
reduve(f: (T, T) => T): T Merge elements using f
groupBy(f: T => K): Map[K, List[T]] Group elements by f(element)
sortBy(f: T => K): Seq[T] Sort elements by f(element)

Resilient Distributed Datasets

  • Key Ideas behind Spark’s Solution: Data Flow Model + Resilient Distributed Datasets (RDDs)

    • Augment Data Flow model with Resilient Distributed Datasets
    • Combine Data Flow with RDDs to unify many cluster programming models
    • Spark makes Working Datasets a first-class concept to efficiently support In-memory Data-Sharing across (different iterations/ stages of ) apps

    • Retain the attractive properties of MapReduce:

      • Fault tolerance (for crashes & stragglers)
      • Data locality
      • Scalability
    • Enhance programmability:

      • Integrate into Scala programming language
      • Allow interactive use from Scala interpreter

Characteristics

  1. Resilient: Remember the source information so it can be reconstructed. RDDs are resilient because they can automatically recover from failures. This is achieved through lineage information, which Spark uses to reconstruct lost partitions due to node failures. If we want to prevent many transformers from being lost, we can save the data in the disk within the execution.

  2. Distributed: RDDs are distributed across multiple nodes in a cluster, enabling parallel processing of data. Each RDD is divided into multiple partitions, with each partition stored on a different node.

  3. Immutable: RDDs are immutable (i.e., become read-only once they are created) collects partitioned across cluster that can be rebuilt if a partition is lost

  4. Lazy: It would not run the transformations unless the user activates (outputs) it

Construction

  • RDD is created by transforming data in stable storage using data flow operations (map, filter, group-by, …)
  • The elements of an RDD need not exist in physical storage
    • a handle to an RDD contains enough information (aka lineage info) to compute the RDD starting from data in reliable storage.
    • RDDs can always be reconstructed if nodes fail
  • RDDs can be cached (persist) in RAM across parallel operations and to shared by different Apps
  • User can control the Partitioning of an RDD (e.g., one comprised of <key, value> pairs based on hash or range of the key)
    • Once partitioned, Spark will remember the way an RDD is partitioned and use the info to reduce unnecessary data shuffling when operating on RDDs (optimization)
      • e.g. Functions that benefit from partitioning include: cogroup(), groupWith(), join(), groupByKey(), reduceByKey(), combineByKey(), lookup()
    • Spark knows internally which operations may affect partitioning, and will automatically set the partitioner of an RDD

RDD Types

  1. Parallelized Collections:
    By calling SparkContext’s parallelize method on an existing Scala collection. Once created, the distributed dataset can be operated on in parallel.

  2. Hadoop Datasets:
    Spark supports text files, SequenceFiles, and any other Hadoop inputFormat

    1
    2
    val distFiles = sc.textFile(URI)
    val distFile = sc.hadoopRDD(URI)

Programming Model

The programming model of Spark uses Resilient Distributed Datasets (RDDs) as basic building blocks and perform Parallel Operations on RDDs

  • Transformations (Lazy), Only compute when an action requires: Operations to create new RDD(s) from existing ones, e.g. map, filter, groupBy, join
  • Actions: Return a result (value) to a driver program after running the computation on the RDD or write it to storage, e.g. reduce, collect, count, save, …

  • Transformations and Actions

Transformations

Transformation Description
map(func) return a new distributed dataset formed by passing each element of the source through a function func
filter(func) return a new dataset formed by selecting those elements of the source on which func returns true
flatMap(func) similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item)
sample(withReplacement, fraction, seed) sample a fraction fraction of the data, with or without replacement, using a given random number generator seed
union(otherDataset) return a new dataset that contains the union of the elements in the source dataset and the argument
distinct([numTasks]) return a new dataset that contains the distinct elements of the source dataset
groupByKey([numTasks]) when called on a dataset of (K, V) pairs, returns a dataset of (K, Seq[V]) pairs
reduceByKey(func, [numTasks]) when called on a dataset of (K, V) pairs, returns a dataset of (K, V) pairs where the values for each key are aggregated using the given reduce function
sortByKey(ascending, [numTasks]) when called on a dataset of (K, V) pairs where K implements Ordered, returns a dataset of (K, V) pairs sorted by keys in ascending or descending order, as specified in the boolean ascending argument
join(otherDataset, [numTasks]) when called on datasets of type (K, V) and (K, W), returns a dataset of (K, (V, W)) pairs with all pairs of elements for each key
cogroup(otherDataset, [numTasks]) when called on datasets of type (K, V) and (K, W), returns a dataset of (K, Seq[V], Seq[W]) tuples – also called groupWith
cartesian(otherDataset) when called on datasets of types T and U, returns a dataset of (T, U) pairs (all pairs of elements)

Basic RDD transformations on two RDDs containing rdd = {1, 2, 3, 3}

Function name Purpose Example Result
map() Apply a function to each element in the RDD and return an RDD of the result. rdd.map(x => x + 1) {2, 3, 4, 4}
flatMap() Apply a function to each element in the RDD and return an RDD of the contents of the iterators returned. Often used to extract words. rdd.flatMap(x => x.to(3)) {1, 2, 3, 2, 3, 3}
filter() Return an RDD consisting of only elements that pass the condition passed to filter(). rdd.filter(x => x != 1) {2, 3, 3}
distinct() Remove duplicates. rdd.distinct() {1, 2, 3}
sample(withReplacement, fraction, [seed]) Sample an RDD, with or without replacement. rdd.sample(false, 0.5) Nondeterministic

Basic RDD transformations on two RDDs containing rdd = {1, 2, 3} and other = {3, 4, 5}

Function name Purpose Example Result
union() Produce an RDD containing elements from both RDDs. rdd.union(other) {1, 2, 3, 3, 4, 5}
intersection() RDD containing only elements found in both RDDs. rdd.intersection(other) {3}
subtract() Remove the contents of one RDD (e.g., remove training data). rdd.subtract(other) {1, 2}
cartesian() Cartesian product with the other RDD. rdd.cartesian(other) {(1, 3), (1, 4), ..., (3, 5)}

Actions

Action Description
reduce(func) Aggregate the elements of the dataset using a function func (which takes two arguments and returns one), and should also be commutative and associative so that it can be computed correctly in parallel
collect() Return all the elements of the dataset as an array at the driver program – usually useful after a filter or other operation that returns a sufficiently small subset of the data
count() Return the number of elements in the dataset
first() Return the first element of the dataset – similar to take(1)
take(n) Return an array with the first n elements of the dataset – currently not executed in parallel, instead the driver program computes all the elements
takeSample(withReplacement, fraction, seed) Return an array with a random sample of num elements of the dataset, with or without replacement, using the given random number generator seed
saveAsTextFile(path) Write the elements of the dataset as a text file (or set of text files) in a given directory in the local filesystem, HDFS or any other Hadoop-supported file system. Spark will call toString on each element to convert it to a line of text in the file
saveAsSequenceFile(path) Write the elements of the dataset as a Hadoop SequenceFile in a given path in the local filesystem, HDFS or any other Hadoop-supported file system. Only available on RDDs of key-value pairs that either implement Hadoop’s Writable interface or are implicitly convertible to Writable (Spark includes conversions for basic types like Int, Double, String, etc.)
countByKey() Only available on RDDs of type (K, V). Returns a Map of (K, Int) pairs with the count of each key
foreach(func) Run a function func on each element of the dataset – usually done for side effects such as updating an accumulator variable or interacting with external storage systems

Basic RDD transformations on an RDD containing rdd = {1, 2, 3, 3}

Function name Purpose Example Result
collect() Return all elements from the RDD. rdd.collect() {1, 2, 3, 3}
count() Number of elements in the RDD. rdd.count() 4
countByValue() Number of times each element occurs in the RDD. rdd.countByValue() {(1, 1), (2, 1), (3, 2)}
take(num) Return num elements from the RDD. rdd.take(2) {1, 2}
top(num) Return the top num elements the RDD. rdd.top(2) {3, 3}
takeOrdered(num, ordering) Return num elements based on provided ordering. rdd.takeOrdered(2, myOrdering) {3, 3}
takeSample(withReplacement, num, [seed]) Return num elements at random. rdd.takeSample(false, 1) Nondeterministic
reduce(func) Combine the elements of the RDD together in parallel (e.g., sum). rdd.reduce((x, y) => x + y) 9
fold(zero)(func) Same as reduce() but with the provided zero value. rdd.fold(0)((x, y) => x + y) 9
aggregate(zeroValue)(seqOp, combOp) Similar to reduce() but used to return a different type. rdd.aggregate((0, 0))((x, y) => (x._1 + y, x._2 + 1), (x, y) => (x._1 + y._1, x._2 + y._2)) (9, 4)
foreach(func) Apply the provided function to each element of the RDD. rdd.foreach(func) Nothing

Parallel Operations

  1. reduce: Combines dataset elements using an associative function to produce a result at the driver program.
  2. collect: Sends all elements of the dataset to the driver program.
  • Example: Log Mining w/ Spark in Scala - Load error messages from a log into memory, then interactively search for various patterns
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // Base RDD
    lines = spark.textFile("hdfs://...")

    // Transformed RDD
    errors = lines.filter(_.startsWith("ERROR"))
    messages = errors.map(_.split('\t')(2))
    cachedMsgs = messages.cache() // Cached RDD

    // Parallel operation
    cachedMsgs.filter(_.contains("foo")).count()
    cachedMsgs.filter(_.contains("bar")).count()

Key-Value Pairs

Spark’s “distributed reduce” transformations operate on RDDs of key-value pairs

1
2
3
val pair = (a, b)
pair._1 // => a
pair._2 // => b

Basic RDD transformations on two RDDs containing rdd = {(1, 2), (3, 4), (3, 6)} and other = {(3, 9)}

Function name Purpose Example Result
reduceByKey(func) Combine values with the same key. rdd.reduceByKey((x, y) => x + y) {(1, 2), (3, 10)}
groupByKey() Group values with the same key. rdd.groupByKey() {(1, [2]), (3, [4, 6])}
mapValues(func) Apply a function to each value of a pair RDD without changing the key. rdd.mapValues(x => x+1) {(1, 3), (3, 5), (3, 7)}
flatMapValues(func) Apply a function that returns an iterator to each value of a pair RDD, and for each element returned, produce a key/value entry with the old key. Often used for tokenization. rdd.flatMapValues(x => x.to(5)) {(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (3, 4), (3, 5)}
keys() Return an RDD of just the keys. rdd.keys() {1, 3, 3}
values() Return an RDD of just the values. rdd.values() {2, 4, 6}
sortByKey() Return an RDD sorted by the key. rdd.sortByKey() {(1, 2), (3, 4), (3, 6)}
combineByKey(createCombiner, mergeValue, mergeCombiners, partitioner) Combine values with the same key using a different result type. rdd.combineByKey(...) See specific example
subtractByKey Remove elements with a key present in the other RDD. rdd.subtractByKey(other) {(1, 2)}
join Perform an inner join between two RDDs. rdd.join(other) {(3, (4, 9)), (3, (6, 9))}
rightOuterJoin Perform a join between two RDDs where the key must be present in the first RDD. rdd.rightOuterJoin(other) {(3, (Some(4), 9)), (3, (Some(6), 9))}
leftOuterJoin Perform a join between two RDDs where the key must be present in the other RDD. rdd.leftOuterJoin(other) {(1, (2, None)), (3, (4, Some(9))), (3, (6, Some(9)))}
cogroup Group data from both RDDs sharing the same key. rdd.cogroup(other) {(1, ([2], [])), (3, ([4, 6], [9]))}

Examples

  • Filtering on Values of a Pair-RDD

    1
    pairs.filter{case(key, value) => value.length < 20}
    1
    result = pairs.filter{lambda keyValue: len(keyValue[1]) < 20}

  • Per-key Averaging

    1
    rdd.mapValues(x => (x, 1)).reduceByKey((x, y) => (x._1 + y._1, x._2 + y._2))
    1
    rdd.mapValues(lambda x: (x, 1)).reduceByKey(lambda x, y: (x[0] + y[0], x[1] + y[1]))

  • Word Count Example

    1
    2
    3
    4
    5
    6
    7
    8
    9
    val input = sc.textFile("s3://...")
    val words = input.flatMap(x => x.split(" "))
    val results = words.map(x => (x, 1)).reduceByKey((x, y) => x + y)

    // shorthand implementation
    val lines = sc.textFile("s3://...")
    val counts = lines.flatMap(line => line.split(" "))
    .map(word => (word, 1))
    .reduceByKey(_ + _)
    1
    2
    3
    rdd = sc.textFile("s3://...")
    words = rdd.flatMap(lambda x: x.split(" "))
    results = words.map(lambda x: (x, 1)).reduceByKey(lambda x, y: x + y)

Fault Tolerance

An RDD has enough information about how it was derived from other datasets (aka its lineage)

  • RDD’s Lineage info can be used to reconstruct lost partitions

  • These datasets will be stored as a chain of objects capturing the lineage of each RDD. Each dataset object contains a pointer to its parent and information about how the parent was transformed.

Algorithm

PageRank

  1. Start each page at a rank of 1
  2. On each iteration, have page p contribute rank$_p$ / |neighbors$_p$| to its neighbors
  3. Set each page’s rank to 0.15 + 0.85 × contribs

  • Naïve Implementation

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    val sc = new SparkContext("local", "PageRank", sparkHome, Seq("pagerank.jar"))

    val links = // RDD of (url, neighbors) pairs
    var ranks = // RDD of (url, rank) pairs

    for (i <- 1 to ITERATIONS) {
    var contribs = links.join(ranks).flatMap {
    case (url, (links, rank)) =>
    links.map(dest => (dest, rank / links.size))
    }
    ranks = contribs.reduceByKey(_ + _).mapValues(0.15 + 0.85 * _)
    }

  • Control the Partitioning of RDDs

    1
    2
    3
    4
    5
    6
    val links = sc.textFile(inputpath)
    .filter(line => !line.startsWith("#"))
    .map{line => line.split("\t")}
    .map{nodes => (nodes(0), nodes(1))}
    .groupByKey()
    .partitionBy(new HashPartitioner(8)) // add paritioner if necessary

  • Execution Flow:

  • RDD Partitioning:

Execution Process

  • DAG Scheduler:
  • Input: RDD and Partitions to compute
  • Output: Output from Actions of those Partitions

Conclusion

  1. Scala: OOP + Functional Programming
  2. RDDs: fault tolerance, data locality/ partitioning-control, scalability
  3. RDD implemented in Spark using Scala
  4. Spark offers a rich API to make data analytics fast: both fast to write and fast to run
  5. Rapidly growing community