eagle

Contents

eagle#

eagle — the Python face of the EAGLE launch engine.

Which call do I use?

one kernel (or a step’s worth), run until every sample finishes – simulate() a plan already paced by its own finish kernel, one call – until_done() build a kernel into a plan that runs where its data lives – deploy() / plan resolve a launchable BY NAME, then call/stream/graph it – KernelRegistry

EAGLE owns everything about executing compiled kernels: the framework-polymorphic launch skeleton (LaunchMixin), the capturable kind-dispatched launch() primitive, input-role marshalling (eagle.marshal), the by-value launch ABI (eagle.abi), DLPack framework adapters (eagle.interop), CUDA-graph capture/replay (GraphPipeline), composing many already-built launchables into one launch list (GraphComposer), and the plugin protocol consumers — KernelRegistry / load_manifest() on the Python side, mirroring the C++ host/ registries.

Producers of launchable artifacts (compiled CUDA sources, PTX bundles with sidecar/manifest metadata) live upstream — the code generator is the first — and depend on this package; the eagle core never imports a producer. The optional framework bridges (eagle.frameworks) are the one exception: they import hawk lazily, on first use, and so does eagle.deploy() (the same function as eagle.plan.auto()), which builds a hawk kernel into a plan that runs where its data lives. eagle.simulate() runs a model (one hawk kernel, or the kernels of one step) on every sample until each one finishes, called exactly like the kernel itself.

exception eagle.Busy[source]#

Bases: RuntimeError

A method was entered while another is in flight on the SAME object. Distinct objects run concurrently; one object is for one caller at a time.

class eagle.ActiveSet(mask, *, reorder=None, classes=None, class_plane=None, class_theta=None, epochs=False, group=1, _lazy_scratch=False, _lazy_map=False)[source]#

Bases: object

The live samples of mask (a terminated plane: set = finished), as an ascending index map plus a count – and, with reorder=theta, the occasional physical reorder of the planes it owns. mask is a one-dimensional, C-contiguous bool/uint8 array (any device or host array), held by reference and read where it is every time. The map, count and device scratch are allocated once, before any capture, and live as long as this object. reorder is an explicit opt-in: the locality threshold theta (in THETA_RANGE, or True for DEFAULT_THETA) that pays on large, irregularly thinning batches (from about 1e5 samples; below that the map alone is as fast). The set then owns the mask and every plane given to own(). The set starts as the identity (every sample live, count == n).

group=G compacts whole groups of G lanes, for a kernel emitted for that group (its lane_space.group): a group is live while any of its lanes is, the map holds group indices (map[t / G] * G + t % G is the lane thread t runs) and count the lanes launched, live groups times G, so a last partial group launches past n. It does not combine with reorder=. check_group() refuses, at bind, a kernel emitted for another group.

classes=K (with class_plane) makes it a K-class set, for a kernel whose samples fall into K branches that diverge a warp when interleaved. class_plane is a C-contiguous uint8 array of n entries, each sample’s class in [0, K); the set owns it (it moves with every other plane) and K is at most MAX_CLASSES (255). The set must reorder (reorder=theta). class_sort() groups the live samples into one run per class, in one stable permutation carried by perm/inv, so the sample pairing is the one of any reorder. The planes it adds:

  • offsets – K + 1 words, the exclusive prefix over the live samples: class c occupies slots [offsets[c], offsets[c + 1]) and offsets[K] == count. Valid after a sort, until the next reorder or restore().

  • class_sorts – how many class sorts ran (a class sort is never counted as a reorders).

  • mixed32 – 32-slot groups holding two or more live classes (written by every compaction).

  • class_fire – 1 when the last compaction found a class sort worth running (see below); reorder() and reorder_if_degraded() run the sort exactly then.

  • stale_count – an input: the samples whose class changed since the last sort, written by a kernel whose branch is chosen from evolving state (0 when classes never change).

A compaction sets class_fire to (mixed32 > 0 and mixed32 >= class_theta * live32 and span >= MIN_CLASS_SORT_SPAN) or stale_count > STALE_MAX * count or fire: the live samples are mixed across at least class_theta of the warps they occupy, or more than STALE_MAX of them changed class, or the liveness reorder already fired. class_theta defaults to CLASS_THETA and is accepted in THETA_RANGE. With epochs=True the set keeps a snapshot of perm after every sort (epochs). On the device the K-class set needs a backend providing the seam symbols compact_classes_device and reorder_classes_device (eagle._core.backend_has()); without them construction is refused, naming the backend and the symbol.

mask#
n#
map#
count#
theta#
perm#
inv#
span#
fire#
live32#
reorders#
classes#
class_theta#
stale_count#

samples whose class changed since the last sort (written by the units of a forced segmented policy; 0 = none)

Type:

IN

class_plane#
offsets#
class_sorts#
mixed32#
class_fire#
group#
n_groups#
__call__()#

Recompute the map and the count from the mask (and, for a reordering set, live32/fire). Device: enqueued on the eagle’s current stream (capturable). Host: computed now. With group > 1 a group of lanes is live while any of its lanes is, the map holds group indices and count the lanes launched (live groups times group).

Return type:

None

bytes_per_sample()[source]#

Bytes one sample’s owned planes occupy: what a step moves per live sample, read by the compaction cadence’s memory term.

Return type:

int

class_sort(*, within_live=False, if_fired=False)[source]#

Stable counting sort of the slots by (live, class). Every owned plane, perm and inv move together; offsets[c] becomes the first live slot of class c (offsets[K] == count), the map the identity over [0, count), class_sorts += 1. within_live=True permutes the slots [0, count) among themselves by class only (the reverse’s form: liveness is the prefix, count/span unchanged); otherwise [0, span) is sorted by (live, class) and span = count. if_fired=True sorts only when the last compaction raised class_fire (mixed32 >= theta * live32 over at least MIN_CLASS_SORT_SPAN samples). Returns whether a sort ran. Host: now. The device face needs the backend’s class symbols.

Return type:

bool

Parameters:
  • within_live (bool)

  • if_fired (bool)

compact()[source]#

Recompute the map and the count from the mask (and, for a reordering set, live32/fire). Device: enqueued on the eagle’s current stream (capturable). Host: computed now. With group > 1 a group of lanes is live while any of its lanes is, the map holds group indices and count the lanes launched (live groups times group).

Return type:

None

property epochs: tuple#

the perm snapshot written after every reorder / class sort of a set built with epochs=True (empty otherwise), oldest first. A snapshot is a private copy.

Type:

The epoch table

in_sample_order(plane)[source]#

A copy of plane in sample order (plane[..., inv]); legal while permuted, capture-legal on the device.

indirect(*planes)[source]#

Declare bound per-sample planes the caller keeps in sample order (its kernel reads sample perm[slot] from them). Returns the set.

Return type:

ActiveSet

property live: int#

The live count as a Python int (a device sync for a device set).

materialize_map()[source]#

Allocate the deferred map (see _lazy_map) and set it to the identity. True when it was deferred, so the caller must re-point every bound plan at map; False when it already is real.

Return type:

bool

own(*planes)[source]#

Hand the set per-sample planes to move with the mask at every reorder (a (D, n) array is D planes). Refused once fixed, for a plane another set owns, or one overlapping an owned plane.

Return type:

ActiveSet

property permuted: bool#

Whether a reorder ran since the last restore() / reset() (a device sync for a device set).

planes()[source]#

The two reserved planes as eagle.plan.Plan.bind() keywords.

Return type:

dict

prepare_compaction()[source]#

Allocate the device compaction scratch (once). The first compact() does it when needed; anything that captures a compaction into a graph calls it first. A runner on a no-compaction fast path never pays for it.

Return type:

None

reorder()[source]#

Run the reorder now if the last compaction fired it: owned planes and perm move so live samples come first, inv/the map reset, span = count, reorders += 1. Device: enqueued on the current stream; host: now.

Return type:

None

reorder_if_degraded()[source]#

The reorder as a eagle.Skippable guarded by fire (one IF node under a graph, an eager check elsewhere).

reset()[source]#

Back to the identity: every sample live, count == n (and, for a reordering set, perm/inv identity, span == n, reorder counter zero). Run before a launch, never recorded; a reordering device set resets with one kernel on the current stream.

Return type:

None

restore()[source]#

Put every owned plane back in sample order; perm/inv reset to identity, span = n, the map recomputed. Eager only (refused under stream capture); a no-op for a set that does not reorder.

Return type:

None

when_finished(finished)[source]#

A eagle.Skippable compaction that runs only when finished moved since it last ran (the guard is evaluated on the device under a graph).

exception eagle.BackendUnavailable[source]#

Bases: RuntimeError

The device backend cannot serve this call (see the message for why).

A RuntimeError, so code that already guards a device call with except RuntimeError keeps working.

class eagle.DeviceProps(name, cc_major, cc_minor, sm_count, clock_rate_khz, memory_clock_rate_khz, memory_bus_width_bits, shared_mem_per_block, shared_mem_per_sm, regs_per_block, regs_per_sm, warp_size, peak_bytes_per_s, peak_flops_sp, peak_flops_dp, fp64_ratio, ridge_flops_per_byte_sp, ridge_flops_per_byte_dp)[source]#

Bases: object

Frozen view of one CUDA device’s raw + derived properties.

Field set mirrors eagle::DeviceProps (eagle/DeviceProps.h) exactly — see that header for every formula’s one-line derivation.

Parameters:
  • name (str)

  • cc_major (int)

  • cc_minor (int)

  • sm_count (int)

  • clock_rate_khz (int)

  • memory_clock_rate_khz (int)

  • memory_bus_width_bits (int)

  • shared_mem_per_block (int)

  • shared_mem_per_sm (int)

  • regs_per_block (int)

  • regs_per_sm (int)

  • warp_size (int)

  • peak_bytes_per_s (float)

  • peak_flops_sp (float)

  • peak_flops_dp (float)

  • fp64_ratio (float)

  • ridge_flops_per_byte_sp (float)

  • ridge_flops_per_byte_dp (float)

ridge_flops_per_byte(dtype)[source]#

flops/byte this device balances at for dtype (“float32” or “float64”) — a SELECT between the two C++-precomputed fields above, the same dtype convention eagle::DeviceProps::ridgeFlopsPerByte uses. Zero arithmetic on the Python side.

Return type:

float

Parameters:

dtype (str)

name: str#
cc_major: int#
cc_minor: int#
sm_count: int#
clock_rate_khz: int#
memory_clock_rate_khz: int#
memory_bus_width_bits: int#
shared_mem_per_block: int#
shared_mem_per_sm: int#
regs_per_block: int#
regs_per_sm: int#
warp_size: int#
peak_bytes_per_s: float#
peak_flops_sp: float#
peak_flops_dp: float#
fp64_ratio: float#
ridge_flops_per_byte_sp: float#
ridge_flops_per_byte_dp: float#
class eagle.GraphComposer(member_flags, *, mode='sequenced', device=-1)[source]#

Bases: object

Compose N members into one launch list, four ways (mode=) – see the module docstring for the pitch and each mode’s guidance.

member_flags (device routing flags / host routing pattern, retained by reference, never rebound):

  • mode="conditional" – required, a uint32 cupy array, one lane per member.

  • the other three modes – any host-side sequence of truthy/falsy values, or None for “every member starts active”.

A caller may mutate member_flags’s contents (via set_routing(), or – mode="conditional" only – direct index assignment) between replays, without recapture, but must never rebind the array itself.

Parameters:
  • mode (str)

  • device (int)

build()[source]#

Perform whatever one-time setup mode needs. Returns self (rejected, every mode, if no members are registered).

mode="conditional" wraps every step in a skippable guard and captures one GraphPipeline once; mode="enabled" registers every member as a plain member of one GraphPipeline, captures once, then applies the initial pattern via set_member_enabled (no recapture from here on); mode="rebuild" captures a super-graph of only the active members, re-capturing from scratch on every later set_routing(); mode="sequenced" is bookkeeping only, since every member already owns its own launchable.

fired_history()[source]#

Per-launch()-call fired-member index sets (frozenset), oldest first, since the last reset_fired_history() (or construction).

Return type:

list

launch(n=1)[source]#

Replay n times. Returns self.

The three flat modes delegate to the one super-pipeline’s GraphPipeline.launch() (a mode="rebuild" composer with an all-inactive pattern owns no pipe, so n replays of nothing is a no-op). mode="sequenced" fires every currently-active registered member (_launch_sequenced()), with the cross-member overlap treatment for stream-owning launchables.

property member_flags#
property mode: str#
node_labels()[source]#

Kernel names of the captured nodes, in declaration order. Same availability caveats as num_nodes().

Return type:

list

property num_members: int#
num_nodes()[source]#

Kernel-node count of the one captured super-graph (after build()). Not available for mode="sequenced" (no single super-graph – introspect each member on its own), nor for a mode="rebuild" composer whose current pattern is all-inactive.

Return type:

int

register(obj, *, name=None, pre_launch=None)[source]#

Register one member; returns its assigned index (registration order).

obj may be:

  • a built launchable – any object with a working .launch(n) (duck-typed). mode="sequenced" only.

  • a plain zero-arg step callable – valid in every mode: one member of this composer’s own super-GraphPipeline under the three flat modes, replayed directly under mode="sequenced".

  • a built mode="sequenced" GraphComposer – the recursion lock. mode="sequenced" outer composers only.

pre_launch (mode="sequenced" only) is an optional zero-arg callable run immediately before this member’s replay(s) – on that member’s own stream if it joins the cross-member overlap group, otherwise host-side. Common rejections, loud: registering after build(); the same object registered twice; a colliding name; nesting a composer under a non-"sequenced" outer composer, or nesting an unbuilt/wrong-mode composer under a "sequenced" one; a pre_launch hook outside mode="sequenced"; an obj that is none of the three accepted shapes.

Return type:

int

reset_fired_history()[source]#

Clear the fired-set history (does not affect current routing).

Return type:

None

set_routing(pattern)[source]#

Update which members are active.

Mechanism + cost depend on mode: "conditional" writes the device flags array in place (no recapture); "enabled" calls GraphPipeline.set_member_enabled per member (no recapture, µs-scale toggle); "rebuild" re-captures a fresh super-graph (paid here, not per replay); "sequenced" updates the host-known launch list.

pattern is any sequence of truthy/falsy values, length == registered member count.

Return type:

GraphComposer

class eagle.Graph(*, record=False, backend=None, dispatch=None, device=None)[source]#

Bases: object

A graph of launches: build it once, launch it many times.

add/add_group/add_node append (chaining); build derives the edges, refuses conflicts, and lowers to the GPU or CPU; launch / enqueue / synchronize are eagle.GraphPipeline’s verbs (on the CPU enqueue is launch). show() / str() / plot() / to_mermaid() / to_dot() draw it. The keywords record, backend, dispatch and device are the defaults of build()’s.

__call__(n=1, /)[source]#

Replay n times and wait; returns result (None without one).

Parameters:

n (int)

add(bound, *, name=None, grad=True)[source]#

Append one plan launch (a eagle.plan.BoundPlan).

grad=False marks the launch as not differentiated (a controller that writes a step size, say): a recorded run and eagle.diff.Reverse skip it, so it needs no vjp and no tape, and its outputs carry no gradient back. A differentiated node may read what it writes only through a one-cell parameter plane; build() with record=True refuses any other plane by name.

Return type:

Graph

add_group(branches, *, names=None)[source]#

Append a fork/join stage: at least two independent branches, each a BoundPlan, a Node, or a list of them (run in order inside the branch; a branch may hold a nested group or a conditional), joined before the next node. Siblings that overlap are refused at build().

Return type:

Graph

add_node(node, *, name=None)[source]#

Append any registered-kind Node, or an existing eagle.skippable / eagle.repeat_while object.

Return type:

Graph

property backend#

"gpu", "cpu", or None before build().

bind(**planes)[source]#

New arrays for the builder’s parameters, by name, in place: same shape, dtype and device, no copy, no rebuild.

Return type:

Graph

build(*, backend=None, record=False, dispatch=None, device=None)[source]#

Derive the edges, refuse conflicts (always), and lower. backend is inferred from where the planes live; "cpu", "gpu" (the one installed GPU kind; two installed kinds are refused) or a kind such as "cuda" states it. record=True keeps what a reverse pass needs (eagle.diff): after each launch(), record is that launch’s Record.

The graph runs on the GPU its planes live on (device=n is checked against them); planes on two GPUs are refused.

The keywords of Graph are the defaults of the same-named ones here.

dispatch lowers the policy="auto" dispatch groups of the graph’s hawk kernels (None or "switch": the fused kernel; "predicated"; or {group: policy}), rebuilding those plans over the planes they were bound with; a plan without an "auto" group is not touched. A built graph is one fixed structure, so a split ("segmented") is refused here: it is decided as a run goes, in eagle.simulate(). dispatch says what was chosen.

Example:

graph = eagle.Graph().add(bound_step).build(dispatch="switch")
graph.dispatch   # {"walker": {"dispatch0": "switch"}}
Return type:

Graph

classmethod builder(fn)[source]#

Decorate fn: a parameter annotated eagle.Graph makes a block that appends to the graph it is given; none makes a builder that makes, records into and returns its Graph (calling it on arrays builds that Graph; nothing runs). Control flow on 1-cell uint32 arrays becomes device control flow. Either call takes layout= ("samples_first" or "samples_last") for every plane its body binds.

cuda_graph()[source]#

