Repository navigation
Expand file tree
/
Copy path13_partIV_GPU_ML.Rmd
More file actions
238 lines (159 loc) · 16.3 KB
/
Copy path13_partIV_GPU_ML.Rmd
File metadata and controls
238 lines (159 loc) · 16.3 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# Econometrics with GPUs
GPUs\index{Graphics Processing Unit (GPU)} have been used for a while in computational economics (see @aldrich_2014 for an overview of early applications in economics). However, until recently most of the work building on GPUs\index{Graphics Processing Unit (GPU)} in economics has focused on solving economic models numerically (see, e.g., @aldrich_etal2011) and more broadly on Monte Carlo simulation. In this chapter, we first look at very basic GPU computation with R before having a look at the nowadays most common application of GPUs\index{Graphics Processing Unit (GPU)} in applied econometrics, machine learning with neural networks.
## OLS on GPUs
In a first simple tutorial, we have a look at how GPUs can be used to speed up basic econometric functions, such as the implementation of the OLS estimator\index{Ordinary Least Squares (OLS)}. To this end, we will build on the `gpuR`\index{gpuR Package} package introduced in Chapter 5. To keep the example code simple, we follow the same basic set-up to implement and test our own OLS estimator function as in Chapter 3. That is, we first generate a sample based on (pseudo-)random numbers. To this end, we first define the sample size parameters `n` (the number of observations in our pseudo-sample) and `p` (the number of variables describing each of these observations) and then initialize the dataset `X`.
```{r}
set.seed(1)
# set parameter values
n <- 100000
p <- 4
# generate a design matrix (~ our 'dataset')
# with p variables and n observations
X <- matrix(rnorm(n*p, mean = 10), ncol = p)
# add column for intercept
#X <- cbind(rep(1, n), X)
```
Following exactly the same code as in Chapter 3, we can now define what the real linear model that we have in mind looks like and compute the output `y` of this model, given the input `X`.
```{r}
# MC model
y <- 1.5*X[,1] + 4*X[,2] - 3.5*X[,3] + 0.5*X[,4] + rnorm(n)
```
Now we re-implement our `beta_ols` function from Chapter 3 such that the OLS estimation is run on our local GPU\index{Graphics Processing Unit (GPU)}. Recall that when computing on the GPU\index{Graphics Processing Unit (GPU)}, we have the choice between keeping the data objects that go into the computation in RAM, or we can transfer the corresponding objects to GPU memory\index{GPU Memory} (which will further speed up the GPU\index{Graphics Processing Unit (GPU)} computation). In the implementation of our `beta_ols_gpu`, I have added a parameter that allows switching between these two approaches. While setting `gpu_memory=TRUE` is likely faster, it might fail due to a lack of GPU memory\index{GPU Memory} (in all common desktop and laptop computers, RAM will be substantially larger than the GPU's own memory). Hence, `gpu_memory` is set to `FALSE` by default.
```{r}
beta_ols_gpu <-
function(X, y, gpu_memory=FALSE) {
require(gpuR)
if (!gpu_memory){
# point GPU to matrix (matrix stored in non-GPU memory)
vclX <- vclMatrix(X, type = "float")
vcly <- vclVector(y, type = "float")
# compute cross products and inverse
XXi <- solve(crossprod(vclX,vclX))
Xy <- crossprod(vclX, vcly)
} else {
# point GPU to matrix (matrix stored in non-GPU memory)
gpuX <- gpuMatrix(X, type = "float")
gpuy <- gpuVector(y, type = "float")
# compute cross products and inverse
XXi <- solve(crossprod(gpuX,gpuX))
Xy <- t(gpuX) %*% gpuy
}
beta_hat <- as.vector(XXi %*% Xy)
return(beta_hat)
}
```
Now we can verify whether the implemented GPU-run\index{Graphics Processing Unit (GPU)} OLS\index{Ordinary Least Squares (OLS)} estimator works as expected.
```{r}
beta_ols_gpu(X,y)
```
```{r}
beta_ols_gpu(X,y, gpu_memory = TRUE)
```
Note how the coefficient estimates are very close to the true values. We can rest assured that our implementation of a GPU-based OLS\index{Ordinary Least Squares (OLS)} estimator works fairly well. Also note how simple the basic implementation of functions to compute matrix-based operations on the GPU\index{Graphics Processing Unit (GPU)} is through the `gpuR`\index{gpuR Package} package.
## A word of caution
From just comparing the number of threads of a modern CPU\index{Central Processing Unit (CPU)} with the number of threads of a modern GPU\index{Graphics Processing Unit (GPU)}, one might get the impression that parallelizable tasks should always be implemented for GPU computing. However, whether one approach or the other is faster can depend a lot on the overall task and the data at hand. Moreover, the parallel implementation of tasks can be done more or less well on either system. Really efficient parallel implementation of tasks can take a lot of coding time (particularly when done for GPUs\index{Graphics Processing Unit (GPU)}).^[For a more detailed discussion of the relevant factors for well-designed parallelization (either on CPUs\index{Central Processing Unit (CPU)} or GPUs\index{Graphics Processing Unit (GPU)}), see @matloff_2015.]
As it turns out, the GPU\index{Graphics Processing Unit (GPU)} OLS implementation above is actually a good example of a potential pitfall. While, as demonstrated in Chapter 4, matrix operations per se are likely much faster on GPUs\index{Graphics Processing Unit (GPU)} than CPUs, the simple `beta_ols_gpu()` function implemented above involves more than the simple matrix operations. The model matrix as well as the vector of the dependent variable first had to be prepared for these operations (either a pointer for the GPU to the object in RAM had to be created or the objects had to be transferred to GPU memory\index{GPU Memory}). Finally, the computed values need to be transferred back to a normal R-object (at least if we want to make the output consistent with our simple `beta_ols()` implementation from Chapter 3). All of these steps create an additional overhead in terms of computing time.^[You can easily verify this by comparing the performance of `beta_ols()` (the simple CPU-based implementation) with the here implemented `beta_ols_gpu()` through the `bench::mark()` function.] Depending on the problem at hand, this overhead resulting from preparatory steps before running the actual computations on the GPU might be dwarfed by the efficiency gain if the computing task is much more demanding then what is involved in OLS\index{Ordinary Least Squares (OLS)}. The section on TensorFlow\index{TensorFlow}/Keras\index{Keras} below points to exactly such a setting, where GPUs\index{Graphics Processing Unit (GPU)} are typically much faster than CPUs\index{Central Processing Unit (CPU)}.
## Higher-level interfaces for basic econometrics with GPUs
The [CRAN Task View on High-Performance and Parallel Computing with R](https://cran.r-project.org/web/views/HighPerformanceComputing.html) lists several projects that provide easy-to-use interfaces to canned implementations of regression\index{Regression} and machine learning\index{Machine Learning} algorithms running on GPUs. For example, the `tfestimators`\index{tfestimators Package} package provides an R interface to use the TensorFlow Estimators framework by @cheng_etal2017. The package provides various canned estimators to be run on GPUs\index{Graphics Processing Unit (GPU)} (through TensorFlow\index{TensorFlow}).^[See https://cran.r-project.org/web/packages/tfestimators/vignettes/estimator_basics.html for an introduction to the basic usage of the package.] Note, however, that this framework is only compatible with TensorFlow version 1. As we will build on the latest version of TensorFlow\index{TensorFlow} (version 2) in the following example (and as most applications now build on version 2), we will not go into details of how to work with `tfestimators`\index{tfestimators Package}. However, there are excellent vignettes provided with the package that help you get started.^[See https://cran.r-project.org/web/packages/tfestimators/.]
## TensorFlow/Keras example: Predict housing prices
The most common application of GPUs\index{Graphics Processing Unit (GPU)} in modern econometrics is machine learning\index{Machine Learning}, in particular deep learning\index{Deep Learning} (a type of machine learning based on artificial neural networks). Training deep learning models can be very computationally intensive and to a great extent depends on tensor (matrix) multiplications. This is also an area where you might come across highly parallelized computing based on GPUs without even noticing it, as the now commonly used software to build and train deep neural nets ([TensorFlow](https://www.tensorflow.org/)\index{TensorFlow}; @tensorflow2015-whitepaper, and the high-level [Keras](https://keras.io/)\index{Keras} API; @chollet2015keras) can easily be run on a CPU or GPU\index{Graphics Processing Unit (GPU)} without any further configuration/preparation (apart from the initial installation of these programs). In this chapter, we look at a simple example of using GPUs\index{Graphics Processing Unit (GPU)} with Keras\index{Keras} in the context of predictive econometrics.
In this example we train a simple sequential model with two hidden layers to predict the median value of owner-occupied homes (in USD 1,000) in the Boston area (data is from the 1970s). The original data and a detailed description can be found here: https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html. The example closely follows [this Keras tutorial](https://keras.rstudio.com/articles/tutorial_basic_regression.html#the-boston-housing-prices-dataset) published by RStudio. See [RStudio's Keras installation guide](https://keras.rstudio.com/index.html) for how to install Keras\index{Keras} (and TensorFlow) and the corresponding R package `keras`\index{keras Package} [@keras].^[This might involve the installation of additional packages and software outside the R environment. The following examples were run with TensorFlow version `tensorflow_gpu-2.9.3`.] While the purpose of the example here is to demonstrate a typical (but very simple!) use case of GPUs in machine learning, the same code should also run on a normal machine (without using GPUs) with a default installation of Keras.
Apart from `keras`, we load packages to prepare the data and visualize the output. Via `dataset_boston_housing()`, we load the dataset (shipped with the Keras installation) in the format preferred by the `keras` library.
```{r echo=FALSE, message=FALSE, warning=FALSE}
if (Sys.info()["sysname"]=="Darwin"){ # run on macOS machine
use_python("/Users/umatter/opt/anaconda3/bin/python") # IMPORTANT: keras/tensorflow is set up to run in this environment on this machine!
}
```
```{r warning=FALSE, message=FALSE}
# load packages
library(keras)
library(tibble)
library(ggplot2)
library(tfdatasets)
# load data
boston_housing <- dataset_boston_housing()
str(boston_housing)
```
### Data preparation
In a first step, we split the data into a training set and a test set. The latter is used to monitor the out-of-sample performance of the model fit. Testing the validity of an estimated model by looking at how it performs out-of-sample is of particular relevance when working with (deep) neural networks, as they can easily lead to over-fitting. Validity checks based on the test sample are, therefore, often an integral part of modeling with TensorFlow/Keras.\index{Keras}\index{TensorFlow}
```{r}
# assign training and test data/labels
c(train_data, train_labels) %<-% boston_housing$train
c(test_data, test_labels) %<-% boston_housing$test
```
In order to better understand and interpret the dataset, we add the original variable names and convert it to a `tibble`.
```{r warning=FALSE, message=FALSE}
library(dplyr)
column_names <- c('CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE',
'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT')
train_df <- train_data %>%
as_tibble(.name_repair = "minimal") %>%
setNames(column_names) %>%
mutate(label = train_labels)
test_df <- test_data %>%
as_tibble(.name_repair = "minimal") %>%
setNames(column_names) %>%
mutate(label = test_labels)
```
Next, we have a close look at the data. Note the usage of the term 'label' for what is usually called the 'dependent variable' in econometrics.^[Typical textbook examples in machine learning deal with classification (e.g., a logit model), while in microeconometrics the typical example is usually a linear model (continuous dependent variable).] As the aim of the exercise is to predict median prices of homes, the output of the model will be a continuous value ('labels').
```{r}
# check training data dimensions and content
dim(train_df)
head(train_df)
```
As the dataset contains variables ranging from per capita crime rate to indicators for highway access, the variables are obviously measured in different units and hence displayed on different scales. This is not a problem per se for the fitting procedure. However, fitting is more efficient when all features (variables) are normalized.
```{r, eval=TRUE, warning=FALSE, message=FALSE}
spec <- feature_spec(train_df, label ~ . ) %>%
step_numeric_column(all_numeric(), normalizer_fn = scaler_standard()) %>%
fit()
```
### Model specification
We specify the model as a linear stack of layers, the input (all 13 explanatory variables), two densely connected hidden layers (each with a 64-dimensional output space), and finally the one-dimensional output layer (the 'dependent variable').
```{r warning=FALSE, message=FALSE, eval=TRUE}
# Create the model
# model specification
input <- layer_input_from_dataset(train_df %>% select(-label))
output <- input %>%
layer_dense_features(dense_features(spec)) %>%
layer_dense(units = 64, activation = "relu") %>%
layer_dense(units = 64, activation = "relu") %>%
layer_dense(units = 1)
model <- keras_model(input, output)
```
In order to fit the model, we first have to compile it (configure it for training). At this step we set the configuration parameters that will guide the training/optimization procedure. We use the mean squared errors\index{Mean Squared Errors (MSE)} loss function (`mse`) typically used for regressions\index{Regression}, and we chose the [RMSProp](http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf) optimizer to find the minimum loss.
```{r eval=TRUE}
# compile the model
model %>%
compile(
loss = "mse",
optimizer = optimizer_rmsprop(),
metrics = list("mean_absolute_error")
)
```
Now we can get a summary of the model we are about to fit to the data.
```{r eval=FALSE}
# get a summary of the model
model
```
### Training and prediction
Given the relatively simple model and small dataset, we set the maximum number of epochs to 500.
```{r}
# Set max. number of epochs
epochs <- 500
```
Finally, we fit the model while preserving the training history, and visualize the training progress.
```{r warning=FALSE, message=FALSE, eval=TRUE}
# Fit the model and store training stats
history <- model %>% fit(
x = train_df %>% select(-label),
y = train_df$label,
epochs = epochs,
validation_split = 0.2,
verbose = 0
)
plot(history)
```
## Wrapping up
- `gpuR` provides a straightforward interface for applied econometrics run on GPUs\index{Graphics Processing Unit (GPU)}. While working with `gpuR`\index{gpuR Package}, be aware of the necessary computational overhead to run commands on the GPU\index{Graphics Processing Unit (GPU)} via this interface. For example, implementing the OLS\index{Ordinary Least Squares (OLS)} estimator with `gpuR`\index{gpuR Package} is a good exercise but does not really pay off in terms of performance.
- There are several ongoing projects in the R world to bring GPU computation closer to basic data analytics tasks, providing high-level interfaces to work with GPUs\index{Graphics Processing Unit (GPU)} (see the [CRAN Task View on High-Performance and Parallel Computing with R](https://cran.r-project.org/web/views/HighPerformanceComputing.html) for some of those).
- A typical application of GPU\index{Graphics Processing Unit (GPU)} computation in applied econometrics is the training of neural nets, particularly deep neural nets (deep learning)\index{Deep Learning}. The `keras`\index{keras Package} and `tensorflow`\index{tensorflow Package} packages provide excellent R interfaces to work with the deep learning libraries TensorFlow and Keras\index{Keras}. Both of those libraries are implemented to directly work with GPUs\index{Graphics Processing Unit (GPU)}.