1 of 87

10-405/605/805�ML FROM LARGE DATASETS

2 of 87

Outline

  • Review (spiral review)
    • MapReduce
    • Spark and Polars
  • Sample Workflows
    • Phrase Finding: Statistics with Multiple Counts
    • K-Means Clustering: Iteration

​

3 of 87

MAP-REDUCE REVIEW

4 of 87

4

2004

of crappy machines

≅ “corpus transformation”

≅ “something you do after a sort”

infrastructure to write your own scalable code (e.g., monitoring jobs, robustness against failing machines/disks, etc)

5 of 87

5

KenChurch 1994

Jeff & Sanjay 2004

Word count

Distributed word count

Bigram count

​

Mutual information for phrases

​

…

​

Grep

Distributed grep

Concordance / inverted index

Distributed inverted index

Sorting by alphabetical, rhyming, …

Distributed sort

pipelines of Unix™ tools to “transform” large data

+ sort

sequences of map-reduce steps

6 of 87

WordCount in MapReduce

6

bash-3.2$ head -1 ../data/brown_nolines.txt

​

The Fulton County Grand Jury said Friday an investigation of Atlanta's recent primary election produced "no evidence" that any irregularities took place.

​

bash-3.2$ py -m fire wc_nano.py WordCount \ map_reduce

--src ../data/brown_nolines.txt --dst wc.txt

​

bash-3.2$ head -5 wc.txt

('the', 69969)

('fulton', 17)

('county', 160)

('grand', 52)

('jury', 68)

wc_nano.py

hz_nano.py

7 of 87

Why MapReduce Scales on Cheap Machines

7

bash-3.2$ head -1 ../data/brown_nolines.txt

​

The Fulton County Grand Jury said Friday an investigation of Atlanta's recent primary election produced "no evidence" that any irregularities took place.

​

bash-3.2$ py -m fire wc_nano.py WordCount \ map_reduce

--src ../data/brown_nolines.txt --dst wc.txt

​

bash-3.2$ head -5 wc.txt

('the', 69969)

('fulton', 17)

('county', 160)

('grand', 52)

('jury', 68)

Better:

  1. sort the key-value pairs by key
  2. iterate through the sorted keys to create keyed groups to pass to reduce

8 of 87

Why does sorting words help?

9 of 87

Why does sorting words help?

10 of 87

Constant-Memory Word Count in Map-Reduce

10

11 of 87

Constant-Memory Word Count in Map-Reduce

11

itertools.groupby

all lazy!

12 of 87

Map-Reduce Can Be�Constant Memory�and Parallel

13 of 87

Map-Reduce in Parallel

13

  • doc 1
  • doc 2
  • ….

Counting logic

Mapper Machine 1

Partition/Sort

Spill 1

Spill 2

Spill 3

…

  • doc 1
  • doc 2
  • ….

Counting logic

Mapper Machine 2

Partition/Sort

Spill 1

Spill 2

Spill 3

…

  • ctr[x1] += 1
  • ctr[x1] += 1
  • ….

Logic to combine counter updates

Reducer Machine 1

Merge Spill Files

  • ctr[x2] += 1
  • ctr[x2] += 1
  • ….

combine counter updates

Reducer Machine 2

Merge Spill Files

Spill n

14 of 87

14

15 of 87

Key ideas in distributed map reduce

15

16 of 87

Key ideas in distributed map reduce

16

17 of 87

Key ideas in distributed map reduce

17

18 of 87

18

2004

of crappy machines

≅ “corpus transformation”

≅ “something you do after a sort”

19 of 87

Takeaways for MapReduce

  • useful substep for scalable computations
  • can parallelize to many workers
    • when data is partitioned evenly
  • can handle lots of data per worker
  • degrades slowly with more data
  • key idea:
    • communication = grouping items by key
    • shuffle-sort does that efficiently

20 of 87

Outline

  • Review
    • MapReduce
    • Spark and Polars
  • Sample Workflows
    • Phrase Finding: Statistics with Multiple Counts
    • K-Means Clustering: Iteration