An owned clone of the built GPU graph’s CUDA graph, taken now, for a foreign runtime to add with cudaGraphAddChildGraphNode (see CudaGraphHandle); it carries every array bind() swapped in. Refused with RuntimeError naming the node and the reason: a CPU graph, a segmented graph (a node outside the capture tier), any host-function node, and what the driver does not accept as a child graph (conditional and memory-allocation nodes; the CUDA error and driver version are quoted).

Return type:

CudaGraphHandle

property dispatch: dict#

{node label: {group: policy}} the last build() lowered (empty when no node had an "auto" dispatch group).

edges()[source]#

tuple[Edge]: Edge(src, dst, plane, kind) with kind in "RAW" | "WAR" | "WAW", indices into node_labels().

Return type:

tuple

enqueue(n=1)[source]#

Enqueue n runs without waiting (CPU: same as launch()). A graph with a stream node stays non-blocking (each stage is fenced on the device); one with a host node waits as launch() does. As for eagle.GraphPipeline, write no plane of the graph between enqueue and synchronize().

Return type:

Graph

Parameters:

n (int)

property host_lanes: tuple#

the threads its next launch uses (1 = in place on the calling thread). A stage’s first launch runs in place and is timed; later launches use one thread per 40 µs of that time, within eagle.exec.host_threads(). Empty on the GPU and before build().

Type:

Per stage on the CPU

host_table()[source]#

The built CPU graph as a table another runtime runs from its own OpenMP region.

The result’s .handle is a const eagle_host_table* (plugin/graph_handoff.h); the result holds this graph, and so its bound arrays, alive. It is a snapshot: bind or a rebuild makes it stale and eagle_host_table_run then refuses it. Refused here for a GPU graph, a node of your own code, and a node that keeps run state.

launch(n=1)[source]#

Run the graph n times and wait (enqueue(n) then synchronize()). A record=True graph runs once per launch and keeps that run’s Record in record.

Return type:

Graph

Parameters:

n (int)

node_labels()[source]#

Labels (the node’s name, else its kind) of every executable node, in add order, the members of a group included.

Return type:

list

num_nodes()[source]#
Return type:

int

parallel()[source]#

with g.parallel() as p: opens a fork in the builder; leaving the with joins. p.branch() yields a branch handle.

plot(ax=None, *, edge_labels=True, show_schedule=True)[source]#

Draw the graph with matplotlib (optional extra: pip install raptor-eagle[plot]) at the coordinates of the same layout show() uses; returns the Figure. ax draws into an existing axes. A figure made here is a plain matplotlib.figure.Figure (no pyplot state), so it is safe on a headless machine and from any thread.

Parameters:
  • edge_labels (bool)

  • show_schedule (bool)

property record#

The Record of the last launch of a record=True graph (what eagle.diff.reverse() takes), else None.

property result#

set while building (an array, or a tuple / list / dict of arrays), read-only after.

Type:

The arrays this graph returns

property schedule: tuple#

on the CPU "work_share" | "branch_tasks"; on the GPU "capture" | "eager_stream" | "eager_host"; empty before build().

Type:

Per stage

show(*, file=None)[source]#

Print the graph as a box block diagram (str() returns the same text): nodes by stage, the planes between them, conditionals as frames, opaque nodes dashed, the schedule per stage after build(). Works on the graph so far; never builds or launches.

Return type:

None

synchronize()[source]#

Block until enqueued runs complete (CPU: a no-op). An exception a host node raised in those runs is raised here.

Return type:

Graph

to_dot()[source]#

The graph as Graphviz DOT text.

Return type:

str

to_mermaid()[source]#

The graph as Mermaid flowchart TD text.

Return type:

str

update(values=None, /, **kw)[source]#

Change parameters of a record=True graph between launches: g.update(k=0.3) sets every node’s k, g.update({"join.k": 0.3}) one node’s. A recorded graph holds its parameters in one-cell planes, so this is a copy into them: nothing is rebuilt or recaptured, forward or reverse. Refused while the last launch’s Record is live (reverse it, or keep() it, first).

Return type:

Graph

wait(*planes)[source]#
class eagle.GraphPipeline(device=-1)[source]#

Bases: object

A CUDA-graph wrapper: capture a sequence of launches once, replay cheaply. Backed by the eagle._core binding of the eagle::cuda C++ core, so capture/instantiate/replay is the same code a native C++ consumer runs.

Parameters:

device (int)

add(step, *, name=None)[source]#

Register a zero-arg callable that issues launches on the current stream. The callable may issue one launch or several; what matters is not the count but the stream – build() captures whatever it launches on the stream that is current at the time it runs. name (optional, keyword-only) aliases this step as an individually addressable member: after build(), pipe.set_member_enabled(name, False) (or its registration-order index, always valid – see member()) disables its launches on replay with no recapture. Every step is a member, named or not.

add_concurrent(members, *, names=None, syncs=())[source]#

Register a fork/join stage: every member is a sibling of every other, and both join before whatever is registered next. members is a sequence of zero-arg callables, len(members) >= 2 – each has the same contract as add()’s step. Co-execution is permitted, never required: replaying members serialized, in registration order, is always a conforming schedule. Within one member its own launches still serialize; fork/join only forks between members. Actual concurrency, if any, is bounded by the device’s own occupancy, never a fixed constant. v1 is series-parallel only: a plain chain of add()/add_concurrent() registrations, each stage joining fully before the next begins. This does not check that members are actually independent – call _concurrent_write_conflict_check() yourself before build() if you want that asserted. names (optional) aliases each member the same way add’s name does – a sequence the same length as members, entries may be None. Every member is individually addressable by its registration-order index regardless of whether it is named.

build()[source]#

Stream-capture the registered launches into an instantiated graph. Immediately before and after each registered member’s launches, this snapshots the in-construction graph’s node set (_core.capture_snapshot_nodes) and records the set difference as that member’s contributed nodes – the only place member boundaries are known at capture time. Toggleability classification (_core.is_node_toggleable) runs separately, right after capture ends: a member is toggleable later only if every one of its nodes is a kernel, memcpy or memset node. A Skippable or RepeatWhile member is marked non-toggleable structurally, from this layer’s own knowledge that it wove a conditional region, without ever driver-querying its nodes (cudaGraphNodeGetType fails on this driver for a conditional/IF node). Either way the member is recorded non-toggleable, never silently accepted.

enqueue(n=1, *, pre_launch=None, seed_events=None)[source]#

Enqueue n replays on this pipeline’s own stream and return immediately – the non-blocking half of launch(). launch(n) is enqueue(n) + synchronize(), verbatim. Use this pair directly only when several independent pipelines should have their device work in flight simultaneously: enqueue them all first, then synchronize them in a second pass, so the total wall time approximates max over the pipelines rather than their sum.

The ordering (see launch()) is applied here, not in synchronize(): an event is recorded on the caller’s current stream (and the legacy Stream.null when different) and waited on this pipeline’s own stream before the replays are issued. pre_launch (optional) is a zero-arg callable run on this pipeline’s own stream after the seed waits and before the replays – the seam for copying per-launch varying data into this pipeline’s buffers. seed_events (optional) are pre-recorded events to wait on instead of recording this pipeline’s own – the shared-event mode eagle.compose.GraphComposer._async_launch_group() needs, one event pair recorded once and waited on every member’s stream. An empty sequence means “I have already ordered this replay myself, issue no seed waits”. HAZARD 1 – one in-flight enqueue per pipeline. A second enqueue before the first has been synchronized re-records the same cached events; overlapping enqueues simply serialize on this pipeline’s single stream, interleaving in a way the caller cannot control. Enqueue once, synchronize, then enqueue again.

HAZARD 2 – the reverse write fence is gone. enqueue returns with the replay still in flight; the ordering events only say replay-after-seeds, nothing about writes issued after:

pipe.enqueue()
buf[...] = new_values  # RACE: the in-flight replay may read these
pipe.synchronize()

is a data race, silently. The discipline is: enqueue -> (only work that does not touch this pipeline’s buffers) -> synchronize -> write; stage new inputs via pre_launch instead. Raises RuntimeError if called before build().

property graph#
is_member_toggleable(handle_or_index)[source]#

Whether set_member_enabled() will accept this member (its captured node set is entirely kernel/memcpy/memset). Requires build() to have run.

Return type:

bool

launch(n=1)[source]#

Replay the captured graph n times. launch(n) guarantees all work previously enqueued on the stream eagle works on for the caller (eagle.stream) and the legacy default stream is visible to replay 1.

A stream-ordering fix. The pipeline’s own stream is non_blocking=True precisely so capture never entangles the legacy default stream ordinary cupy/torch launches land on – but that means replay is not otherwise sequenced after host-side seeding (buffer[...] = ...) done on the caller’s current or legacy stream. Under ambient GPU load the seed can lose the race and replay 1 reads pre-seed buffer contents. The fix: record an event on the caller’s stream (eagle.stream) and on the legacy Stream.null (when different) and wait on both, on the pipeline’s own stream, before the replay loop. This orders every consumer of launch() for free, at the facility seam, with no host block (~1-2us/call). Exactly enqueue(n) followed by synchronize() – same events, same order, same host block, same return value. The two halves are also available separately (see enqueue()) for a caller that wants several pipelines’ replays in flight at once.

member(name_or_index)[source]#

Resolve a name or registration-order index to this pipeline’s stable MemberHandle. Available any time after registration; does not require build() (only set_member_enabled() does, since toggleability is a build-time fact).

Return type:

MemberHandle

member_nodes(handle_or_index)[source]#

Raw node handles (as ints) attributed to one registered member by build() – the per-member analogue of node_labels(). A copy; mutating it has no effect. Requires build() to have run.

Return type:

list

node_labels()[source]#

Kernel function names of the captured nodes, in declaration order.

Return type:

list

num_nodes()[source]#

Number of kernel nodes in the captured graph.

Return type:

int

set_member_enabled(handle_or_index, enabled)[source]#

Enable or disable one registered member’s launches on this instantiated graph, effective on the next launch() – no recapture, no change to graph structure (composition mode “enabled”: capture once at full sibling concurrency, then flip driver-level enabled bits between replays). The host-paced sibling of the device-paced conditional (IF) node: where a conditional’s predicate is re-read by an in-graph kernel on every replay, this toggles a driver bit from Python between replays, for zero per-replay gate cost – the right tool when routing decisions are made in Python, not on-device. A member’s captured node set never changes after build(); this only flips whether that fixed node set runs. A disabled member’s nodes become driver-level no-ops (any buffer it would have written is left untouched); an enabled member’s nodes run exactly as captured. Requires CUDA >= 12.3 (the same floor the conditional facility already imposes on the compiled eagle._core extension). Raises NonToggleableMemberError if build() recorded this member as non-toggleable (its node set contains something other than kernel/memcpy/memset – most commonly a Skippable’s conditional node). UnknownMemberError for a bad name or index, and RuntimeError if called before build().

Return type:

GraphPipeline

Parameters:

enabled (bool)

set_node_enabled(node, enabled)[source]#

Enable/disable ONE raw captured node directly, bypassing this pipeline’s own member registry. For a caller that tracks its own node attribution outside add()/add_concurrent()’s member bookkeeping. The same underlying call set_member_enabled() makes per node (Launcher.set_node_enabled); this is only a narrower, public door to it for a caller already holding valid node handles (from capture_snapshot_nodes()).

node must be a real handle from this pipeline’s own capture – passing a foreign or stale one is undefined at the driver level. Requires build() to have run.

Return type:

GraphPipeline

Parameters:
  • node (int)

  • enabled (bool)

property stream: int#

This pipeline’s own cudaStream_t, as a raw integer handle (the family’s shared stream name: the same value a DLPack consumer passes as __dlpack__(stream=...)). For capture composition: a caller that needs to bind a cuBLAS/cuSOLVER-style handle to this pipeline’s stream, or run warm-up passes before build() captures, needs this exact stream – launching on any other stream would race the graph. Read-only, valid for this pipeline’s entire lifetime.

synchronize()[source]#

Block the host until this pipeline’s enqueued replays have completed – the blocking half of launch(). Safe to call with nothing in flight (a cheap no-op query on an already-idle stream). Raises RuntimeError if called before build().

class eagle.KernelRegistry(kernels=None)[source]#

Bases: object

A name -> launchable map for resolving a launchable by name.

Values are any launchable sharing the __call__ + launch protocol. Dict-like: reg[name], name in reg, len(reg), iteration over names, .get / .names.

get(name, default=None)[source]#

Return the launchable registered under name, or default.

Parameters:

name (str)

names()[source]#

The registered names, in insertion order.

Return type:

list

register(kernel, name=None)[source]#

Register kernel under name (default __name__); return the key.

Raises on a duplicate name – pass an explicit name= to disambiguate.

Return type:

str

Parameters:

name (str | None)

exception eagle.LayoutWarning[source]#

Bases: UserWarning

A sample-major plane was copied into eagle’s component-major layout.

Filterable like any warning; make it an error with warnings.filterwarnings("error", category=eagle.LayoutWarning).

exception eagle.PerformanceWarning[source]#

Bases: UserWarning

A request that is correct but known to run slower than the alternative.

Raised once per call, for example by dispatch="segmented" on a group whose selector reads a plane the step writes: the split kernels must then re-check the selector and sweep the samples that changed branch. Filter it on its own:

warnings.simplefilter("ignore", eagle.PerformanceWarning)
eagle.samples_first(x)[source]#

Mark x as sample-major: its FIRST axis holds the samples, (N, w) (a matrix plane (N, R, C)). Zero-copy, honoured for any shape; passes through any eagle or hawk door that binds per-sample planes, and beats the door’s layout=. A shape that contradicts it is refused.

eagle.samples_last(x)[source]#

Mark x as component-major (native): its LAST axis holds the samples, (w, N). Zero-copy, honoured for any shape; passes through any eagle or hawk door and beats the door’s layout=. A shape that contradicts it is refused.

class eagle.LoadedKernel(ptx_path, *, abi_kind)[source]#

Bases: LaunchMixin

Common scaffolding for a PTX-loaded launcher (no nvcc at runtime): reads the shared sidecar fields, rejects a binary-ABI mismatch, and driver-loads the module. Subclasses read their own fields, build self._allowed, and define launch / __call__ over the inherited _dispatch(). The parsed sidecar is kept on self._meta.

function(device, name=None)[source]#

The function name (default: the kernel) on CUDA device device, loaded into that device’s context the first time it is asked for (a kernel has no device of its own).

Parameters:
  • device (int)

  • name (str | None)

abi_tag#

The artifact’s own ABI generation, read by _refuse_v2_door() and by eagle.plan.plan’s legacy-partition bridge.

lane_space#

launch.lane_space (LaneSpace), the exact launch.block (None when the artifact states none), the sinks with named axes, the Sorted inputs and the thread box.

block#

launch.lane_space (LaneSpace), the exact launch.block (None when the artifact states none), the sinks with named axes, the Sorted inputs and the thread box.

plane_axes#

launch.lane_space (LaneSpace), the exact launch.block (None when the artifact states none), the sinks with named axes, the Sorted inputs and the thread box.

sorted_inputs#

launch.lane_space (LaneSpace), the exact launch.block (None when the artifact states none), the sinks with named axes, the Sorted inputs and the thread box.

box#

launch.lane_space (LaneSpace), the exact launch.block (None when the artifact states none), the sinks with named axes, the Sorted inputs and the thread box.

plane_meta#

The opaque notes on planes (plane_meta), by plane name.

param_names#

The binding names of params.

class eagle.LoadedPure(ptx_path)[source]#

Bases: LoadedKernel

A precompiled pure kernel loaded from a PTX (+ sidecar) artifact – no nvcc. Drop-in equivalent to the in-process compiled pure launcher via eagle.launch. The Mutable buffers are the handoff (read-modify-written in place), so there is no separate out=.

__call__(**kw)[source]#

Launch the pure kernel and return the updated Mutable buffers as a dict, in the caller’s framework.

launch(*, grid=None, block=None, **kw)[source]#

Capturable single pure launch on the current stream (cupy arrays only). The writable Mutable buffers, any inputs, lookup tables, and the terminated mask must be pre-allocated; read-modify-written in place. block=None defers to eagle’s launch-policy resolver.

class eagle.LoadedVector(ptx_path)[source]#

Bases: LoadedKernel

A precompiled vector kernel loaded from a PTX (+ sidecar) artifact – no nvcc.

Drop-in equivalent to the in-process compiled vector-kernel launcher.

__call__(*, out=None, **kw)[source]#

Allocate, launch, and return the contribution, in the caller’s tensor framework (numpy in -> numpy out, cupy/torch -> same via DLPack): blocking for numpy, non-blocking on the framework’s stream otherwise. Pass out= a pre-allocated device buffer to fill it in place – see as_out_buffer().

launch(*, out, grid=None, block=None, **kw)[source]#

Capturable single launch on the current stream (cupy arrays only). Inputs, out, and any lookup tables must be pre-allocated and passed by name. block=None defers to eagle’s launch-policy resolver.

class eagle.RepeatWhile(step, guard, max_iters=None, limit=None, brk=None)[source]#

Bases: object

A zero-arg step repeated on the device while a SkipGuard holds, at most max_iters times per replay (None: until the guard fails) – the loop sibling of Skippable (not a subclass: 0..N runs and 0..1 runs are different contracts).

Under GraphPipeline.build() the step becomes the body of one CUDA WHILE conditional node: a head kernel resets the [remaining, ran] cell and decides entry, the body runs, and a tail kernel decides continuation. launch(1) is one cudaGraphLaunch regardless of iteration count; launch(n) replays the whole loop n times.

max_iters is None or a plain Python int >= 1 frozen at build as a kernel argument – a new cap needs a new build(). A reverse pass needs the cap. limit (a uint32 cell) is a runtime trip count (ran < limit[0]) and brk (a uint32 cell the body writes) ends the loop after the iteration that leaves it nonzero; guard may be None when one of them stops the loop. Called directly it is the host arm: while ran < max_iters and guard.evaluate(): step(), writing the same cell so iterations() reads the same in every mode. The cell lives in the guard’s array module (cupy or numpy), allocated at construction; iteration_index exposes its ran word to body kernels as the device-visible iteration index (0 on the first iteration).

Composition: the body step may be a Skippable, or a tuple of such parts run in order (e.g. (k_steps, skippable(compact, guard))); a RepeatWhile, a Skippable or a fork/join group nests in any of them, and a RepeatWhile may be an add_concurrent member. One hidden inside an opaque body callable is not detected structurally: called mid-capture it runs its host arm, whose guard read syncs and fails the capture loudly.

Parameters:
  • guard (SkipGuard | None)

  • max_iters (int | None)

step#
guard#
max_iters#
limit#
brk#
property cap: int#

max_iters, or UNCAPPED.

Type:

The device cap

property iteration_index#

One-element uint32 view of the ran word – the 0-based index of the iteration in flight. Pass it to a body kernel that needs it; same array module as the guard.

iterations()[source]#

Iterations the last run performed (host read of ran; a device sync under a cupy guard, eager/debug paths only). 0 before any run.

Return type:

int

property parts: tuple#

The body as a tuple of parts, run in order (a single-step body is a one-part tuple).

class eagle.RunReport(n, finished, done, launches, steps, compactions, reorders, build_s, launches_by_k=<factory>, exact_steps=False, slot_fill=None, mode='band', probe=False, timed=False, dispatch=None, class_sorts=0, mapped=0)[source]#

Bases: object

What one Runner.run() did.

finished counts samples whose mask is set when the run ends, done is finished == n, launches the loop’s iteration count, and steps the steps the loop ran (launches * K, or the summed k for an automatic artifact). exact_steps says steps is exact (true for K=1, or an automatic artifact that launched nothing, hit the cap early, or ended on a one-step launch). compactions/reorders count what ran, build_s the one-time capture wall (0 on host), launches_by_k each k’s launch count. slot_fill (the steps run over the persist entry’s chunk slots, 32 lanes times the chunk length per warp per chunk head, in (0, 1]; a lane waiting masked for the next head is an empty slot) is set only for a persist-entry run that counted it; None otherwise (every other mode, or a persist run that skipped the counter). mode is the launch shape this run actually took: "fused_one"/ "persist" for a no-graph fast-path run, "band" for the WHILE-graph/policy path (the only mode before the fast path existed). probe is true for a fast-path run taken to time the entry the batch is not currently using (see Runner._pick_entry()); timed is true for a fast-path run that carried the timing event pair (a probe, the first run, or a run after the walls were invalidated), so a caller can warm until a run is neither probe nor timed. dispatch is None unless the run decided a dispatch group (dispatch=): {group: (policy, mix, gain)} with the policy in force at the end, the samples that took each branch at the last look and the predicted gain of splitting (above 1 the split wins); class_sorts counts the sorts of samples by branch a split run made. mapped is the samples the launches ran over, summed over the launches: n for a fast-path run (one launch over the whole batch), the live samples of each launch for a compacting run, launches * n for one that does not compact; 0 for a report that does not count them.

Parameters:
  • n (int)

  • finished (int)

  • done (bool)

  • launches (int)

  • steps (int)

  • compactions (int)

  • reorders (int)

  • build_s (float)

  • launches_by_k (dict)

  • exact_steps (bool)

  • slot_fill (float | None)

  • mode (str)

  • probe (bool)

  • timed (bool)

  • dispatch (dict | None)

  • class_sorts (int)

  • mapped (int)

class_sorts: int = 0#
dispatch: dict | None = None#
exact_steps: bool = False#
mapped: int = 0#
mode: str = 'band'#
probe: bool = False#
slot_fill: float | None = None#
timed: bool = False#
n: int#
finished: int#
done: bool#
launches: int#
steps: int#
compactions: int#
reorders: int#
build_s: float#
launches_by_k: dict#
class eagle.Runner(plan, *, max_steps, every=None, reorder=None, record=False, window=None, steps_reverse='per_step', memory_budget=None, events='step', on_no_event='raise', **planes)[source]#

Bases: object

A bound, built run-until-done loop over one plan, or a step of several plans launched in order (see until_done()).

Attributes: step (the eagle.plan.BoundPlan, or a tuple), loop, pipeline (the device eagle.GraphPipeline, built on first run()), active (the eagle.ActiveSet, or None), finished/terminated, steps_per_launch (K, or "auto"), every/launches_per_compaction. For an automatic artifact fused_steps is the device steps-per-launch word and policy reads the policy’s cells (a sync). host_policy picks how a host run paces automatic launches: "auto" (default: "tiled" when the entry’s fused side is tiled, else "measured"), "tiled" (steps_max steps per launch), "measured" (sweeps one step per launch until a timed fused probe wins) or "band" (the device’s band). host_threads is the host team size: None (default) lets eagle pick it (one thread per physical core for a short run, every logical CPU for a long one — see eagle._host_loop.host_team_size()), an int forces it. Planes are held by reference: a run writes the caller’s arrays in place; a new binding is a new runner.

step#
loop#
pipeline#
active#
finished#
terminated#
n#
steps_per_launch#
every#
launches_per_compaction#
fused_steps#
auto#
host_policy#
host_threads#
property event_status#

Per sample, how an events="refine" run located its event (int8): 1 inside the stop step, 2 at the step’s end, 3 no event (with on_no_event="zero"); None without events="refine".

property launch_policy: dict#

What the launch rules chose for this runner, for a probe report: block and grid of the persist launch (None when the runner has none), chunk (steps per fetch; None when the entry takes none), fill (the step fill the sizing last read, first run 0.5), rate (R) and k (the band’s current steps per launch; None off the band). Pair it with eagle.plan.BoundPlan.entry_reports() (registers, local memory, code size, bound, demanded threads).

property policy: dict | None#

The automatic loop’s policy cells as host ints (a device sync): k, finished_at_launch, steps_done, max_steps, go; None for a fixed artifact.

property record#

The eagle.diff.Record of the last run of a record=True runner (None before the first run, or without record=True): pass it to eagle.diff.reverse().

Example: runner.run(); grads = eagle.diff.reverse(runner.record, {"x": dJ_dx}).

reset()[source]#

Clear the mask/counter/active set: the next run() starts the batch over.

Return type:

None

result(name)[source]#

The plane name after a run, as the caller’s own array type. A numpy or cupy plane is the caller’s array, written in place. A plane from another framework (jax, torch, …) is read in place and never written: a plane the kernel writes comes back as a NEW array of that framework holding the answer (a copy per call), an unwritten one as the caller’s array itself.

Parameters:

name (str)

run()[source]#

Run until every sample is done (or the cap is reached) and report; the counter is re-synced to the mask first, so a run continues from the current state (a reordering set’s planes land back in sample order).

The counters this needs before/after the launch (not counting the automatic policy’s own steps_done/histogram/ fused_steps reads, still separate – see _build_auto()) are read as ONE packed transfer per snapshot (_packed_read()) instead of a separate full round-trip sync each: a plain, non-compacting run (self.active is None) needs no PRE snapshot at all (_compactions can only ever be 0 without an active set, so it is never even read), and the POST snapshot folds iterations/finished/compactions/reorders into one.

A fast mode (_build_fast()) skips all of the above: one launch IS the run, so _run_fast() handles it entirely.

Return type:

RunReport

property t_stop#

The event time of each sample of an events="refine" run (the step’s end time for a sample with no located event); None otherwise. A per-sample plane, written by every run.

class eagle.SimResult(*, state, finished, report, wall_s, allocated, record=None, t_stop=None, event_status=None, history=None)[source]#

Bases: object

What one Simulation.run() produced. state maps each state plane to its array (written in place, plus allocated ones, listed in allocated); each is also an attribute (result.x) and an item (result["x"]). finished is the per-sample mask, done whether every sample did, status "finished"/"max_steps", steps/report/wall_s the loop’s steps, full eagle.RunReport and wall time. An events="refine" run also fills t_stop (each sample’s event time) and event_status (see eagle.Runner.event_status); both are None otherwise. A history= run fills history: each state plane’s rows (the state before the first step, then after every k-th), None otherwise.

state#
finished#
done#
steps#
status#
report#
n#
record#
wall_s#
allocated#
t_stop#
event_status#
history#
returned(returns)[source]#

This result with its arrays as returns’s type ("numpy", "cupy", "torch", "jax"; see eagle.Array.to()); None keeps the eagle.Array s. A framework that is not installed warns once and keeps them.

class eagle.Simulation(model, args, kwargs, *, until=None, max_steps, every=None, reorder=None, scalar_type=None, layout=None, record=False, window=None, steps_reverse='per_step', memory_budget=None, dispatch=None, events='step', on_no_event='raise', history=False)[source]#

Bases: object

A bound, built simulation (see simulation()): run() runs it, reset() starts the batch over. runner is the eagle.Runner driving the model, loop/pipeline its loop and device eagle.GraphPipeline (None on host), plans the plans per kernel, n the batch size, names the state/params/allocated plane names.

runner#
loop#
plans#
n#
names#
active#
finished#
terminated#
every#
property pipeline#

The device eagle.GraphPipeline (built on the first run()); None on the host and before.

property record#

The eagle.diff.Record of the last run() of a record=True simulation (None otherwise): pass it to eagle.diff.reverse().

Example: sim.run(); grads = eagle.diff.reverse(sim.record, {"x": dJ_dx}).

reset()[source]#

Clear the finished mask (and the active set): the next run() starts the batch over; the caller re-seeds its state.

Return type:

None

run()[source]#

Run until every sample finishes or the step cap is reached; the state is written in place and returned in the SimResult. A second call continues from the current state.

Return type:

SimResult

class eagle.SkipGuard(count_arr, count_idx=0, baseline_arr=None, baseline_idx=0, negate=False)[source]#

Bases: object

Region runs iff count_arr[count_idx] != (baseline_arr[baseline_idx] or 0). Arrays are uint32 device (cupy) or host (numpy) arrays; references are retained so pointer lifetime stays pinned to the pipeline.

count_arr#
count_idx#
baseline_arr#
baseline_idx#
negate#
evaluate()[source]#

Host read; eager/debug paths ONLY (syncs on cupy).

Return type:

bool

classmethod intent(flags, index)[source]#

Router/user-owned intent flag: flags[index] != 0.

flags is a uint32 array the caller owns and writes between graph replays, one lane per guarded region (e.g. SkipGuard.intent(expert_flags, e) for expert e). No baseline: a plain on/off decision.

Under GraphPipeline.build() the predicate is read fresh from the device every replay, so flipping flags[index] takes effect with no recapture; in eager/numpy mode the same flag is read host-side by evaluate().

index has no default (unlike nonzero()’s 0): it is load-bearing at every call site.

negated()[source]#

The guard that holds exactly when this one does not (the else arm); one device-side flag, no derived cell.

Return type:

SkipGuard

classmethod nonzero(n_active)[source]#

Plain nonzero count: n_active[0] != 0.

class eagle.Skippable(step, guard)[source]#

Bases: object

A zero-arg step wrapped with a SkipGuard. Works as a GraphPipeline.add() step or an add_concurrent member – GraphPipeline.build() recognizes it by type and weaves an IF node around it; called directly, it evaluates its guard eagerly: if guard.evaluate(): step().

Parameters:

guard (SkipGuard)

step#
guard#
eagle.assemble_args(arg_spec, *, out, vec, per_sample, terminated, uniforms, n, tables=None, mutables=None, mutable_vec=None, mutable_mat=None, mats=None, wide_in=None, wide_out=None, plan=None)[source]#

Build the kernel argument tuple in the order the signature expects.

The mutable output, input vectors, and matrix inputs are by-value GRef structs (a matrix GRef composes the flat vector one); per-sample scalars, the termination mask, lookup tables, and a pure kernel’s scalar/int Mutable slots are by-value HandleT views; broadcast constants are float64. A vector kernel’s GRef carries its own samples_; a pure kernel takes an explicit nsamples instead. wide_in/wide_out are also HandleT views, each riding its own caller-populated dict so they never collide with an unrelated per-sample-scalar or lookup-table name.

The ABI-shape decision per role is eagle.roles.classify_arg() (single-sourced with the ctypes host path); this function keeps only the construction – which dict a role’s value comes from, and which make_* helper builds it. An unrecognised role raises before any role-specific branch runs.

plan (optional) is the LaunchPlan for THIS signature. When given, the per-argument classification and POD boxes come from it instead of being re-derived here; the resulting argument list is byte-identical either way (read LaunchPlan’s box-reuse note first). Omit plan for fresh boxes per call, as always.

eagle.check_aether_abi(meta, *, kind, name)[source]#

Reject an artifact whose meta["aether_abi"] is not one of ACCEPTED_ABI_TAGS (absent/empty included). kind names the artifact in the error (e.g. ‘vector plugin’, ‘plugin manifest’).

Return type:

None

Parameters:
  • meta (dict)

  • kind (str)

  • name (str)

eagle.compaction_body(step, active, *, every=16, finished=None, reorder=None, steps_per_call=1)[source]#

The eagle.repeat_while() body that runs step every times, then compacts active – only when finished moved, if given, else unconditionally – and, for a set built with reorder=theta over at least MIN_REORDER_SPAN samples, reorders when the compaction fired (reorder=False/True overrides this). The loop guard is checked once per every steps, so it may run up to every - 1 steps past the last sample finishing; size max_iters as ceil(max_steps / every). steps_per_call is the steps one step() call advances (a fused kernel’s K): the body then runs every * K steps between compactions, and a cadence below MIN_EVERY steps is refused.

Return type:

tuple

Parameters:
  • active (ActiveSet)

  • every (int)

  • steps_per_call (int)

eagle.copy(src, *, into, name=None)[source]#

into[...] = src as a graph node, where either array may live on the host or on the device: the direction (host to device, device to host, device to device, host to host) follows from where the two live. Both are your arrays, of one shape and dtype, contiguous; eagle allocates nothing. src and into sharing their storage make a node that does nothing (the edges stay).

Inside a builder the node is recorded and into is returned, so h = eagle.copy(d, into=h) reads as the data flow. Elsewhere the node is returned, for Graph.add_node. eagle.copy(x, into=eagle.pinned(...)) is torch’s .cpu() with the buffer in your hands.

Example:

h_probe = eagle.copy(probe, into=h_probe)     # device -> host
flags = eagle.copy(h_flags, into=flags)       # host -> device
class eagle.Array#

Bases: object

property T#

(self) -> eagle._core.Array

astype#
copy#
property device#

(self) -> str

property dtype#

(self) -> eagle._core.DType

fill#
get#
property is_contiguous#

(self) -> bool

item#
property itemsize#

(self) -> int

property nbytes#

(self) -> int

property ndim#

(self) -> int

property ptr#

(self) -> int

ravel#
reshape#
set#
property shape#

(self) -> tuple

property size#

(self) -> int

property stream#

(self) -> int

property strides#

(self) -> tuple

sum#
synchronize#
to(framework)#

self as framework’s array type ("numpy", "cupy", "torch", "jax"), through that framework’s bridge (eagle.frameworks.<framework>.from_eagle): zero-copy where the framework can alias the memory. Raises ImportError with the install hint if the framework is missing.

tolist#
transpose#
view#
class eagle.IndexSet[source]#

Bases: object

The host builder of an index set’s planes: IndexSet.planes(selection, extent).

static planes(selection, extent, *, width='auto', capacity=None, device=None)[source]#

{"active_map": ..., "active_count": ...} for the lanes selection names out of extent.

selection is a boolean mask over the extent lanes, or the lane ids (any integer sequence or array, each lane once). The map holds the ids in the order given (a mask: ascending) and has room for capacity entries (default: as many as selected; the unused tail is zero); active_count is one uint32 cell. width is "auto" (32, or 64 past 2**31 - 1 lanes), 32 or 64. The planes are checked, and live on device (default: the host).

Return type:

dict

eagle.check_index_set(map, count, extent, *, width=None, what='the index set')[source]#

Check the plane pair of an index set: count[0] entries of map, each in [0, extent), none twice.

map and count are arrays (an eagle.Array, numpy, cupy, torch…; a device array is read back). width (32 or 64), when given, is the unit’s map word: a map of the other word is refused. Raises ValueError naming the first offending position. Run it after rewriting a bound map in place: a replay does not.

Return type:

None

class eagle.DType#

Bases: object

property code#

(self) -> int

property itemsize#

(self) -> int

property kind#

(self) -> str

property name#

(self) -> str

property typestr#

(self) -> str

eagle.deploy(plugin, *, targets=None, cache_dir=None, scalar_type=None, **plan_kw)#

An AutoPlan for plugin: run it where its data lives. eagle.deploy is this same function.

plugin is a built plugin, a hawk kernel, or a list built into one bundle (returned as a tuple of plans in order). The build uses hawk’s cache under cache_dir (None: hawk’s default); a repeat call compiles nothing. targets (None: both sides when a GPU is usable – the call returns with the device built, the host still building beside it – else the host alone), cache_dir and scalar_type are refused for an already-built plugin. scalar_type is the precision hawk builds in: "float64" (None, the default), "float32" or "banded"; the planes passed at run time must match it (banded planes are packed with eagle.banded_pack()). Banded is a device feature for GPUs with weak or no FP64; on a CPU use float64 (a banded deploy with no usable device, or with a host target, is refused).

plan_kw are plan()’s keywords but structure (inner/gather do not apply); a side the plugin lacks is refused when first selected.

Return type:

AutoPlan | tuple[AutoPlan, ...]

eagle.detect(x)[source]#

Identify x’s framework adapter without importing the framework. None for a value we don’t recognize as a tensor (to_array() then treats it as a host buffer).

Return type:

Adapter | None

eagle.device_props(device=-1)[source]#

Query device device’s properties (-1: the current device) via eagle._core.device_props() and wrap the resulting dict in a frozen DeviceProps — no Python-side computation, only a dict-to-dataclass reshape.

eagle._core (the compiled extension) is imported LOCALLY, here, never at this module’s top — importing eagle on a cuda-free box must not force-load it (the same discipline eagle.pipeline. GraphPipeline.__init__() follows for the same reason).

Return type:

DeviceProps

Parameters:

device (int)

eagle.launch(kind, fn, arg_spec, vector_inputs, params, per_sample, *, kw, grid, block, dt='float64', **extra)[source]#

Issue ONE capturable launch of any kernel kind on the current stream. kind ("vector" | "pure") selects the ABI binding shape; kind-specific inputs ride extra (a vector kernel’s out=, or a pure kernel’s mutables_decl=, each with optional matrix_inputs=/wide_inputs=/wide_outputs=/ wide_out_exempt=, named identically to pure_prepare()’s). Every array argument must be pre-allocated cupy. Returns the vector out, or the pure Mutable dict merged with wide outputs.

eagle.load_manifest(path)[source]#

Load a deployed manifest.json by its top-level pattern.

The Python analogue of the C++ PluginRegistry::from_manifest – but where that injects the whole ordered set, this returns a by-name result:

  • "vector" / "pure" – each enabled entry’s artifact is path-loaded into LoadedVector / LoadedPure and keyed by its manifest id into a KernelRegistry.

  • "graph_block" – a graph-block deployment unit: the inline blocks[] compose one ordered layer whose exec references resolve against the plugins[] kernels, returned as a frozen graph-block layer wrapper. Recognized but not launch-certified, so it never enters the by-name map.

An unknown or absent pattern is a hard error. Returns KernelRegistry | LoadedBlockLayer.

eagle.make_gref(arr, n)[source]#

Build a by-value GRef over a contiguous (3, N) device array (anything with .ptr): compStride_ == samples_ == n, sampleStride_ == 1.

eagle.make_handle(arr, n)[source]#

Build a by-value scalar-array HandleT over a contiguous (N,) device array; n is required since the struct carries its own extent.

eagle.opaque(fn, *, reads=(), writes=(), eager=False, stream=None, name=None, grad=True)[source]#

Your own code as a graph node: a zero-arg callable (a cupy custom kernel, a torch op, a host closure) with the arrays it touches DECLARED – a sequence of arrays, or a {name: array} mapping. Edges are derived from those arrays (the declaration says WHICH planes, never which edges) and the conflict check covers them; name every plane the node touches, since an array it touches but you did not declare is invisible to the conflict check and the reverse.

How it runs on the GPU (the CPU always calls it eagerly, in order):

  • default – captured: fn issues its device work on the current stream at build and is replayed with the graph (also inside groups, conditionals and until_done steps). It must not allocate.

  • stream=S – stream-ordered: fn runs on the host each launch with S (an int, a torch/Warp/CuPy stream or a __cuda_stream__ object) as cupy’s current stream; issue its device work on S (torch.cuda.stream(S) for torch). S waits for the stage before and the stage after waits for S; the host never waits. Keep what that work reads alive until it ran (torch: tensor.record_stream(S)).

  • eager=True – host-synchronized: fn runs on the host each launch between two device syncs, on any stream, host readbacks allowed. The sync waits for every stream of the device, other threads’ work included.

g.schedule names the tier per stage (capture / eager_stream / eager_host) and str(g) tags the node. A reverse pass through it needs vjps={label: fn} (eagle.diff.reverse()): the label is name when given (Graph.add(name=) wins over it), the kind otherwise. grad=False marks the node as not differentiated (see eagle.Graph.add()): a reverse skips it and needs no vjp for it.

Return type:

Node

eagle.origin_adapter(candidates)[source]#

Pick the adapter the kernel’s output should be returned as, over the state-vector inputs in signature order: the first strong framework (torch/jax/tensorflow) wins (two distinct ones raise TypeError), else the first device adapter, else numpy.

Return type:

Adapter

eagle.pinned(shape, dtype='float64')[source]#

An eagle.Array in page-locked host memory, uninitialised.

A copy between the device and a pinned array is a plain DMA transfer; from an ordinary host array the driver stages it first (it works, without overlap). Pinning is yours: eagle never pins an array behind your back. The memory is freed with the array. Without a GPU backend, or with no device visible, this is an ordinary host array (not page-locked). numpy.asarray(h) views it with no copy.

Example:

h_probe = eagle.pinned((3, n))
eagle.copy(probe, into=h_probe)     # device -> host
eagle.pure_prepare(fn, arg_spec, *, vector_inputs, per_sample, params, mutables_decl, mutable_defaults, lookup_counts, kw, mat_shapes=None, vec_widths=None, wide_inputs=None, wide_outputs=None, wide_out_exempt=(), dt='float64', readonly_mask=False)[source]#

Coerce inputs, bind the writable Mutables, assemble args, launch (no sync). The pure allocate-and-launch body, shared by the in-process compiled pure launcher and the deployed LoadedPure so the two can never drift.

State vectors -> (3, N) f64; matrix inputs -> flat (R*C, N) f64; provided Mutable arrays -> device buffers (also sizing N); per-sample scalars -> (N,); lookup tables -> flat handles; wide inputs -> 2-D (rows, N); wide gradient outputs -> 2-D (rows, N) written in place, never auto-allocated. wide_out_exempt names the wide_outputs that are row-indexed destinations (e.g. an atomic by-key store output), skipping N-reconciliation. A Mutable omitted from kw is a broadcast scalar fill or its declared default. Returns the Mutable buffers merged with any wide gradient outputs (RMW in place). Meant to run inside the caller’s launch context (see LaunchMixin._dispatch()).

readonly_mask (default False) is the sidecar-declared opt-in letting an omitted terminated mask be served from the cached all-false mask (see coerce_terminated()); never inferred, since marshal cannot read a kernel’s source.

eagle.reduce(x, out, *, op='sum', comp=None, policy='compensated', device=None)[source]#

A graph node that reduces the samples of x into out.

Parameters:
  • x – the plane to reduce, a contiguous numpy or cupy array with at least one sample: 1-D (n,), or 2-D (rows, N) reduced column by column. Floating-point and integer planes take "sum", "max" and "min"; a bool plane takes "all".

  • out – a contiguous array of the same dtype on the same backend, shape (1,) for a 1-D x and (N,) for a 2-D one; it receives the result.

  • op (str) – "sum", "max", "min" or "all" (numpy’s names).

  • comp – the companion plane of a floating-point sum, same shape and dtype as x: each term is the pair x + comp (rows of (hi, comp) partials), finished together.

  • policy (str) – "compensated" (default), "ordered" or "auto" (compensated in this release). Integer sums, max and all ignore it.

  • device – a CUDA device checked against the arrays’ (None: the arrays decide); it never moves data.

Return type:

Node

Returns:

A node for eagle.Graph.add_node(). The edges to the nodes that produce x (and comp) and consume out are derived from the arrays.

Raises:
  • ValueError – for an unknown op or policy, an empty x, an out of the wrong shape, comp of another shape, or an out that overlaps an input.

  • TypeError – for a dtype the operator does not take, a dtype mismatch, arrays on different backends, or comp on anything but a floating-point sum.

eagle.repeat_while(step, guard=None, max_iters=None, *, limit=None, brk=None)[source]#

Repeat step (a zero-arg callable, a Skippable, or a tuple of such parts) while guard holds, at most max_iters times (None: until guard fails): one device-side WHILE node under GraphPipeline.build(), a host loop everywhere else. A refined run phase is refused: a phase count must be static.

Return type:

RepeatWhile

Parameters:
  • guard (SkipGuard | None)

  • max_iters (int | None)

eagle.run_until_done(plan, *, max_steps, every=None, reorder=None, record=False, window=None, steps_reverse='per_step', memory_budget=None, events='step', on_no_event='raise', **planes)[source]#

until_done() then Runner.run(): the one-call form.

Return type:

RunReport

Parameters:
  • max_steps (int)

  • every (int | None)

  • record (bool)

  • memory_budget (int | None)

  • events (str)

  • on_no_event (str)

eagle.simulate(model, *args, until=None, max_steps, every=None, reorder=None, scalar_type=None, layout=None, record=False, window=None, steps_reverse='per_step', memory_budget=None, dispatch=None, events='step', on_no_event='raise', history=False, returns=None, **kwargs)[source]#

Run model on every sample until each one finishes (or max_steps is reached) and return the SimResult.

model is a hawk kernel, a list of them (one step, in list order), or plans from eagle.deploy(); until is the kernel that finishes the samples, placed last (at least one kernel must finish). The rest of the call is the kernel’s own: *args/**kwargs bind to its parameters exactly as a call to the kernel function would (positionally, by name, or both), by its own annotations – except that a model built from a PREBUILT plan (no raw kernel to read a call signature from) refuses *args outright, naming the keyword call to use instead; keyword binding always works. A Mutable plane is the state it updates (its initial value; one never read before it is written may be left out, zero-filled instead), a Param a number shared by every sample, a Scalar/Vector/Table plane one value per sample (a number where the kernel allows it, an array otherwise); Terminated is never passed. host arrays and numbers run on the CPU, cupy on the GPU. returns (“numpy”, “cupy”, “torch” or “jax”) hands the result arrays back as that framework’s arrays through its bridge; the default is eagle.Array. max_steps is required; every/reorder are eagle.until_done()’s compaction cadence and reorder threshold, scalar_type the precision the kernels are built in ("float64", the default, or "float32"; see eagle.deploy()), layout ("samples_first" or "samples_last") which axis holds the samples of a per-sample plane whose shape reads both ways ((w, w)), which is otherwise refused; eagle.samples_first(x) / eagle.samples_last(x) say it for one array and win. All keyword-only like every one of eagle’s own options – after the kernel’s own arguments.

record=True records the run for a reverse pass: the result’s .record goes to eagle.diff.reverse() (window and memory_budget are eagle.until_done()’s, for advanced tuning). Example:

res = eagle.simulate(model, x=x0, v=v0, max_steps=1000, record=True)
grads = eagle.diff.reverse(res.record, {"x": eagle.arrays.ones_like(x0)})

events="refine" stops each sample AT its stop rule’s crossing, inside the stop step, instead of at the step’s end (on_no_event is eagle.until_done()’s); the result’s SimResult.t_stop is the event time, and a recorded run’s reverse includes its sensitivity:

res = eagle.simulate(fall, y=y0, v=v0, t=t0, dt=0.01, max_steps=1000,
                     events="refine", record=True)
res.t_stop                    # when each sample hit the ground
grads = eagle.diff.reverse(res.record, {"t": eagle.arrays.ones_like(y0)})

history=True (or an interval k) keeps the state of every step: res.history[name] holds max_steps // k + 1 rows per state plane (row 0 the initial state, then after every k-th step; a sample that finished repeats its state, and rows past the last step repeat the final one). It runs one launch per step, so memory is rows * n * planes and the kernel must advance one step per launch. The final state equals the run without it:

res = eagle.simulate(model, x=x0, v=v0, max_steps=100, history=True)
res.history["x"]              # (101, n)

dispatch chooses how the model’s policy="auto" dispatch groups run. None (default) keeps every group the author declared and decides the "auto" ones by measurement: the model starts fused, counts how many samples take each branch, and every 16 steps splits the group into one kernel per branch when that is predicted to be at least 15% faster (and back when under 5%); only a group whose selector no kernel of the step writes is ever split. A policy name ("switch", "segmented", "predicated") or {group: policy} forces "auto" groups; a group the author gave a policy is refused, never overridden. Forcing "segmented" on a group whose selector the step writes is correct and answers with one eagle.PerformanceWarning. What was decided is in result.report.dispatch. Splitting runs on the host and on the GPU.

Example:

result = eagle.simulate(walker, k=k, x=x, t=t, max_steps=100)
result.report.dispatch   # {"dispatch0": ("segmented", (990, 6, 4), 1.9)}
Return type:

SimResult

Parameters:
  • max_steps (int)

  • every (int | None)

  • record (bool)

  • memory_budget (int | None)

  • events (str)

  • on_no_event (str)

  • history (bool | int)

  • returns (str | None)

eagle.simulation(model, *args, until=None, max_steps, every=None, reorder=None, scalar_type=None, layout=None, record=False, window=None, steps_reverse='per_step', memory_budget=None, dispatch=None, events='step', on_no_event='raise', history=False, **kwargs)[source]#

Bind and build model once; returns the Simulation, whose run() runs it (again, after reset(), without rebuilding). *args/**kwargs are the kernel’s own, bound exactly like a call to it; the rest are simulate()’s own options.

Return type:

Simulation

Parameters:
  • max_steps (int)

  • every (int | None)

  • record (bool)

  • memory_budget (int | None)

  • events (str)

  • on_no_event (str)

  • history (bool | int)

eagle.skippable(step, guard)[source]#

Wrap step (a zero-arg callable) so it only runs while guard holds: one IF node under GraphPipeline.build(), an eager guard check everywhere else.

Return type:

Skippable

Parameters:

guard (SkipGuard)

eagle.stream(s, device=None)[source]#

with eagle.stream(s): runs eagle’s work on s until the block ends.

s is a raw handle, a __cuda_stream__ object, a torch or Warp stream (.cuda_stream) or a CuPy stream (.ptr); device limits the scope to that device’s work (default: all).

Parameters:

device (int | None)

eagle.to_array(x, *, device=None, stream=None)[source]#

Import a framework / DLPack / CUDA-array-interface / buffer-protocol tensor as an eagle.Array, zero-copy: the array views the producer’s memory and keeps the producer alive. device ("cpu", "pinned" or "cuda:N") moves it there when it lives elsewhere. stream (any __cuda_stream__ object, a .cuda_stream / .ptr stream or a raw handle, default eagle’s current stream) is the stream the caller will use a device producer’s data on: the producer’s pending work is ordered before it. Also the pre-import helper for the capturable launch path, since a DLPack import can synchronize and is unsafe mid-capture.

eagle.until_done(plan, *, max_steps, every=None, reorder=None, record=False, window=None, steps_reverse='per_step', memory_budget=None, events='step', on_no_event='raise', **planes)[source]#

Bind plan and build the loop that runs it until every sample is done; returns the Runner (.run() runs it).

**planes binds every name of the plan’s arg_spec by eagle.plan.Plan.bind()’s rules, except the reserved FINISHED_PLANE, active_map and active_count (the runner allocates these); the terminated mask is all-false when omitted. plan may be an eagle.plan.AutoPlan (residency picks host/device), or a list of plans run as one step, in order, over one namespace of planes; each takes one step per launch, at least one finishes the samples, and they share one mask and guard.

max_steps caps the steps a sample may take (a compacting loop may overrun by up to every - 1 steps; RunReport.steps counts them). Guard(active_set=True) compacts every every steps (a multiple of K, at least 4, default the smallest at least 16), and reorder=theta also reorders the bound planes; both are refused on a plain artifact.

An automatic artifact (steps="auto") runs the policy loop instead (see the module docstring): the cap is exact, every= is refused, reorder only with reorder=theta, and the runner owns the FUSED_STEPS_PLANE word.

record=True records each run for a reverse pass: Runner.record after Runner.run() goes to eagle.diff.reverse(). The run takes one step per launch and keeps the state every window steps (None: clamp(ceil(sqrt(max_steps)), 16, 1024); "full": every step, one window). memory_budget (bytes; None: half the free device memory, or of the available host RAM) bounds what a reverse holds: over it, the reverse runs the batch in passes, with the same bits (grads.report.chunks counts the passes). Example:

runner = eagle.until_done(plan, max_steps=1000, record=True, x=x, v=v)
runner.run()
grads = eagle.diff.reverse(runner.record, {"x": dJ_dx})

events="refine" locates each sample’s stop INSIDE its stop step (the default "step" stops at the step the rule fires, with a zero derivative through the stop time). The kernel declares its time plane and step, @hawk.kernel(time="t", time_step="dt"), and its stop rule is a smooth crossing (terminated = x < a * t). Each run then leaves the state AT the crossing in the planes, Runner.t_stop holds the event time and Runner.event_status how it was located; under record=True the reverse includes the stop time’s sensitivity. A sample with no crossing in its stop step (it hit max_steps) is refused unless on_no_event="zero" (its stop stays the stepped one, with zero event sensitivity); a grazing crossing and two stop rules crossing in one step are always refused. Example:

runner = eagle.until_done(plan, max_steps=1000, events="refine",
                          record=True, x=x, v=v, t=t)
runner.run()
runner.t_stop                       # the event time of each sample
grads = eagle.diff.reverse(runner.record, {"t": numpy.ones(n)})
Return type:

Runner

Parameters:
  • max_steps (int)

  • every (int | None)

  • record (bool)

  • memory_budget (int | None)

  • events (str)

  • on_no_event (str)