hash_table.cuh 9.47 KB
Newer Older
1
2
3
4
5
// -------------------------------------------------------------
// cuDPP -- CUDA Data Parallel Primitives library
// -------------------------------------------------------------
// $Revision:$
// $Date:$
6
// -------------------------------------------------------------
7
8
// This source code is distributed under the terms of license.txt in
// the root directory of this source distribution.
9
// -------------------------------------------------------------
10
11
12
13
14
15
16
17
18
19
20
21
22

/**
 * @file hash_table.cuh
 *
 * @brief Implements kernel and __device__ functions for a basic hash table.
 */

#ifndef CUDAHT__CUCKOO__SRC__LIBRARY__HASH_TABLE__CUH
#define CUDAHT__CUCKOO__SRC__LIBRARY__HASH_TABLE__CUH

#include "definitions.h"
#include "hash_table.h"
#include <driver_types.h>
23
#include <tensorview/tensorview.h>
24

traveller59's avatar
traveller59 committed
25
namespace cuhash {
26
27
28
29
30
31
32
33

//! Makes an 64-bit Entry out of a key-value pair for the hash table.
TV_HOST_DEVICE_INLINE Entry make_entry(unsigned key, unsigned value) {
  return (Entry(key) << 32) + value;
}

//! Returns the key of an Entry.
TV_HOST_DEVICE_INLINE unsigned get_key(Entry entry) {
34
  return (unsigned)(entry >> 32);
35
36
37
38
}

//! Returns the value of an Entry.
TV_HOST_DEVICE_INLINE unsigned get_value(Entry entry) {
39
  return (unsigned)(entry & 0xffffffff);
40
41
42
43
44
45
46
}

//! @name Internal
//! @brief Functions used for building the hash table.
//! @{

//! Fills the entire array with a specific value.
47
48
49
50
template <class T>
__global__ void clear_table(const unsigned table_size, const T value,
                            T *table) {
  unsigned thread_index = threadIdx.x + blockIdx.x * blockDim.x +
51
52
53
54
55
56
57
58
                          blockIdx.y * blockDim.x * gridDim.x;
  if (thread_index < table_size) {
    table[thread_index] = value;
  }
}

//! Determine where in the hash table the key could be located.
template <unsigned kNumHashFunctions>
59
60
61
62
63
__device__ void KeyLocations(const Functions<kNumHashFunctions> constants,
                             const unsigned table_size, const unsigned key,
                             unsigned locations[kNumHashFunctions]) {
// Compute all possible locations for the key in the big table.
#pragma unroll
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
  for (int i = 0; i < kNumHashFunctions; ++i) {
    locations[i] = hash_function(constants, i, key) % table_size;
  }
}
//! @}

/* --------------------------------------------------------------------------
   Retrieval functions.
   -------------------------------------------------------------------------- */
//! Answers a single query.
/*! @ingroup PublicInterface
 *  @param[in]  key                   Query key
 *  @param[in]  table_size            Size of the hash table
 *  @param[in]  table                 The contents of the hash table
 *  @param[in]  constants             The hash functions used to build the table
 *  @param[in]  stash_constants       The hash function used to build the stash
 *  @param[in]  stash_count           The number of items in the stash
81
82
83
84
 *  @param[out] num_probes_required   Debug only: The number of probes required
 * to resolve the query.
 *  @returns The value of the query key, if the key exists in the table.
 * Otherwise, \ref kNotFound will be returned.
85
 */
86
87
88
89
90
91
template <unsigned kNumHashFunctions>
__device__ unsigned
retrieve(const unsigned query_key, const unsigned table_size,
         const Entry *table, const Functions<kNumHashFunctions> constants,
         const uint2 stash_constants, const unsigned stash_count,
         unsigned *num_probes_required = NULL) {
92
93
94
95
96
97
  // Identify all of the locations that the key can be located in.
  unsigned locations[kNumHashFunctions];
  KeyLocations(constants, table_size, query_key, locations);

  // Check each location until the key is found.
  unsigned num_probes = 1;
98
99
  Entry entry = table[locations[0]];
  unsigned key = get_key(entry);
100

101
#pragma unroll
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
  for (unsigned i = 1; i < kNumHashFunctions; ++i) {
    if (key != query_key && key != kNotFound) {
      num_probes++;
      entry = table[locations[i]];
      key = get_key(entry);
    }
  }

  // Check the stash.
  if (stash_count && get_key(entry) != query_key) {
    num_probes++;
    const Entry *stash = table + table_size;
    unsigned slot = stash_hash_function(stash_constants, query_key);
    entry = stash[slot];
  }

#ifdef TRACK_ITERATIONS
  if (num_probes_required) {
    *num_probes_required = num_probes;
  }
#endif

  if (get_key(entry) == query_key) {
    return get_value(entry);
  } else {
    return kNotFound;
  }
}

131
132
133
134
135
136
137
138
139
//! Perform a retrieval from a basic hash table.  Each thread manages a single
//! query.
template <unsigned kNumHashFunctions>
__global__ void hash_retrieve(const unsigned n_queries, const unsigned *keys_in,
                              const unsigned table_size, const Entry *table,
                              const Functions<kNumHashFunctions> constants,
                              const uint2 stash_constants,
                              const unsigned stash_count, unsigned *values_out,
                              unsigned *num_probes_required = NULL) {
140
  // Get the key.
141
  unsigned thread_index = threadIdx.x + blockIdx.x * blockDim.x +
142
143
144
145
146
                          blockIdx.y * blockDim.x * gridDim.x;
  if (thread_index >= n_queries)
    return;
  unsigned key = keys_in[thread_index];

147
148
149
150
  values_out[thread_index] = retrieve<kNumHashFunctions>(
      key, table_size, table, constants, stash_constants, stash_count,
      (num_probes_required ? num_probes_required + thread_index : NULL));
}
151
152
153
154
155
156
157

/* --------------------------------------------------------------------------
   Build a cuckoo hash table.
   -------------------------------------------------------------------------- */
//! @name Internal
//! @{

158
159
160
161
162
163
164
//! Determine where to insert the key next.  The hash functions are used in
//! round-robin order.
template <unsigned kNumHashFunctions>
__device__ unsigned
determine_next_location(const Functions<kNumHashFunctions> constants,
                        const unsigned table_size, const unsigned key,
                        const unsigned previous_location) {
165
166
  // Identify all possible locations for the entry.
  unsigned locations[kNumHashFunctions];
167
#pragma unroll
168
169
170
171
172
173
  for (unsigned i = 0; i < kNumHashFunctions; ++i) {
    locations[i] = hash_function(constants, i, key) % table_size;
  }

  // Figure out where the item should be inserted next.
  unsigned next_location = locations[0];
174
#pragma unroll
175
  for (int i = kNumHashFunctions - 2; i >= 0; --i) {
176
177
    next_location =
        (previous_location == locations[i] ? locations[i + 1] : next_location);
178
179
180
181
182
183
184
185
186
187
  }
  return next_location;
}

//! Attempts to insert a single entry into the hash table.
/*! This process stops after a certain number of iterations.  If the thread is
    still holding onto an item because of an eviction, it tries the stash.
    If it fails to enter the stash, it returns false.
    Otherwise, it succeeds and returns true.
 */
188
189
190
191
192
193
template <unsigned kNumHashFunctions>
__device__ bool
insert(const unsigned table_size, const Functions<kNumHashFunctions> constants,
       const uint2 stash_constants, const unsigned max_iteration_attempts,
       Entry *table, unsigned *stash_count, Entry entry,
       unsigned *iterations_used) {
194
195
196
197
198
  unsigned key = get_key(entry);

  // The key is always inserted into its first slot at the start.
  unsigned location = hash_function(constants, 0, key) % table_size;

199
200
  // Keep inserting until an empty slot is found or the eviction chain grows too
  // large.
201
202
203
  for (unsigned its = 1; its <= max_iteration_attempts; its++) {
    // Insert the new entry.
    entry = atomicExch(&table[location], entry);
204
    key = get_key(entry);
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

    // If no key was evicted, we're done.
    if (key == kKeyEmpty) {
      *iterations_used = its;
      break;
    }

    // Otherwise, determine where the evicted key will go.
    location = determine_next_location(constants, table_size, key, location);
  }

  if (key != kKeyEmpty) {
    // Shove it into the stash.
    unsigned slot = stash_hash_function(stash_constants, key);
    Entry *stash = table + table_size;
    Entry replaced_entry = atomicCAS(stash + slot, kEntryEmpty, entry);
    if (replaced_entry != kEntryEmpty) {
      return false;
    } else {
      atomicAdd(stash_count, 1);
    }
  }

  return true;
}

// Build a basic hash table, using one big table.
232
233
234
235
236
237
238
239
template <unsigned kNumHashFunctions>
__global__ void CuckooHash(const unsigned n_entries, const unsigned *keys,
                           const unsigned *values, const unsigned table_size,
                           const Functions<kNumHashFunctions> constants,
                           const unsigned max_iteration_attempts, Entry *table,
                           uint2 stash_constants, unsigned *stash_count,
                           unsigned *failures,
                           unsigned *iterations_taken = nullptr) {
240
  // Check if this thread has an item and if any previous threads failed.
241
  unsigned thread_index = threadIdx.x + blockIdx.x * blockDim.x +
242
243
244
245
246
247
                          blockIdx.y * blockDim.x * gridDim.x;
  if (thread_index >= n_entries || *failures)
    return;
  Entry entry = make_entry(keys[thread_index], values[thread_index]);

  unsigned iterations = 0;
248
249
250
  bool success = insert<kNumHashFunctions>(
      table_size, constants, stash_constants, max_iteration_attempts, table,
      stash_count, entry, &iterations);
251
252
253

  if (success == false) {
    // The eviction chain grew too large.  Report failure.
254
#ifdef COUNT_UNINSERTED
255
    atomicAdd(failures, 1);
256
#else
257
    *failures = 1;
258
#endif
259
260
261
262
263
  }

#ifdef TRACK_ITERATIONS
  iterations_taken[thread_index] = iterations;
#endif
264
}
265
266
//! @}

267
}; // namespace cuhash
268
269
270
271
272
273
274
275

#endif

// Leave this at the end of the file
// Local Variables:
// mode:c++
// c-file-style: "NVIDIA"
// End: