Skip to content

Instantly share code, notes, and snippets.

@myfavouritekk
Last active January 28, 2016 05:52
Show Gist options
  • Save myfavouritekk/f43155a35caecea16fe4 to your computer and use it in GitHub Desktop.
Save myfavouritekk/f43155a35caecea16fe4 to your computer and use it in GitHub Desktop.
Generate Logistic Distribution random numbers on GPU in Matlab

#Generate Logistic Distribution random numbers on GPU in Matlab

GPU implementation of random('Logistic', mu, sigma, shape) in Matlab. Copyright @ Kai Kang (myfavouritekk@gmail.com) 2016

##Time profiling with built-in random function

gpuLogistic has similar interface with random, but is suitable for generating large number of random numbers thanks to GPU.

    >> comparison
    CPU time: 17.82s
    GPU time: 3.36s

##Qualitative validation Generating large number of random samples and we can validate that the GPU implementation gets the same distribution with built-in CPU version.

    >> validation

Qualitative validation

%% CPU
iter=10000;
shape = [64 64];
tic;
for i=1:iter
eps = random('logistic', 0, 1, shape);
end
cpu_time = toc;
fprintf('CPU time: %.02fs\n', cpu_time);
%% GPU
tic;
for i=1:iter
eps = gpuLogisticRandom(0, 1, shape);
end
gpu_time = toc;
fprintf('GPU time: %.02fs\n', gpu_time);
function x = gpuLogisticRandom(mu, sigma, shape)
y = reshape(gpuArray.rand(prod(shape), 1), shape);
x = gather(log(y./(1-y)) * sigma + mu);
end
n=1000000;
cpu_random = random('logistic', 0, 1, [n 1]);
gpu_random = gpuLogisticRandom(0,1,[n 1]);
hist([cpu_random, gpu_random], 50);
legend('Built-in CPU', 'GPU');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment