Multibox resident timesteps and continuation
Multibox resident timesteps and continuation
Section titled “Multibox resident timesteps and continuation”Why can a quantity called a conservation residual change even when the model is working as configured? This example makes gas replacement and particle loss visible alongside resident ownership. It is intended for readers examining the low-level scheduler; begin with session ownership or use the prepared interface for a study.
The three boxes have volumes 1, 2, and 3 m³ and prescribed gas densities 0.25, 0.5, and 0.75 kg m⁻³. The sole lane is named water but uses an illustrative constant pure vapor pressure of 800 Pa. These are test inputs, not a calibrated water-cloud state. The request builds dependencies, binds physical state and scratch arrays, then observes diagnostics after two one-second steps.
Run the complete low-level resident schedule across three heterogeneous
boxes, inspect CPU diagnostics, and explicitly resume a checkpoint.
Run with --cuda to reproduce the saved figures. CUDA is required
for publication; unavailable hardware never becomes a successful GPU run.
Python · section 1
"""Run a complete multi-box GPU-resident scheduler example.
Warp and the concrete resident seams are optional at import time. When Warp isenabled, this example uploads primary CPU state once during setup, stagesper-request gas and environment forcing, runs two resident timesteps, observescaller-owned diagnostics, then manually checkpoints and restarts on the samedevice. It is a bounded resident-loop example, not a CPU fallback,automatic restart facility, direct-kernel orchestration, graph-capture example,or performance claim."""
from __future__ import annotations
import importlibimport osfrom dataclasses import dataclassfrom types import SimpleNamespacefrom typing import Any
import numpy as npfrom particula.gas import EnvironmentData, GasDatafrom particula.particles import ParticleData
_FORCE_NO_WARP_ENV = "PARTICULA_EXAMPLE_FORCE_NO_WARP"_NODE_IDS = ( "communication", "volume_evolution", "environment_update", "gas_update", "vapor_pressure_refresh", "saturation_refresh", "condensation", "brownian_coagulation", "dilution", "wall_loss", "nucleation", "diagnostics",)
@dataclassclass ExampleRun: """Retain address-free observations from the resident-loop example.
Attributes: output: Deterministic status and ownership statements. session: Source resident session, or ``None`` without Warp. registry: Source registry, or ``None`` without Warp. guard: Source closed step guard, or ``None`` without Warp. checkpoint: Active source checkpoint created before restart. restarted: Fresh restarted ``(session, registry, guard)`` binding. terminal_checkpoint: Cached checkpoint from source finalization. gas_snapshot: Caller-owned gas diagnostic with shape ``(3, 1)``. saturation_snapshot: Caller-owned saturation diagnostic with shape ``(3, 1)``. initial_total_mass: Initial particle-plus-gas extensive inventory. conservation_residual: Net change against that inventory with zero source/sink ledgers. Prescribed gas and wall removal make this an open system; this diagnostic is not closed-system conservation. restart_gas_before_physics: Restarted gas observed before dispatch. restart_temperature_before_physics: Restarted temperature observed before dispatch. source_steps: Completed source scheduler steps. restarted_steps: Completed restarted scheduler steps. """
output: list[str] session: Any | None = None registry: Any | None = None guard: Any | None = None checkpoint: Any | None = None restarted: tuple[Any, Any, Any] | None = None terminal_checkpoint: Any | None = None gas_snapshot: np.ndarray | None = None saturation_snapshot: np.ndarray | None = None initial_total_mass: np.ndarray | None = None conservation_residual: np.ndarray | None = None restart_gas_before_physics: np.ndarray | None = None restart_temperature_before_physics: np.ndarray | None = None source_steps: int = 0 restarted_steps: int = 0
def _warp_enabled() -> bool: """Return whether optional Warp is explicitly enabled and importable.""" if os.getenv(_FORCE_NO_WARP_ENV) == "1": return False try: importlib.import_module("warp") except ModuleNotFoundError as error: if error.name == "warp": return False raise return True
def _disabled_output() -> list[str]: """Return deterministic guidance for the intentional no-Warp path.""" return [ "Canonical path: docs/examples/gpu/resident/gpu_resident_multi_timestep.py", "Warp is unavailable or disabled; install warp-lang or enable Warp.", "No CPU fallback ran; no fixture, upload, diagnostics, or restart ran.", ]
def _load_enabled_runtime() -> SimpleNamespace: """Load Warp and concrete resident seams only for enabled execution.""" names = ( "warp", "particula.execution", "particula.execution.availability", "particula.execution.gpu_session", "particula.execution.gpu_resources", "particula.execution.checkpoint", "particula.execution.process_graph", "particula.execution.scheduler", "particula.execution.resident_scheduler", "particula.execution.diagnostics", "particula.execution.state_updates", "particula.execution.process_adapters", "particula.execution.communication", "particula.execution.resident_communication", "particula.execution.adapters.condensation", "particula.execution.adapters.coagulation", "particula.gpu.kernels.thermodynamics", "particula.gpu.kernels.wall_loss", "particula.gpu.kernels.nucleation", ) loaded = { name.rsplit(".", 1)[-1]: importlib.import_module(name) for name in names } return SimpleNamespace(**loaded)
def _build_cpu_state() -> tuple[ParticleData, GasData, EnvironmentData]: """Build three native resolved boxes for one explicit source upload.
Preserve total number densities 1.5, 3 and 4.5 m⁻³, using equal counts within each box as required by native coagulation. The former unequal slot weights were unsupported. Stored counts are density times volume; this fixture illustrates ownership and is not a calibrated population. Wall loss uses resolved stochastic survival, matching the population tag, rather than the former untagged density-style decay configuration. """ return ( ParticleData( masses=np.array( [ [[1.0e-18], [2.0e-18]], [[3.0e-18], [4.0e-18]], [[5.0e-18], [6.0e-18]], ], dtype=np.float64, ), concentration=np.array( [[0.75, 0.75], [3.0, 3.0], [6.75, 6.75]], dtype=np.float64 ), charge=np.zeros((3, 2), dtype=np.float64), density=np.array([1000.0], dtype=np.float64), volume=np.array([1.0, 2.0, 3.0], dtype=np.float64), distribution_type="particle_resolved", ), GasData( name=["water"], molar_mass=np.array([0.018], dtype=np.float64), concentration=np.array([[0.25], [0.5], [0.75]], dtype=np.float64), partitioning=np.array([True], dtype=np.bool_), ), EnvironmentData( temperature=np.array([295.0, 296.0, 297.0], dtype=np.float64), pressure=np.array([101325.0, 100800.0, 100000.0], dtype=np.float64), saturation_ratio=np.ones((3, 1), dtype=np.float64), ), )
def _resolved_graph( runtime: SimpleNamespace,) -> tuple[Any, Any, dict[str, Any]]: """Create the resolver-produced canonical twelve-node graph and schedule.""" execution = runtime.execution graph_module = runtime.process_graph resource = graph_module.ResourceRequirement invalidated = graph_module.InvalidatedState schemas = { "communication": ( graph_module.NodeKind.COMMUNICATION, None, frozenset( {resource.PARTICLES, resource.GAS, resource.PROCESS_SIDECARS} ), frozenset({invalidated.SATURATION_RATIO}), ), "volume_evolution": ( graph_module.NodeKind.VOLUME_EVOLUTION, None, frozenset( {resource.PARTICLES, resource.GAS, resource.PROCESS_SIDECARS} ), frozenset({invalidated.SATURATION_RATIO}), ), "environment_update": ( graph_module.NodeKind.ENVIRONMENT_UPDATE, None, frozenset({resource.ENVIRONMENT}), frozenset( {invalidated.VAPOR_PRESSURE, invalidated.SATURATION_RATIO} ), ), "gas_update": ( graph_module.NodeKind.GAS_UPDATE, None, frozenset({resource.GAS}), frozenset({invalidated.SATURATION_RATIO}), ), "vapor_pressure_refresh": ( graph_module.NodeKind.VAPOR_PRESSURE_REFRESH, None, frozenset( {resource.GAS, resource.ENVIRONMENT, resource.THERMODYNAMICS} ), frozenset(), ), "saturation_refresh": ( graph_module.NodeKind.SATURATION_REFRESH, None, frozenset( {resource.GAS, resource.ENVIRONMENT, resource.THERMODYNAMICS} ), frozenset(), ), "condensation": ( graph_module.NodeKind.PROCESS, execution.CONDENSATION_PROCESS, frozenset( { resource.PARTICLES, resource.GAS, resource.ENVIRONMENT, resource.THERMODYNAMICS, resource.PROCESS_SIDECARS, } ), frozenset({invalidated.SATURATION_RATIO}), ), "brownian_coagulation": ( graph_module.NodeKind.PROCESS, execution.Process("brownian_coagulation"), frozenset( { resource.PARTICLES, resource.ENVIRONMENT, resource.PROCESS_SIDECARS, } ), frozenset(), ), "dilution": ( graph_module.NodeKind.PROCESS, execution.Process("dilution"), frozenset({resource.PARTICLES, resource.GAS}), frozenset(), ), "wall_loss": ( graph_module.NodeKind.PROCESS, execution.Process("wall_loss"), frozenset( { resource.PARTICLES, resource.ENVIRONMENT, resource.PROCESS_SIDECARS, } ), frozenset(), ), "nucleation": ( graph_module.NodeKind.PROCESS, execution.Process("nucleation"), frozenset( { resource.PARTICLES, resource.GAS, resource.ENVIRONMENT, resource.PROCESS_SIDECARS, } ), frozenset({invalidated.SATURATION_RATIO}), ), "diagnostics": ( graph_module.NodeKind.DIAGNOSTIC, None, frozenset( { resource.PARTICLES, resource.GAS, resource.ENVIRONMENT, resource.THERMODYNAMICS, resource.DIAGNOSTICS, } ), frozenset(), ), } condensation_requirements = next( item.requirements for item in execution.CONDENSATION_CAPABILITY_MATRIX.declarations if item.process == execution.CONDENSATION_PROCESS ) nodes = tuple( graph_module.ProcessNode( node_id, schemas[node_id][0], schemas[node_id][1], condensation_requirements if node_id == "condensation" else execution.CapabilityRequirements(frozenset()), schemas[node_id][2], schemas[node_id][3], ) for node_id in _NODE_IDS ) dependencies = ( (graph_module.DependencyEdge("communication", "volume_evolution"),) + tuple( graph_module.DependencyEdge("volume_evolution", node_id) for node_id in _NODE_IDS if node_id not in {"communication", "volume_evolution"} ) + tuple( graph_module.DependencyEdge(node_id, "diagnostics") for node_id in ( "condensation", "brownian_coagulation", "dilution", "wall_loss", "nucleation", ) ) ) schedule = runtime.scheduler.resolve_timestep_schedule( graph_module.TimestepPlan(nodes, dependencies), runtime.scheduler.EnabledNodeSelection(frozenset(_NODE_IDS)), runtime.scheduler.SchedulerProfile( runtime.scheduler.NucleationCondensationDirection.CONDENSATION_THEN_NUCLEATION ), ) graph = schedule.source_graph if graph is None: raise RuntimeError("resolved schedule did not produce a source graph.") return graph, schedule, {node.node_id: node for node in graph.nodes}
def _mass_species_map(session: Any) -> Any: """Declare the complete water gas order and its particle material lane.""" from particula.dynamics.condensation.species_mapping import ( CondensationSpeciesMap, )
return CondensationSpeciesMap(session.metadata.gas_names, ((0, 0),))
def _prepare_species_bindings(session: Any) -> tuple[Any, Any]: """Prepare new maps for this exact source or explicitly restarted session.
Restart creates fresh carriers and arrays; source bindings cannot be reused. These explicit configuration uploads occur outside ordinary dispatch. """ from particula.dynamics.nucleation.species_mapping import ( NucleationSpeciesMap, ) from particula.gpu.nucleation_species_mapping import ( prepare_nucleation_species_map, ) from particula.gpu.species_mapping import prepare_condensation_species_map
return ( prepare_condensation_species_map( session.particles, session.gas, gas_names=session.metadata.gas_names, species_map=_mass_species_map(session), ), prepare_nucleation_species_map( session.particles, session.gas, gas_names=session.metadata.gas_names, species_map=NucleationSpeciesMap( session.metadata.gas_names, ((0, 0),) ), ), )
def _diagnostics_plan( runtime: SimpleNamespace, session: Any, registry: Any, graph: Any, schedule: Any, nodes: dict[str, Any], initial_total_mass: np.ndarray,) -> tuple[Any, Any, Any]: """Bind all closed diagnostics, retaining two caller-owned observations.""" wp = runtime.warp diagnostics = runtime.diagnostics shape = (session.dimensions.n_boxes, session.dimensions.n_species) device = session.particles.masses.device
def matrix() -> Any: """Allocate one caller-owned diagnostic matrix.""" return wp.zeros(shape, dtype=wp.float64, device=device)
gas_snapshot, saturation_snapshot, total = matrix(), matrix(), matrix() baseline = wp.array(initial_total_mass, dtype=wp.float64, device=device) registrations = ( diagnostics.ResidentDiagnosticRegistration( diagnostics.ResidentDiagnosticOperation.GAS_CONCENTRATION_SNAPSHOT, gas_snapshot, ), diagnostics.ResidentDiagnosticRegistration( diagnostics.ResidentDiagnosticOperation.SATURATION_RATIO_SNAPSHOT, saturation_snapshot, ), diagnostics.ResidentDiagnosticRegistration( diagnostics.ResidentDiagnosticOperation.TOTAL_SPECIES_MASS, total, species_map=_mass_species_map(session), ), diagnostics.ResidentDiagnosticRegistration( diagnostics.ResidentDiagnosticOperation.PARTICLE_NUMBER_CONCENTRATION, wp.zeros(shape[0], dtype=wp.float64, device=device), ), diagnostics.ResidentDiagnosticRegistration( diagnostics.ResidentDiagnosticOperation.LATENT_HEAT_ENERGY, matrix(), energy_transfer=matrix(), ), diagnostics.ResidentDiagnosticRegistration( diagnostics.ResidentDiagnosticOperation.CONSERVATION_RESIDUAL, matrix(), baseline_total_mass=baseline, source_ledger=matrix(), sink_ledger=matrix(), ), ) return ( diagnostics.ResidentDiagnosticsPlan( session, registry, graph, schedule, nodes["diagnostics"], registrations, ), gas_snapshot, saturation_snapshot, )
def _request( runtime: SimpleNamespace, session: Any, registry: Any, guard: Any, duration: float, cpu_gas: GasData, cpu_environment: EnvironmentData, initial_total_mass: np.ndarray,) -> tuple[Any, Any, Any]: # noqa: C901 """Build fresh exact request carriers from the binding's resource views.""" wp = runtime.warp execution = runtime.execution graph, schedule, nodes = _resolved_graph(runtime) device = session.particles.masses.device condensation_binding, nucleation_binding = _prepare_species_bindings( session ) communication_view = registry.get_communication_resources() if communication_view is None: map_data = runtime.communication.CommunicationMap( runtime.communication.CommunicationMapForm.ARBITRARY_PAIRS, runtime.communication.CommunicationTransportMode.GAS, 0, wp.zeros(0, dtype=wp.int32, device=device), wp.zeros(0, dtype=wp.int32, device=device), wp.zeros(0, dtype=wp.int32, device=device), wp.zeros(0, dtype=wp.float64, device=device), ) communication_view = registry.acquire_communication( runtime.communication.CommunicationConfiguration( map_data, runtime.communication.PrescribedVolumeUpdate( wp.array([1.0, 2.0, 3.0], dtype=wp.float64, device=device) ), ( runtime.communication.CommunicationResourceShape( "edge_rates", wp.float64, runtime.communication.CommunicationShapeKind.E, ), ), ) ) condensation_view = registry.acquire_condensation() coagulation_view = registry.acquire_coagulation(1) wall_loss_view = registry.acquire_wall_loss() nucleation_view = registry.acquire_nucleation() exhaustion = nucleation_view.exhaustion unit_scale = wp.ones( session.dimensions.n_boxes, dtype=wp.float64, device=device ) wp.copy(exhaustion.requested_scale, unit_scale) wp.copy(exhaustion.minimum_scale, unit_scale) wp.copy(exhaustion.minimum_volume, unit_scale) thermodynamics = runtime.thermodynamics.ThermodynamicsConfig( modes=wp.zeros(1, dtype=wp.int32, device=device), parameters=wp.array( [[800.0, 0.0, 0.0, 0.0]], dtype=wp.float64, device=device ), molar_mass_reference=wp.array( cpu_gas.molar_mass, dtype=wp.float64, device=device ), ) condensation = runtime.condensation.WarpCondensationExecutionState( runtime.condensation.WarpCondensationState( runtime.condensation.CondensationExecutionConfig( execution.CondensationConfiguration( execution.CondensationExecutionMode.EQUAL_STEP, False, execution.CondensationActivityMode.IDEAL, execution.CondensationSurfaceMode.STATIC, ) ), session.particles, session.gas, session.environment, thermodynamics, scratch_buffers=condensation_view.scratch_buffers, species_binding=condensation_binding, ), duration, ) coagulation = runtime.coagulation.ResidentBrownianCoagulationExecutionState( runtime.coagulation.WarpBrownianCoagulationExecutionState( runtime.coagulation.WarpBrownianCoagulationState( runtime.coagulation.BrownianCoagulationConfig(), session.particles, None, None, duration, collision_pairs=coagulation_view.collision_pairs, n_collisions=coagulation_view.n_collisions, rng_states=coagulation_view.rng_states, initialize_rng=False, environment=session.environment, ) ), session, registry, coagulation_view, ) diagnostics, gas_snapshot, saturation_snapshot = _diagnostics_plan( runtime, session, registry, graph, schedule, nodes, initial_total_mass, ) inventory = registry.register_capture_resources( session, communication_view, diagnostics.registrations ) map_data = communication_view.configuration.communication_map capacities = runtime.gpu_resources.ResourceInventoryCapacities( coagulation_view.collision_capacity, map_data.edge_capacity if map_data.transport_mode is runtime.communication.CommunicationTransportMode.GAS else 0, map_data.edge_capacity if map_data.transport_mode is runtime.communication.CommunicationTransportMode.PARTICLES else 0, ) capture_requirements = runtime.gpu_resources.CaptureResourceRequirements( session, capacities, inventory, runtime.gpu_resources.PreparedResourceViews( condensation_view, coagulation_view, None, wall_loss_view, nucleation_view, ), communication_view, ( "condensation", "coagulation", "wall_loss", "nucleation", "dilution", ), condensation_view.scratch_buffers, coagulation_view, wall_loss_view, nucleation_view, ) capture_set = registry.prepare_capture_resources(capture_requirements) dilution_view = capture_set.dilution assert dilution_view is not None request = runtime.resident_scheduler.ResidentSimulationRequest( session, registry, guard, graph, schedule, thermodynamics, condensation, coagulation, runtime.process_adapters.ResidentDilutionRequest( session, registry, dilution_view.normalized_coefficient, duration, dilution_view, ), runtime.process_adapters.ResidentWallLossRequest( session, registry, wall_loss_view, runtime.wall_loss.NeutralWallLossConfig( "spherical", 1.0, chamber_radius=1.0, distribution_type="particle_resolved", ), duration, enabled_box_indices=(0, 1, 2), ), runtime.process_adapters.ResidentNucleationRequest( session, registry, nucleation_view, runtime.nucleation.NucleationConfig( "activation", 0.0, 1.0, 0, (1,), 1e-9, 0.0, 1e30, 200.0, 400.0, ), duration, runtime.nucleation.NucleationExhaustionControls(False, False), species_binding=nucleation_binding, ), diagnostics, runtime.state_updates.ResidentEnvironmentUpdateRequest( session, registry, graph, nodes["environment_update"], wp.array( cpu_environment.temperature, dtype=wp.float64, device=device ), wp.array(cpu_environment.pressure, dtype=wp.float64, device=device), ), runtime.state_updates.ResidentGasUpdateRequest( session, registry, graph, nodes["gas_update"], wp.array(cpu_gas.concentration, dtype=wp.float64, device=device), ), runtime.resident_communication.ResidentCommunicationRequest( session, registry, graph, communication_view, nodes["communication"], nodes["volume_evolution"], duration, ), capture_requirements, ) return request, gas_snapshot, saturation_snapshot
def run_example(device: str = "cpu") -> ExampleRun: """Run the bounded complete resident loop and explicit checkpoint restart.
Device arrays and diagnostic buffers remain caller-owned. This example synchronizes only to observe diagnostics; setup, ordinary dispatch, and restart do not hide transfers or host inspection. Gas is prescribed each step and wall loss can remove particles. The residual uses zero ledgers and therefore reports net inventory change; it is not a closed-system conservation assertion. """ if not _warp_enabled(): return ExampleRun(output=_disabled_output()) runtime = _load_enabled_runtime() selected_device = runtime.execution.Device( runtime.execution.Backend.WARP, device ) requirements = runtime.execution.CapabilityRequirements(frozenset()) process = runtime.execution.Process("resident_simulation") request = runtime.execution.ExecutionRequest( runtime.execution.Backend.WARP, selected_device, process, requirements ) matrix = runtime.execution.CapabilityMatrix( frozenset( { runtime.execution.CapabilityDeclaration( selected_device, process, requirements ) } ) ) decision = runtime.availability.resolve_availability(request, matrix) if decision.request is not request: raise RuntimeError( "availability resolution returned a different request." ) particles, gas, environment = _build_cpu_state() initial_total_mass = ( np.sum(particles.masses * particles.concentration[:, :, None], axis=1) + gas.concentration * particles.volume[:, None] ) if not np.any(initial_total_mass > 0.0): raise RuntimeError( "resident example initial inventory must be nonzero." ) session = runtime.gpu_session.setup_resident_session( particles, gas, environment, selected_device ) registry = runtime.gpu_resources.GPUResourceRegistry(session) guard = runtime.gpu_session.ResidentStepGuard(session, registry) source_request, gas_output, saturation_output = _request( runtime, session, registry, guard, 1.0, gas, environment, initial_total_mass, ) scheduler = runtime.resident_scheduler.ResidentSimulationScheduler( source_request ) for _ in range(2): scheduler.execute(1.0) guard.assert_step_closed() runtime.warp.synchronize_device(session.particles.masses.device) gas_snapshot, saturation_snapshot = ( gas_output.numpy().copy(), saturation_output.numpy().copy(), ) conservation_residual = ( source_request.diagnostics.registrations[5].output.numpy().copy() ) checkpoint = session.checkpoint(registry, guard) if session.lifecycle is not runtime.gpu_session.ResidentLifecycle.ACTIVE: raise RuntimeError( "source session did not remain active at checkpoint." ) restarted_session, restarted_registry, restarted_guard = ( runtime.checkpoint.restart_resident_session(checkpoint, selected_device) ) if restarted_session is session or restarted_registry is registry: raise RuntimeError("restart reused source identities.") if restarted_guard is guard: raise RuntimeError("restart reused the source guard.") restart_gas_before_physics: np.ndarray | None = None restart_temperature_before_physics: np.ndarray | None = None try: restart_request, _, _ = _request( runtime, restarted_session, restarted_registry, restarted_guard, 1.0, checkpoint.gas, checkpoint.environment, np.sum( checkpoint.particles.masses * checkpoint.particles.concentration[:, :, None], axis=1, ) + checkpoint.gas.concentration * checkpoint.particles.volume[:, None], ) runtime.warp.synchronize_device( restarted_session.particles.masses.device ) restart_gas_before_physics = ( restarted_session.gas.concentration.numpy().copy() ) restart_temperature_before_physics = ( restarted_session.environment.temperature.numpy().copy() ) if not np.array_equal( restart_gas_before_physics, checkpoint.gas.concentration ) or not np.array_equal( restart_temperature_before_physics, checkpoint.environment.temperature, ): raise RuntimeError( "restart forcing does not match checkpoint state." ) runtime.resident_scheduler.ResidentSimulationScheduler( restart_request ).execute(1.0) restarted_guard.assert_step_closed() finally: restarted_session.close(restarted_registry, restarted_guard) terminal_checkpoint = session.finalize(registry, guard) if session.finalize(registry, guard) is not terminal_checkpoint: raise RuntimeError("finalization did not return the cached checkpoint.") return ExampleRun( output=[ "Warp CPU is the installed-Warp baseline; CUDA is optional.", "Caller owns resident data and diagnostic buffers; " "synchronization is explicit.", "Restart is manual, exact-device, and uses canonical " "checkpoint bytes.", # No graph capture or performance guarantee is claimed. "No CPU fallback, hidden transfer, automatic restart, graph " "capture, or performance guarantee.", "Unsupported physics and exact cross-backend RNG replay are " "not claimed.", ], session=session, registry=registry, guard=guard, checkpoint=checkpoint, restarted=(restarted_session, restarted_registry, restarted_guard), terminal_checkpoint=terminal_checkpoint, gas_snapshot=gas_snapshot, saturation_snapshot=saturation_snapshot, initial_total_mass=initial_total_mass, conservation_residual=conservation_residual, restart_gas_before_physics=restart_gas_before_physics, restart_temperature_before_physics=restart_temperature_before_physics, source_steps=2, restarted_steps=1, )Compare boxes after two resident timesteps
Section titled “Compare boxes after two resident timesteps”The boxes have distinct volume, gas concentration and temperature. Prescribed gas is refreshed during each step and walls may remove particles. The plotted inventory change is therefore an open-system response, not conservation error. The checkpoint is then restarted and advanced once more; its forcing must match exactly before that continuation begins.
Python · section 2
def run_publication(): """Require CUDA and plot heterogeneous gas and open-system inventories.""" import matplotlib.pyplot as plt import warp as wp
if not _warp_enabled() or not wp.is_cuda_available(): raise RuntimeError("This publication run requires CUDA") _, initial_gas, _ = _build_cpu_state() result = run_example(device="cuda:0") if result.gas_snapshot is None or result.conservation_residual is None: raise RuntimeError("CUDA produced no diagnostic snapshots") boxes = np.arange(3) + 1 fig, axes = plt.subplots(1, 2, figsize=(9, 3.6), constrained_layout=True) axes[0].bar( boxes - 0.18, initial_gas.concentration[:, 0], width=0.36, label="Initial", ) axes[0].bar( boxes + 0.18, result.gas_snapshot[:, 0], width=0.36, label="After two steps", ) axes[0].set(xlabel="Box", ylabel="Water gas (kg m$^{-3}$)", xticks=boxes) axes[0].legend() relative = np.asarray(result.conservation_residual).reshape(3, -1)[:, 0] relative = relative / result.initial_total_mass[:, 0] axes[1].bar(boxes, relative, color="#be6c39") axes[1].set( xlabel="Box", ylabel="Net inventory change / initial", xticks=boxes ) axes[1].axhline(0, color="0.5", linewidth=0.8) fig.suptitle( "Resident multibox evolution · " + wp.get_device("cuda:0").name ) print("\n".join(result.output)) print("Checkpoint forcing matched exactly before continuation.") plt.show() return result
def main() -> None: """Run the example and print its deterministic status lines.""" for line in run_example().output: print(line)
if __name__ == "__main__": import sys
if "--cuda" in sys.argv[1:]: run_publication() else: main()Explicit cuda invocation
result = run_publication()Warp 1.11.1 initialized:
CUDA Toolkit 12.9, Driver 13.4
Devices:
"cpu" : "CPU"
"cuda:0" : "NVIDIA GeForce RTX 5060" (8 GiB, sm_120, mempool enabled)
Kernel cache:
~/.cache/warp/1.11.1
Module particula.execution.communication 2909959 load on device 'cuda:0' took 0.74 ms (cached)
Module particula.gpu.kernels.communication ac9b2a2 load on device 'cuda:0' took 2.02 ms (cached)
Module particula.execution.state_updates 9e694ef load on device 'cuda:0' took 0.37 ms (cached)
Module particula.gpu.kernels.environment e11375e load on device 'cuda:0' took 0.41 ms (cached)
Module particula.gpu.kernels.coagulation 9ee9d75 load on device 'cuda:0' took 0.45 ms (cached)
Module particula.gpu.kernels._coagulation_native f93a244 load on device 'cuda:0' took 0.37 ms (cached)
Module particula.gpu.kernels._brownian_parallel 17ce68f load on device 'cuda:0' took 0.93 ms (cached)
Module particula.gpu.kernels._brownian_parallel 326c699 load on device 'cuda:0' took 1.20 ms (cached)
Module particula.gpu.kernels.coagulation 542143a load on device 'cuda:0' took 0.42 ms (cached)
Module particula.gpu.kernels.coagulation 8fc901f load on device 'cuda:0' took 0.40 ms (cached)
Module particula.gpu.kernels.dilution 0472484 load on device 'cuda:0' took 0.40 ms (cached)
Module particula.gpu.kernels._population_validation 65eaa49 load on device 'cuda:0' took 0.34 ms (cached)
Module particula.gpu.kernels.thermodynamics 10b2126 load on device 'cuda:0' took 0.33 ms (cached)
Module particula.execution.thermodynamic_updates 610ef79 load on device 'cuda:0' took 0.26 ms (cached)
Module particula.gpu.kernels.condensation aaea4cd load on device 'cuda:0' took 0.24 ms (cached)
Module particula.gpu.kernels._condensation_native 34375de load on device 'cuda:0' took 0.35 ms (cached)
Module particula.gpu.kernels.condensation ff745d0 load on device 'cuda:0' took 0.29 ms (cached)
Module particula.gpu.kernels.condensation 8cf5639 load on device 'cuda:0' took 0.39 ms (cached)
Module particula.gpu.kernels.condensation 11662eb load on device 'cuda:0' took 0.71 ms (cached)
Module particula.gpu.kernels._condensation_native 9623455 load on device 'cuda:0' took 0.31 ms (cached)
Module particula.gpu.kernels.condensation 2482550 load on device 'cuda:0' took 0.74 ms (cached)
Module particula.gpu.kernels._condensation_native 76403ad load on device 'cuda:0' took 0.39 ms (cached)
Module particula.gpu.kernels.condensation 65f5174 load on device 'cuda:0' took 0.72 ms (cached)
Module particula.gpu.kernels._condensation_native c295a4d load on device 'cuda:0' took 0.39 ms (cached)
Module particula.gpu.kernels._condensation_native a80ebff load on device 'cuda:0' took 0.51 ms (cached)
Module particula.gpu.kernels.condensation ba1f931 load on device 'cuda:0' took 0.90 ms (cached)
Module particula.gpu.kernels.condensation 70a5efd load on device 'cuda:0' took 0.82 ms (cached)
Module particula.gpu.kernels.condensation dec71d1 load on device 'cuda:0' took 0.88 ms (cached)
Module particula.gpu.kernels._condensation_native 731ad93 load on device 'cuda:0' took 0.56 ms (cached)
Module particula.gpu.kernels.nucleation 1124f09 load on device 'cuda:0' took 2.08 ms (cached)
Module particula.gpu.kernels.slot_management 0375e2c load on device 'cuda:0' took 0.61 ms (cached)
Module particula.gpu.kernels.exhaustion ccbadfa load on device 'cuda:0' took 1.34 ms (cached)
Module particula.gpu.kernels.wall_loss 6dc09db load on device 'cuda:0' took 3.83 ms (cached)
Module particula.gpu.kernels._wall_loss_native 314c0ac load on device 'cuda:0' took 0.53 ms (cached)
Module particula.execution.diagnostics ade82cd load on device 'cuda:0' took 0.36 ms (cached)
Module particula.execution.diagnostics 903c22d load on device 'cuda:0' took 0.31 ms (cached)
Module particula.execution.diagnostics ce5a797 load on device 'cuda:0' took 0.32 ms (cached)
Module particula.execution.diagnostics 1ea62de load on device 'cuda:0' took 0.33 ms (cached)
Module particula.execution.diagnostics 037f64e load on device 'cuda:0' took 0.36 ms (cached)
Module particula.execution.diagnostics f921a30 load on device 'cuda:0' took 0.41 ms (cached)
Warp CPU is the installed-Warp baseline; CUDA is optional.
Caller owns resident data and diagnostic buffers; synchronization is explicit.
Restart is manual, exact-device, and uses canonical checkpoint bytes.
No CPU fallback, hidden transfer, automatic restart, graph capture, or performance guarantee.
Unsupported physics and exact cross-backend RNG replay are not claimed.
Checkpoint forcing matched exactly before continuation.

Explain the source and sink before the residual
Section titled “Explain the source and sink before the residual”Each source step restores the prescribed gas, so particle uptake can be followed by external vapor replenishment. Wall loss can export particle material. The residual buffer uses the initial inventory and zero source/sink ledger arrays; its plotted change consequently is not an accounted conservation error. Communication has zero edges, prescribed volumes stay fixed, and nucleation has a zero coefficient. Listing those schedule nodes does not mean they transport material or create particles in this run.
The restart check verifies gas and temperature before its additional step; the plotted bars describe the original two-step state. There is no uninterrupted three-step comparison here. For a coupled-box research model, add actual transfer edges and an external-exchange ledger, then compare a complete resumed trajectory with an uninterrupted control. The prepared lifecycle provides that stronger continuation and process-accounting example.
Explore this topic: Resident execution