<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Daniel Han-Chen on Medium]]></title>
        <description><![CDATA[Stories by Daniel Han-Chen on Medium]]></description>
        <link>https://medium.com/@danielhanchen?source=rss-7c02e43b531e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KK8QQ8TdMxFXMurk</url>
            <title>Stories by Daniel Han-Chen on Medium</title>
            <link>https://medium.com/@danielhanchen?source=rss-7c02e43b531e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 13:16:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danielhanchen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Accelerating TSNE with GPUs: From hours to seconds]]></title>
            <link>https://medium.com/rapids-ai/tsne-with-gpus-hours-to-seconds-9d9c17c941db?source=rss-7c02e43b531e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d9c17c941db</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Daniel Han-Chen]]></dc:creator>
            <pubDate>Fri, 22 Nov 2019 19:52:22 GMT</pubDate>
            <atom:updated>2019-11-28T04:48:47.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/689/0*cMaHujI0QQdPqrXe" /><figcaption>Figure 1. cuML TSNE on MNIST Fashion takes 3 seconds. Scikit-Learn takes 1 hour.</figcaption></figure><p><a href="https://en.wikipedia.org/wiki/T-distributed_stochastic_neighbor_embedding">TSNE</a> (T-Distributed Stochastic Neighbor Embedding) is a popular unsupervised dimensionality reduction algorithm that finds uses as varied as<a href="https://socr.umich.edu/HTML5/SOCR_TensorBoard_UKBB/"> neurology</a>, image similarity, and <a href="https://cs.stanford.edu/people/karpathy/cnnembed/">visualizing neural networks.</a> Unfortunately, its biggest drawback has been the long processing times in most available implementations. <a href="https://rapids.ai/">RAPIDS</a> now provides fast GPU-accelerated TSNE, building on the GPU-based Barnes-Hut approach developed at <a href="https://github.com/CannyLab/tsne-cuda">CannyLab.</a> TSNE in RAPIDS’ cuML machine learning library can run up to 2,000x faster<strong> </strong>than the corresponding CPU implementation (Scikit-Learn) and uses up to 30% less GPU memory than current GPU versions and can be 2x faster. (CannyLab’s BH TSNE).</p><p>This blog starts by presenting some example use cases, followed by benchmarks comparing cuML’s GPU TSNE implementation against <a href="https://scikit-learn.org/stable/modules/generated/sklearn.manifold.TSNE.html">scikit-learn</a>. It then goes into a detailed explanation of how TSNE works and how it has been optimized in cuML to run on GPUs.</p><h3>Applications of TSNE</h3><p>TSNE contrasts with traditional supervised methods like <a href="https://en.wikipedia.org/wiki/Linear_regression">Linear Regression</a> and <a href="https://en.wikipedia.org/wiki/Decision_tree">Decision Trees</a>, as it requires no labels. TSNE tries to discern structure in the data by moving points that are similar together and dis-similar points away from each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*649JDe6GT7QYGg3W" /><figcaption>Figure 2. TSNE used in a fashion use case.</figcaption></figure><p>In Figure 2 above, TSNE is being applied to a fashion dataset that consists of<a href="https://github.com/zalandoresearch/fashion-mnist"> 60,000 images of articles of clothing</a>. This is useful for finding a natural grouping that will put “similar” garments close together. TSNE is able to reduce the complex space of fashion images to a smaller space, which is easier to work with. The vectors of pixels for each image are used as input and TSNE maps them to 2 dimensions, or 2 values for each image. In Figure 5, the 2-dimensional output from TSNE is plotted and color-coded according to the clothing category of the original input (e.g. boots are blue). TSNE is unaware of these categories, but finds a grouping that is able to put more similar items closer together.</p><p>Here is another example using the <a href="https://en.wikipedia.org/wiki/MNIST_database">MNIST digits dataset</a>. Given handwritten digits, the task is to classify each digit as 0, 1, 2 etc. After applying TSNE on all 60,000 images of digits, we find that without any labels, TSNE manages to separate the data. You can see in Figure 3 how there are clear clusters color-coded by digit type (0 to 9).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/0*-ynu7FklLyGqd6aF" /><figcaption>Figure 3. TSNE plot of the MNIST digits dataset</figcaption></figure><p>TSNE is also used to visualize <a href="https://cs231n.github.io/understanding-cnn/">Convolutional Neural Nets</a> to help practitioners discern whether complex classifiers are actually “learning.” Below shows TSNE applied to AlexNet, where the output of the CNN of images before the actual classifier (4096 dimensions) is reduced to 2 dimensions, then visualized with the actual input image. Notice in Figure 4, similar images tend to be close, which implies how AlexNet “sees” them as being similar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/0*upBkxWuGt6DtWVJr" /><figcaption>Figure 4. Source: <a href="https://cs231n.github.io/">CS231n Convolutional Neural Networks for Visual Recognition</a></figcaption></figure><h3><em>TSNE vs. Principal Component Analysis (PCA)</em></h3><p>TSNE is a nonlinear dimensionality reduction algorithm, whilst <a href="https://en.wikipedia.org/wiki/Principal_component_analysis">Principal Component Analysis</a> is linear. This mean’s PCA’s components often have some meaning, while TSNE’s are no longer ordered by importance, or at all interpretable outside of the neighborhoods they create. On the CPU, it’s often recommended to reduce dimensions using PCA to 50 before feeding into TSNE for performance improvements. This is not the case for GPUs.</p><h3>RAPIDS cuML Speed-Up over Scikit-Learn</h3><p>Many data scientists start with the popular TSNE implementation from <a href="https://scikit-learn.org/stable/modules/generated/sklearn.manifold.TSNE.html">scikit-learn</a>. Scikit-learn’s TSNE (single threaded) provides a familiar, easy to use interface, but can run into scalability issues. For instance, a 60,000 example dataset could take 1 hour<strong> </strong>to converge in scikit-learn on CPU. The cuML TSNE implementation running on an NVIDIA V100 GPU can finish in<strong> </strong>3 seconds on that same dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/0*OmxBsNgfHwppMaz2" /><figcaption>Table 1. cuML’s TSNE time running on an NVIDIA DGX-1 with using 1 V100 GPU.</figcaption></figure><p>Notice the log scale in Table 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/0*jB4RuUnVkuchmlnc" /><figcaption>Table 2. The timings in seconds between cuML and Scikit-Learn (DGX 1)</figcaption></figure><p>So cuML’s TSNE runs 1,000x faster, and it also attains similar <a href="https://scikit-learn.org/dev/modules/generated/sklearn.manifold.trustworthiness.html">trustworthiness</a> scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*6trsNkZkWawUAMej" /><figcaption>Table 3. The full graph showcasing speedup of cuML over scikit-learn running on NVIDIA DGX 1.</figcaption></figure><p>On a dataset with 204,800 samples and 80 features, cuML takes 5.4 seconds while Scikit-learn takes almost 3 hours. This is a massive 2,000x speedup<strong>.</strong> We also tested TSNE on an NVIDIA <a href="https://www.nvidia.com/en-au/data-center/dgx-1/">DGX-1</a> machine using only one V100 GPU (<em>DGX1: 32gb GV100 GPU, Intel Xeon E5–2698 v4 CPU@ 2.20GHz w/20 cores &amp; 40 threads). </em>The data transfer times were also included in this benchmark. Figure 5 shows a dataset containing 100 samples and 80 columns. Notice how cuML can be faster even on small datasets. Furthermore, RAPIDS TSNE is also around 200x faster than multicore TSNE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/0*2klTOkQWh5eHK31h" /><figcaption>Figure 5. cuML TSNE on the small Breast Cancer Data (1 second)</figcaption></figure><p>Using the PCA trick described above does give scikit-learn’s TSNE a slight boost in end-to-end performance, however, RAPIDS cuML TSNE is still demonstrating more than 1,000x speedup on tall datasets with 204,800 samples and 50 columns. This enables TSNE to be trained on datasets without first having to reduce the dimensions using PCA.</p><h3><em>How TSNE Works</em></h3><p>cuML’s TSNE is based largely on <a href="https://github.com/CannyLab/tsne-cuda">CannyLab’s</a> original Barnes Hut implementation. Currently, two algorithms are supported: <a href="https://arxiv.org/abs/1301.3342">Barnes Hut TSNE</a> and <a href="http://www.jmlr.org/papers/volume9/vandermaaten08a/vandermaaten08a.pdf">Exact TSNE</a>. Barnes Hut runs much faster than the Exact version, but is very slightly less accurate (at most <a href="https://scikit-learn.org/stable/modules/generated/sklearn.manifold.TSNE.html">3% error</a>). For large datasets (samples &gt;= 2,000), the Barnes Hut algorithm is recommended for superior speed.</p><p>TSNE has 2 key objectives:</p><ol><li>Close points should remain close.</li><li>Far points should remain distant.</li></ol><p>Given some data points in a high dimensional setting (say 3D or 1,000 D), the goal is to embed the points in a lower space (eg. 2 dimensions), such that the local neighborhood structure of the input data is preserved as much as possible in its embedded form.</p><p>More concretely, points in the original high-dimensional space are first converted to probability densities that look like a <a href="https://en.wikipedia.org/wiki/Normal_distribution">bell curve</a>, or normal distribution, like the red line in Figure 6 below. Points that are close increase each other’s probabilities, and so dense areas tend to have higher values. Likewise, outliers and dissimilar points have small values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*SEcVQTtiTJexmZpb" /><figcaption>Figure 6. Source: study.com</figcaption></figure><p>Now here’s where the “T-Distributed” part in TSNE’s name comes in. The points in the lower space are also modeled using a bell curve, though one which is stretched out like the blue line in Figure 6.</p><p>People have tried using a non-stretched version, but this causes a problem known as the “<a href="http://www.jmlr.org/papers/volume9/vandermaaten08a/vandermaaten08a.pdf">Crowding Problem</a>”, where the embedded points clump together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*8w3dceJ2jheh8NQ0RmxnKQ.png" /><figcaption>Figure 7. Left showcases the crowding problem. TSNE solves this by using the T-Distribution.</figcaption></figure><p>Now, imagine springs connecting every point in the low dimensional space to every other point. Imagine the following scenario:</p><ol><li>Points which are close originally will tug on each other. (Attraction)</li><li>Points which are dis-similar originally will push on each other. (Repulsion)</li></ol><p>Essentially our spring’s function has been reversed. One would expect that far away points will cause the spring to pull them together, but in TSNE it’s the opposite.</p><p>Now let the springs in the low dimensional space be free. This is the optimization phase for TSNE. We terminate the evolving system when all the springs stop moving. We remove the springs, and the ending positions of each point becomes the final embedding.</p><h3>TSNE Optimizations</h3><p>There are four optimizations used to improve the performance of TSNE on GPUs:</p><ol><li>calculating higher dimensional probabilities with less GPU memory,</li><li>approximating higher dimensional probabilities,</li><li>reducing arithmetic operations, and</li><li>broadcasting along rows.</li></ol><h4><em>Optimization 1 — Calculating Higher Dimensional Probabilities with less GPU Memory</em></h4><p>Remember the goal to calculate the probabilities of each point by considering every other point’s influence? When the influence of point A to point B is not the same as point B on A, they are not symmetric. To make them equal, both contributions are summed up and divided between them. This is called symmetrizing the probabilities.</p><p>Originally, the symmetrization step was inefficient due to the use of unnecessary intermediate memory buffers. In the <a href="https://github.com/rapidsai/cuml/blob/branch-0.10/cpp/src_prims/sparse/coo.h">RAPIDS implementation</a>, memory usage was reduced by 30% and is now highly parallelized. In total running times, symmetrization now takes 1%, or less of total elapsed times, as compared to 25% previously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/0*vz4mMtJns0sICHxA" /><figcaption>Table 4. Timings of each kernel on the GPU. Symmetrization takes 1% of total time.</figcaption></figure><p>To implement this optimization, we first converted the distances between points into a <a href="https://en.wikipedia.org/wiki/Sparse_matrix">COO (Coordinate Format) Sparse Matrix</a> using fast <a href="https://github.com/rapidsai/cuml">cuML primitives</a>. Sparse matrix formats are good at representing graphs of connected nodes and edges. This is especially true in the case of k-nearest neighbors graphs, which have a fixed number of connected edges, since only the closest neighbors of each point needs to be considered. Sparse formats only require the connected vertices to be stored, providing a significant speedup and lower storage overhead for algorithms like TSNE. The COO format is represented by 3 very simple arrays — the data values (<em>COO_Vals</em>), the column indices (<em>COO_Cols</em>), and the individual row indices (<em>COO_Rows</em>).</p><p>As an example, let’s say there’s a given point (0, 7) with value 10. It’s transpose (or reverse) is (7, 0), also with value 10. Here’s how to store this in the final COO sparse matrix:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f295069b739ed1d912ff0cf871c3523c/href">https://medium.com/media/f295069b739ed1d912ff0cf871c3523c/href</a></iframe><p>To get its transpose or reverse, simply flip the col and row pointers like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9328eef9c2c11e94d24ab2b0f4ba52ac/href">https://medium.com/media/9328eef9c2c11e94d24ab2b0f4ba52ac/href</a></iframe><p>Notice how the example above also includes an array named “<em>RowPointer</em>”. The COO layout does not include information about where each row starts or ends. Including this information allows us to parallelize lookups and quickly sum the transposed values in the symmetrization step. This RowPointer idea comes from the CSR (Compressed Sparse Row) Sparse Matrix layout. In the CSR layout, entries are indexed by which rows they are in. For example, all elements with row index 1 are placed together, in sorted order, at the start of the RowPointer index. The CSR layout is excellent for algorithms where data is accessed in a row-wise fashion.</p><p>Combining these two layouts allows us to use the COO format for efficient parallel computations over each element in the graph, while the CSR format is used to perform the transpose of the elements. Since the RowPointer contains the number of elements present in each row, the contributions of each pair of points can be summed in parallel using <a href="https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#atomic-functions">atomicAdd</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/066a85ddf6d38bde0ee3aeb7584864a3/href">https://medium.com/media/066a85ddf6d38bde0ee3aeb7584864a3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*_FO78Gq1bhrsulSu" /><figcaption>Figure 8. Diagram showcasing our Symmetrization Kernel in action.</figcaption></figure><p>Figure 8 shows the whole process. Given the point (0, 7) with value 10, index the Row Pointer to get the row index for the point, and store it. Then, flip to (7, 0), access the Row Pointer, and store this as well in parallel with the first.</p><h4><em>Optimization 2 — Approximating Higher Dimensional Probabilities</em></h4><p>It has been noted by <a href="https://lvdmaaten.github.io/tsne/">van der Maaten, the author of TSNE</a> that instead of computing full distances between all points, one can compute the top nearest neighbors and calculate the high dimensional probabilities from them. cuML followed <a href="https://github.com/CannyLab/tsne-cuda">CannyLabs</a>’ approach of using <a href="https://github.com/facebookresearch/faiss">Facebook’s FAISS library</a> to compute the top-k neighbors on the GPU. This reduces the probability computation from having to store <em>N²</em> elements to storing only <em>N*k</em> elements (N is the number of data samples and k is the number of neighbors.)</p><h4><em>Optimization 3 — Reduce Arithmetic Operations</em></h4><p>In many TSNE implementations, the <a href="https://github.com/rapidsai/cuml/blob/branch-0.10/cpp/src/tsne/bh_kernels.h">attractive force computation</a> (the spring tugging) is split to first be computed on point A and then on point B. TSNE can be made significantly faster if one computes the interaction, not separately, but at the same time. This reduces the number of multiplications and addresses from originally 9 to around 4, and makes this computation <strong>50% faster.</strong></p><h4><em>Optimization 4 — Broadcast along rows</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/0*wFDIhh7K6POMWH-E" /><figcaption>Figure 9. Calculate common values and distribute it across each row!</figcaption></figure><p>Another fundamental optimization is noticing distances between point A in dimension 1 and dimension 2 are repeated across rows. This means instead of separately computing values for each dimension, compute it once, then broadcast and re-use the computation for the other dimension. This once again reduces arithmetic operations, and further speeds TSNE up. This is a<a href="https://github.com/rapidsai/cuml/blob/branch-0.10/cpp/src_prims/linalg/matrix_vector_op.h"> general technique</a> used by many CUDA algorithms, including many in cuML.</p><h3><em>Improving TSNE’s Numerical Stability</em></h3><p>cuML has fixed some rare issues with numerical stability in CannyLab’s original implementation, including some infinite loops and out of bounds memory accesses. It is also known that TSNE is very sensitive to its hyperparameters. In cuML, an <a href="https://rapidsai.github.io/projects/cuml/en/0.10.0/api.html#cuml.TSNE">adaptive learning scheme</a> is provided where parameters are adjusted based on the user’s input data.</p><p>Sometimes if the learning rate is too large, embedded points can become outliers. In cuML, a MAX_BOUND is specified which carefully pushes the outlier back and resets all momentum variables. This also helps improve TSNE’s precision and <a href="https://lvdmaaten.github.io/publications/papers/AISTATS_2009.pdf">trustworthiness.</a></p><h3><strong><em>How Do We Run TSNE in RAPIDS?</em></strong></h3><p>Let’s compare scikit-learn’s API to RAPIDS cuML’s API. This example uses the scikit-learn’s digits dataset.</p><p>scikit-learn API:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b626b687d3631221c76ad5e24547271/href">https://medium.com/media/0b626b687d3631221c76ad5e24547271/href</a></iframe><p>Now compare it with cuML:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67310d8fec74366c58136b4c19d35897/href">https://medium.com/media/67310d8fec74366c58136b4c19d35897/href</a></iframe><p>Since cuML is a near drop-in replacement for scikit-learn, the “sklearn.manifold” package can be replaced with “cuml.manifold” and everything else will just work.</p><p>Here’s a <a href="https://github.com/rapidsai/notebooks/blob/branch-0.11/cuml/tsne_demo.ipynb">Jupyter Notebook</a> showing a demo of cuML TSNE on Fashion MNIST.</p><p>For more TSNE examples and a deeper dive into the mathematical optimizations on TSNE, check out a more extended Jupyter Notebook<a href="https://nbviewer.jupyter.org/github/rapidsai/notebooks/blob/5bd0a28bd64077a55e68db44388030a971acdb08/cuml/TSNEdemo.ipynb"> here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/0*DAsQZCkZM_uByq5q" /><figcaption>cuML TSNE on Boston Housing Data</figcaption></figure><h3><em>Conclusion</em></h3><p>TSNE has been very successful at enabling the visualization of very large and complex datasets. It is able to discern structure in datasets without labels. Unfortunately, its biggest drawback has been its slow execution time.</p><p>With the new <a href="https://github.com/rapidsai/cuml">RAPIDS TSNE</a> implementation, speedups up to 2,000x<strong> </strong>can be achieved while also using 30% less GPU memory. See what you think and provide feedback. Try out the free cuML TSNE for yourself on a Google Colab instance <a href="https://medium.com/rapids-ai/run-rapids-on-google-colab-for-free-1617ac6323a8"><strong>here</strong></a><strong>.</strong></p><h3>References for TSNE</h3><p><em>David M. Chan, Roshan Rao, Forrest Huang, John F. Canny : t-SNE-CUDA: GPU-Accelerated t-SNE and its Applications to Modern Data </em><a href="https://arxiv.org/pdf/1807.11824.pdf"><em>https://arxiv.org/pdf/1807.11824.pdf</em></a><em> [31 Jul 2018]</em></p><p><em>George C. Linderman, Manas Rachh, Jeremy G. Hoskins, Stefan Steinerberger, Yuval Kluger: Efficient Algorithms for t-distributed Stochastic Neighborhood Embedding </em><a href="https://arxiv.org/abs/1712.09005"><em>https://arxiv.org/abs/1712.09005</em></a><em> [25 Dec 2017]</em></p><p><em>Laurens van der Maaten, Geoffrey Hinton : Visualizing High-Dimensional Data Using t-SNE </em><a href="https://lvdmaaten.github.io/publications/papers/JMLR_2008.pdf"><em>https://lvdmaaten.github.io/publications/papers/JMLR_2008.pdf</em></a><em> [2008]</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d9c17c941db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rapids-ai/tsne-with-gpus-hours-to-seconds-9d9c17c941db">Accelerating TSNE with GPUs: From hours to seconds</a> was originally published in <a href="https://medium.com/rapids-ai">RAPIDS AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>