Skip to content

Instantly share code, notes, and snippets.

@mcgrof
Last active October 29, 2025 21:39
Show Gist options
  • Select an option

  • Save mcgrof/5b9207cb6efafe0ab4060046969c9667 to your computer and use it in GitHub Desktop.

Select an option

Save mcgrof/5b9207cb6efafe0ab4060046969c9667 to your computer and use it in GitHub Desktop.
Mini Modular Mojo GPU/CPU compute kernel with adaptive mesh support
# GPU/CPU compute kernel snippet example as a concept sketch of a
# Modular Mojo GPU/CPU compute kernel if you were designing a
# mesh-like data structure that supports dynamic
# topologies (nodes appearing, disappearing, remapping).
struct Mesh {
ids: NDArray[i64] # dense iteration order → stable id
id_to_slot: NDArray[i32] # stable id → slot in SoA buffers (or -1 if dead)
# SoA fields (slots are dense/compact within an epoch)
rho: NDArray[f32]
u: NDArray[f32]
v: NDArray[f32]
# adjacency in CSR over stable ids
nbr_offsets: NDArray[i64] # len = num_ids+1
nbr_ids: NDArray[i64] # concatenated neighbor ids
epoch: i64
}
@kernel
fn build_alive_mask(id_to_slot: NDArray[i32], alive: NDArray[i32]):
parfor i in range(id_to_slot.len()):
alive[i] = 1 if id_to_slot[i] >= 0 else 0
@kernel
fn remap_fields(
old_to_new_slot: NDArray[i32],
rho_old: NDArray[f32], rho_new: NDArray[f32]
):
parfor old_slot in range(rho_old.len()):
let ns = old_to_new_slot[old_slot]
if ns >= 0:
rho_new[ns] = rho_old[old_slot]
# adjacency rebuild (given updated id_to_slot)
@kernel
fn rebuild_csr(
ids: NDArray[i64],
nbr_offsets_old: NDArray[i64], nbr_ids_old: NDArray[i64],
id_to_slot: NDArray[i32],
nbr_offsets_new: NDArray[i64], nbr_ids_new: NDArray[i64]
):
parfor row in range(ids.len()):
let id = ids[row]
let start = nbr_offsets_old[row]
let end = nbr_offsets_old[row+1]
var out = nbr_offsets_new[row]
for k in range(start, end):
let nid = nbr_ids_old[k]
if id_to_slot[nid] >= 0: # neighbor still alive
nbr_ids_new[out] = nid
out += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment