Skip to content

Ib collision optimization - #2201

Merged
sbryngelson merged 5 commits into
MFlowCode:masterfrom
danieljvickers:IB-collision-optimization
Nov 21, 2026
Merged

sbryngelson merged 5 commits into
MFlowCode:masterfrom
danieljvickers:IB-collision-optimization

Conversation

@danieljvickers

Copy link
Copy Markdown
Member

The collision optimization currently works fantastic in dilute particle suspensions, where the true number of collisions is quite low. There is a host-side deduplication loop that is sufficient when parsing 10s-100s of collision entries in the LUT. In dense suspensions, is quickly devolves into a host-side O($$N^2$$) detection, which I determined to actually be slower overall in this edge case. In our stress tests up until now, this was not tested when the list holds 100's of thousands of particle collision pairs. I have swapped the deduplication to a device-side version which maintains the per-particle filter, but runs 100x faster.

Below is shown a cae with a lop-sided distribution of particles in a sense suspension and the time spent per time step comparing the two LUTs on master and this branch.

image

@github-actions

github-actions Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Claude Code Review

Head SHA: 7aa71ca

Files changed:

  • 1
  • src/simulation/m_collisions.fpp

Findings:
No issues found. Checked in step 4: src/simulation/m_collisions.fpp (the callee routines s_decode_patch_periodicity and s_get_neighborhood_idx in m_ib_patches.fpp are GPU_ROUTINE seq, so the device-side calls are valid; bit-clear and allocate/deallocate pairing are consistent; collision_lookup is now only read on the device after being written on the device).

@sbryngelson
sbryngelson marked this pull request as ready for review November 19, 2026 15:58
@sbryngelson
sbryngelson requested a review from a team as a code owner November 19, 2026 15:58
@sbryngelson
sbryngelson requested review from sbryngelson and removed request for a team November 19, 2026 15:58
@sbryngelson

Copy link
Copy Markdown
Member

Review of the full diff, read against the helpers it calls in master. I did not build or run it.

Main point: the bitset is a fixed size and grows quadratically with the cap

pair_bits holds one bit per unordered pair over num_local_ibs_max, so its size is N(N-1)/2 bits, set by the compile-time cap and not by the run:

num_local_ibs_max Bits Memory (host and device, each)
30000 (today) 4.5e8 56 MB
100000 5.0e9 625 MB
300000 4.5e10 5.6 GB

Consequences:

  • Every run with collision_model > 0 pays the full 56 MB on the host and again on the GPU, even with two bodies.
  • The cost of raising the cap is hidden here. Someone who bumps num_local_ibs_max for a larger suspension will get a quadratic jump in memory per rank with nothing pointing at this array.
  • word = int(idx/32) + 1 is a default integer, so the word index overflows once the cap passes about 3.7e5.

The number of real contacts is linear in the body count (collision_lookup already assumes a bounded number per body), so a quadratic structure is more than the problem needs. Options, in order of effort:

  1. Size the bitset from the rank's actual body count (num_ibs, local plus neighborhood) and regrow when that grows. Same code, memory follows the run.
  2. Keep the cap-sized bitset but say so in a comment next to num_local_ibs_max in m_constants.fpp, with the table above, and abort at start-up if the allocation would exceed some limit.
  3. Replace it with a per-body claim list (a few slots per body, claimed with compare-and-swap) or a sort-and-unique pass on the device. Linear memory.

I'd take option 1 at least before merging.

What it does

s_detect_ib_collisions finds candidate IB pairs from ghost points on the GPU and used a host loop to drop duplicates. That loop is quadratic in the number of candidates. This PR moves the deduplication to the device: each candidate sorts its pair and claims that pair's bit with an atomic OR, only the thread that flips the bit appends to collision_lookup, and s_clear_pair_bits zeroes the touched words after the forces.

