-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcuda_replace.cu
More file actions
2603 lines (2332 loc) · 82.7 KB
/
cuda_replace.cu
File metadata and controls
2603 lines (2332 loc) · 82.7 KB
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// cuda_replace.cu
// High-throughput byte-pattern replace (GPU). Leftmost, non-overlapping semantics
// identical to Python's bytes.replace. Pure CUDA C++.
//
// Build (Windows):
// nvcc -O3 -std=c++17 -m64 -Xcompiler "/MD" -shared -o cuda_replace.dll cuda_replace.cu --linker-options "/DEF:cuda_replace.def,/MACHINE:X64,/NODEFAULTLIB:LIBCMT"
//
// Exports:
// int cuda_replace_unified(...);
// void cuda_free_host(void*);
//
// // Persistent session API (GPU-resident buffer):
// int cuda_replace_open(void** ph, const uint8_t* src, size_t len);
// int cuda_replace_build_index(void* h, size_t chunk_size); // optional presence index
// int cuda_replace_apply(void* h, const uint8_t* pat, int pat_len,
// const uint8_t* rep, int rep_len, size_t* new_len);
// int cuda_replace_apply_batch(void* h,
// const uint8_t** pats, const int* pat_lens,
// const uint8_t** reps, const int* rep_lens,
// int count, size_t* new_len);
// int cuda_replace_result(void* h, uint8_t** out_host, size_t* outlen_host);
// void cuda_replace_close(void* h);
// const char* cuda_replace_version();
//
// // NEW (2025-09):
// int cuda_replace_reset(void* h, const uint8_t* src, size_t len);
// int cuda_replace_apply_seeded(void* h,
// const uint8_t* pat, int pat_len,
// const uint8_t* rep, int rep_len,
// long long prev_last_rel, long long* out_last_rel,
// size_t* new_len);
// int cuda_replace_query_prefix(void* h, size_t limit,
// int* kept_before_limit, int* last_kept_before_limit);
//
// Notes:
// - Legacy path: proven-correct global bitmap + suppression.
// - Fused path (enable with CUDA_REPLACE_FUSED=1): tiled mark+greedy in shared memory.
// Auto-fallback if SMEM is insufficient.
// - This version implements:
// * Safe batch path (sync H2D copies, no host staging reuse).
// * Range-sliced expansion scatter to avoid long kernels / TDR on Windows.
// * **Split capacity** for main buffers vs aux arrays so we never clobber
// flags/prefix/local between build and scatter (fixes intermittent mismatches).
// - 2025-09 Thread-Safety Fix:
// * Per-handle (session) mutex serializes all public API calls that take `void* h`.
// * Contract: A handle may be shared across threads, but calls on the SAME handle
// are serialized internally. Do NOT call any API on a handle after `cuda_replace_close`.
// Cross-handle parallelism is still fully supported.
//
// CRITICAL THREAD-SAFETY WARNING (now enforced):
// • The session handle (`void* h`) is a mutable resource. This build adds a mutex to
// `CRContext`, and every exported function that operates on a session acquires it,
// ensuring calls on the same handle are serialized and race-free.
// • You MUST NOT use a handle after `cuda_replace_close(h)` returns. The library cannot
// protect against use-after-free if user code retains the raw pointer.
#include <cuda_runtime.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <algorithm>
#include <mutex> // per-handle mutex
#include <atomic>
#ifndef BLOCK_SIZE
#define BLOCK_SIZE 256
#endif
#ifndef DEFAULT_CHUNK_SIZE
#define DEFAULT_CHUNK_SIZE (1u << 20) // 1 MiB presence-index chunking
#endif
#ifndef SCAN_TILE
#define SCAN_TILE 1024 // device prefix tile (power of 2)
#endif
#ifndef FUSED_TILE_BYTES
#define FUSED_TILE_BYTES 8192 // bytes of input per fused tile (before halo)
#endif
#define PADDING_MARKER_16 999
#if defined(_WIN32)
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __attribute__((visibility("default")))
#endif
// ---------------- Error helpers ----------------
static inline const char *cu_errname(cudaError_t e) { return cudaGetErrorString(e); }
#define CUDA_OK(expr) \
do \
{ \
cudaError_t _e = (expr); \
if (_e != cudaSuccess) \
{ \
err = _e; \
goto cuda_fail; \
} \
} while (0)
#define KERNEL_OK() \
do \
{ \
cudaError_t _e = cudaGetLastError(); \
if (_e != cudaSuccess) \
{ \
err = _e; \
goto cuda_fail; \
} \
} while (0)
// ---------------- Device utils ----------------
__device__ __forceinline__ size_t grid_stride_start() { return blockIdx.x * blockDim.x + threadIdx.x; }
__device__ __forceinline__ size_t grid_stride_step() { return (size_t)gridDim.x * (size_t)blockDim.x; }
__device__ __forceinline__ bool simple_pattern_match(
const uint8_t *data, size_t pos, size_t data_len,
const uint8_t *pat, int pat_len)
{
if ((size_t)pat_len > data_len || pos + (size_t)pat_len > data_len)
return false;
for (int i = 0; i < pat_len; ++i)
if (data[pos + i] != pat[i])
return false;
return true;
}
static inline uint64_t div_ceil_u64(uint64_t a, uint64_t b) { return (b ? (a + b - 1) / b : 0); }
// ===========================
// Core context & helpers
// ===========================
// ===========================
// Core context & helpers
// ===========================
struct CRContext
{
// Thread-safety
std::mutex mtx; // serialize all API calls per handle
bool alive = true; // set false at close() while under lock
// Main buffer (input/output)
uint8_t *d_buf = nullptr;
uint8_t *d_tmp = nullptr;
size_t len = 0;
// **Split capacities**
size_t cap = 0; // capacity of d_buf / d_tmp
size_t aux_cap = 0; // capacity for aux arrays below
// temps (byte-level, length-dependent)
bool *d_match = nullptr; // [aux_cap] final kept-starts
bool *d_match2 = nullptr; // [aux_cap] scratch
uint16_t *d_padded = nullptr; // [aux_cap]
uint8_t *d_flags = nullptr; // [aux_cap]
int *d_local = nullptr; // [aux_cap]
int *d_bcounts = nullptr; // [blocks]
int *d_bprefix = nullptr; // [blocks]
size_t *d_outlen = nullptr; // [1]
int *d_totmatch = nullptr; // [1]
// kept info (device scalars)
int *d_kept_count = nullptr;
int *d_first_kept = nullptr;
int *d_last_kept = nullptr;
// device-wide scan temporaries
int *d_tile_sums = nullptr; // [num_tiles]
// --- FIX START ---
// Promote tile_prefix to 64-bit to handle massive expansion offsets.
size_t *d_tile_prefix = nullptr; // [num_tiles]
// --- FIX END ---
int tiles_cap = 0;
// block launch cache for byte-grids
int blocks_cap = 0;
dim3 grid, block;
// chunk presence index (optional)
size_t chunk_size = DEFAULT_CHUNK_SIZE;
int num_chunks = 0;
size_t *d_chunk_addrs = nullptr; // [num_chunks]
uint64_t *d_chunk_masks = nullptr; // [num_chunks][4]
uint8_t *d_chunk_flags = nullptr; // [num_chunks]
int *d_chunk_local = nullptr; // [num_chunks]
int *d_chunk_bcounts = nullptr; // [(num_chunks+BLOCK_SIZE-1)/BLOCK_SIZE]
int *d_chunk_bprefix = nullptr; // [same]
int *d_chunk_indices = nullptr; // [num_chunks]
int active_chunks = 0;
// fused pipeline temps
int fused_tile_bytes = FUSED_TILE_BYTES;
int fused_num_tiles = 0;
int *d_fused_last = nullptr; // [fused_num_tiles]
int *d_fused_prev = nullptr; // [fused_num_tiles]
// device staging for batch (single-buffer, sync H2D)
uint8_t *d_pat_buf[1] = {nullptr};
size_t d_pat_cap = 0;
uint8_t *d_rep_buf[1] = {nullptr};
size_t d_rep_cap = 0;
// streams
cudaStream_t stream = nullptr;
cudaStream_t copy_stream = nullptr; // kept for ABI compat, unused
// (unused now, but kept for ABI stability)
cudaEvent_t ev_copy_done[2]{};
cudaEvent_t ev_compute_done[2]{};
// execution
int use_fused = 0; // runtime toggle via env
};
static int dev_max_smem()
{
int dev = 0, max_smem = 0;
cudaGetDevice(&dev);
cudaDeviceGetAttribute(&max_smem, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev);
if (max_smem == 0)
cudaDeviceGetAttribute(&max_smem, cudaDevAttrMaxSharedMemoryPerBlock, dev);
return (max_smem > 0 ? max_smem : 49152);
}
static void compute_launch(CRContext *c)
{
c->block = dim3(BLOCK_SIZE, 1, 1);
c->grid = dim3((unsigned)((c->len + BLOCK_SIZE - 1) / BLOCK_SIZE), 1, 1);
}
// ===========================
// Tiled device prefix (Blelloch)
// ===========================
__global__ void scan_counts_stage1_kernel(
const int *__restrict__ in, int n,
int *__restrict__ out_excl, // exclusive per-element scan within tiles
int *__restrict__ tile_sums) // per-tile totals
{
__shared__ int s[SCAN_TILE];
const int tile = blockIdx.x;
const int base = tile * SCAN_TILE;
int limit = n - base;
if (limit <= 0)
{
if (threadIdx.x == 0)
tile_sums[tile] = 0;
return;
}
if (limit > SCAN_TILE)
limit = SCAN_TILE;
int t = threadIdx.x;
s[t] = (t < limit) ? in[base + t] : 0;
__syncthreads();
// upsweep
for (int d = 1; d < SCAN_TILE; d <<= 1)
{
int idx = (t + 1) * (d << 1) - 1;
if (idx < SCAN_TILE)
s[idx] += s[idx - d];
__syncthreads();
}
int total = s[SCAN_TILE - 1];
if (t == 0)
s[SCAN_TILE - 1] = 0;
__syncthreads();
// downsweep
for (int d = SCAN_TILE >> 1; d >= 1; d >>= 1)
{
int idx = (t + 1) * (d << 1) - 1;
if (idx < SCAN_TILE)
{
int tmp = s[idx - d];
s[idx - d] = s[idx];
s[idx] += tmp;
}
__syncthreads();
}
if (t < limit)
out_excl[base + t] = s[t];
if (t == 0)
tile_sums[tile] = total;
}
// Corrected scan_counts_stage2_kernel
__global__ void scan_counts_stage2_kernel(
const int *__restrict__ tile_sums, int num_tiles,
// --- FIX START ---
// Match the 64-bit data type for the output buffer.
size_t *__restrict__ tile_prefix) // exclusive
// --- FIX END ---
{
if (blockIdx.x != 0 || threadIdx.x != 0)
return;
size_t acc = 0;
for (int i = 0; i < num_tiles; ++i)
{
tile_prefix[i] = acc;
acc += tile_sums[i];
}
}
// Corrected scan_counts_stage3_add_kernel
__global__ void scan_counts_stage3_add_kernel(
int *__restrict__ out_excl, int n,
// --- FIX START ---
// Match the 64-bit data type for the input buffer.
const size_t *__restrict__ tile_prefix)
// --- FIX END ---
{
const int tile = blockIdx.x;
const int base = tile * SCAN_TILE;
int limit = n - base;
if (limit <= 0)
return;
if (limit > SCAN_TILE)
limit = SCAN_TILE;
// --- FIX START ---
// Use a 64-bit variable to hold the prefix value before adding it.
size_t add = tile_prefix[tile];
// --- FIX END ---
int t = threadIdx.x;
if (t < limit)
out_excl[base + t] += add;
}
__global__ void scan_counts_stage3_add_kernel(
int *__restrict__ out_excl, int n,
const int *__restrict__ tile_prefix)
{
const int tile = blockIdx.x;
const int base = tile * SCAN_TILE;
int limit = n - base;
if (limit <= 0)
return;
if (limit > SCAN_TILE)
limit = SCAN_TILE;
int add = tile_prefix[tile];
int t = threadIdx.x;
if (t < limit)
out_excl[base + t] += add;
}
static cudaError_t ensure_tiles(CRContext *c, int n_elems)
{
cudaError_t err = cudaSuccess;
int num_tiles = (n_elems + SCAN_TILE - 1) / SCAN_TILE;
if (num_tiles <= c->tiles_cap)
return cudaSuccess;
if (num_tiles == 0)
return cudaSuccess;
int *ts = nullptr;
// --- FIX START ---
// Match the type of tp and old_tp to the 64-bit d_tile_prefix in CRContext.
size_t *tp = nullptr;
CUDA_OK(cudaMalloc(&ts, (size_t)num_tiles * sizeof(int)));
CUDA_OK(cudaMalloc(&tp, (size_t)num_tiles * sizeof(size_t)));
int *old_ts = c->d_tile_sums;
size_t *old_tp = c->d_tile_prefix;
// --- FIX END ---
c->d_tile_sums = ts;
c->d_tile_prefix = tp;
c->tiles_cap = num_tiles;
if (old_ts)
cudaFree(old_ts);
if (old_tp)
cudaFree(old_tp);
return cudaSuccess;
cuda_fail:
if (ts)
cudaFree(ts);
if (tp)
cudaFree(tp);
return err;
}
// ===========================
// Presence index over chunks (optional, kept minimal)
// ===========================
struct Bit256
{
uint64_t w[4];
};
__device__ __forceinline__ void bit256_set(Bit256 &m, uint8_t byte) { m.w[byte >> 6] |= (1ull << (byte & 63)); }
__global__ void build_chunk_index_kernel(
const uint8_t *__restrict__ data, size_t data_len,
size_t chunk_size, int num_chunks,
size_t *__restrict__ chunk_addrs,
uint64_t *__restrict__ chunk_masks) // [num_chunks][4]
{
int cid = blockIdx.x;
if (cid >= num_chunks)
return;
size_t start = (size_t)cid * chunk_size;
size_t end = start + chunk_size;
if (start >= data_len)
{
if (threadIdx.x == 0)
{
chunk_addrs[cid] = start;
chunk_masks[cid * 4 + 0] = chunk_masks[cid * 4 + 1] = chunk_masks[cid * 4 + 2] = chunk_masks[cid * 4 + 3] = 0;
}
return;
}
if (end > data_len)
end = data_len;
__shared__ Bit256 s_mask;
if (threadIdx.x == 0)
s_mask.w[0] = s_mask.w[1] = s_mask.w[2] = s_mask.w[3] = 0ull;
__syncthreads();
for (size_t i = start + threadIdx.x; i < end; i += blockDim.x)
{
uint8_t b = data[i];
atomicOr((unsigned long long *)&s_mask.w[b >> 6], 1ull << (b & 63));
}
__syncthreads();
if (threadIdx.x == 0)
{
chunk_addrs[cid] = start;
chunk_masks[cid * 4 + 0] = s_mask.w[0];
chunk_masks[cid * 4 + 1] = s_mask.w[1];
chunk_masks[cid * 4 + 2] = s_mask.w[2];
chunk_masks[cid * 4 + 3] = s_mask.w[3];
}
}
// ===========================
// Legacy mark / suppress path
// ===========================
__global__ void mark_match_positions_kernel_smem(
bool *__restrict__ match_positions,
const uint8_t *__restrict__ data, size_t data_len,
const uint8_t *__restrict__ pattern, int pattern_len)
{
extern __shared__ uint8_t smem[];
uint8_t *shared_pattern = smem;
for (int i = threadIdx.x; i < pattern_len; i += blockDim.x)
shared_pattern[i] = pattern[i];
__syncthreads();
for (size_t pos = grid_stride_start(); pos < data_len; pos += grid_stride_step())
{
bool m = (pos + (size_t)pattern_len <= data_len) &&
simple_pattern_match(data, pos, data_len, shared_pattern, pattern_len);
match_positions[pos] = m;
}
}
__global__ void mark_match_positions_kernel_gmem(
bool *__restrict__ match_positions,
const uint8_t *__restrict__ data, size_t data_len,
const uint8_t *__restrict__ pattern, int pattern_len)
{
for (size_t pos = grid_stride_start(); pos < data_len; pos += grid_stride_step())
{
bool m = (pos + (size_t)pattern_len <= data_len) &&
simple_pattern_match(data, pos, data_len, pattern, pattern_len);
match_positions[pos] = m;
}
}
// pass1: local greedy (inside each block's byte-range), store last kept per block
__global__ void suppress_local_pass(
const bool *__restrict__ match_in, size_t n, int L,
bool *__restrict__ keep_tmp, // zeroed before call
int *__restrict__ block_last_keep // [gridDim.x]
)
{
const size_t base = (size_t)blockIdx.x * blockDim.x;
const size_t end = min(base + (size_t)blockDim.x, n);
long long last = LLONG_MIN / 4;
if (threadIdx.x == 0)
{
for (size_t i = base; i < end; ++i)
{
if (match_in[i])
{
long long dist = (long long)i - last;
if (dist >= (long long)L)
{
keep_tmp[i] = true;
last = (long long)i;
}
}
}
block_last_keep[blockIdx.x] = (last < 0 ? -1 : (int)last);
}
}
// compute prev_keep[b] = last kept among all blocks [0..b-1], or -1
__global__ void scan_last_keep_prefix(
const int *__restrict__ block_last_keep, int num_blocks,
int *__restrict__ prev_keep // [num_blocks]
)
{
if (blockIdx.x == 0 && threadIdx.x == 0)
{
int last = -1;
for (int b = 0; b < num_blocks; ++b)
{
prev_keep[b] = last;
if (block_last_keep[b] >= 0)
last = block_last_keep[b];
}
}
}
// pass2: greedy seeded with prev_keep
__global__ void suppress_local_apply(
const bool *__restrict__ match_in, size_t n, int L,
const int *__restrict__ prev_keep, // [gridDim.x]
bool *__restrict__ match_out // zeroed before call
)
{
const size_t base = (size_t)blockIdx.x * blockDim.x;
const size_t end = min(base + (size_t)blockDim.x, n);
long long last = (long long)prev_keep[blockIdx.x];
if (threadIdx.x == 0)
{
for (size_t i = base; i < end; ++i)
{
if (match_in[i])
{
long long dist = (long long)i - last;
if (dist >= (long long)L)
{
match_out[i] = true;
last = (long long)i;
}
}
}
}
}
// ===========================
// Compaction / expansion path
// ===========================
__global__ void fill_u16_kernel(uint16_t *__restrict__ buf, size_t n, uint16_t value)
{
for (size_t i = grid_stride_start(); i < n; i += grid_stride_step())
buf[i] = value;
}
__global__ void comp_flags_localpos_kernel(
const uint16_t *__restrict__ padded, size_t n,
uint8_t *__restrict__ flags, int *__restrict__ local_pos, int *__restrict__ block_counts)
{
__shared__ int s_scan[BLOCK_SIZE];
const size_t base = (size_t)blockIdx.x * blockDim.x;
const int lane = threadIdx.x;
size_t idx = base + lane;
int f = 0;
if (idx < n)
{
f = (padded[idx] != (uint16_t)PADDING_MARKER_16) ? 1 : 0;
flags[idx] = (uint8_t)f;
}
s_scan[lane] = f;
__syncthreads();
for (int off = 1; off < blockDim.x; off <<= 1)
{
int add = (lane >= off) ? s_scan[lane - off] : 0;
__syncthreads();
s_scan[lane] += add;
__syncthreads();
}
if (idx < n)
local_pos[idx] = s_scan[lane] - f;
int valid = (int)((base < n) ? min((size_t)BLOCK_SIZE, n - base) : (size_t)0);
if (valid > 0 && lane == (valid - 1))
block_counts[blockIdx.x] = s_scan[lane];
}
__global__ void comp_scatter_kernel(
const uint16_t *__restrict__ padded, size_t n,
const uint8_t *__restrict__ flags, const int *__restrict__ local_pos,
const int *__restrict__ block_prefix, uint8_t *__restrict__ out)
{
const size_t base = (size_t)blockIdx.x * blockDim.x;
const int lane = threadIdx.x;
size_t idx = base + lane;
if (idx >= n)
return;
if (flags[idx])
{
int pos = block_prefix[blockIdx.x] + local_pos[idx];
out[pos] = (uint8_t)(padded[idx] & 0xFF);
}
}
__global__ void compute_total_len_kernel(
const int *__restrict__ block_prefix, const int *__restrict__ block_counts, int num_blocks,
size_t *__restrict__ out_len)
{
if (blockIdx.x == 0 && threadIdx.x == 0)
{
int last_prefix = (num_blocks > 0) ? block_prefix[num_blocks - 1] : 0;
int last_count = (num_blocks > 0) ? block_counts[num_blocks - 1] : 0;
*out_len = (size_t)(last_prefix + last_count);
}
}
// Expand helpers (rely on kept-starts bitmap)
__global__ void build_match_flags_localpos_kernel(
const bool *__restrict__ match_positions, size_t n,
uint8_t *__restrict__ flags, int *__restrict__ local_pos, int *__restrict__ block_counts)
{
__shared__ int s_scan[BLOCK_SIZE];
const size_t base = (size_t)blockIdx.x * blockDim.x;
const int lane = threadIdx.x;
size_t idx = base + lane;
int f = 0;
if (idx < n)
{
f = match_positions[idx] ? 1 : 0;
flags[idx] = (uint8_t)f;
}
s_scan[lane] = f;
__syncthreads();
for (int off = 1; off < blockDim.x; off <<= 1)
{
int add = (lane >= off) ? s_scan[lane - off] : 0;
__syncthreads();
s_scan[lane] += add;
__syncthreads();
}
if (idx < n)
local_pos[idx] = s_scan[lane] - f;
int valid = (int)((base < n) ? min((size_t)BLOCK_SIZE, n - base) : (size_t)0);
if (valid > 0 && lane == (valid - 1))
block_counts[blockIdx.x] = s_scan[lane];
}
__global__ void compute_total_matches_kernel(
const int *__restrict__ block_prefix, const int *__restrict__ block_counts, int num_blocks,
int *__restrict__ total_matches)
{
if (blockIdx.x == 0 && threadIdx.x == 0)
{
int last_prefix = (num_blocks > 0) ? block_prefix[num_blocks - 1] : 0;
int last_count = (num_blocks > 0) ? block_counts[num_blocks - 1] : 0;
*total_matches = last_prefix + last_count;
}
}
__global__ void expansion_scatter_kernel(
const uint8_t *__restrict__ src, size_t src_len,
const bool *__restrict__ match_positions,
const uint8_t *__restrict__ replacement, int pattern_len, int replacement_len,
const int *__restrict__ match_block_prefix, const int *__restrict__ match_local_pos,
uint8_t *__restrict__ dst, size_t /*dst_len*/)
{
const int diff = replacement_len - pattern_len;
for (size_t pos = grid_stride_start(); pos < src_len; pos += grid_stride_step())
{
int block = (int)(pos / (size_t)BLOCK_SIZE);
int excl_before = match_block_prefix[block] + match_local_pos[pos];
size_t dst_pos = (size_t)pos + (size_t)(excl_before * diff);
if (match_positions[pos])
{
for (int i = 0; i < replacement_len; ++i)
dst[dst_pos + i] = replacement[i];
}
else
{
bool covered = false;
int start = (int)pos - (pattern_len - 1);
if (start < 0)
start = 0;
for (int s = start; s <= (int)pos; ++s)
{
if (s < (int)src_len && match_positions[s] && (size_t)s + (size_t)pattern_len > pos)
{
covered = true;
break;
}
}
if (!covered)
dst[dst_pos] = src[pos];
}
}
}
// ===========================
// NEW fused mark + suppression
// ===========================
// unaligned-safe 8B compares
__device__ __forceinline__ bool vec_match64_shared(const uint8_t *__restrict__ s,
const uint8_t *__restrict__ p,
int L)
{
int i = 0;
for (; i + 8 <= L; i += 8)
{
unsigned long long a, b;
memcpy(&a, s + i, 8);
memcpy(&b, p + i, 8);
if (a != b)
return false;
}
for (; i < L; ++i)
if (s[i] != p[i])
return false;
return true;
}
// Pass 1: per-tile local greedy (seed = -inf). Output last kept global position per tile.
__global__ void fused_tile_lastkeep_kernel(
const uint8_t *__restrict__ data, size_t n,
const uint8_t *__restrict__ pat, int L,
int tile_bytes,
int *__restrict__ tile_last_keep // size = num_tiles
)
{
const int tile = blockIdx.x;
const size_t start = (size_t)tile * (size_t)tile_bytes;
if (start >= n)
{
if (threadIdx.x == 0)
tile_last_keep[tile] = -1;
return;
}
const size_t end_excl = min(start + (size_t)tile_bytes, n);
const int tlen = (int)(end_excl - start);
extern __shared__ uint8_t smem[];
uint8_t *sp = smem;
uint8_t *sd = sp + L;
uint8_t *sm = sd + tlen + max(0, L - 1);
for (int i = threadIdx.x; i < L; i += blockDim.x)
sp[i] = pat[i];
const int halo = max(0, L - 1);
for (int i = threadIdx.x; i < tlen + halo; i += blockDim.x)
{
size_t g = start + (size_t)i;
sd[i] = (g < n ? data[g] : 0);
}
__syncthreads();
for (int pos = threadIdx.x; pos < tlen; pos += blockDim.x)
{
bool m = (pos + L <= tlen + halo) && vec_match64_shared(sd + pos, sp, L);
sm[pos] = (uint8_t)(m ? 1 : 0);
}
__syncthreads();
int last = INT_MIN / 4;
int last_kept = -1;
if (threadIdx.x == 0)
{
for (int pos = 0; pos < tlen; ++pos)
{
if (sm[pos])
{
if (pos - last >= L)
{
last = pos;
last_kept = pos;
}
}
}
tile_last_keep[tile] = (last_kept < 0) ? -1 : (int)(start + (size_t)last_kept);
}
}
// tiny prefix: prev_last[t] = last kept across tiles [0..t-1]
__global__ void fused_tile_prevlast_kernel(
const int *__restrict__ tile_last_keep, int num_tiles,
int *__restrict__ tile_prev_last)
{
if (blockIdx.x != 0 || threadIdx.x != 0)
return;
int last = -1;
for (int t = 0; t < num_tiles; ++t)
{
tile_prev_last[t] = last;
int lk = tile_last_keep[t];
if (lk >= 0)
last = lk;
}
}
// Pass 2: recompute matches + greedy with carry-in and write FINAL kept-starts bitmap.
__global__ void fused_tile_write_bitmap_kernel(
bool *__restrict__ kept_bitmap, size_t n,
const uint8_t *__restrict__ data,
const uint8_t *__restrict__ pat, int L,
int tile_bytes,
const int *__restrict__ tile_prev_last)
{
const int tile = blockIdx.x;
const size_t start = (size_t)tile * (size_t)tile_bytes;
if (start >= n)
return;
const size_t end_excl = min(start + (size_t)tile_bytes, n);
const int tlen = (int)(end_excl - start);
extern __shared__ uint8_t smem[];
uint8_t *sp = smem;
uint8_t *sd = sp + L;
uint8_t *sm = sd + tlen + max(0, L - 1);
for (int i = threadIdx.x; i < L; i += blockDim.x)
sp[i] = pat[i];
const int halo = max(0, L - 1);
for (int i = threadIdx.x; i < tlen + halo; i += blockDim.x)
{
size_t g = start + (size_t)i;
sd[i] = (g < n ? data[g] : 0);
}
__syncthreads();
for (int pos = threadIdx.x; pos < tlen; pos += blockDim.x)
{
bool m = (pos + L <= tlen + halo) && vec_match64_shared(sd + pos, sp, L);
sm[pos] = (uint8_t)(m ? 1 : 0);
}
__syncthreads();
int last = tile_prev_last[tile]; // global coordinate
if (threadIdx.x == 0)
{
for (int pos = 0; pos < tlen; ++pos)
{
if (!sm[pos])
continue;
size_t gpos = start + (size_t)pos;
long long dist = (long long)gpos - (long long)last;
if (last < 0 || dist >= (long long)L)
{
kept_bitmap[gpos] = true;
last = (int)gpos;
}
}
}
}
// ===== NEW: Seeded fused prefix composer (with initial carry-in) =====
__global__ void fused_tile_prevlast_kernel_seeded(
const int *__restrict__ tile_last_keep, int num_tiles,
int seed_last,
int *__restrict__ tile_prev_last)
{
if (blockIdx.x != 0 || threadIdx.x != 0)
return;
int last = seed_last;
for (int t = 0; t < num_tiles; ++t)
{
tile_prev_last[t] = last;
int lk = tile_last_keep[t];
if (lk >= 0)
last = lk;
}
}
// ===========================
// Extra helper kernels at file scope
// ===========================
__global__ void match_indices_scatter_kernel(
const uint8_t *__restrict__ flags, const int *__restrict__ local_pos,
const int *__restrict__ block_prefix, size_t n, int *__restrict__ out_indices)
{
const size_t base = (size_t)blockIdx.x * blockDim.x;
const int lane = threadIdx.x;
size_t idx = base + lane;
if (idx >= n)
return;
if (flags[idx])
{
int pos = block_prefix[blockIdx.x] + local_pos[idx];
out_indices[pos] = (int)idx;
}
}
__global__ void greedy_keep_on_indices_kernel(
const int *__restrict__ indices, int m, int L,
uint8_t *__restrict__ keep_flags,
int *__restrict__ kept_count,
int *__restrict__ first_kept_pos,
int *__restrict__ last_kept_pos)
{
if (blockIdx.x != 0 || threadIdx.x != 0)
return;
int last = INT_MIN / 4;
int kept = 0;
int first = -1;
for (int i = 0; i < m; ++i)
{
int p = indices[i];
if (p - last >= L)
{
keep_flags[i] = 1;
last = p;
if (first < 0)
first = p;
++kept;
}
}
if (kept_count)
*kept_count = kept;
if (first_kept_pos)
*first_kept_pos = first;
if (last_kept_pos)
*last_kept_pos = (kept > 0 ? last : -1);
}
// ===== NEW: Seeded greedy over indices =====
__global__ void greedy_keep_on_indices_kernel_seeded(
const int *__restrict__ indices, int m, int L, int initial_last,
uint8_t *__restrict__ keep_flags,
int *__restrict__ kept_count,
int *__restrict__ first_kept_pos,
int *__restrict__ last_kept_pos)
{
if (blockIdx.x != 0 || threadIdx.x != 0)
return;
int last = initial_last;
int kept = 0;
int first = -1;
for (int i = 0; i < m; ++i)
{
int p = indices[i];
if (p - last >= L)
{
keep_flags[i] = 1;
last = p;
if (first < 0)
first = p;
++kept;
}
}
if (kept_count)
*kept_count = kept;
if (first_kept_pos)
*first_kept_pos = first;
if (last_kept_pos)
*last_kept_pos = (kept > 0 ? last : -1);
}
__global__ void set_bitmap_from_kept_indices_kernel(
bool *__restrict__ out_bitmap, size_t n,
const int *__restrict__ indices, const uint8_t *__restrict__ keep_flags, int m)
{
for (size_t i = grid_stride_start(); i < (size_t)m; i += grid_stride_step())
{
if (keep_flags[i])
{
int pos = indices[i];
if ((size_t)pos < n)
out_bitmap[pos] = true;
}
}
}
// ===== NEW: last kept-start strictly before a limit (atomicMax) =====
__global__ void last_true_before_limit_kernel(
const bool *__restrict__ bm, size_t n, size_t limit, int *out_idx)
{
size_t end = (limit < n ? limit : n);
for (size_t pos = grid_stride_start(); pos < end; pos += grid_stride_step())
{
if (bm[pos])
atomicMax(out_idx, (int)pos);
}
}
// ===========================
// Atomic allocation helpers
// ===========================