​

21 of 87

SPARK AND POLARS

22 of 87

Spark: A Dataflow Language for MapReduce

  • Data abstraction
    • Resilient Distributed Datasets (RDD) ~ “sharded” files
      • RDDs are immutable, partitioned, and distributed
      • RDDs are created by
        • Transformations
          • step of lazy ‘plan’ to make altered copy of RDD
        • Actions
          • eager, usually force execution of a map-reduce pipeline and return some Python object
        • A “chaining API” combines transformations/actions
    • Computations are executed in parallel on a cluster using map-reduce operations

​

22

23 of 87

Classic PySpark examples: wordcount

23

24 of 87

Spark examples: wordcount

24

25 of 87

Classic spark examples: batch logistic regression

25

reduce is an action – it produces a numpy vector

p.x and w are vectors, from the numpy package

p.x and w are vectors, from the numpy package. Python overloads operations like * and + for vectors.

26 of 87

Spark examples: batch logistic regression

26

Important note: p.x, w are stored in memory as numpy vectors/matrices. Numpu is not just “syntactic sugar”.

  • They are much more compact than something like a list of python floats.
  • numpy operations like dot, *, + are calls to optimized C code
  • a little python logic around a lot of numpy calls is pretty efficient

27 of 87

Spark examples: batch logistic regression

27

dataset of points is cached in cluster memory to reduce i/o

we don’t need to scan the data on disk in each iteration!

28 of 87

Spark examples: batch logistic regression

28

gradient computation is done in parallel, locally on each worker, using data kept in memory.

summing the gradient vectors is done in parallel, and intermediate sums are set across the network

updating the weights is done on the local machine

The lambda function, including the current value of w, is broadcast to the workers

29 of 87

Spark logistic regression example

29

30 of 87

Takeaways for Spark

  • Resilient Distributed Datasets (RDD) ~ “sharded” files
    • RDDs are immutable, partitioned, and distributed
    • A “chaining API” combines transformations/actions
  • Computations are executed in parallel on a cluster using map-reduce operations
  • Can avoid reading large datasets repeatedly in iterative ML algorithms by caching RDDs in cluster memory

​

​

30

31 of 87

What is Polars?

  • A dataflow language related to Spark
    • Similar chaining API, similar operations, …
  • Fairly new (1.0 in 2024 – Spark is ~ 2014)
  • Heavily influenced by both cluster dataflow languages and database technology
  • Fast enough to most of what you want without a cluster – on a single desktop
    • Up to ~ 100Gb ?

31

32 of 87

Polars vs Spark

32

filter() is a transformation

count() is an action

Recap: Spark has transformations and actions

Polars has LazyFrames:

a LazyFrame

a LazyFrame

a LazyFrame

33 of 87

33

Polars has LazyFrames:

a LazyFrame

a LazyFrame

a LazyFrame

Polars also has eager DataFrames

a DataFrame

a DataFrame

a DataFrame

pl.read_csv

34 of 87

34

Polars also has eager DataFrames

a DataFrame

a DataFrame

a DataFrame

pl.read_csv

eager pl.DataFrames are kept in memory and operations are performed immediately

  • nice for debugging

​

lazy pl.LazyFrames are plans, usually based on scanning from disk

  • keeps big data out of memory, and can be optimized

35 of 87

LazyFrames Are Query Plans�That Can be Optimized

35

convert to lowercase then filter

filter then convert to lowercase

36 of 87

Parallelism in Polars

  • Modern CPUs have SIMD vector processors
    • Used by NumPy, …, Rust, …
    • Can use to process data: if its in big homogeneous chunks
    • Polars stores DataFrame-like data in chunks in memory (Arrow)

36

c1

c2

…

​

​

​

​

​

​

cN

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

…

…

…

..

…

…

…

…

…

…

​

​

​

​

​

​

​

​

​

​

Row Group 1

Row Group 2

Row Group 3

