MapReduce Programming

Hello World

  • Java WordCount Program:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    import java.io.IOException;
    import java.util.StringTokenizer;

    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.Path;
    import org.apache.hadoop.io.IntWritable;
    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapreduce.Job;
    import org.apache.hadoop.mapreduce.Mapper;
    import org.apache.hadoop.mapreduce.Reducer;
    import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
    import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

    public class WordCount {
    public static class TokenizerMapper
    extends Mapper<Object, Text, Text, IntWritable>{
    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();

    public void map(Object key, Text value, Context context)
    throws IOException, InterruptedException {
    StringTokenizer itr = new StringTokenizer(value.toString());
    while (itr.hasMoreTokens()) {
    word.set(itr.nextToken());
    context.write(word, one);
    }
    }
    }

    public static class IntSumReducer
    extends Reducer<Text,IntWritable,Text,IntWritable> {
    private IntWritable result = new IntWritable();
    public void reduce(Text key, Iterable<IntWritable> values, Context context)
    throws IOException, InterruptedException {
    int sum = 0;
    for (IntWritable val : values) {
    sum += val.get();
    }
    result.set(sum);
    context.write(key, result);
    }
    }

    public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();
    Job job = Job.getInstance(conf, "word count");
    job.setJarByClass(WordCount.class);
    job.setMapperClass(TokenizerMapper.class);
    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);
    FileInputFormat.addInputPath(job, new Path(args[0]));
    FileOutputFormat.setOutputPath(job, new Path(args[1]));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
    }
  • Compile the program:

    1
    2
    3
    $ mkdir wordcount
    $ javac -classpath `yarn classpath` WordCount.java -d wordcount
    $ jar -cvf wordcount.jar -C wordcount/ .
  • Run the program:

    1
    $ hadoop jar wordcount.jar WordCount /input /output
  • Input:

    1
    2
    Hello World Bye World
    Hello Hadoop Goodbye Hadoop
  • Output:

    1
    2
    3
    4
    5
    Bye 1
    Goodbye 1
    Hadoop 2
    Hello 2
    World 2

Dissection

Mapper

  • Interface: public class Mapper<KEYIN, VALUEIN, KEYOUT, VALUEOUT>
    1
    2
    3
    4
    5
    6
    7
    8
    public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
    ...
    public void map(LongWritable key, Text value, Context context)
    throws IOException, InterruptedException {
    ...
    context.write(...); // EMIT
    }
    }

Combiner

  • We specify a combiner which performs local aggregation on the map results after being sorted on keys
    1
    job.setCombinerClass(Reduce.class);

Reducer

  • Interface: public class Reducer<KEYIN, VALUEIN, KEYOUT, VALUEOUT>

    1
    2
    3
    4
    5
    6
    7
    public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {
    public void reduce(Text key, Iterable<IntWritable> values, Context context)
    throws IOException, InterruptedException {
    ...
    context.write(...);
    }
    }
  • Reducer has three phases:

    1. Shuffle

      • The Reducer copies the sorted output from each Mapper using HTTP across the network
    2. Sort

      • The framework merge sorts Reducer inputs by keys (since different Mappers may have output the same key)
      • Secondary sort on intermediate keys is allowed
      • The shuffle and sort phases occur simultaneously
    3. Reduce

      • Implemented in reduce() method

Debug

  • The MapReduce program can run in standalone (local) mode using the following lines (without modifying XML configuration files and restarting hadoop)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    public static void main(String[] args) throws Exception {
    // Run on a local node
    Configuration conf = new Configuration();
    conf.set("fs.defaultFS", "file:");
    conf.set("mapreduce.framework.name", "local");

    Job job = Job.getInstance(conf, "wordcount");
    ...
    }

Job Run

  • Entities are involved in a MapReduce job run:
    1. Client, which submits the MapReduce job
    2. YARN resource manager, which coordinates allocation of cluster resources
    3. YARN node managers, which launch and monitor compute containers
    4. MapReduce application master, which coordinates the tasks of the MapReduce job
    5. Distributed filesystem, which stores and shares job files between the other entities

  • Job Submission

    • Step 2. The client asks the resource manager for a new job ID
    • Step 3. The client copies resources to the filesystem
    • Step 4. The client tells the resource manager the job is ready for execution
  • Job Initialization

    • Step 5. The resource manager hands off requests to YARN scheduler, which allocates a container to run the application (managed by Node Manager)
    • Step 6. The application master keeps track of job progress
    • Step 7. The application master retrieves input splits from the file system
    • The application master may run tasks of a “small” job within the same JVM as itself, without asking for new containers
  • Task Assignment

    • Step 8. For large jobs, the application master requests containers for all map and reduce tasks in the job from the resource manager
  • Task Execution

    • Step 9. The application master starts the container by contacting the node manager, under a YarnChild class
    • Step 10. The YarnChild class localizes resources (e.g., job configuration and JAR file)
    • Step 11. Run the map/reduce task

Handling Failures

  • Task failure
    • If a task is crashed or hanging, it fails
    • The application master reschedules the task on a different node manager. If any task fails 4 times (default), whole job fails
  • Application master failure
    • The resource manager detects the failure and starts a new master instance in a new container, and tries to recover the state of tasks using job history
  • Node manager failure
    • The resource manager recovers task/application master failures as above, and removes the failed node manager
  • Resource manager failure
    • Single point of failure
    • Need active and standby resource managers

Additional

