Repository navigation
Expand file tree
/
Copy pathmap.c
More file actions
1943 lines (1802 loc) · 73.8 KB
/
Copy pathmap.c
File metadata and controls
1943 lines (1802 loc) · 73.8 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
72
8000
0
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
/*
* Copyright (C) 2026 Advanced Micro Devices, Inc. All rights reserved.
*
* SPDX-License-Identifier: MIT
*/
// MIT License
//
// Copyright (c) 2023-2025 Advanced Micro Devices, Inc. All rights reserved.
// Copyright (c) 2018-2022 Heng Li; Dana-Farber Cancer Institute; Broad Institute
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the &quo
8000
t;Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include "kthread.h"
#include "kvec.h"
#include "kalloc.h"
#include "sdust.h"
#include "map_priv.h"
#include "mm2_seed.h"
#include "align_priv.h"
#include "khash.h"
#include "mm_log.h"
#include "mm_profiler.h"
#include "mm_dump.h"
#include "core_ctx.h"
#ifdef MM_ENABLE_HIP
#include "gpu/plchain.h"
#endif
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
#ifndef MAX
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif
// Free chain_read_t pointers except a, u, mini_pos because they are freed in mm_map_align.
static inline void free_read(chain_read_t* in, void* km)
{
if (in->qseqs) kfree(km, in->qseqs);
if (in->qlens) kfree(km, in->qlens);
if (in->minimizers_a) kfree(km, in->minimizers_a);
//DEBUG: for SCORE CHECK after chaining
#if defined(DEBUG_CHECK) && 0
if (in->f) kfree(km, in->f);
if (in->p) kfree(km, in->p);
in->f = 0, in->p = 0;
#endif
in->qseqs = 0, in->qlens = 0;
in->minimizers_a = 0, in->minimizers_n = 0;
in->a = 0, in->u = 0;
}
/**
* Initialize a thread buffer with memory pool.
* @return pointer to newly initialized mm_tbuf_t structure
*
* This function allocates and initializes a per-thread buffer used for memory management
* during sequence mapping. Each thread gets its own memory pool (km) to minimize contention.
* The debug flag can suppress km allocation for testing purposes.
*/
mm_tbuf_t* mm_tbuf_init(void)
{
mm_tbuf_t* b;
b = (mm_tbuf_t*)calloc(1, sizeof(mm_tbuf_t));
if (!(mm_dbg_flag & 1))
b->km = km_init();
return b;
}
/**
* Deallocate thread buffer and clean up memory pool.
* @param b pointer to mm_tbuf_t to destroy
*
* Releases all resources associated with a thread buffer including the memory pool.
* Safe to call with NULL pointer.
*/
void mm_tbuf_destroy(mm_tbuf_t* b)
{
if (b == 0)
return;
km_destroy(b->km);
free(b);
}
/**
* Get memory pool pointer from thread buffer.
* @param b pointer to mm_tbuf_t
* @return void* pointer to the memory pool (km) contained in the buffer
*
* Simple accessor function to retrieve the memory pool from a thread buffer.
* This allows other functions to allocate memory from the thread-local pool.
*/
void* mm_tbuf_get_km(mm_tbuf_t* b)
{
return b->km;
}
/**
* Initialize a batch of reads for pipelined processing.
* @param batch_ pointer to mm_batch_trbuf_t to initialize
* @param batch_max_reads maximum number of reads this batch can hold
*
* Prepares a read batch by allocating space for chain_read_t structures and
* creating a dedicated memory pool. Batches accumulate reads for processing
* (either CPU or GPU chaining depending on configuration).
*/
static void mm_trbuf_batch_init(mm_batch_trbuf_t* batch_, int batch_max_reads)
{
batch_->count = 0;
batch_->total_n = 0;
batch_->reads = (chain_read_t*)malloc(sizeof(chain_read_t) * batch_max_reads);
memset(batch_->reads, 0, sizeof(chain_read_t) * batch_max_reads);
batch_->batchid = -1;
batch_->km = km_init();
}
/**
* Reset a batch after processing - free reads and manage memory.
* @param batch_
8BD0
pointer to mm_batch_trbuf_t to reset
* @param batch_max_reads (unused) maximum number of reads in batch
* @param opt mapping options (used for memory limit settings)
*
* Clears all reads from a batch and validates memory pool consistency.
* May destroy and reinitialize the memory pool if it has grown too large.
* This is crucial for maintaining reasonable memory usage across many reads.
*/
static void mm_trbuf_batch_reset(mm_batch_trbuf_t* batch_, int batch_max_reads, const mm_mapopt_t* opt, const mm_core_ctx_t* ctx)
{
// free all the reads in the batch
for (int i = 0; i < batch_->count; i++) {
free_read(&batch_->reads[i], batch_->km);
}
/* reset memory pool km */
km_stat_t kmst;
if (batch_->km) {
chain_read_t* last_read = batch_->reads + batch_->count;
km_stat(batch_->km, &kmst);
if (mm_core_ctx_dbg_flag(ctx) & MM_DBG_PRINT_QNAME)
mm_log_debug("QM\t%s\t%d\tBid=%d\tcap=%ld,avail=%ld,nCore=%ld,largest=%ld",
last_read->seq.name, last_read->seq.qlen_sum, batch_->batchid, kmst.capacity, kmst.available, kmst.n_cores, kmst.largest);
assert(kmst.n_blocks == kmst.n_cores); // memory leak if not equal
assert(kmst.capacity == kmst.meta_size + kmst.available); // memory accounting error
if ((opt->cap_kalloc_largest > 0 && kmst.largest > (size_t)opt->cap_kalloc_largest) || (opt->cap_kalloc > 0 && kmst.capacity > opt->cap_kalloc)) {
if (mm_core_ctx_dbg_flag(ctx) & MM_DBG_PRINT_QNAME)
mm_log("[W::%s] reset thread-local memory after read %s", __func__, last_read->seq.name);
km_destroy(batch_->km);
batch_->km = km_init();
batch_->pool_reset_count++;
}
}
batch_->count = 0;
batch_->total_n = 0;
batch_->batchid = -1;
}
/**
* mm_trbuf_batch_destroy: Complete cleanup of a batch - destroy reads and memory pool
* @param batch_ pointer to mm_batch_trbuf_t to destroy
*
* Performs full cleanup of a read batch including all contained reads, associated data,
* and the dedicated memory pool. Validates memory consistency before destroying.
*/
static void mm_trbuf_batch_destroy(mm_batch_trbuf_t* batch_, const mm_core_ctx_t* ctx)
{
// free reads in the batch
for (int i = 0; i < batch_->count; i++) {
free_read(&batch_->reads[i], batch_->km);
}
batch_->batchid = -1;
batch_->total_n = 0;
batch_->count = 0;
/* clean memory pool */
km_stat_t kmst;
if (batch_->km) {
km_stat(batch_->km, &kmst);
if (mm_core_ctx_dbg_flag(ctx) & MM_DBG_PRINT_QNAME)
mm_log_debug("Destroy memory pool cap=%ld,avail=%ld,nCore=%ld,largest=%ld",
kmst.capacity, kmst.available, kmst.n_cores, kmst.largest);
assert(kmst.n_blocks == kmst.n_cores); // memory leak if not equal
assert(kmst.capacity == kmst.meta_size + kmst.available); // memory accounting error
km_destroy(batch_->km);
batch_->km = 0;
}
free(batch_->reads);
batch_->reads = 0;
}
/**
* mm_trbuf_init: Initialize thread read batch buffer with 3-batch pipelining
* @param batch_max_reads max reads per batch
* @param opt mapping options
* @return pointer to initialized mm_trbuf_t structure
*
* Creates a pipelined buffering system with 3 batches:
* - acc_batch: accumulates reads (CPU processes seeds)
* - pending_batch: ready for chaining (CPU or GPU)
* - launched_batch: chaining in progress (batch being processed)
* This enables overlap of seeding, chaining, and alignment stages.
*/
static mm_trbuf_t* mm_trbuf_init(const int batch_max_reads, const mm_mapopt_t* opt)
{
mm_trbuf_t* tr;
tr = (mm_trbuf_t*)calloc(1, sizeof(mm_trbuf_t));
tr->is_full = 0;
tr->is_pending = 0;
tr->has_launched = 0;
mm_trbuf_batch_init(&tr->acc_batch, batch_max_reads);
tr->acc_batch.batchid = 0;
mm_trbuf_batch_init(&tr->pending_batch, batch_max_reads);
tr->pending_batch.batchid = 1;
mm_trbuf_batch_init(&tr->launched_batch, batch_max_reads);
tr->launched_batch.batchid = 2;
return tr;
}
/**
* mm_trbuf_destroy: Destroy all 3 batches in thread read buffer
* @param tr pointer to mm_trbuf_t to destroy
*
* Cleans up the entire pipelined batch system by destroying each of the three
* batches (accumulation, pending, and launched) and freeing the container.
*/
static void mm_trbuf_destroy(mm_trbuf_t* tr, const mm_core_ctx_t* ctx)
{
if (tr == 0) return;
mm_trbuf_batch_destroy(&tr->acc_batch, ctx);
mm_trbuf_batch_destroy(&tr->pending_batch, ctx);
mm_trbuf_batch_destroy(&tr->launched_batch, ctx);
free(tr);
}
static step_t* init_step(pipeline_t* p)
{
int with_qual = (!!(p->opt->flag & MM_F_OUT_SAM) && !(p->opt->flag & MM_F_NO_QUAL));
int with_comment = !!(p->opt->flag & MM_F_COPY_COMMENT);
int frag_mode = (p->n_fp > 1 || !!(p->opt->flag & MM_F_FRAG_MODE));
step_t* s;
s = (step_t*)calloc(1, sizeof(step_t));
if (p->n_fp > 1)
s->seq = mm_bseq_read_frag2(p->n_fp, p->fp, p->mini_batch_size, with_qual, with_comment, &s->n_seq);
else
s->seq = mm_bseq_read3(p->fp[0], p->mini_batch_size, with_qual, with_comment, frag_mode, &s->n_seq);
if (s->seq) {
s->p = p;
for (int i = 0; i < s->n_seq; ++i)
s->seq[i].rid = p->n_processed++;
s->buf = (mm_tbuf_t**)calloc(p->n_threads, sizeof(mm_tbuf_t*));
for (int i = 0; i < p->n_threads; ++i)
s->buf[i] = mm_tbuf_init();
s->n_reg = (int*)calloc(5 * s->n_seq, sizeof(int));
s->seg_off = s->n_reg + s->n_seq; // seg_off, n_seg, rep_len and frag_gap are allocated together with n_reg
s->rep_len = s->n_seg + s->n_seq;
s->frag_gap = s->rep_len + s->n_seq;
s->reg = (mm_reg1_t**)calloc(s->n_seq, sizeof(mm_reg1_t*));
for (int i = 1, j = 0; i <= s->n_seq; ++i)
if (i == s->n_seq || !frag_mode || !mm_qname_same(s->seq[i - 1].name, s->seq[i].name)) {
s->n_seg[s->n_frag] = i - j;
s->seg_off[s->n_frag++] = j;
j = i;
}
// MM_F_GPU_CHAIN flag indicates --gpu-chain CLI flag was provided
#ifdef MM_ENABLE_HIP
if (s->p->opt->flag & MM_F_GPU_CHAIN && s->p->chain_ctx && s->p->chain_ctx->gpu_chain) {
// GPU mode: use auto-derived anchor threshold, increase batch size
s->batch_max_anchors = gpu_chain_ctx_target_batch_anchors(s->p->chain_ctx->gpu_chain);
// Increase max reads to allow accumulation for short-read datasets
// Assumes worst-case ~10K anchors/read: 125M / 10K = 12,500 reads
// Cap to GPU's preallocated memory limit
int gpu_max_reads = gpu_chain_ctx_max_reads(s->p->chain_ctx->gpu_chain);
size_t computed_max_reads = (s->batch_max_anchors / 10000) + N_ACCUM;
s->batch_max_reads = (int)MIN(computed_max_reads, gpu_max_reads);
} else
#endif
{
// CPU mode or GPU not available: unlimited anchors, static read threshold
s->batch_max_anchors = SIZE_MAX;
s->batch_max_reads = N_ACCUM;
}
s->trbuf = (mm_trbuf_t**)calloc(s->p->n_threads, sizeof(mm_trbuf_t*));
for (int i = 0; i < s->p->n_threads; ++i)
s->trbuf[i] = mm_trbuf_init(s->batch_max_reads, s->p->opt);
return s;
} else
free(s);
return NULL;
}
static void free_step(step_t* s)
{
const mm_core_ctx_t* ctx = s->p->core_ctx;
for (int i = 0; i < s->p->n_threads; ++i)
mm_trbuf_destroy(s->trbuf[i], ctx);
free(s->trbuf);
for (int k = 0; k < s->n_frag; ++k) {
int seg_st = s->seg_off[k], seg_en = s->seg_off[k] + s->n_seg[k];
for (int i = seg_st; i < seg_en; ++i) {
for (int j = 0; j < s->n_reg[i]; ++j)
free(s->reg[i][j].p);
free(s->reg[i]);
free(s->seq[i].seq);
free(s->seq[i].name);
if (s->seq[i].qual)
free(s->seq[i].qual);
if (s->seq[i].comment)
free(s->seq[i].comment);
}
}
for (int i = 0; i < s->p->n_threads; ++i)
mm_tbuf_destroy(s->buf[i]);
free(s->buf);
free(s->reg);
free(s->n_reg);
free(s->seq); // seg_off, n_seg, rep_len and frag_gap were allocated with reg; no memory leak here
if (mm_core_ctx_verbose(ctx) >= 3)
mm_log("[M::%s::%.3f*%.2f] mapped %d sequences", __func__, realtime() - mm_realtime0, cputime() / (realtime() - mm_realtime0), s->n_seq);
free(s);
}
/**
* align_regs: Perform sequence alignment on regions to generate CIGAR strings
* @param opt mapping options
* @param mi minimap2 index
* @param km memory pool for allocation
* @param qlen query length
* @param seq query sequence
* @param n_regs pointer to number of regions
* @param regs array of mapping regions
* @param a array of anchors
* @return aligned regions with CIGAR strings (if MM_F_CIGAR flag set)
*
* Performs fine-grained dynamic programming alignment on chain regions if
* CIGAR strings are requested. Also applies post-chain filtering and selects
* primary mappings based on score and quality metrics.
*
* NOTE: This is only used by mm_map_frag (public API without context).
* The pipeline path uses align_regs() inside align.c which receives ctx.
*/
static mm_reg1_t* align_regs(const mm_mapopt_t* opt, const mm_idx_t* mi, void* km, int qlen, const char* seq, int* n_regs, mm_reg1_t* regs, mm128_t* a)
{
if (!(opt->flag & MM_F_CIGAR))
return regs;
regs = mm_align_skeleton(km, opt, mi, qlen, seq, n_regs, regs, a, NULL, NULL, 0); // this calls mm_filter_regs()
if (!(opt->flag & MM_F_ALL_CHAINS)) { // don't choose primary mapping(s)
mm_set_parent(km, opt->mask_level, opt->mask_len, *n_regs, regs, opt->a * 2 + opt->b, opt->flag & MM_F_HARD_MLEVEL, opt->alt_drop);
mm_select_sub(km, opt->pri_ratio, mi->k * 2, opt->best_n, 0, opt->max_gap * 0.8, n_regs, regs);
mm_set_sam_pri(*n_regs, regs);
}
return regs;
}
static void mm_timer_stats_record_batch(mm_timer_stats_t* ts,
const mm_tbuf_timers_t* stage_sum,
const mm_tbuf_timers_t* stage_min,
const mm_tbuf_timers_t* stage_max,
uint64_t query_count,
int n_threads);
/**
* mm_map_frag: Orchestrate all three mapping stages - seed, chain, align
* @param mi minimap2 index
* @param n_segs number of query segments
* @param qlens array of segment lengths
* @param seqs array of segment sequences
* @param n_regs output number of mappings per segment
* @param regs output mapping regions
* @param b thread buffer for memory management
* @param opt mapping options
* @param qname query name
*
* High-level wrapper that coordinates the entire three-stage mapping pipeline:
* 1. Stage 1 (Seed): Finds candidate matches
* 2. Stage 2 (Chain): Groups matches into colinear chains
* 3. Stage 3 (Align): Aligns chains and produces final mappings
*
* This is the main entry point for mapping a sequence with optional paired-end support.
* Handles memory management and error checking across all stages.
*/
#ifdef MM_ENABLE_HIP
/* Per-read GPU chaining: drive the double-buffered submit/finish pipeline for a
* single, already-seeded read using GPU worker slot `slot`. gpu_chain_submit
* launches `read` on the GPU and returns the previously launched batch (NULL on
* a fresh slot, which we ignore); gpu_chain_finish then synchronizes and drains
* `read` in place, populating read->u / read->n_u for the alignment stage. */
static void mm_chain_one_gpu(gpu_chain_ctx_t* gctx, const mm_idx_t* mi, const mm_mapopt_t* opt, chain_read_t* read, int slot, void* km)
{
chain_read_t* arr = read;
int n = 1;
gpu_chain_submit(gctx, mi, opt, &arr, &n, slot, km); // launches `read`; returns prev batch (ignored)
chain_read_t* out = NULL;
int n_out = 0;
gpu_chain_finish(gctx, mi, opt, &out, &n_out, slot, km); // drains `read` in place
}
#endif
#ifdef HAVE_GPU_ALIGNMENT
/* Per-read GPU alignment: acquire a shared accumulator, add the single read,
* flush immediately (batch-of-1), then release. mm_gpu_accum_add_read frees
* read->a / read->u / read->mini_pos from `km`, matching mm_map_align's
* ownership, and internally falls back to the CPU aligner for reads the GPU
* kernel cannot handle (multi-segment, splice, SR, or no-CIGAR). */
static void mm_align_one_gpu(mm_align_ctx_t* actx, const mm_idx_t* mi, const mm_mapopt_t* opt, chain_read_t* read, mm_reg1_t** regs, int* n_regs, mm_stage_timer_t* t_align, void* km, const mm_core_ctx_t* core_ctx)
{
gpu_align_accum_t* accum = mm_gpu_align_ctx_acquire_accum(actx->gpu_align, opt, mi);
mm_gpu_accum_add_read(accum, read, regs, n_regs, t_align, km, core_ctx);
mm_gpu_accum_flush(accum, t_align, core_ctx);
mm_gpu_align_ctx_release_accum(actx->gpu_align, accum);
}
#endif
/* Single-read path. When `mapctx` is NULL (the legacy mm_map / mm_map_frag
* entry points) every stage runs on the CPU, byte-for-byte as before. When a
* mapctx is supplied (mm_map_ctx / mm_map_frag_ctx), chaining and alignment are
* toggled to the GPU per the opt flags + available sub-contexts, exactly like
* the file pipeline; `slot` selects the per-thread GPU worker slot. GPU stages
* apply only to single-segment reads; everything else falls back to CPU. */
static void mm_map_frag_core(const mm_idx_t* mi, int n_segs, const int* qlens, const char** seqs, int* n_regs, mm_reg1_t** regs, mm_tbuf_t* b, const mm_mapopt_t* opt, const char* qname, mm_mapctx_t* mapctx, int slot)
{
int i, qlen_sum = 0;
chain_read_t read;
const mm_core_ctx_t* core_ctx = mapctx ? mapctx->core_ctx : NULL;
(void)slot;
// Initialize output (must be done even on early return)
for (i = 0; i < n_segs; ++i) {
n_regs[i] = 0;
regs[i] = NULL;
}
// Early validation - return before profiling starts
if (!mi || !qlens || !seqs || !n_regs || !regs || !b || !opt)
return;
if (n_segs <= 0 || n_segs > MM_MAX_SEG)
return;
// Calculate total query length for validation
for (i = 0; i < n_segs; ++i)
qlen_sum += qlens[i];
if (qlen_sum == 0)
return;
if (opt->max_qlen > 0 && qlen_sum > opt->max_qlen)
return;
// All validation passed - start profiling
MM_PROFILE_FUNCTION();
// Initialize chain_read_t structure
memset(&read, 0, sizeof(chain_read_t));
read.n_seg = n_segs;
read.qlens = (int*)qlens;
read.qseqs = seqs;
read.seq.qlen_sum = qlen_sum;
if (qname) {
strncpy(read.seq.name, qname, sizeof(read.seq.name) - 1);
read.seq.name[sizeof(read.seq.name) - 1] = '\0';
} else {
read.seq.name[0] = '\0';
}
// Stage 1: Seed - Find k-mer matches
MM_PROFILE_SEED("mm_map_seed");
mm_map_seed(mi, opt, &read, &b->timers.seed, b->km, core_ctx);
MM_PROFILE_RANGE_POP();
// Stage 2: Chain - Link seeds into chains (if seeds were found)
if (read.n > 0) {
MM_PROFILE_CHAIN("mm_map_chain");
#ifdef MM_ENABLE_HIP
if ((opt->flag & MM_F_GPU_CHAIN) && !(opt->flag & MM_F_RMQ) && n_segs == 1 && opt->max_frag_len <= 0 && mapctx && mapctx->chain_ctx && mapctx->chain_ctx->gpu_chain) {
mm_chain_one_gpu(mapctx->chain_ctx->gpu_chain, mi, opt, &read, slot, b->km);
} else
#endif
{
mm_map_chain(mi, opt, &read, &b->timers.chain, b->km, core_ctx);
}
MM_PROFILE_RANGE_POP();
}
// Stage 3: Align - Perform sequence alignment (if chains were found)
if (read.n_u > 0) {
MM_PROFILE_ALIGN("mm_map_align");
#ifdef HAVE_GPU_ALIGNMENT
if ((opt->flag & MM_F_GPU_ALIGN) && n_segs == 1 && mapctx && mapctx->align_ctx && mapctx->align_ctx->gpu_align) {
mm_align_one_gpu(mapctx->align_ctx, mi, opt, &read, regs, n_regs, &b->timers.align, b->km, core_ctx);
} else
#endif
{
mm_map_align(mi, opt, &read, regs, n_regs, &b->timers.align, b->km, core_ctx, NULL, 0);
}
MM_PROFILE_RANGE_POP();
} else {
// mm_map_align normally frees a, u, mini_pos. When it doesn't run,
// we must free any km-allocated fields to avoid pool leaks.
kfree(b->km, read.a);
kfree(b->km, read.u);
kfree(b->km, read.mini_pos);
}
kfree(b->km, read.minimizers_a);
// Memory pool management: check and reset if pool grows too large
if (b->km) {
km_stat_t kmst;
km_stat(b->km, &kmst);
if (mm_dbg_flag & MM_DBG_PRINT_QNAME)
mm_log_debug("QM\t%s\t%d\tcap=%ld,nCore=%ld,largest=%ld", qname, read.seq.qlen_sum, kmst.capacity, kmst.n_cores, kmst.largest);
assert(kmst.n_blocks == kmst.n_cores); // memory leak if not equal
if ((opt->cap_kalloc_largest > 0 && kmst.largest > (size_t)opt->cap_kalloc_largest) || (opt->cap_kalloc > 0 && kmst.capacity > opt->cap_kalloc)) {
if (mm_dbg_flag & MM_DBG_PRINT_QNAME)
mm_log("[W::%s] reset thread-local memory after read %s", __func__, qname);
km_destroy(b->km);
b->km = km_init();
b->pool_reset_count++;
}
}
MM_PROFILE_FUNCTION_END();
}
void mm_map_frag(const mm_idx_t* mi, int n_segs, const int* qlens, const char** seqs, int* n_regs, mm_reg1_t** regs, mm_tbuf_t* b, const mm_mapopt_t* opt, const char* qname)
{
if ((opt->flag & MM_F_WEAK_PAIRING) && n_segs == 2 && opt->pe_ori >= 0 && (opt->flag & MM_F_CIGAR)) {
int i;
for (i = 0; i < n_segs; ++i)
mm_map_frag_core(mi, 1, &qlens[i], &seqs[i], &n_regs[i], ®s[i], b, opt, qname, NULL, 0);
mm_pair(b->km, opt->max_gap_ref, opt->pe_bonus, opt->a * 2 + opt->b, opt->a, qlens, n_regs, regs);
} else {
mm_map_frag_core(mi, n_segs, qlens, seqs, n_regs, regs, b, opt, qname, NULL, 0);
}
}
/* Ctx-aware twin of mm_map_frag. Threads a shared mm_mapctx_t (created once by
* the caller, e.g. mappy's Aligner) and a GPU worker slot through the per-read
* pipeline so chaining/alignment can run on the GPU when enabled. Passing a
* NULL mapctx is equivalent to mm_map_frag (pure CPU). */
void mm_map_frag_ctx(const mm_idx_t* mi, int n_segs, const int* qlens, const char** seqs, int* n_regs, mm_reg1_t** regs, mm_tbuf_t* b, const mm_mapopt_t* opt, const char* qname, mm_mapctx_t* mapctx, int slot)
{
// Bind this thread's logger to the context's logger for the duration of the
// call so any logging (incl. GPU debug logs) uses an owned, live logger,
// then restore the caller's previous binding on exit. This avoids leaving a
// stale thread-local pointer behind and avoids permanently changing the
// caller's (e.g. main thread's) logger. See AIOSS-4548.
mm_logger_t* prev_tl = mm_tl_logger();
if (mapctx && mapctx->core_ctx && mapctx->core_ctx->log)
mm_set_tl_logger(mapctx->core_ctx->log);
if ((opt->flag & MM_F_WEAK_PAIRING) && n_segs == 2 && opt->pe_ori >= 0 && (opt->flag & MM_F_CIGAR)) {
int i;
for (i = 0; i < n_segs; ++i)
mm_map_frag_core(mi, 1, &qlens[i], &seqs[i], &n_regs[i], ®s[i], b, opt, qname, mapctx, slot);
mm_pair(b->km, opt->max_gap_ref, opt->pe_bonus, opt->a * 2 + opt->b, opt->a, qlens, n_regs, regs);
} else {
mm_map_frag_core(mi, n_segs, qlens, seqs, n_regs, regs, b, opt, qname, mapctx, slot);
}
mm_set_tl_logger(prev_tl);
}
/**
* mm_map: Convenience wrapper for single-sequence mapping. Forwards to
* mm_map_frag with n_segs=1.
*/
mm_reg1_t* mm_map(const mm_idx_t* mi, int qlen, const char* seq, int* n_regs, mm_tbuf_t* b, const mm_mapopt_t* opt, const char* qname)
{
mm_reg1_t* regs;
mm_map_frag(mi, 1, &qlen, &seq, n_regs, ®s, b, opt, qname);
return regs;
}
/* Ctx-aware twin of mm_map. Forwards to mm_map_frag_ctx with n_segs=1. */
mm_reg1_t* mm_map_ctx(const mm_idx_t* mi, int qlen, const char* seq, int* n_regs, mm_tbuf_t* b, const mm_mapopt_t* opt, const char* qname, mm_mapctx_t* mapctx, int slot)
{
mm_reg1_t* regs;
mm_map_frag_ctx(mi, 1, &qlen, &seq, n_regs, ®s, b, opt, qname, mapctx, slot);
return regs;
}
static void mm_timer_stats_record_batch(mm_timer_stats_t* ts,
const mm_tbuf_timers_t* stage_sum,
const mm_tbuf_timers_t* stage_min,
const mm_tbuf_timers_t* stage_max,
uint64_t query_count,
int n_threads)
{
if (!ts)
return;
const uint64_t prev_batches = ts->batch_count;
const double denom_threads = (double)(n_threads > 0 ? n_threads : 1);
ts->seed_sum += stage_sum->seed.sum;
ts->chain_sum += stage_sum->chain.sum;
ts->align_sum += stage_sum->align.sum;
if (prev_batches == 0) {
ts->seed_min = stage_min->seed.sum;
ts->seed_max = stage_max->seed.sum;
ts->chain_min = stage_min->chain.sum;
ts->chain_max = stage_max->chain.sum;
ts->align_min = stage_min->align.sum;
ts->align_max = stage_max->align.sum;
} else {
ts->seed_min = MIN(ts->seed_min, stage_min->seed.sum);
ts->chain_min = MIN(ts->chain_min, stage_min->chain.sum);
ts->align_min = MIN(ts->align_min, stage_min->align.sum);
ts->seed_max = MAX(ts->seed_max, stage_max->seed.sum);
ts->chain_max = MAX(ts->chain_max, stage_max->chain.sum);
ts->align_max = MAX(ts->align_max, stage_max->align.sum);
}
ts->batch_count = prev_batches + 1;
ts->query_count += query_count;
const double denom = denom_threads * (double)ts->batch_count;
ts->seed_avg = denom > 0.0 ? (ts->seed_sum / denom) : 0.0;
ts->chain_avg = denom > 0.0 ? (ts->chain_sum / denom) : 0.0;
ts->align_avg = denom > 0.0 ? (ts->align_sum / denom) : 0.0;
// Per-call stats from stage_sum (which has merged per-call data across threads)
if (stage_sum->seed.call_count > 0) {
if (ts->seed_call_count == 0) {
ts->seed_call_min = stage_sum->seed.call_min;
ts->seed_call_max = stage_sum->seed.call_max;
} else {
ts->seed_call_min = MIN(ts->seed_call_min, stage_sum->seed.call_min);
ts->seed_call_max = MAX(ts->seed_call_max, stage_sum->seed.call_max);
}
ts->seed_call_count += stage_sum->seed.call_count;
ts->seed_call_avg = ts->seed_sum / (double)ts->seed_call_count;
}
if (stage_sum->chain.call_count > 0) {
if (ts->chain_call_count == 0) {
ts->chain_call_min = stage_sum->chain.call_min;
ts->chain_call_max = stage_sum->chain.call_max;
} else {
ts->chain_call_min = MIN(ts->chain_call_min, stage_sum->chain.call_min);
ts->chain_call_max = MAX(ts->chain_call_max, stage_sum->chain.call_max);
}
ts->chain_call_count += stage_sum->chain.call_count;
ts->chain_call_avg = ts->chain_sum / (double)ts->chain_call_count;
}
if (stage_sum->align.call_count > 0) {
if (ts->align_call_count == 0) {
ts->align_call_min = stage_sum->align.call_min;
ts->align_call_max = stage_sum->align.call_max;
} else {
ts->align_call_min = MIN(ts->align_call_min, stage_sum->align.call_min);
ts->align_call_max = MAX(ts->align_call_max, stage_sum->align.call_max);
}
ts->align_call_count += stage_sum->align.call_count;
ts->align_call_avg = ts->align_sum / (double)ts->align_call_count;
}
}
// consolidate timers from worker threads
/**
* mm_consolidate_timers: Consolidate timing statistics from all worker threads
* @param s step data with worker thread buffers
* @param p pipeline data
*
* Collects and aggregates timing information from each thread's buffer.
* Calculates run-level min/max/avg times for seed, chain, and align stages.
* Useful for performance profiling and load balancing analysis.
*/
static void mm_consolidate_timers(step_t* s, pipeline_t* p)
{
if (p->n_threads <= 0 || !p->timer_stats)
return;
mm_timer_stats_t* ts = p->timer_stats;
// Aggregate this batch across all worker threads.
mm_tbuf_timers_t batch_sum;
mm_tbuf_timers_t batch_min, batch_max;
memset(&batch_sum, 0, sizeof(batch_sum));
memset(&batch_min, 0, sizeof(batch_min));
memset(&batch_max, 0, sizeof(batch_max));
batch_min.seed.sum = batch_max.seed.sum = s->buf[0]->timers.seed.sum;
batch_min.chain.sum = batch_max.chain.sum = s->buf[0]->timers.chain.sum;
batch_min.align.sum = batch_max.align.sum = s->buf[0]->timers.align.sum;
for (int i = 0; i < p->n_threads; ++i) {
const double t_s = s->buf[i]->timers.seed.sum;
const double t_c = s->buf[i]->timers.chain.sum;
const double t_a = s->buf[i]->timers.align.sum;
batch_sum.seed.sum += t_s;
batch_sum.chain.sum += t_c;
batch_sum.align.sum += t_a;
if (i > 0) {
batch_min.seed.sum = MIN(batch_min.seed.sum, t_s);
batch_min.chain.sum = MIN(batch_min.chain.sum, t_c);
batch_min.align.sum = MIN(batch_min.align.sum, t_a);
batch_max.seed.sum = MAX(batch_max.seed.sum, t_s);
batch_max.chain.sum = MAX(batch_max.chain.sum, t_c);
batch_max.align.sum = MAX(batch_max.align.sum, t_a);
}
// Merge per-call stats across threads
mm_stage_timer_merge_calls(&batch_sum.seed, &s->buf[i]->timers.seed);
mm_stage_timer_merge_calls(&batch_sum.chain, &s->buf[i]->timers.chain);
mm_stage_timer_merge_calls(&batch_sum.align, &s->buf[i]->timers.align);
}
mm_timer_stats_record_batch(ts, &batch_sum, &batch_min, &batch_max, (uint64_t)s->n_seq, p->n_threads);
// Consolidate pool reset counts from per-thread batch buffers
for (int i = 0; i < p->n_threads; ++i) {
ts->pool_reset_count += s->trbuf[i]->acc_batch.pool_reset_count;
ts->pool_reset_count += s->trbuf[i]->pending_batch.pool_reset_count;
ts->pool_reset_count += s->trbuf[i]->launched_batch.pool_reset_count;
s->trbuf[i]->acc_batch.pool_reset_count = 0;
s->trbuf[i]->pending_batch.pool_reset_count = 0;
s->trbuf[i]->launched_batch.pool_reset_count = 0;
}
if (mm_core_ctx_dbg_flag(s->p->core_ctx) & MM_DBG_PRINT_QNAME) {
const double inv_threads = 1.0 / (double)p->n_threads;
const double batch_savg = batch_sum.seed.sum * inv_threads;
const double batch_cavg = batch_sum.chain.sum * inv_threads;
const double batch_aavg = batch_sum.align.sum * inv_threads;
mm_log_debug("----------------------------------------------------");
mm_log_debug(" Min (sec) Max (sec) Avg (sec) ");
mm_log_debug("----------------------------------------------------");
mm_log_debug("Seed = %11.3f %11.3f %11.3f", batch_min.seed.sum, batch_max.seed.sum, batch_savg);
mm_log_debug("Chain = %11.3f %11.3f %11.3f", batch_min.chain.sum, batch_max.chain.sum, batch_cavg);
mm_log_debug("Align = %11.3f %11.3f %11.3f", batch_min.align.sum, batch_max.align.sum, batch_aavg);
mm_log_debug("----------------------------------------------------");
mm_log_debug("Avg (seed + chain + align) per thread (this batch) = %.3f secs", (batch_savg + batch_cavg + batch_aavg));
mm_log_debug("Total (seed + chain + align) (all batches) for %d thread(s) = %.3f secs", p->n_threads, (ts->seed_sum + ts->chain_sum + ts->align_sum));
}
}
/**
* mm_trbuf_is_full: Check if accumulation batch is full and manage pipelining
* @param tr thread read buffer with 3-batch pipeline
* @param s step data with batch configuration
*
* Monitors accumulation batch size and moves reads to pending batch when
* accumulation exceeds the anchor limit. This implements the pipelined batching
* strategy that allows chaining (CPU or GPU) to process pending batch while new
* seeds are collected into the accumulation batch.
*/
static inline int mm_seg_independent(const mm_mapopt_t* opt); // defined below
static void mm_trbuf_is_full(mm_trbuf_t* tr, step_t* s)
{
while (tr->acc_batch.total_n > s->batch_max_anchors) { // if the batch is full
tr->is_full = 1;
tr->is_pending = 1;
// move last read from acc_batch to pending batch (another memory poll)
chain_read_t* read_ptr_acc_batch = &tr->acc_batch.reads[tr->acc_batch.count - 1];
chain_read_t* read_ptr_pending_batch = &tr->pending_batch.reads[tr->pending_batch.count];
/* deep copy, with memory pool transaction*/
*read_ptr_pending_batch = *read_ptr_acc_batch;
if (mm_seg_independent(s->p->opt)) {
read_ptr_pending_batch->qlens = (int*)kmalloc(tr->pending_batch.km, sizeof(int));
read_ptr_pending_batch->qseqs = (const char**)kmalloc(tr->pending_batch.km, sizeof(const char*));
read_ptr_pending_batch->qlens[0] = read_ptr_acc_batch->qlens[0];
read_ptr_pending_batch->qseqs[0] = read_ptr_acc_batch->qseqs[0];
} else {
read_ptr_pending_batch->qlens = (int*)kmalloc(tr->pending_batch.km, sizeof(int) * read_ptr_acc_batch->n_seg);
read_ptr_pending_batch->qseqs = (const char**)kmalloc(tr->pending_batch.km, sizeof(const char*) * read_ptr_acc_batch->n_seg);
memcpy(read_ptr_pending_batch->qlens, read_ptr_acc_batch->qlens, sizeof(int) * read_ptr_acc_batch->n_seg);
memcpy(read_ptr_pending_batch->qseqs, read_ptr_acc_batch->qseqs, sizeof(const char*) * read_ptr_acc_batch->n_seg);
}
read_ptr_pending_batch->mini_pos = (uint64_t*)kmalloc(tr->pending_batch.km, read_ptr_acc_batch->n_mini_pos * sizeof(uint64_t));
read_ptr_pending_batch->a = (mm128_t*)kmalloc(tr->pending_batch.km, read_ptr_acc_batch->n * sizeof(mm128_t));
memcpy(read_ptr_pending_batch->mini_pos, read_ptr_acc_batch->mini_pos, read_ptr_acc_batch->n_mini_pos * sizeof(uint64_t));
memcpy(read_ptr_pending_batch->a, read_ptr_acc_batch->a, read_ptr_acc_batch->n * sizeof(mm128_t));
strcpy(read_ptr_pending_batch->seq.name, read_ptr_acc_batch->seq.name);
tr->pending_batch.count++;
tr->pending_batch.total_n += read_ptr_acc_batch->n;
// remove read from acc_batch
tr->acc_batch.count--;
tr->acc_batch.total_n -= read_ptr_acc_batch->n;
kfree(tr->acc_batch.km, read_ptr_acc_batch->mini_pos);
kfree(tr->acc_batch.km, read_ptr_acc_batch->a);
kfree(tr->acc_batch.km, read_ptr_acc_batch->qlens);
kfree(tr->acc_batch.km, read_ptr_acc_batch->qseqs);
}
// After the while loop that moves excess reads to pending
// If we're in GPU mode and acc_batch has sufficient anchors, mark full
if ((s->p->opt->flag & MM_F_GPU_CHAIN) &&
tr->acc_batch.total_n >= s->batch_max_anchors) {
// Anchor threshold reached - mark batch full if we have any reads to dispatch
if (tr->acc_batch.count > 0) {
tr->is_full = 1;
}
}
}
// ============================================================================
// Stage Wrapper Functions for Profiling and Modularity
// ============================================================================
/**
* mm_seg_independent: whether a paired read's segments are mapped *independently*
* (one chain_read_t per segment) rather than as a single joint fragment.
*
* True for --pairing no (MM_F_INDEPEND_SEG) and for weak pairing
* (MM_F_WEAK_PAIRING, under the same gate the mm_map_frag wrapper uses:
* pe_ori >= 0 && CIGAR). Weak pairing maps each mate on its own and then
* re-pairs them with mm_pair in a post-alignment pass (see step 1); --pairing no
* leaves them unpaired. The legacy mm_map_frag wrapper carries this dispatch for
* the public API, but the staged worker pipeline must implement it here.
*/
static inline int mm_seg_independent(const mm_mapopt_t* opt)
{
return (opt->flag & MM_F_INDEPEND_SEG) ||
((opt->flag & MM_F_WEAK_PAIRING) && opt->pe_ori >= 0 && (opt->flag & MM_F_CIGAR));
}
/**
* prepare_read_for_batch: Prepare a single read/fragment for batch processing
* @param s step_t structure with sequence data
* @param i fragment index
* @param read_ptr pointer to chain_read_t to populate
* @param km memory pool for allocations
* @param pe_ori paired-end orientation settings
* @return number of independent reads created (1 for paired, n_seg for independent)
*
* Prepares chain_read_t structures for a fragment. In independent mode (--no-pairing),
* creates separate structures for each segment. In paired mode, creates a single
* structure containing both segments.
*/
static int prepare_read_for_batch(step_t* s, long i, chain_read_t* read_ptr, void* km, int pe_ori)
{
int j, off = s->seg_off[i];
int n_indep_reads = mm_seg_independent(s->p->opt) ? s->n_seg[i] : 1;
if (mm_seg_independent(s->p->opt)) {
// Independent mode: each segment gets its own chain_read_t structure
for (j = 0; j < s->n_seg[i]; ++j) {
read_ptr->qlens = (int*)kmalloc(km, sizeof(int));
read_ptr->qseqs = (const char**)kmalloc(km, sizeof(const char*));
// Apply reverse complement if needed
if (s->n_seg[i] == 2 && ((j == 0 && (pe_ori >> 1 & 1)) || (j == 1 && (pe_ori & 1))))
mm_revcomp_bseq(&s->seq[off + j]);
read_ptr->qlens[0] = s->seq[off + j].l_seq;
read_ptr->qseqs[0] = s->seq[off + j].seq;
read_ptr->n_seg = 1;
read_ptr->seq.i = i;
read_ptr->seq.seg_id = j;
strcpy(read_ptr->seq.name, s->seq[off + j].name);
read_ptr->seq.n_alt = s->p->mi->n_alt;
read_ptr->seq.is_alt = 0;
read_ptr++;
}
} else {
// Paired mode: both segments in single chain_read_t
read_ptr->qlens = (int*)kmalloc(km, s->n_seg[i] * sizeof(int));
read_ptr->qseqs = (const char**)kmalloc(km, s->n_seg[i] * sizeof(const char*));
read_ptr->n_seg = s->n_seg[i];
for (j = 0; j < s->n_seg[i]; ++j) {
if (s->n_seg[i] == 2 && ((j == 0 && (pe_ori >> 1 & 1)) || (j == 1 && (pe_ori & 1))))
mm_revcomp_bseq(&s->seq[off + j]);
read_ptr->qlens[j] = s->seq[off + j].l_seq;
read_ptr->qseqs[j] = s->seq[off + j].seq;
}
read_ptr->seq.i = i;
read_ptr->seq.seg_id = 0;
strcpy(read_ptr->seq.name, s->seq[off].name);
read_ptr->seq.n_alt = s->p->mi->n_alt;
read_ptr->seq.is_alt = 0;
}
return n_indep_reads;
}
/**
* process_seeding_batch: Run seeding stage on prepared reads
* @param s step_t structure
* @param read_ptr pointer to first read (will be decremented)
* @param n_reads number of reads to process
* @param timer pointer to seed timer accumulator
* @param km memory pool
* @param batch batch structure to update anchor counts
*
* Runs mm_map_seed() on each read and updates batch anchor counts.
* Note: read_ptr is expected to point one past the last read (will decrement).
*/
static void process_seeding_batch(step_t* s, chain_read_t* read_ptr, int n_reads,
mm_stage_timer_t* timer, void* km, mm_batch_trbuf_t* batch)
{
for (int j = 0; j < n_reads; j++) {
read_ptr--;
mm_map_seed(s->p->mi, s->p->opt, read_ptr, timer, km, s->p->core_ctx);
batch->total_n += read_ptr->n;
assert(read_ptr->n_mini_pos >= 0);
}
}
/**
* process_chaining_batch_cpu: Run CPU chaining on a batch of reads
* @param s step_t structure
* @param batch batch containing reads to chain
* @param timer pointer to chain timer accumulator
*
* Processes all reads in the batch through CPU chaining (mg_lchain_dp).
*/
static void process_chaining_batch_cpu(step_t* s, mm_batch_trbuf_t* batch, mm_stage_timer_t* timer)
{
for (int iread = 0; iread < batch->count; iread++) {
mm_map_chain(s->p->mi, s->p->opt, &batch->reads[iread], timer, batch->km, s->p->core_ctx);
}
}
#ifdef MM_ENABLE_HIP
/**
* process_chaining_batch_gpu: Run GPU chaining with CPU fallback
* @param s step_t structure
* @param tr thread read buffer with batch pipeline
* @param timer pointer to chain timer accumulator
* @param tid thread ID
* @return 1 if GPU processed batch, 0 if batch was queued
*
* Submits batch to GPU for chaining. Handles the 3-batch pipeline:
* - Submits acc_batch to GPU
* - Retrieves results for launched_batch
* - Rotates batches through pipeline
* Falls back to CPU for reads that don't fit in GPU microbatch.
*/
static int process_chaining_batch_gpu(step_t* s, mm_trbuf_t* tr, mm_stage_timer_t* timer, int tid)
{
const double t_start = realtime();
/* Snapshot before the rotation below moves acc_batch elsewhere. Used as
* n_calls so sum/count stays meaningful on the first submit (when
* launched_batch is still empty). */
const uint64_t n_submitted = (uint64_t)tr->acc_batch.count;
mm_batch_trbuf_t kernel_batch = tr->acc_batch;
gpu_chain_submit(s->p->chain_ctx ? s->p->chain_ctx->gpu_chain : NULL, s->p->mi, s->p->opt, &kernel_batch.reads, &kernel_batch.count, tid, tr->launched_batch.km);
if (kernel_batch.reads) {
// GPU returned results - process any CPU fallback reads
assert(tr->has_launched);
for (; kernel_batch.count < tr->launched_batch.count; kernel_batch.count++) {
mm_log_debug("[gpu-chain] read '%s' exceeded GPU microbatch capacity; chaining on CPU",
kernel_batch.reads[kernel_batch.count].seq.name);
mm_map_chain(s->p->mi, s->p->opt, &kernel_batch.reads[kernel_batch.count], NULL, tr->launched_batch.km, s->p->core_ctx);
}
assert(kernel_batch.count == tr->launched_batch.count);
// Dump GPU chain results for comparison with CPU
for (int i = 0; i < tr->launched_batch.count; i++) {
mm_dump_chains(s->p->core_ctx, tr->launched_batch.reads[i].seq.name,
&tr->launched_batch.reads[i], s->p->mi);
}
// Rotate batches: launched->pending, acc->launched, pending->acc
kernel_batch = tr->launched_batch;
tr->launched_batch = tr->acc_batch;
tr->acc_batch = tr->pending_batch;
tr->pending_batch = kernel_batch;
tr->is_pending = 1;
} else {
// No results yet - just rotate
assert(!tr->has_launched);
kernel_batch = tr->launched_batch;
tr->launched_batch = tr->acc_batch;
tr->acc_batch = tr->pending_batch;
tr->pending_batch = kernel_batch;
tr->is_pending = 0;
}
tr->is_full = 0;
tr->has_launched = 1;