1

2

3

4

5

2

4

6

8

10

1 Mb

Not row-by-row or column-by-column: chunks are one column in a group of rows

Vector processing by chunk

37 of 87

Pros and Cons of Polars

  • Its new! 😎
  • It optimizes for you! 😎

​

  • It supports lazy, memory-efficient streaming! 😎

​

​

​

  • Very efficient host language (Rust) 😎
  • Polars Cloud!

​

​

​

  • Its new 🐣🚧
  • Unpredictable performance 🧐

​

  • It caches aggressively and this can lead to OOM 💣
  • Joins/group-by use in-memory hashes 👎

​

  • Lots of built-in functions to learn 🧐
  • .. is proprietary ☹

37

38 of 87

Outline

  • Review
    • MapReduce
    • Spark and Polars
  • Sample Workflows
    • Phrase Finding: Statistics with Multiple Counts
    • K-Means Clustering: Iteration

​

39 of 87

SAMPLE WORKFLOW:�COMPARING COUNTS IN TWO CORPORA

40 of 87

Two corpora: conservative political community, liberal community (2010)�Goal: find words most characteristic of each community

41 of 87

 

Naïve Bayes:

 

 

One corpus is “foreground” and one is “background”

PySpark code

42 of 87

Same Method for Comparing Bigrams

Problem: many of the common bigrams don’t seem to have meaning as a phrase….

43 of 87

Scoring bigrams as phrases

​

explanation

word_v

#distinct words

phrase_v

#distinct phrases

word_n

#words in corpus

phrase_n

#phrases in corpus

xy

phrase

x

first word

y

second word

As a phrase “x y”

As a random co-occurrence of x and y

unix™ poetry example

44 of 87

Comparing Phrases

Filtered for high “phrasiness”

45 of 87

Comparing bigrams and compute filter by phrasiness

In Spark Polars

46 of 87

Warmup: wordcount

47 of 87

Polars subroutines-in-chains

48 of 87

# drop first token from line

# tokens[0:2], tokens[2:4], …

# list of all bigrams

49 of 87

 

50 of 87

51 of 87

52 of 87

Similar for bigrams

53 of 87

Computing ‘phrasiness’

54 of 87

Computing ‘phrasiness’

55 of 87

56 of 87

Sorting Phrases by Foreground/Background and Filtering by Phraseness

57 of 87

Outline

  • Review
    • MapReduce
    • Spark and Polars
  • Sample Workflows
    • Phrase Finding: Statistics with Multiple Counts
    • K-Means Clustering: Iteration

​

58 of 87

AN ITERATIVE WORKFLOW:�K-MEANS

59 of 87

Background: Expectation-Maximization

59

60 of 87

Expectation-Maximization

60

EM is a kind of coordinate ascent:

  1. Split variables w to optimize into two sets: x,y
  2. Fix one set (x) and optimize the other (y)
  3. Then fix y and optimize x
  4. Then repeat…

​

​

​

​

​

​

61 of 87

Expectation-Maximization

61

In EM there is typically

  • instances X
  • a “soft assignment” of each xi to a “cluster”, zi
    • zi,j = Pr(xi in cluster j)
  • parameters w

​

Then do coordinate descent on w, Z to maximize

​

–log Pr(X| w, Z)

​

62 of 87

An example from Ron Bekkerman�k-means in Map-Reduce

62

63 of 87

Example: k-means clustering

  • An EM-like algorithm:
  • Initialize k cluster centroids
  • E-step: associate each data instance with the closest centroid
    • Find “expected values” of cluster assignments given the data and centroids
  • M-step: recalculate centroids as an average of the associated data instances
    • Find new centroids that “maximize that expectation”
  • And repeat…

63

64 of 87

k-means Clustering

64

centroids

65 of 87

k-means in Polars

  • Initialize k cluster centroids
  • E-step: associate each instance with the closest centroid
  • M-step: recalculate centroids as an average of the associated instances

65

66 of 87

k-means in Polars

  • We cluster documents encoded as TFIDF vectors
    • clusters are also unit length vectors
    • closest means “largest dot product”

67 of 87

Spherical k-means in Polars

  • We cluster documents encoded as sparse TFIDF vectors
    • clusters are dense unit length vectors
    • closest means “largest dot product”

docs are short, vocab is large

68 of 87

Aside: Are Two Entity Names the Same?

Possible solutions:

  • Normalize the entity names
    • fold case, collapse corp/corporation, …
  • Design a similarity function and match entities when similarity(a,b) > threshold

69 of 87

Aside: Are Two Entity Names the Same?

    • Surface similarity can be high for descriptions of distinct items:

​

      • AERO TGX-Series Work Table -42'' x 96'' Model 1TGX-4296 All tables shipped KD AEROSPEC- 1TGX Tables are Aerospec Designed. In addition to above specifications; - All four sides have a V countertop edge ...
      • AERO TGX-Series Work Table -42'' x 48'' Model 1TGX-4248 All tables shipped KD AEROSPEC- 1TGX Tables are Aerospec Designed. In addition to above specifications; - All four sides have a V countertop .. 
    • Surface can be low for descriptions of identical items:

​

      • Canon Angle Finder C 2882A002 Film Camera Angle Finders Right Angle Finder C (Includes ED-C & ED-D Adapters for All SLR Cameras) Film Camera Angle Finders & Magnifiers The Angle Finder C lets you adjust  ...
      •  CANON 2882A002 ANGLE FINDER C FOR EOS REBEL® SERIES PROVIDES A FULL SCREEN IMAGE SHOWS EXPOSURE DATA BUILT-IN DIOPTRIC ADJUSTMENT COMPATIBLE WITH THE CANON® REBEL, EOS & REBEL EOS SERIES.
  • Emphasizing matching on rare terms helps 🡺 TFIDF similarity

70 of 87

k-means in Polars

  • Initialize k cluster centroids
  • E-step: associate each document with the closest centroid
  • M-step: recalculate centroids as an average of the associated documents

70

assign doc to cluster by similarity

docs and clusters are vectors: dimension is #words, each components is a weight

O(corpus): the big one

O(vocab * k)

O(#docs)

71 of 87

71

72 of 87

Initialize Centroids

72

each cluster has just one document

73 of 87

73

74 of 87

Assign docs to closest centroid

74

75 of 87

75

76 of 87

Recompute centroids�

76

77 of 87

Recompute centroids: alternative

77

????

78 of 87

Recompute centroids: alternative

78

create groups with same ‘cluster_id’ and compute the L2 norm of the cluster

'broadcast’ the computed cluster norm to every row with the same ‘cluster_id’

divide w by the cluster norm

79 of 87

Recompute centroids: alternative

79

I don’t like “over” because it hides a group_by and group_by / join operations can be expensive

80 of 87

80

81 of 87

81

82 of 87

Can you be too lazy?

82

assignmentt = f(centroidst-1)

centroidst = g(assignmentt) =

g(f(centroidst-1))

centroidsn =

​

g(f(g(f(…)))

This can lead to big problems:

  • consuming a lazyFrame in multiple ways often means recomputing it
  • sometimes unwinding a loop can lead to exponentially many recomputations

​

If assignment_df doesn’t fit in memory consider caching the computation:

  • saving assignment on disk explicitly with ldf.sink(tmpfile)
  • redefining assignment_df as pl.scan_csv(tmpfile)

​

83 of 87

CLUSTER-PARALLEL K-MEANS

83

84 of 87

Parallelizing k-means

84

85 of 87

Parallelizing k-means

85

86 of 87

Parallelizing k-means

86

87 of 87

k-means on MapReduce

  • Mappers read data partitions + centroids
  • Mappers assign data instances to clusters
  • Mappers compute new local centroids and local cluster sizes
  • Reducers aggregate local centroids (weighted by local cluster sizes) into new global centroids
  • Reducers write the new centroids

87