Configuration Tuning

  • Specify configurations in XML file with property-value pair
    1
    2
    3
    4
    5
    6
    Configuration conf = new Configuration();

    // set memory buffer for map outputs to 200MB
    conf.setInt(“mapreduce.task.io.sort.mb", 200);

    Job job = Job.getInstance(conf, "wordcount");

Optimization

  • Speculative execution

    • Job execution time is bottlenecked by the slowest running task
    • Straggler: a machine that takes unusually long time to finish the last few tasks (it is hard to determine it is failure or not as it is still running)
    • If a task is running slow, Hadoop launches another equivalently, task as a backup (When the task finishes, any duplicate tasks are killed)
  • Skipping bad records

    • Bad records throw runtime exceptions, causing a task to retry or even halt (after 4 retries)
    • If skipping mode is enabled, failed records are skipped (some small parts is not that importance, ignore them may not affect the big picture, which is acceptable)

Counters

  • a useful channel for gathering statistics about a job, Hadoop maintains built-in counters for a job
  • User-defined counters:
    • Java enum type
    • Counters are global: MapReduce aggregates them across all map and reduce tasks
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      enum WordCount {
      NUM_OF_TOKENS
      }

      public static class Map extends
      Mapper<LongWritable, Text, Text, IntWritable> {
      public void map(LongWritable key, Text value, Context context)
      throws IOException, InterruptedException {
      // Counter
      context.getCounter(WordCount.NUM_OF_TOKENS).increment(1);
      }
      }

MapReduce Algorithm Design

Local Aggregation

  • In Hadoop, intermediate results (i.e., map outputs) are written to local disk before being sent over the network
  • Local aggregation of intermediate results reduces the number of key-value pairs that need to be shuffled from the mappers to the reducers
  • Default combiner: Aggregate map outputs with the same key, acts like a mini-reducer

In-mapper Combiners

  • Version 1:
    • Emits a key-value pair for each unique term per document
  • Version 2:

    • Recall a map object is created for each map task
    • Aggregate all data appearing in the input block processed by the map task
  • Advantages:

    1. Provide control over where and how local aggregation takes place.
    2. In-mapper combiners are applied inside the code. Default combiners are applied to the map outputs.
  • Disadvantages:

    1. States are preserved within mappers → potentially large memory overhead.
    2. Potential order-dependent bugs.

Combiner Design

  • Combiner and reducer must share the same signature

    • Combiner is treated as mini-reducer
    • Combiner input and output key-value types must match the reducer input key-value type
  • Combiner are optional optimizations

    • With/without combiner should not affect algorithm correctness
  • Example: Computing the Mean

    • Version 1 (Correct):

    • Notice: Mean of the means is not the original mean

    • Version 2 (WRONG):

      The output type of the mapper does not match the input type of the reducer
    • Version 3 (Correct):

    • Version 4 (In-mapper combiners):

Pairs and Stripes

  • constructing complex keys and values improves the performance of computation

Co-occurrence Matrix

  • Example: building a word co-occurrence matrix over a text collection

    • $M = n \times n$ matrix (n = number of unique words), $m_{ij} = $ number of times word $w_i$ co-occurs with word $w_j$ within a specific context

    • Challenge: Space requirement: $O(n^2)$

    • Approach: Mappers generate partial counts, Reducers aggregate partial counts
  • Pairs

    • Mapper:
      • Emits intermediate key-value pairs with each co-occurring word pair and integer 1
    • Reducer:

      • Sums up all values associated with the same co-occurring word pair
      • MapReduce execution framework guarantees that all values associated with the same key are brought together in the reduce

    • Advantages:

      1. Easy to understand and implement
    • Disadvantages:
      1. Generate many key-value pairs
  • Stripes

    • Mapper:
      • For each particular word, stores co-occurrence information in an associative array
      • Emits intermediate key-value pairs with words as keys and corresponding associative arrays as values
    • Reducer:

      • Sums all the counts in the associative arrays
      • MapReduce execution framework guarantees that all associative arrays with the same key are brought together in the reducer


    • Advantages:

      1. Generate fewer key-value pairs
      2. Make better use of combiners
    • Disadvantages:
      1. Memory size of associative arrays in mappers could be huge
  • Stripes much faster than pairs

Relative Frequencies

  • Stripes Approach
    Similar to the approach of constructing co-occurrence matrix: Sum all the counts in the associative array for each word

  • Pair Approach

    • Mapper emits (a,*) for every word being observed
    • Mapper makes sure same word goes to the same reducer (use partitioner)
    • Mapper makes sure (a,*) comes first, before individual counts
    • Reducer holds state to remember the count of (a,*), until all pairs with the word “a” have been computed

Order Inversion

  • Computing relative frequencies requires marginal counts because it cannot be computed until getting all counts
    For every pair, the mapper adds the count to the marginal count
    When all pairs are processed, the mapper also emits the marginal count
    Using order inversion, the marginal count arrives before the pairs at the reducer
    The reducer remembers the marginal count, and computes the relative frequency for each pair being observed
  • Control the sort order of the intermediate key so that the marginal count comes before individual counts job.setSortComparatorClass()

Secondary Sort

MapReduce sorts input to reducers by key, but values may be arbitrarily ordered. What if want to sort value also?
E.g., Sensors record temperature over time (id, time t, temperature v)

  • Value-to-key conversion
    Each mapper emits (id, t) → v. Let execution framework do the sorting.
    Preserve state across multiple key-value pairs to handle processing.

Tools for Synchronization

  • Cleverly-constructed data structures
    Bring data together
  • Sort order of intermediate keys
    Control order in which reducers process keys
  • Partitioner
    Control which reducer processes which keys
  • Preserving state in mappers and reducers
    Capture dependencies across multiple keys and values