# Histograms in CUDA: Privatized for Fast, Level Performance

Due to contention, naïve CUDA implementations suffer poor performance on degenerate input data. Nicholas Wilt, author of The CUDA Handbook: A Comprehensive Guide to GPU Programming, shows how to use privatized (per-thread) histograms to balance performance of the average case against data-dependent performance of degenerate cases.

If you were trying to characterize a set of Mars' M&M candies, one of the more obvious ways to do so would be to examine each candy and record its color. Wikipedia lists eight (8) main colors of M&M over the decades: blue, brown, green, orange, red, tan, violet, and yellow. If you start with eight counters—one for each color—and for each candy increment the counter corresponding to the color of the candy, you will have constructed a histogram, a statistical function that counts the number of observations that fall into each of some number of discrete categories. An often-used metaphor for histograms is to say that each input element is put into a specific bin. The M&M candies would have eight bins, and after processing some set of M&M's, the histogram would be represented by the number of candies in each bin. Histograms are often depicted as graphical representations of the data distribution. For computers, however, a histogram usually consists of an array of k integers, where k is the number of bins; in the case of our M&M candies example, k==8. After accumulating N observations, the sum of the k integers is equal to N.

As an example, I recorded the colors of the 24 M&M's from a snack-size bag:

`BOYRGBYRVYOBVBYGRVVBBGGR`

With one bucket per possible color, Table 1 gives the counts. Note that this random sample did not contain any tan candies, so the T count is 0.

Table 1

#### Number of Candies by Color

 Color Number B (Blue/Brown) 6 G (Green) 4 O (Orange) 2 R (Red) 4 T (Tan) 0 V (Violet) 4 Y (Yellow) 4

If k is much smaller than N, as with our colored candies (that is, the number of possible colors is much smaller than the number of candies), then an array of k integers (one for each of the k categories) is a suitable representation for a histogram.

Histograms have many applications. For statisticians, they help to visualize the central location(s), spread, and shape of the input data. Histograms can be used to compute order statistics such as the median (middle) element. In image processing, the peaks and valleys of the histogram can be used for thresholding for image segmentation.

A final application of histograms that deserves mention is counting sort: If the k bins in the histogram are in sorted order, you can emit a sorted list by sweeping across the histogram bins [0..k–1] and using the count in the histogram bin to emit that number of elements. For our example of 24 candies, we can use the histogram to emit the following array, sorted in order of candy color:

`BBBBBBGGGGOORRRRVVVVYYYY`

This sort is not done by sorting the array per se, but by simply printing the letter B six times (since the histogram element for B is 6), the letter G four times (since the G histogram element is 4), and so on. If each histogram element can be processed in constant time, counting sort runs in O(N) time. Because it does not compare elements, counting sort is not subject to the minimum asymptotic O(NlgN) runtime of comparison-based sorting algorithms.

Counting sort harkens to an alternative solution for computing the histogram, one that is suitable when N is much smaller than k (for example, if N is the number of transactions by a customer and k is the number of items available from an electronic retailer): Sort the N inputs and look for adjacent duplicates to identify the number of elements that belong in each bin of the (sparse) histogram. (CUDA's Thrust library refers to this operation as "reduce_by_key.")

Histograms of any number of elements can be of interest, but for this article we will focus on the special case of 256 elements, which is important for image processing of 8-bit images. Figure 1 shows coins.pgm, the image used in The CUDA Handbook Chapter 15, "Image Processing: Normalized Correlation."

Figure 2 shows the histogram for coins.pgm. The histogram has two "spikes" that roughly correspond to the "background" and "coins." An image processing algorithm could "binarize" the image by replacing each pixel with a 0 or 1, depending on whether the pixel value was above or below a threshold selected by analyzing the histogram.

For this image and histogram, a value around 100 works; Figure 3 shows the resulting black-and-white image.

For the remainder of this article, we will focus on 256-element histograms of 8-bit input data. For clarity, the code will not use texturing or 2D pitch memory (though such code is included in the sample code on GitHub). Listing 1 gives the C code to compute a histogram: The output array is initialized to zero; then, for each input element, the corresponding histogram element is incremented.

#### Listing 1—1D histogram (CPU implementation).

```void
hist1DCPU(
unsigned int *pHist,
unsigned char *p, size_t N )
{
memset( pHist, 0, 256*sizeof(unsigned int) );
for ( size_t i = 0; i < N; i++ ) {
pHist[ p[i] ] += 1;
}
}```

Two basic strategies can be used to parallelize the histogram computation:

1. Multiple threads update a histogram concurrently.
2. Compute multiple histograms and then merge them together into the final output.

On CPUs, the OS and hardware support for multithreading make the first approach prohibitively expensive, whether acquiring and releasing an OS mutex per histogram element or invoking atomic operations via intrinsics such as InterlockedAdd() or sync_add_and_fetch(). In contrast, option 2 can be implemented with a simple fork/join idiom that divides the problem size evenly among threads (say, 1–2 threads per CPU core), and then computes the final output after waiting on the child threads. [1]

## One Global Histogram—and Contention

For CUDA, the tradeoffs are more complex, since the hardware supports more threads and provides mechanisms for enforcing mutual exclusion in both global and shared memory. Listing 2 gives a CUDA C implementation that looks similar to the serial CPU implementation of Listing 1; it uses global memory atomics to operate directly on the output histogram. [2]

#### Listing 2—1D histogram (CUDA implementation).

```__global__ void
histogram1DPerGrid(
unsigned int *pHist,
const unsigned char *base, size_t N )
{
for ( size_t i = blockIdx.x*blockDim.x+threadIdx.x;
i < N;
i += blockDim.x*gridDim.x ) {
atomicAdd( &pHist[ base[i] ], 1 );
}
}```

Global memory atomics were introduced in SM 1.1, but they were so slow as to be almost unusable. For randomly distributed data, this kernel on flagship chips for Tesla (GeForce GTX 280), Fermi (Tesla M2050), and Kepler (GeForce GRID K520) yields the performance results summarized in Table 2.

Table 2

#### Global Atomics Performance, SM 1.0 through SM 3.0

 Chip Speed (Mpix/s) Tesla (GeForce GTX 280) 58 Fermi (M2050) 1530 Kepler (GeForce GTX 680) 10720

You read that correctly: SM 2.0 increased performance by 26x over SM 1.3, and SM 3.0 increased performance again by another 7x. [3] Apparently NVIDIA thinks developers want fast atomics! (And NVIDIA would be correct.)

One downside of this histogram implementation is data-dependent behavior: If all the input values are the same, the kernel of Listing 2 performs N atomic adds on the same 32-bit memory location. In this case, the hardware facilities that ensure mutual exclusion for atomics suffer from contention. Our test program can measure the effects of contention by reducing the number of possible random values (specified by the --random parameter to the test program).

With threads contending for the hardware facilities that enable atomicity in global memory, performance degrades as the number of possible values goes down, as shown in Table 3.

Table 3

#### Performance Versus Number of Values

 Values Tesla Fermi Kepler 256 58 1530 10720 128 39 969 7074 64 28 660 4734 32 26 749 3058 16 22 557 3767 8 16 349 4422 4 11 210 2864 2 7 121 1725 1 4 68 988

The slowdown in the degenerate case (only a single value in the input image) is 14.5x for Tesla, 22.5x for Fermi, and 11x for Kepler. Most applications cannot tolerate a large performance degradation due solely to the contents of the input data, but data-dependent performance is difficult to avoid in light of the realities of hardware implementation. To achieve so-called "level" performance (which is not data-dependent), software must cope with the hardware limitations.

### Loop Unrolling

The CUDA kernel of Listing 2 uses 8-bit loads from global memory, which are much slower than 32- or 64-bit loads due to a lack of coalescing. Coalescing constraints are discussed in detail in The CUDA Handbook Chapter 5, "Memory," but for this article we will simply use 32-bit loads and process four 8-bit values in each loop iteration

The resulting kernel, shown in Listing 3, is more than 20% faster than the kernel of Listing 2.

This combination of loop unrolling and larger memory operands is used throughout the rest of this article; it is even more effective when the operations being unrolled expose more instructions for the compiler to schedule.

#### Listing 3—1D histogram (unrolled).

```__global__ void
histogram1DNaiveAtomic(
unsigned int *pHist,
const unsigned char *base, size_t N )
{
for ( size_t i = blockIdx.x*blockDim.x+threadIdx.x;
i < N/4;
i += blockDim.x*gridDim.x ) {
unsigned int value = ((unsigned int *) base)[i];
atomicAdd( &pHist[ value & 0xff ], 1 ); value >>= 8;
atomicAdd( &pHist[ value & 0xff ], 1 ); value >>= 8;
atomicAdd( &pHist[ value & 0xff ], 1 ); value >>= 8;
atomicAdd( &pHist[ value ]       , 1 );
}
}```

The performance of Listings 2 and 3 is the same for degenerate input data, as the effects of contention become dominant.

### InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

## Overview

Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

## Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

### Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

### Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

### Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

### Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

### Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

### Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

## Other Collection and Use of Information

### Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

### Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

### Do Not Track

This site currently does not respond to Do Not Track signals.

## Security

Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

## Children

This site is not directed to children under the age of 13.

## Marketing

Pearson may send or direct marketing communications to users, provided that

• Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
• Such marketing is consistent with applicable law and Pearson's legal obligations.
• Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
• Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

## Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

## Choice/Opt-out

Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

## Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

## Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

## Sharing and Disclosure

Pearson may disclose personal information, as follows:

• As required by law.
• With the consent of the individual (or their parent, if the individual is a minor)
• In response to a subpoena, court order or legal process, to the extent permitted or required by law
• To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
• In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
• To investigate or address actual or suspected fraud or other illegal activities
• To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
• To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
• To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.