-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoaph.cpp
367 lines (331 loc) · 12.3 KB
/
oaph.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
#include "helpers.hpp"
#include "io.hpp"
#include "timer.hpp"
#include <fmt/color.h>
#include <fmt/format.h>
#include <algorithm>
#include <functional>
#include <iterator>
#include <limits>
#include <memory>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <unordered_set>
#include <utility>
#include <vector>
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
namespace
{
#if defined(_OPENMP)
constexpr bool kFindPerfectHash = false;
#endif
constexpr bool kEnableOpenAddressing = false; // requires a key comparison
alignas(__m128i) char input[1 << 29];
auto inputEnd = input;
// perfect hash seeds: 10675, 98363, 102779, 103674, 105067, 194036, 242662,
// 290547, 313385, ... seeds 8, 23, 89, 126, 181, 331, 381, 507, ... are also
// perfect hash seeds, but kHashTableOrder-bit prefix of hash values gives more
// than 8 collisions per unique one, thus requires an open addressing for
// hashtable enabled
constexpr uint32_t kInitialChecksum = 10675;
constexpr uint16_t kDefaultChecksumHigh = 0xFFFF;
struct alignas(kHardwareDestructiveInterferenceSize) Chunk
{
__m128i hashesHigh;
uint32_t count[sizeof(__m128i) / sizeof(uint16_t)];
};
static_assert((alignof(Chunk) % alignof(__m128i)) == 0, "!");
constexpr auto kHashTableOrder =
std::numeric_limits<uint16_t>::digits +
1; // one bit window to distinct kDefaultChecksumHigh
constexpr uint32_t kHashTableMask = (uint32_t(1) << kHashTableOrder) - 1;
Chunk hashTable[1 << kHashTableOrder];
alignas(__m128i) char output[1 << 22] = {};
auto o = std::next(output); // words[i][j] == std::distance(output, o) is 0 for
// unused hashes only
uint32_t words[std::extent_v<decltype(hashTable)>]
[std::extent_v<decltype(Chunk::count)>] = {};
void incCounter(uint32_t hash, const char * __restrict wordEnd, uint32_t len)
{
uint32_t hashLow = hash & kHashTableMask;
uint32_t hashHigh = hash >> kHashTableOrder;
for (;;) {
Chunk & chunk = hashTable[hashLow];
__m128i hashesHigh = _mm_load_si128(&chunk.hashesHigh);
__m128i mask =
_mm_cmpeq_epi16(hashesHigh, _mm_set1_epi16(int16_t(hashHigh)));
uint16_t m = uint16_t(_mm_movemask_epi8(mask));
unsigned long index;
if LIKELY (m != 0) {
BSF(index, m);
index /= 2;
if (kEnableOpenAddressing &&
UNLIKELY(!std::equal(std::prev(wordEnd, len),
std::next(wordEnd),
std::next(output, words[hashLow][index]))))
{
hashLow = (hashLow + 1) & kHashTableMask; // linear probing
continue;
}
} else {
m = uint16_t(_mm_movemask_epi8(hashesHigh)) & 0b1010101010101010u;
if (kEnableOpenAddressing && UNLIKELY(m == 0)) {
hashLow = (hashLow + 1) & kHashTableMask; // linear probing
continue;
}
BSF(index, m);
index /= 2;
reinterpret_cast<uint16_t *>(&chunk.hashesHigh)[index] = hashHigh;
words[hashLow][index] = uint32_t(std::distance(output, o));
o = std::next(std::copy_n(std::prev(wordEnd, len), len, o));
}
++chunk.count[index];
return;
}
}
void countWords()
{
uint32_t hash = kInitialChecksum;
uint32_t len = 0;
for (auto i = input; LIKELY(i < inputEnd); i += sizeof(__m128i)) {
__m128i str = _mm_load_si128(reinterpret_cast<const __m128i *>(i));
__m128i mask;
if (kEnableOpenAddressing) {
mask = _mm_cmpeq_epi8(str, _mm_setzero_si128());
} else {
str = _mm_add_epi8(
_mm_and_si128(_mm_cmplt_epi8(str, _mm_set1_epi8('a')),
_mm_set1_epi8('a' - 'A')),
str);
mask = _mm_or_si128(_mm_cmplt_epi8(str, _mm_set1_epi8('a')),
_mm_cmpgt_epi8(str, _mm_set1_epi8('z')));
}
uint16_t m = uint16_t(_mm_movemask_epi8(mask));
// clang-format off
#define BYTE(offset) \
if UNPREDICTABLE ((m & (uint32_t(1) << offset)) == 0) { \
++len; \
hash = _mm_crc32_u8(hash, uint8_t(_mm_extract_epi8(str, offset))); \
} else if UNPREDICTABLE (len != 0) { \
incCounter(hash, std::next(i, offset), len); \
len = 0; \
hash = kInitialChecksum; \
}
BYTE(0)
BYTE(1)
BYTE(2)
BYTE(3)
BYTE(4)
BYTE(5)
BYTE(6)
BYTE(7)
BYTE(8)
BYTE(9)
BYTE(10)
BYTE(11)
BYTE(12)
BYTE(13)
BYTE(14)
BYTE(15)
#undef BYTE
// clang-format on
}
if (len != 0) {
incCounter(hash, inputEnd, len);
}
}
} // namespace
#if defined(_OPENMP)
#include <omp.h>
static void findPerfectHash()
{
Timer timer{fmt::format(fg(fmt::color::dark_orange), "total")};
toLower(input, inputEnd);
timer.report("make input lowercase");
auto words = []() -> std::vector<std::string_view> {
std::size_t wordCount = 0;
std::unordered_set<std::string_view> words;
auto lo = std::find(input, inputEnd, '\0');
while (lo != inputEnd) {
auto hi =
std::find_if(lo, inputEnd, [](char c) { return c != '\0'; });
lo = std::find(hi, inputEnd, '\0');
words.emplace(hi, std::size_t(std::distance(hi, lo)));
++wordCount;
}
fmt::print(stderr, "{} words read\n", wordCount);
fmt::print(stderr, "{} unique words read\n", words.size());
return {std::cbegin(words), std::cend(words)};
}();
timer.report("collect words");
std::sort(std::begin(words), std::end(words), [](auto && lhs, auto && rhs) {
return std::make_tuple(lhs.size(), std::cref(lhs)) <
std::make_tuple(rhs.size(), std::cref(rhs));
});
timer.report(fmt::format(fg(fmt::color::dark_orange), "sort words"));
constexpr auto hashTableOrder = kHashTableOrder;
constexpr uint32_t hashTableMask = (uint32_t(1) << hashTableOrder) - 1;
constexpr auto maxCollisions = std::extent_v<decltype(Chunk::count)>;
const auto printStatusPeriod = 1000 / omp_get_num_threads();
#pragma omp parallel firstprivate(timer)
{
uint32_t iterationCount = 0;
std::size_t maxPrefix = 0;
std::unordered_set<uint32_t> hashesFull;
std::vector<uint8_t> hashesLowPopCnt;
#pragma omp for schedule(static, 1)
for (int32_t initialChecksum = 0;
initialChecksum < std::numeric_limits<int32_t>::max();
++initialChecksum)
{ // MSVC: error C3016: 'initialChecksum': index variable in OpenMP
// 'for' statement must have signed integral type
bool bad = false;
for (const auto & word : words) {
auto hash = uint32_t(initialChecksum);
for (char c : word) {
hash = _mm_crc32_u8(hash, uint8_t(c));
}
if (!hashesFull.insert(hash).second) {
bad = true;
break;
}
}
uint8_t collision = 0;
if (!kEnableOpenAddressing && !bad) {
hashesLowPopCnt.resize(std::size_t(1) << hashTableOrder);
std::size_t prefix = 0;
for (uint32_t hash : hashesFull) {
++prefix;
collision = std::max(
collision, ++hashesLowPopCnt[hash & hashTableMask]);
if (collision > maxCollisions) {
bad = true;
break;
}
}
if (prefix > maxPrefix) {
maxPrefix = prefix;
}
hashesLowPopCnt.clear();
}
hashesFull.clear();
if (!bad) {
fmt::print(stderr, fg(fmt::color::dark_orange),
"FOUND: iterationCount {} ; initialChecksum = "
"{} ; collision = {} ; hashTableOrder {} "
"; time {:.3} ; tid {}\n",
iterationCount, uint32_t(initialChecksum), collision,
hashTableOrder, timer.dt(), omp_get_thread_num());
}
if ((++iterationCount % printStatusPeriod) == 0) {
fmt::print(stderr, "failed at {} of {}\n",
std::exchange(maxPrefix, 0), words.size());
fmt::print(stderr,
"status: totalIterationCount ~{} ; tid {} ; "
"initialChecksum {} ; time {:.3}\n",
iterationCount * omp_get_num_threads(),
omp_get_thread_num(), uint32_t(initialChecksum),
timer.dt());
}
}
}
}
#endif
int main(int argc, char * argv[])
{
Timer timer{fmt::format(fg(fmt::color::dark_green), "total")};
if (argc != 3) {
fmt::print(stderr, "usage: {} in.txt out.txt\n", argv[0]);
return EXIT_FAILURE;
}
using namespace std::string_view_literals;
auto inputFile =
(argv[1] == "-"sv) ? wrapFile(stdin) : openFile(argv[1], "rb");
if (!inputFile) {
fmt::print(stderr, "failed to open '{}' file to read\n", argv[1]);
return EXIT_FAILURE;
}
auto outputFile =
(argv[2] == "-"sv) ? wrapFile(stdout) : openFile(argv[2], "wb");
if (!outputFile) {
fmt::print(stderr, "failed to open '{}' file to write\n", argv[2]);
return EXIT_FAILURE;
}
std::size_t readSize =
readInput(std::begin(input), std::size(input), inputFile);
if (readSize == 0) {
return EXIT_SUCCESS;
}
inputEnd += readSize;
timer.report("read input");
for (Chunk & chunk : hashTable) {
chunk.hashesHigh = _mm_set1_epi16(int16_t(kDefaultChecksumHigh));
}
timer.report("init hashTable");
#if defined(_OPENMP)
if ((kFindPerfectHash)) {
findPerfectHash();
return EXIT_SUCCESS;
}
#endif
if (kEnableOpenAddressing) {
toLower(input, inputEnd);
timer.report("make input lowercase");
}
countWords();
timer.report(fmt::format(fg(fmt::color::dark_blue), "count words"));
toLower(output, o);
timer.report("make output lowercase");
std::vector<std::pair<uint32_t, std::string_view>> rank;
rank.reserve(std::extent_v<decltype(words)> *
std::extent_v<decltype(words), 1>);
{
uint32_t hashLow = 0;
for (const auto & w : words) {
const Chunk & chunk = hashTable[hashLow];
uint32_t index = 0;
for (uint32_t word : w) {
if (word != 0) {
rank.emplace_back(chunk.count[index],
std::next(output, word));
}
++index;
}
++hashLow;
}
}
fmt::print(stderr, "load factor = {:.3}\n",
double(rank.size()) / double(rank.capacity()));
timer.report("collect word counts");
auto less = [](auto && lhs, auto && rhs) {
return std::tie(rhs.first, lhs.second) <
std::tie(lhs.first, rhs.second);
};
std::sort(std::begin(rank), std::end(rank), less);
timer.report(fmt::format(fg(fmt::color::dark_orange), "sort words"));
OutputStream<> outputStream{outputFile};
for (const auto & [count, word] : rank) {
if (!outputStream.print(count)) {
fmt::print(stderr, "output failure\n");
return EXIT_FAILURE;
}
if (!outputStream.putChar(' ')) {
fmt::print(stderr, "output failure\n");
return EXIT_FAILURE;
}
if (!outputStream.print(word.data())) {
fmt::print(stderr, "output failure\n");
return EXIT_FAILURE;
}
if (!outputStream.putChar('\n')) {
fmt::print(stderr, "output failure\n");
return EXIT_FAILURE;
}
}
timer.report("write output");
return EXIT_SUCCESS;
}