Compare commits

..
Author SHA1 Message Date
ClaudeandClaude Opus 5.5 1cbdc479cf test_block_step_sync: locate block_stepper without importing it
The module-level import of CelerisLab.lbm.block_stepper loaded
pycuda.driver into the shared test process, unlike the other CPU host
tests (which load mocked copies via AST). find_spec gives the source path
without the import. Test content and assertions unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 01:39:52 +00:00
15 changed files with 62 additions and 61 deletions

No files matched your search

+2 -2
View File
@@ -90,8 +90,8 @@ def main():
# The caller owns the CUDA context; the stepper must be closed first (the # The caller owns the CUDA context; the stepper must be closed first (the
# nested with-statement does that). # nested with-statement does that).
with CudaContext(0) as context, FixedPatchStepper( with CudaContext(0) as context, FixedPatchStepper(
cfg, context=context, coarse_boundary=args.mode, refinements=[BOUNDS], cfg, BOUNDS, context=context, coarse_boundary=args.mode,
level_blocks=[None, fine_block], level_objects=[(), (body,)]) as run: fine_objects=[body], fine_block=fine_block) as run:
p = run.patch p = run.patch
# Rest equilibrium is already postcollision G, so no initial collision is # Rest equilibrium is already postcollision G, so no initial collision is
# needed. Non-leaf entries (covered, ghost, solid) are discarded by initialize. # needed. Non-leaf entries (covered, ghost, solid) are discarded by initialize.
+2 -2
View File
@@ -148,8 +148,8 @@ def main():
samples=[], status='running', last_synchronized_coarse_step=0) samples=[], status='running', last_synchronized_coarse_step=0)
start, run = time.monotonic(), None start, run = time.monotonic(), None
try: try:
with CudaContext(0) as context, FixedPatchStepper(cfg, context=context, with CudaContext(0) as context, FixedPatchStepper(cfg, BOUNDS, context=context,
coarse_boundary='slot_reservoir', refinements=[BOUNDS]) as run: coarse_boundary='slot_reservoir') as run:
p = run.patch p = run.patch
masks = [np.ones(p.coarse_shape, bool), p.fine_kind == ACTIVE] masks = [np.ones(p.coarse_shape, bool), p.fine_kind == ACTIVE]
masks[0][[0, -1]] = False masks[0][[0, -1]] = False
+1 -1
View File
@@ -48,7 +48,7 @@ def main():
nx=16, ny=16, viscosity=.1, velocity=1e-3, rho=1.0, nx=16, ny=16, viscosity=.1, velocity=1e-3, rho=1.0,
lattice_model="D2Q9", collision="SRT", streaming="double_buffer", lattice_model="D2Q9", collision="SRT", streaming="double_buffer",
store_precision="FP32", ddf_shifting=False, les_enabled=False) store_precision="FP32", ddf_shifting=False, les_enabled=False)
with CudaContext(0) as context, PeriodicPatchStepper(cfg, context=context, refinements=[(4, 4, 12, 12)]) as run: with CudaContext(0) as context, PeriodicPatchStepper(cfg, (4, 4, 12, 12), context=context) as run:
p = run.patch p = run.patch
coarse = shear_equilibrium(p.coarse_shape, (0, 0), 1.0, cfg.ny) coarse = shear_equilibrium(p.coarse_shape, (0, 0), 1.0, cfg.ny)
fine = shear_equilibrium(p.fine_shape, p.fine_origin, .5, cfg.ny) fine = shear_equilibrium(p.fine_shape, p.fine_origin, .5, cfg.ny)
+4 -3
View File
@@ -670,9 +670,10 @@ class FixedPatchStepper:
old, new, source, base_count=count, level_steps=(count, 2*count, 4*count), old, new, source, base_count=count, level_steps=(count, 2*count, 4*count),
phase="postcollision_g", **options) phase="postcollision_g", **options)
candidate = type(self)( candidate = type(self)(
cfg, context=self.ctx, refinements=[pairs[0].bounds, new.child.bounds], cfg, pairs[0].bounds, context=self.ctx, base_block=base_block,
level_blocks=[base_block, fine_block, child_block], fine_block=fine_block, child_block=child_block,
level_objects=[(), (), child_objects], level_jets=[(), (), jets], child_rectangles_in_parent=new.child.bounds,
child_objects=child_objects, child_jets=jets,
observe_raw_exchange=self._observe_raw_exchange, observe_raw_exchange=self._observe_raw_exchange,
observe_window_exchange=self._observe_window, explosion=self._explosion) observe_window_exchange=self._observe_window, explosion=self._explosion)
try: try:
+4 -2
View File
@@ -1,6 +1,7 @@
"""Host contract of PeriodicBlockStepper.step(n): one stream wait per call (mocked driver).""" """Host contract of PeriodicBlockStepper.step(n): one stream wait per call (mocked driver)."""
import ast import ast
from contextlib import nullcontext from contextlib import nullcontext
import importlib.util
from pathlib import Path from pathlib import Path
import types import types
from unittest.mock import Mock from unittest.mock import Mock
@@ -8,14 +9,15 @@ import unittest
import numpy as np import numpy as np
import CelerisLab.lbm.block_stepper as b
from CelerisLab.config import LBMConfig from CelerisLab.config import LBMConfig
from CelerisLab.lbm.blocks import BlockLayout2D from CelerisLab.lbm.blocks import BlockLayout2D
def host_module(): def host_module():
"""block_stepper with pycuda/compiler replaced by mocks; no GPU context.""" """block_stepper with pycuda/compiler replaced by mocks; no GPU context."""
path = Path(b.__file__) # Locate the source without importing it: importing block_stepper loads pycuda.driver,
# which CPU-only import-boundary tests (test_build_contracts) must never see.
path = Path(importlib.util.find_spec("CelerisLab.lbm.block_stepper").origin)
tree = ast.parse(path.read_text()) tree = ast.parse(path.read_text())
tree.body = [node for node in tree.body if not ( tree.body = [node for node in tree.body if not (
isinstance(node, ast.Import) and any(a.name == "pycuda.driver" for a in node.names) isinstance(node, ast.Import) and any(a.name == "pycuda.driver" for a in node.names)
+2 -2
View File
@@ -80,8 +80,8 @@ def test_evolved_ghost_snapshot_and_physical_download():
host.cuda.memcpy_dtoh.side_effect = lambda a, ptr: np.copyto(a, storage[id(ptr)]) host.cuda.memcpy_dtoh.side_effect = lambda a, ptr: np.copyto(a, storage[id(ptr)])
context = Mock(activate=nullcontext, sm_arch="sm_70") context = Mock(activate=nullcontext, sm_arch="sm_70")
cfg = LBMConfig(nx=24, ny=20, viscosity=.1, velocity=.025) cfg = LBMConfig(nx=24, ny=20, viscosity=.1, velocity=.025)
backend = host.FixedPatchStepper(cfg, context=context, coarse_boundary="channel", backend = host.FixedPatchStepper(cfg, (6, 6, 18, 14), context=context,
refinements=[(6, 6, 18, 14)], level_blocks=[(4, 6), (4, 4)]) coarse_boundary="channel", base_block=(4, 6), fine_block=(4, 4))
try: try:
weights = np.array([4/9]+[1/9]*4+[1/36]*4)[:, None, None] weights = np.array([4/9]+[1/9]*4+[1/36]*4)[:, None, None]
arrays = [np.broadcast_to(weights, level.shape).copy() for level in backend._levels] arrays = [np.broadcast_to(weights, level.shape).copy() for level in backend._levels]
+2 -3
View File
@@ -157,9 +157,8 @@ class RawExchange(unittest.TestCase):
host = host_module() host = host_module()
ctx = Mock() ctx = Mock()
with self.assertRaisesRegex(ValueError, 'blocked body'): with self.assertRaisesRegex(ValueError, 'blocked body'):
host.FixedPatchStepper(LBMConfig(nx=32, ny=32, viscosity=.1), context=ctx, host.FixedPatchStepper(LBMConfig(nx=32, ny=32, viscosity=.1), (4, 4, 28, 28),
refinements=[(4, 4, 28, 28)], context=ctx, fine_objects=[body(radius=2.15)], observe_raw_exchange=True)
level_objects=[(), (body(radius=2.15),)], observe_raw_exchange=True)
ctx.activate.assert_not_called() ctx.activate.assert_not_called()
def test_all_depth_weights(self): def test_all_depth_weights(self):
@@ -173,10 +173,8 @@ def bodies_and_jets(speed=.002):
return bodies,jets return bodies,jets
def levels(parents=PARENTS,children=CHILDREN,blocks=((4,4),)*3,objects=((),(),()),jets=((),(),())): KW=dict(base_block=(4,4),fine_block=(4,4),child_block=(4,4),
"""Level-list constructor keywords for the L0 set, L1 set and L2 set used here.""" child_rectangles_in_parent=CHILDREN)
return dict(refinements=[parents,children],level_blocks=list(blocks),
level_objects=list(objects),level_jets=list(jets))
def mock_backend(*, children=CHILDREN, bodies=False, fail_compile=False, fail_upload=False): def mock_backend(*, children=CHILDREN, bodies=False, fail_compile=False, fail_upload=False):
@@ -203,8 +201,9 @@ def mock_backend(*, children=CHILDREN, bodies=False, fail_compile=False, fail_up
module.cuda.memcpy_htod.side_effect=upload module.cuda.memcpy_htod.side_effect=upload
objects,jets=bodies_and_jets() if bodies else ((),()) objects,jets=bodies_and_jets() if bodies else ((),())
try: try:
run=module.FixedPatchStepper(CFG,context=context, run=module.FixedPatchStepper(CFG,PARENTS,context=context,
**levels(children=children,objects=((),(),objects),jets=((),(),jets))) child_objects=objects,child_jets=jets,
**dict(KW,child_rectangles_in_parent=children))
except RuntimeError: except RuntimeError:
for allocation in allocations: for allocation in allocations:
allocation.free.assert_called_once_with() allocation.free.assert_called_once_with()
@@ -215,29 +214,28 @@ def mock_backend(*, children=CHILDREN, bodies=False, fail_compile=False, fail_up
class ConstructorAndSchedule(unittest.TestCase): class ConstructorAndSchedule(unittest.TestCase):
def test_invalid_inputs_fail_before_context_or_allocations(self): def test_invalid_inputs_fail_before_context_or_allocations(self):
context=Mock() context=Mock()
b=(4,4) cases=[dict(child=(8,8,16,16)),dict(child_rectangles_in_parent=[]),
cases=[dict(children=(8,8,16,16)),dict(children=[]), dict(child_rectangles_in_parent=[(16,16,32)]),
dict(children=[(16,16,32)]), dict(child_rectangles_in_parent=[(16.5,16,32,40)]),
dict(children=[(16.5,16,32,40)]), dict(child_rectangles_in_parent=[(16,16,32,24),(16,27,32,55)]),
dict(children=[(16,16,32,24),(16,27,32,55)]), dict(child_rectangles_in_parent=[(40,16,48,40)]),
dict(children=[(40,16,48,40)]), dict(child_rectangles_in_parent=[(8,16,32,40)]),
dict(children=[(8,16,32,40)]), dict(child_block=None),dict(fine_block=None),dict(base_block=None),
dict(blocks=(b,b,None)),dict(blocks=(b,None,b)),dict(blocks=(None,b,b)), dict(child_block=(5,4)),dict(fine_block=(5,4)),
dict(blocks=(b,b,(5,4))),dict(blocks=(b,(5,4),b)), dict(child_block=(4,)),dict(child_rectangles_in_parent=(16,16,32,40))]
dict(blocks=(b,b,(4,))),dict(children=(16,16,32,40))]
for changes in cases: for changes in cases:
with self.subTest(changes=changes),self.assertRaises((ValueError,TypeError)): with self.subTest(changes=changes),self.assertRaises((ValueError,TypeError)):
host.FixedPatchStepper(CFG,context=context,**levels(**changes)) host.FixedPatchStepper(CFG,PARENTS,context=context,**dict(KW,**changes))
with self.assertRaisesRegex(ValueError,'margin'): with self.assertRaisesRegex(ValueError,'margin'):
host.FixedPatchStepper(CFG,context=context,**levels(parents=[(1,4,20,28),(23,4,44,28)])) host.FixedPatchStepper(CFG,[(1,4,20,28),(23,4,44,28)],context=context,**KW)
objects,jets=bodies_and_jets() objects,jets=bodies_and_jets()
with self.assertRaisesRegex(ValueError,'only on the finest level'): with self.assertRaisesRegex(ValueError,'only on L2'):
host.FixedPatchStepper(CFG,context=context,**levels(objects=((),objects,()))) host.FixedPatchStepper(CFG,PARENTS,context=context,fine_objects=objects,**KW)
from CelerisLab.body.jets import Jet,Tube,Parallel from CelerisLab.body.jets import Jet,Tube,Parallel
spanning=Jet(Tube((10.5,14.),0.,25.,.3),Parallel(0.),amplitude=0.) spanning=Jet(Tube((10.5,14.),0.,25.,.3),Parallel(0.),amplitude=0.)
with self.assertRaisesRegex(ValueError,'one jet'): with self.assertRaisesRegex(ValueError,'one jet'):
host.FixedPatchStepper(CFG,context=context, host.FixedPatchStepper(CFG,PARENTS,context=context,child_objects=objects,
**levels(objects=((),(),objects),jets=((),(),[spanning]))) child_jets=[spanning],**KW)
context.activate.assert_not_called() context.activate.assert_not_called()
host.cuda.mem_alloc.assert_not_called() host.cuda.mem_alloc.assert_not_called()
+6 -5
View File
@@ -54,13 +54,14 @@ class ShiftedJets(unittest.TestCase):
(Jet(Tube((10.,14.),0.,26.,.3),Parallel(0.)),))] (Jet(Tube((10.,14.),0.,26.,.3),Parallel(0.)),))]
for objects,jets in cases: for objects,jets in cases:
with self.subTest(objects=len(objects),jets=len(jets)),self.assertRaises(ValueError): with self.subTest(objects=len(objects),jets=len(jets)),self.assertRaises(ValueError):
module.FixedPatchStepper(CFG,context=None,refinements=[backend.PARENTS,A], module.FixedPatchStepper(CFG,backend.PARENTS,context=None,
level_blocks=[(4,4)]*3,level_objects=[(),(),objects],level_jets=[(),(),jets]) base_block=(4,4),fine_block=(4,4),child_block=(4,4),
child_rectangles_in_parent=A,child_objects=objects,child_jets=jets)
for blocks in ((None,None,None),((4,4),None,(4,4))): for blocks in ((None,None,None),((4,4),None,(4,4))):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
module.FixedPatchStepper(CFG,context=None,refinements=[backend.PARENTS,A], module.FixedPatchStepper(CFG,backend.PARENTS,context=None,
level_blocks=list(blocks),level_objects=[(),(),(body(),)], base_block=blocks[0],fine_block=blocks[1],child_block=blocks[2],
level_jets=[(),(),(jet(),)]) child_rectangles_in_parent=A,child_objects=(body(),),child_jets=(jet(),))
module.cuda.mem_alloc.assert_not_called() module.cuda.mem_alloc.assert_not_called()
module.compiler.compile_kernel.assert_not_called() module.compiler.compile_kernel.assert_not_called()
+3 -4
View File
@@ -129,10 +129,9 @@ class ShiftedStorage(unittest.TestCase):
def test_dense_or_mixed_shifted_rejected_before_compilation(self): def test_dense_or_mixed_shifted_rejected_before_compilation(self):
module=backend.host_module() module=backend.host_module()
cfg=replace(backend.CFG,ddf_shifting=True) cfg=replace(backend.CFG,ddf_shifting=True)
for blocks in ([None,None],[(4,4),None],[None,(4,4)]): for kwargs in ({},dict(base_block=(4,4)),dict(fine_block=(4,4))):
with self.assertRaisesRegex(ValueError,'all-blocked|blocked refined levels below'): with self.assertRaisesRegex(ValueError,'all-blocked|base_block requires fine_block'):
module.FixedPatchStepper(cfg,context=None,refinements=[(4,4,20,28)], module.FixedPatchStepper(cfg,(4,4,20,28),context=None,**kwargs)
level_blocks=blocks)
module.compiler.compile_kernel.assert_not_called() module.compiler.compile_kernel.assert_not_called()
def test_uniform_block_codec_and_raw_snapshot(self): def test_uniform_block_codec_and_raw_snapshot(self):
+2 -2
View File
@@ -126,8 +126,8 @@ def run_case(a, h, case):
cfg, pair, body, host = rr.host_geometry(a.source, h, a.collision) cfg, pair, body, host = rr.host_geometry(a.source, h, a.collision)
context = stack.enter_context(CudaContext(0)) context = stack.enter_context(CudaContext(0))
backend = stack.enter_context(FixedPatchStepper( backend = stack.enter_context(FixedPatchStepper(
cfg, context=context, coarse_boundary="channel", refinements=[rr.PLACEMENTS["wide"]], cfg, rr.PLACEMENTS["wide"], context=context, coarse_boundary="channel",
level_blocks=[rr.BASE_BLOCK, rr.FINE_BLOCK], level_objects=[(), (body,)], base_block=rr.BASE_BLOCK, fine_block=rr.FINE_BLOCK, fine_objects=(body,),
observe_raw_exchange=True, observe_window_exchange=True)) observe_raw_exchange=True, observe_window_exchange=True))
from CelerisLab.lbm.channel import channel_masks from CelerisLab.lbm.channel import channel_masks
from CelerisLab.lbm.refinement import ACTIVE from CelerisLab.lbm.refinement import ACTIVE
+5 -4
View File
@@ -279,11 +279,12 @@ def run_case(c, ctx, output, provenance, continuation=False):
PeriodicBlockStepper(fine_cfg, layout, context=ctx, objects=[fobj]) as uniform, PeriodicBlockStepper(fine_cfg, layout, context=ctx, objects=[fobj]) as uniform,
FixedPatchStepper( FixedPatchStepper(
cfg, cfg,
c["bounds"],
context=ctx, context=ctx,
refinements=[c["bounds"]], base_block=(8, 8),
level_blocks=[(8, 8), (8, 8)], fine_block=(8, 8),
level_objects=[(), (obj,)], fine_objects=[obj],
level_jets=[(), tuple(jets)], jets=jets,
observe_raw_exchange=True, observe_raw_exchange=True,
) as amr, ) as amr,
): ):
+5 -4
View File
@@ -383,12 +383,13 @@ def run_case(a, h, periodic, case):
backend = stack.enter_context( backend = stack.enter_context(
FixedPatchStepper( FixedPatchStepper(
cfg, cfg,
PLACEMENTS[a.placement],
context=context, context=context,
coarse_boundary="channel", coarse_boundary="channel",
refinements=[PLACEMENTS[a.placement]], base_block=BASE_BLOCK,
level_blocks=[BASE_BLOCK, FINE_BLOCK], fine_block=FINE_BLOCK,
level_objects=[(), (body,)], fine_objects=(body,),
level_jets=[(), public_jets((80.5, 81.0), 20.0, a.jet_scenario)], jets=public_jets((80.5, 81.0), 20.0, a.jet_scenario),
observe_raw_exchange=True, observe_raw_exchange=True,
**({"observe_window_exchange": True} if a.observation_mode == "window" else {}), **({"observe_window_exchange": True} if a.observation_mode == "window" else {}),
) )
+2 -3
View File
@@ -173,9 +173,8 @@ def time_refined(a, h, sched):
cfg, pair, body, host = r.host_geometry(a.source, h, "MRT") cfg, pair, body, host = r.host_geometry(a.source, h, "MRT")
context = stack.enter_context(CudaContext(0)) context = stack.enter_context(CudaContext(0))
backend = stack.enter_context(FixedPatchStepper( backend = stack.enter_context(FixedPatchStepper(
cfg, context=context, coarse_boundary="channel", refinements=[r.BOUNDS], cfg, r.BOUNDS, context=context, coarse_boundary="channel", base_block=r.BASE_BLOCK,
level_blocks=[r.BASE_BLOCK, r.FINE_BLOCK], level_objects=[(), (body,)], fine_block=r.FINE_BLOCK, fine_objects=(body,), observe_raw_exchange=True))
observe_raw_exchange=True))
masks = [channel_masks(pair.coarse_shape)[0] & ~pair.covered, # as run_refined_dfg masks = [channel_masks(pair.coarse_shape)[0] & ~pair.covered, # as run_refined_dfg
(pair.fine_kind == ACTIVE) & ((host.flags.reshape(pair.fine_shape) & SOLID) == 0)] (pair.fine_kind == ACTIVE) & ((host.flags.reshape(pair.fine_shape) & SOLID) == 0)]
fresh = (r.initial_state(pair.coarse_shape, (0.0, 0.0), 1.0, root=True), fresh = (r.initial_state(pair.coarse_shape, (0.0, 0.0), 1.0, root=True),
+2 -2
View File
@@ -130,8 +130,8 @@ def main():
cfg, pair, body, host = r.host_geometry(a.source, h, "MRT") cfg, pair, body, host = r.host_geometry(a.source, h, "MRT")
context = stack.enter_context(CudaContext(0)) context = stack.enter_context(CudaContext(0))
backend = stack.enter_context(FixedPatchStepper( backend = stack.enter_context(FixedPatchStepper(
cfg, context=context, coarse_boundary="channel", refinements=[r.BOUNDS], cfg, r.BOUNDS, context=context, coarse_boundary="channel", base_block=r.BASE_BLOCK,
level_blocks=[r.BASE_BLOCK, r.FINE_BLOCK], level_objects=[(), (body,)], observe_raw_exchange=True, fine_block=r.FINE_BLOCK, fine_objects=(body,), observe_raw_exchange=True,
observe_window_exchange=True)) observe_window_exchange=True))
masks = [channel_masks(pair.coarse_shape)[0] & ~pair.covered, masks = [channel_masks(pair.coarse_shape)[0] & ~pair.covered,
(pair.fine_kind == ACTIVE) & ((host.flags.reshape(pair.fine_shape) & SOLID) == 0)] (pair.fine_kind == ACTIVE) & ((host.flags.reshape(pair.fine_shape) & SOLID) == 0)]