Advanced runtime¶
Advanced runtime primitives, for authors of custom algorithm harnesses.
Everything on this page lives in dynaplex.runtime, except dynaplex.gc. Everyday modelling
and solving does not need anything here.
Engine¶
Engine ¶
Engine(root_class: type, *ctor_args: object, type_bindings: dict[str, type] | None = None, jit: bool | None = None, checks: bool | None = None)
Compile a dataclass and run its methods on the DynaPlex engine.
An Engine takes one root class (a DynaML dataclass), compiles the class,
its methods, and everything reachable from them, constructs a single root
object, and then executes method calls on that object inside the engine —
interpreted or JIT-compiled. State lives engine-side between calls, so a
long-lived stateful computation pays the Python boundary cost only at the
call sites.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root_class
|
type
|
The dataclass to compile and instantiate. All of its public methods become callable entry points. |
required |
*ctor_args
|
object
|
Arguments passed to |
()
|
type_bindings
|
dict[str, type] | None
|
Optional mapping of placeholder annotation names to
concrete dataclasses (e.g. |
None
|
jit
|
bool | None
|
|
None
|
checks
|
bool | None
|
|
None
|
Example
close ¶
Tear the engine down now: release the root object, the DataStore and every world thread, and drop the compile state. Idempotent; call() raises RuntimeError afterwards. Dropping the last reference does the same (see del), so explicit close() is for when the teardown moment matters (e.g. before measuring threads).
call ¶
Call a method on the root object. Arguments and the return value must be numeric primitives or ndarrays. Returns the native Python result (scalar / numpy array), None for a void method, or a tuple for multiple return values.
view ¶
A LIVE, read-only view of the root object: engine.view().field[i].attr.
The read-side door of the engine (docs/asbuilt/dcl_sample_info.md). The view is
non-owning and re-reads the store on every access, so it always shows the current
state — including lists the root grew during later calls — and it survives GC
sweeps (everything reachable from the root is never swept; ids are stable). Leaves
come back as Python ints/floats/bools/enums, ndarrays as numpy arrays sharing the
backing, objects and lists as nested views. Valid while the engine lives and no
call is in flight (worker worlds are quiescent between calls). Views do not cross
processes: materialize what you need (a flat dataclass is one getattr per field).
collect_garbage ¶
Whole-tree mark-and-sweep GC: the root store and every contained world, each on its own thread. Safe to call between engine.call() invocations.
enable_deferred_gc ¶
Deferred (aligned) auto-GC: stores RAISE a request flag when their adaptive
threshold trips instead of self-sweeping mid-task; poll take_gc_request() and run
collect_garbage() at a safe boundary (e.g. between DCL rounds — the sweep then
never stalls a running round). Call before the first world-spawning call (like
set_gc_threshold); contained worlds inherit the flag at construction.
take_gc_request ¶
Read-and-clear the deferred auto-GC request (any store over threshold since the
last call). Meaningful only after enable_deferred_gc().
set_gc_threshold ¶
Set the automatic-GC trigger threshold (bytes since last sweep). Worlds created afterward inherit it; the threshold adapts per sweep and is floored at 1 MiB. Set this before the first call that spawns worlds (e.g. setup) so it propagates through the tree.
set_gc_force_at_safe_points ¶
TEST KNOB: sweep at every GC safe point — task-top and dynaplex.gc() — regardless
of the allocation threshold, so a handle that a safe point failed to keep alive is freed
at the FIRST safe point instead of after a threshold's worth of garbage. Call before the
first world-spawning call (worlds inherit it at construction).
net_live_bytes_tree ¶
Net live bytes (alloc - freed) across the root store and every contained world.
State recycling and streams¶
clone_into ¶
Deep in-place assignment: overwrite dst so it becomes value-equal to a deep
copy of src, preserving dst's identity wherever structure matches.
Both arguments must be two instances of the same MUTABLE dataclass, or two lists of
the same type. External aliases of reused dst sub-objects observe the new values
(that is the defined semantics, not an accident); where structure mismatches (None
flips, ndarray shape changes, aliasing duals) the affected position falls back to a
fresh clone. Overlapping src/dst graphs are unsupported. clone_into(x, x) is a
no-op. Returns None (unmistakably a mutation).
reseed ¶
reseed(rng: np.random.Generator | Generator | EventProbe, seed: int) -> None
Re-seed rng in place (see _reseed_generator, the kernel this calls).
Written DynaML: the union parameter is an overload set — the two generator
members call the kernel (DP!reseed_dp / DP!reseed_np); the EventProbe
member is a compile-time failure, because reseeding an enumerator is
meaningless — the exact solver never reseeds, and a model that does so under
the probe is wrong. In CPython the same call raises DynaPlexError.
combine_seeds ¶
combine_seeds — deterministic, collision-free RNG seed combiner.
Ports the legacy DynaPlex CombineSeeds (legacy rng.cpp): the trajectory
coordinates (sample, trajectory, stream) are packed into DISJOINT bit-fields
of a single integer, XOR'd with a global_seed, and a high bit is reserved for the
train/eval partition. Because the fields are disjoint the mapping is a bijection —
distinct coordinate tuples give distinct seeds by construction (range-checked, not
"probably distinct"). The result is a NON-NEGATIVE int64, so it feeds
numpy.random.default_rng(seed) directly.
Dual role (like clone/sync_worlds): a real CPython function used when DynaML code
runs in pure Python, AND recognized by the interpreter frontend as a builtin that
lowers to the C++ DP!combine_seeds CALL_BI. Both paths are bit-identical — this is
what keeps CRN / reproducibility exact between a CPython reference and compiled workers.
Bit layout (bit 63 kept 0 so the value stays non-negative): bit 63 : 0 (sign — guarantees a valid non-negative int64 seed) bit 62 : eval (train = 0 / eval = 1 → disjoint train/eval seed spaces) bits 33..61 : sample (< 229) bits 10..32 : trajectory (< 223) bits 0..9 : stream (< 2**10)
This deviates from legacy in ONE way: legacy put eval at bit 63 (the MSB), yielding a
uint64 that is negative when reinterpreted as int64. numpy's SeedSequence rejects negative
entropy (scalar AND list forms), so eval is moved to bit 62 to keep the seed non-negative.
global_seed is therefore bounded to < 2**62 so its XOR can never touch the eval/sign bits.
combine_seeds ¶
Pack (eval, global_seed, sample, trajectory, stream) into one non-negative int64 seed.
Raises ValueError if any coordinate is out of range (mirrors the C++ builtin, so
silent overflow — the classic seeding footgun — is turned into a hard error).
Any nonzero eval selects the evaluation seed space.
monotonic ¶
Monotonic process-wide clock in seconds (arbitrary epoch); timing only.
Memory¶
Algorithms free unreachable memory on their own. dynaplex.gc() is for a
compiled function of your own that runs for a long time in one call; see
Advanced runtime primitives.
gc ¶
In-function GC safe point (threshold-gated; deferred-mode aware).
The compiler derives the root set: every in-scope named local/parameter holding an object or list, plus loop iterables the compiler itself holds. Place it at the top of a long-running per-trajectory/per-episode loop; do NOT place it in code that runs per period (each safe point pins the frame's handles — cheap, not free). No-op in CPython.
Concurrent worlds¶
separate_world_class ¶
Decorator combining @dataclass with world marking for the DynaML compiler.
Instances of the decorated class live in their own Program/DataStore/thread. Method calls on a world instance are dispatched asynchronously to that thread.
Accepts the same keyword arguments as @dataclass (init, slots, frozen, etc.).
Usage
@separate_world_class class World: base: int
def compute(self, num_steps: int) -> float:
...
sync_worlds ¶
Barrier over all outstanding @separate_world_class method dispatches.
Inside a compiled DynaML function, w.method(...) on a world instance posts
work to that world's thread and returns immediately, writing a placeholder
into the result temp. sync_worlds() blocks until every outstanding world
call has finished and flushes each world's result into its result temp.
Usage contract (not compiler-enforced, like reading an uninitialized value):
- Bind each world method call's result to a FRESH variable
(e.g. r0 = w0.compute(n); for multiple returns a, b = w.stats(n)).
- Do NOT use those variables until after sync_worlds() has run. Reading or
copying them before the barrier yields a placeholder, not the result.
Calling this directly in CPython is a no-op (it is meaningful only when compiled by the DynaML interpreter).
Compilation pipeline¶
The classes below are deep plumbing; they are listed for completeness and documented by their docstrings only.
Program ¶
Python wrapper for the C++ compiled module + _cpp_program runtime classes.
Provides a high-level interface for working with DynaPlex programs, including DataModel management and function registration.
Create a new Program, optionally from a list of functions.
Automatically discovers all dataclasses used in function signatures, performs all Python-side parsing, then creates the C++ Program and DataModel at the end (unless disabled).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
functions
|
list | None
|
Optional list of Python function objects to register. If None, creates empty Program. |
None
|
build_backend
|
bool
|
If False, skip building the C++ backend (front-end only). |
True
|
checks
|
bool | None
|
|
None
|
compile_function_from_string ¶
compile_function_from_string(source: str, namespace: dict[str, Any] | None = None, filename: str | None = None) -> Callable
Compile a function from a source string and make it compatible with DynaPlex.
This function handles the linecache setup needed for DynaPlex to extract source code from dynamically created functions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Python source code containing a single function definition |
required |
namespace
|
dict[str, Any] | None
|
Dictionary of globals to use when executing the source. If None, uses an empty namespace. |
None
|
filename
|
str | None
|
Name to use for the source (for error messages and debugging). If None, generates a name based on the function name. |
None
|
Returns:
| Type | Description |
|---|---|
Callable
|
The compiled function object, ready to be registered with DynaPlex. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If source doesn't contain exactly one function definition, or if compilation fails. |
Example
from dataclasses import dataclass
import dynaplex
@dataclass
class Point:
x: int
y: int
source = '''
def distance(p1: Point, p2: Point) -> int:
dx: int = p1.x - p2.x
dy: int = p1.y - p2.y
return dx * dx + dy * dy
'''
distance = dynaplex.runtime.compile_function_from_string(
source, namespace={"Point": Point}
)
prog = dynaplex.runtime.Program([distance])
build_datamodel_from_dataclasses(dataclasses) — build a DataModel from a
list of dataclass types (see its docstring via help()).