The sections below list the public Python interfaces of the gpuastar package.
import gpuastarThe top-level package provides version metadata and runtime bootstrap.
Attributes:
__version__: Package version string__author__: Author name
from gpuastar.main import mainConsole script entry point for the Hydra CLI. Not typically called directly.
from gpuastar.cli import run_configTyped command dispatch for Hydra-composed GPUAStar settings.
Functions:
Run one validated GPUAStar command configuration.
Parameters:
settings: Validated configuration object (SearchAStarConfig,AOTIExportConfig, orCppWorkflowConfig)
from gpuastar.backends import get_backend, available_backends, BackendProtocol, BackendUnavailableErrorBackend discovery and selection. Backends are found through the gpuastar.backends entry-point group, so separately installed solver packages (such as gpuastar-cpp and gpuastar-cu) register themselves without changes to the base package.
Classes:
Protocol implemented by every registered backend descriptor.
Attributes:
name: Stable backend identifier
Methods:
available() -> bool: Return whether this backend is usable
Functions:
Discover installed GPUAStar backends.
Returns: Mapping of backend name to backend descriptor.
Select a backend by name.
Parameters:
requested: Requested backend name ("py","cpp","cu", or"auto")
Returns: Available backend descriptor.
Raises: BackendUnavailableError if an explicitly requested backend is unavailable.
from gpuastar.config import SearchAStarConfig, AOTIExportConfig, CppWorkflowConfig, SearchRuntimeConfig, load_configHydra-composed, Pydantic-validated settings.
Classes:
Mutable one-run execution context derived from validated settings.
Attributes:
state_progress_callback: Optional callback for per-state progress
Dataset, model, environment, and output paths for search. The base package defines no defaults for the first four fields. Installed environment providers, such as the gpuastar[experiments] extra, inject defaults through Hydra composition.
Fields:
states: Path to the initial states datasetmodel: Neural network checkpoint pathenv: Environment nameresults_dir: Output directorystart_idx: Starting state indexmax_states: Maximum states to process (-1 for unlimited)
Algorithmic controls for weighted A* behavior.
Fields:
batch_size: Nodes expanded per iterationweight: Heuristic weightinstance_batch_size: Number of search instances run in parallelhash_capacity_factor: Hash table capacity factorcapacity_mode:"adaptive"or"fixed"hashtable_algorithm:"linear_probing"or"python_dict"solution_move_source:"infer"or"stored"duplicate_update_mode:"in_place"or"new_slot"goal_stop_mode:"stop_before_goal"or"expand_popped_batch"expand_push_mode:"single_pass"or"flatten"- (Python CPU A* only) child-materialization mechanism (single_pass(default) matches the paper's reference implementation,flattenis a heavier flatten/unflatten variant producing identical child nodes)nnet_batch_size: Batch size for heuristic evaluationsearch_budget: Maximum node expansions per state (0 = unlimited)
Backend, device, and implementation selection.
Fields:
language:"py","cpp","cu", or"auto"gpu_only: Run the entire search loop in device-resident tensorsdevice: Device stringheuristic_device: Heuristic device override
Torch execution, compilation, precision, and memory controls.
Fields:
compile_all: Enabletorch.compilefor all targetscompile: Compile settings for heuristic evaluationcompile_env: Compile settings for environment transition functionscompile_astar_closed: Compile settings for closed-set matchingfsdp: Fully Sharded Data Parallel (FSDP2)tensor_parallel: Tensor parallelismdtensor: DTensor placementcuda_graphs: CUDA graph captureamp: Automatic mixed precisionamp_dtype: AMP dtype ("float16"or"bfloat16")
Profiler and operation-timing settings.
Fields:
enabled: Enable profilingsteps: Number of profiler stepsoperation_breakdown: Per-operation timingcuda_sync_timing: CUDA synchronization around measured intervalsrecord_shapes: Record tensor shapesmemory: Memory profilingstack: Stack tracingflops: FLOP counting
Dtype names used by tensor-backed A* storage.
Fields:
node_state,open_index,open_cost,closed_key,closed_costparent_index,parent_move,path_cost,heuristic,total_cost
Validated configuration for the batch weighted A* runner.
Validated configuration for exporting heuristic models to AOTInductor packages.
Validated configuration for C++ build workflows.
Functions:
Load and validate configuration from Hydra.
from gpuastar.environments.environment_abstract import Environment, StateAbstract state and environment contracts for GPUAStar search domains.
Abstract base class for hashable environment states.
Abstract Methods:
Return a hash that uniquely identifies the state.
Return True when both states describe the same configuration.
Base environment API shared by all search domains.
Attributes:
dtype: NumPy dtype for state representationfixed_actions: Whether the environment has fixed discrete actionssuggested_compile_max_nodes: Optional node-store capacity hint used to size compiled GPU search artifacts
Abstract Methods:
Return successor states and transition costs for an action.
Parameters:
states: State batch to transformaction: Zero-based action index
Returns: Pair (next_states, transition_costs) aligned with states.
Return predecessor states produced by reversing an action.
Generate num_states solved states.
Return a solved-state mask with shape (batch_size,).
Convert states into float32 arrays accepted by the heuristic model.
Return the number of discrete actions available.
Return the neural network architecture used for heuristic evaluation.
Concrete Methods:
Return a single solved state.
generate_states(self, num_states: int, backwards_range: tuple[int, int]) -> tuple[list[State], list[int]]
Sample states by scrambling solved states with reverse moves.
Generate all fixed-action successors and transition costs.
from gpuastar.utils.environments.registry import register_environment, register_lazy, get_environmentRegistration and lookup of environments by name.
Functions:
Register an environment class under a name usable as input.env.
Register an environment by module path so that the module is imported only when the environment is requested.
Instantiate a registered environment by name.
from gpuastar.environments.torch_env import make_torch_envAdapter constructor for tensor-based environments. The TorchEnv protocol is defined in gpuastar.protocols. The bundled adapter implementations live in the gpuastar-experiments package, so make_torch_env requires the gpuastar[experiments] extra for the example domains.
Protocol: TorchEnv
Attributes:
device: Torch devicestate_dim: State dimensionnum_moves: Number of moves
Methods:
Encode CPU state objects into a tensor on the device.
Decode a tensor batch into CPU state objects.
Return a solved-state mask.
Expand states into all children and transition costs.
Returns: (children, costs) where children has shape (batch_size, num_moves, state_dim) and costs has shape (batch_size, num_moves).
Return tensors formatted for the heuristic network.
Functions:
Create a TorchEnv adapter for an Environment.
from gpuastar.astar.backends.python import bwas_pythonPython implementation of batch weighted A* search.
Parameters:
args:SearchRuntimeConfigenv:Environmentinstancestates: List of initial statesoperation_config: OptionalOperationConfig
Returns: Tuple (solutions, paths, times, nodes_generated)
from gpuastar.astar.backends.cpp import bwas_cpp, bwas_cpp_extensionRun the C++ solver. This wrapper validates the requested devices, converts states into the solver payload, dispatches to bwas_cpp_extension, and produces the per-state reports.
Call the solver in the gpuastar_cpp extension module directly and return (solutions, paths, times, nodes_generated).
from gpuastar.astar.backends.cuda import bwas_cuRun weighted A* search through the gpuastar-cu kernel backend.
from gpuastar.astar.backends.torch import bwas_torchRun batch weighted A* search with device-resident tensors and TorchDict.
from gpuastar.utils.aoti.export import main as aoti_export_main, run_exportAOTInductor model export utilities.
Functions:
Export a heuristic model checkpoint to an AOTInductor package.
from gpuastar.utils.models.neural_networks import load_heuristic_fn, load_nnet, get_deviceNeural network loading and heuristic function adapters.
Functions:
load_heuristic_fn(checkpoint, device, on_gpu, model_factory, env, clip_zero=True, batch_size=0, compile_cfg=None, aoti_package_path=None, fuse_conv_bn=False, prune_amount=0.0, sparsity_structured=0.0)
Load a heuristic function from a checkpoint.
Returns: TimedNNetHeuristicFn callable.
Load network weights from a checkpoint into a model.
Resolve a device specification.
from gpuastar.utils.torchdict.core import TorchDict, KeySpec, ValueSpecOpen-addressing hash table stored in PyTorch tensors on the selected device.
Compact open-addressing dictionary implemented with PyTorch tensors.
Constructor:
TorchDict(
key_spec: KeySpec,
value_spec: ValueSpec,
capacity: int,
device: torch.device | str | None = None,
*,
hashtable_algorithm: str = "python_dict",
salt: int | None = None,
)Methods:
Insert or update key-value pairs.
Retrieve values for keys.
Check key membership.
Get values with a default for missing keys.
Remove and return values for keys.
Return a tensor of all keys.
Return a tensor of all values.
Return (keys, values) tensors.
Return the number of live items.
Return hash table statistics.
Fused closed-set update. For existing keys, the stored value becomes the minimum of the old and new values. Returns a boolean mask marking entries accepted as strict path cost improvements.
Describe how keys are encoded in the tensor storage.
Attributes:
kind:"int64"or"int64_vec"length: Vector width forint64_veckeys
Describe the dtype and per-key shape of the stored values.
Attributes:
dtype: Tensor dtypeshape: Per-key value shape tuple
from gpuastar.utils.data.state_datasets import load_states, save_statesState dataset I/O utilities.
Functions:
Load states from a pickle file.
Save states to a pickle file.
Structural protocols for optional GPUAStar integrations.
Callable returning cost-to-go estimates for a batch of states.
def __call__(self, states: list[State], is_nnet_format: bool = False) -> NDArray[np.float32]Protocol for callable models accepting variadic tensor inputs.
def __call__(self, *inputs: Tensor) -> Tensor | tuple[Tensor, ...] | list[Tensor]Protocol for states that provide their C++ solver payload directly.
def cpp_payload(self) -> Sequence[int]States without colors or tiles sequences implement this method so the C++ backend can serialize them.
Protocol for tensor-based environment adapters.
Minimal protocol for objects that support TorchDict-like views.
Shared type aliases and protocols for the search interfaces.
Type Aliases:
FloatArray:NDArray[np.float32]BoolArray:NDArray[np.bool_]Node: TypeVar for node typesOpenSetElem:tuple[float, int, Node]NNetBatch:list[FloatArray]UpdateResult:tuple[NNetBatch, FloatArray, BoolArray]StateBatch:list[State]StateOrNNetBatch:StateBatch | NNetBatchClosedState:TorchDict | TensorClosedStateJSONValue: JSON-serializable value
Protocols:
State-batch heuristic callable.
State-batch heuristic with forward-only timing.
State-or-network-batch heuristic callable.
Tensor-batch heuristic callable.
Dataclasses:
Tensor-backed closed-set storage.
TypedDict:
Serialized solver results.
Runtime Checkable Protocols:
Callback invoked after each state completes.
def __call__(self, state_index: int, solved: bool, nodes_generated: int, solve_time_seconds: float) -> NoneType Guards:
Return True if the state provides a colors attribute.
Return True if the state provides a tiles attribute.