Correctness: looks right

  • Same pair set as master. The candidate rule is unchanged (first marker of another patch in the 5-cell cube), self-pairs are still skipped, and pairs are still keyed on the sorted neighborhood indices.
  • Index bounds hold. s_get_neighborhood_idx returns a patch_ib slot, so a and b stay within num_local_ibs_max, and the allocation matches the largest index.
  • The claim is race-free. The capture reads the old word and ORs in one atomic step, so two threads cannot both win a pair, and two pairs sharing a word do not interfere.
  • Clearing whole words is valid. Every set bit belongs to a recorded pair. Several iterations may zero the same word at once, which is harmless.
  • The helpers are device routines. s_get_neighborhood_idx (a binary search) and s_decode_patch_periodicity are both GPU_ROUTINE.

Other points

  1. Not yet run on the Frontier or Phoenix GPU lanes. CI shows 27 passes, all GitHub-hosted. The atomic capture with ior on an array element is worth seeing compile and run under amdflang and Cray OpenMP offload before merging.
  2. It conflicts with Integrate collisions #2171. Both rewrite s_apply_collision_forces and the detection routine in this file. Whichever merges second needs a rebase, and in Integrate collisions #2171's structure the pair_bits allocation belongs under if (ib).
  3. No test for the dense case. The existing collision goldens cover the function and the pair set is unchanged, so I expect them to pass. The 100x figure rests on the plot in the description.

Minor

  • slot is both the swap temporary and the lookup slot; a separate temporary would read better.
  • The periodic image stored for a pair comes from whichever thread claims it. The comment notes this only matters in a domain about two particles across.
  • Pair order in the lookup is nondeterministic, as it already was on master, so forces can differ at roundoff between identical GPU runs.

Summary

A sound change with a clear benefit, and I found no bug. Before merging I'd want the bitset sized from the run (or the quadratic cost documented), and the self-hosted GPU lanes run.

Review written with Claude Code (AI-assisted).

@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.08333% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.75%. Comparing base (750c46a) to head (7daede8).
⚠️ Report is 40 commits behind head on master.

Files with missing lines Patch % Lines
src/simulation/m_collisions.fpp 77.08% 3 Missing and 8 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #2201      +/-   ##
==========================================
- Coverage   65.79%   65.75%   -0.05%     
==========================================
  Files         111      111              
  Lines       30092    30496     +404     
  Branches     4582     4666      +84     
==========================================
+ Hits        19799    20052     +253     
- Misses       6609     6689      +80     
- Partials     3684     3755      +71     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@danieljvickers

Copy link
Copy Markdown
Member Author

@sbryngelson I added option 1. Option 3 sounds better than it is, because it can result in many missed collisions. Our detection needs to be perfect for stability, so I have a dynamic setting for now. There is a world where the answer to all of our problems here is a nearest neighbor list, which would conveniently work with EL particles/bubbles as well. I would be interested to see what @thierrydaoud plans to add for those optimizations. Perhaps we can test both and see. I think this is important to merge for now, and then we can look into a proper refactor later in a way that avoids all of it.

@github-actions

Copy link
Copy Markdown

Lines of Code

File Lines Diff
src/simulation/m_collisions.fpp 338 +25
Directory Lines Diff
simulation 40305 +25
total 60291 +25

@sbryngelson

Copy link
Copy Markdown
Member

@danieljvickers thanks for sizing the bitset from the run and making the index 64-bit; that settles the main point of the earlier review, and all the Frontier GPU lanes passed. Merging.

One thing to keep in mind afterwards, not a blocker: s_resize_pair_bits deallocates and reallocates pair_bits when num_ibs outgrows pair_bits_capacity, and pair_bits is a GPU_DECLARE(create=...) array. Two comments in m_ibm.fpp (lines 222 and 334 on master) say such arrays are allocated once because a reallocation corrupts the Cray present table; the AMR side works around it with move_alloc plus GPU_ENTER_DATA. The regrow path only runs when the body count on a rank more than doubles, so I doubt any test reaches it (Codecov reports 11 uncovered lines in the patch; I did not check that they are these). If you have a case where bodies migrate heavily between ranks, it would be worth running it once under Cray offload on Frontier, or sizing the bitset once at start-up from the global body count.

Also a reminder that this and #2171 both rewrite the detection and force routines in m_collisions.fpp, so #2171 will need a rebase.

Written with Claude Code (AI-assisted); read from the diff, not run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants