Category Archives: GPGPU

Binomial Tree methods for European options using GPU

Binomial methods are versatile in pricing options for it is suitable for American, European, and Asian options. With an European call option with maturity t, strike price k, spot price S, volatility σ, risk-free rate r:

binom1.1

For put option, the last effective term shall be in the max function shall be:
binomput2

Stock’s increment, decrements, and probability to move up are given by the below respectively:

binom2

One of the CUDA samples from Nvidia is to implement the binomial model on GPU.

binom3

 

Advertisements

Test driving Nvidia RTX 2060 with TensorFlow and VS2017

Finally my new laptop that sports the new GeForce Nvidia RTX 2060 arrived. It is time to check out the muscle of this little beast with the toolset I’m familiar with.

On the hardware, the laptop is a i7-8750 and 16G RAM with a Turing architecture based GeForce RTX 2060.

rtx1.PNG

The laptop came with full drivers installed. Nevertheless I downloaded the latest drivers and CUDA for the most up-to-date experience. The software include Nvidia GeForce drivers, Visual Studio Express 2017, CUDA Toolkit, and TensorFlow.

rtx6.PNG

Be careful when trying all these bleeding edge technologies, not only because TensorFlow 2.0 is currently in Alpha, compatibility issues may haunt like with previous 1.x TensorFlow on CUDA 10.1. I have to fallback to 10.0 to have TF happy with it (although one can always choose the compile from source approach).

rtx2

And here are my favorite nbody and Mandelbrot simulation, and also the Black Scholes sample in CUDA. The diagnostic tool in VS gives a nice real time profiling interface with graphs.

rtx5

Finally for this test drive – TensorFlow with GPU. The installation is smooth until I tried to verify TF on GPU. After several failed attempts I realized it could be that CUDA 10.1 may not be compatible with the TF version installed. There are couples of suggested solutions out there, including downgrading to CUDA 9, but since my GPU is the Turing series this is not an option. Actually TF supports CUDA 10 since v.13. So I finally decided to fall back CUDA to 10.0 from 10.1 and it worked!rtx7

 

Logistic Regression – from Nspire to R to Theano

Logistic regression is a very powerful tool for classification and prediction. It works very well with linearly separable problem. This installment will attempt to recap on its practical implementation, from traditional perspective by maximum likelihood, to more machine learning approach by neural network, as well as from handheld calculator to GPU cores.

The heart of the logistic regression model is the logistic function. It takes in any real value and return value in the range from 0 to 1. This is ideal for binary classifier system. The following is a graph of this function.
theanologistic1

TI Nspire

In the TI Nspire calculator, logistic regression is provided as a built-in function but is limited to single variable. For multi-valued problems, custom programming is required to apply optimization techniques to determine the coefficients of the regression model. One such application as shown below is the Nelder-Mead method in TI Nspire calculator.

Suppose in a data set from university admission records, there are four attributes (independent variables: SAT score, GPA, Interview score, Aptitude score) and one outcome (“Admission“) as the dependent variable.
theano-new1

Through the use of a Nelder-Mead program, the logistic function is first defined as l. It takes all regression coefficients (a1, a2, a3, a4, b), dependent variable (s), independent variables (x1, x2, x3, x4), and then simply return the logistic probability. Next, the function to optimize in the Nelder-Mead program is defined as nmfunc. This is the likelihood function on the logistic function. Since Nelder-Mead is a minimization algorithm the negative of this function is taken. On completion of the program run, the regression coefficients in the result matrix are available for prediction, as in the following case of a sample data with [GPA=1500, SAT=3, Interview=8, Aptitude=60].

theanologistic2(nspire1)

R

In R, as a sophisticated statistical package, the calculation is much simpler. Consider the sample case above, it is just a few lines of commands to invoke its built-in logistic model.

theano-new2

Theano

Apart from the traditional methods, modern advances in computing paradigms made possible neural network coupled with specialized hardware, for example GPU, for solving these problem in a manner much more efficiently, especially on huge volume of data. The Python library Theano is a complex library supporting and enriching these calculations through optimization and symbolic expression evaluation. It also features compiler capabilities for CUDA and integrates Computer Algebra System into Python.

One of the examples come with the Theano documentation depicted the application of logistic regression to showcase various Theano features. It first initializes a random set of data as the sample input and outcome using numpy.random. And then the regression model is created by defining expressions required for the logistic model, including the logistic function and likelihood function. Lastly by using the theano.function method, the symbolic expression graph coded for the regression model is finally compiled into callable objects for the training of neural network and subsequent prediction application.

theanologistic5(theano1)

A nice feature from Theano is the pretty printing of the expression model in a tree like text format. This is such a feel-like-home reminiscence of my days reading SQL query plans for tuning database queries.

theanologistic5(theano2).PNG

 

CUDA, Theano, and Antivirus

Most ubiquitous antivirus products monitor new process from executables in real time and will attempt to terminate their execution if deemed a potential threat. Some of these antivirus products simply do a signature match while some do more sophisticated heuristic or intelligent scanning.

However, there are times when antivirus might turn up a false positive. This is rare, but many software developers must have experienced the slow-down caused merely by the suspending and scanning of the new build from their favorite IDE. Recently my antivirus product let me know he has been very edgy on some Theano python programs with this scan alert.

theanoavast2

This rings a bell. I remember the same happened when working with CUDA on Visual Studio. And a test with some sample CUDA programs quickly confirmed my memory.

theanoavast3

The solution to get rid of the scan is quite simple. On most antivirus products there is an option to whitelist certain programs from being scanned. And on my Avast installation, simply adding the full file path of the nvcc output will do the trick. Note that doing so may pose certain security risks as this essentially neutralized the protection. So to compensate for the increased risk, the whitelist path should be set as precise as possible, such as including a wildcard filename as shown below.

theanoavast1

One last interesting point is, as one of the great benefits from Theano is a high level abstraction of the CUDA layer, it performs some compiling to GPU executable on the CUDA platform using nvcc. Comparing the profiling results obtained before and after antivirus whitelisting shown improvement not only in the overall speed but also in the compile time. With reference to the before-whitelisting profiling result

 Function profiling
==================
 Message: train
 Time in 10000 calls to Function.__call__: 1.122200e+01s
 Time in Function.fn.__call__: 1.089400e+01s (97.077%)
 Time in thunks: 1.069661e+01s (95.318%)
 Total compile time: 5.477000e+01s
 Number of Apply nodes: 17
 Theano Optimizer time: 3.589900e+01s
 Theano validate time: 4.000425e-03s
 Theano Linker time (includes C, CUDA code generation/compiling): 1.772000e+00s
 Import time 1.741000e+00s

and the whitelisted, optimized results:

Function profiling
==================
 Message: train
 Time in 10000 calls to Function.__call__: 9.727999e+00s
 Time in Function.fn.__call__: 9.469999e+00s (97.348%)
 Time in thunks: 9.293550e+00s (95.534%)
 Total compile time: 2.827000e+00s
 Number of Apply nodes: 17
 Theano Optimizer time: 1.935000e+00s
 Theano validate time: 1.999855e-03s
 Theano Linker time (includes C, CUDA code generation/compiling): 3.799987e-02s
 Import time 2.199984e-02s

If Avast only scan the executable before it starts executing, there should be no improvement at all in the compilation. It seems more likely, from analyzing the profiling breakdowns, Avast scans the GPU executable on its creation on the file system by Theano. Turning off Avast’s “File Shield” with no whitelisting triggered no scan alert, therefore confirmed the suspicion.

Exploring Theano with Keras

Theano needs no introduction in the field of deep learning. It is based on Python and supports CUDA. Keras is a libray that wraps the complexity of Theano to provide a high level abstraction for developing deep learning solutions.

Installing Theano and Keras are easy and there are tons of resources available online. However, my primary CUDA platform is on Windows so most standard guides that are based on Linux required some adaptations. Most notably are the proper setting of the PATH variable and the use of the Visual Studio command prompt.

The basic installation steps include setting up of CUDA, a scientific python environment, and then Theano and Keras. CuDNN is optional and required Compute Capability of greater than 3.0 which unfortunately my GPU is a bit old and does not meet this requirement.

keras1

Some programs on Windows platform encountered errors and found to be library related issues. Like this one that failed to compile on Spyder can be resolved using the Visual Studio Cross Tool Command Prompt.
keras4keras3a

The Nvidia profiler checking for the performance of the GPU, running the Keras example of the MNIST digits with MLP.keras2

Compiling CUDA in command line

For getting acquainted to more unix based CUDA development, the following command line and related environment are found to works in the current Visual Studio based platform.

cd /d "C:\ProgramData\NVIDIA Corporation\CUDA Samples\v6.5\1_Utilities\deviceQuery"

set path=C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin;%path%

nvcc -arch=sm_21 -I..\..\common\inc deviceQuery.cpp -o deviceQuery

cudawin3

The command line environment on Microsoft Visual Studio platform that have CUDA properly setup (like the one for approximating the value of pi here) relied on native commands like msbuild as below.

msbuild BlackScholes_vs2010.sln /t:rebuild

cudawin
cudawin2cudawin4