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()/planresolve 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:
RuntimeErrorA 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:
objectThe live samples of
mask(aterminatedplane: set = finished), as an ascending index map plus a count – and, withreorder=theta, the occasional physical reorder of the planes it owns.maskis a one-dimensional, C-contiguousbool/uint8array (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.reorderis an explicit opt-in: the locality thresholdtheta(inTHETA_RANGE, orTrueforDEFAULT_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 toown(). The set starts as the identity (every sample live,count == n).group=Gcompacts whole groups ofGlanes, for a kernel emitted for that group (itslane_space.group): a group is live while any of its lanes is, the map holds group indices (map[t / G] * G + t % Gis the lane threadtruns) andcountthe lanes launched, live groups timesG, so a last partial group launches pastn. It does not combine withreorder=.check_group()refuses, at bind, a kernel emitted for another group.classes=K(withclass_plane) makes it a K-class set, for a kernel whose samples fall intoKbranches that diverge a warp when interleaved.class_planeis a C-contiguousuint8array ofnentries, each sample’s class in[0, K); the set owns it (it moves with every other plane) andKis at mostMAX_CLASSES(255). The set must reorder (reorder=theta).class_sort()groups the live samples into one run per class, in one stable permutation carried byperm/inv, so the sample pairing is the one of any reorder. The planes it adds:offsets–K + 1words, the exclusive prefix over the live samples: classcoccupies slots[offsets[c], offsets[c + 1])andoffsets[K] == count. Valid after a sort, until the next reorder orrestore().class_sorts– how many class sorts ran (a class sort is never counted as areorders).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()andreorder_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_fireto(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 leastclass_thetaof the warps they occupy, or more thanSTALE_MAXof them changed class, or the liveness reorder already fired.class_thetadefaults toCLASS_THETAand is accepted inTHETA_RANGE. Withepochs=Truethe set keeps a snapshot ofpermafter every sort (epochs). On the device the K-class set needs a backend providing the seam symbolscompact_classes_deviceandreorder_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. Withgroup > 1a group of lanes is live while any of its lanes is, the map holds group indices andcountthe lanes launched (live groups timesgroup).- 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,permandinvmove together;offsets[c]becomes the first live slot of classc(offsets[K] == count), the map the identity over[0, count),class_sorts += 1.within_live=Truepermutes the slots[0, count)among themselves by class only (the reverse’s form: liveness is the prefix,count/spanunchanged); otherwise[0, span)is sorted by(live, class)andspan = count.if_fired=Truesorts only when the last compaction raisedclass_fire(mixed32>=theta * live32over at leastMIN_CLASS_SORT_SPANsamples). 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. Withgroup > 1a group of lanes is live while any of its lanes is, the map holds group indices andcountthe lanes launched (live groups timesgroup).- Return type:
None
- property epochs: tuple#
the
permsnapshot written after every reorder / class sort of a set built withepochs=True(empty otherwise), oldest first. A snapshot is a private copy.- Type:
The epoch table
- in_sample_order(plane)[source]#
A copy of
planein 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:
- 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.Truewhen it was deferred, so the caller must re-point every bound plan atmap;Falsewhen 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:
- 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
permmove 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.Skippableguarded byfire(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/invidentity,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/invreset 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.Skippablecompaction that runs only whenfinishedmoved since it last ran (the guard is evaluated on the device under a graph).
Bases:
RuntimeErrorThe device backend cannot serve this call (see the message for why).
A
RuntimeError, so code that already guards a device call withexcept RuntimeErrorkeeps 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:
objectFrozen 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 conventioneagle::DeviceProps::ridgeFlopsPerByteuses. 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#
-
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:
objectCompose 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, auint32cupy array, one lane per member.the other three modes – any host-side sequence of truthy/falsy values, or
Nonefor “every member starts active”.
A caller may mutate
member_flags’s contents (viaset_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
modeneeds. Returnsself(rejected, every mode, if no members are registered).mode="conditional"wraps every step in askippableguard and captures oneGraphPipelineonce;mode="enabled"registers every member as a plain member of oneGraphPipeline, captures once, then applies the initial pattern viaset_member_enabled(no recapture from here on);mode="rebuild"captures a super-graph of only the active members, re-capturing from scratch on every laterset_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 lastreset_fired_history()(or construction).- Return type:
list
- launch(n=1)[source]#
Replay
ntimes. Returnsself.The three flat modes delegate to the one super-pipeline’s
GraphPipeline.launch()(amode="rebuild"composer with an all-inactive pattern owns no pipe, sonreplays 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 formode="sequenced"(no single super-graph – introspect each member on its own), nor for amode="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).
objmay 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-
GraphPipelineunder the three flat modes, replayed directly undermode="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 afterbuild(); the same object registered twice; a collidingname; nesting a composer under a non-"sequenced"outer composer, or nesting an unbuilt/wrong-mode composer under a"sequenced"one; apre_launchhook outsidemode="sequenced"; anobjthat 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"callsGraphPipeline.set_member_enabledper 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.patternis any sequence of truthy/falsy values, length == registered member count.- Return type:
- class eagle.Graph(*, record=False, backend=None, dispatch=None, device=None)[source]#
Bases:
objectA graph of launches: build it once, launch it many times.
add/add_group/add_nodeappend (chaining);buildderives the edges, refuses conflicts, and lowers to the GPU or CPU;launch/enqueue/synchronizeareeagle.GraphPipeline’s verbs (on the CPUenqueueislaunch).show()/str()/plot()/to_mermaid()/to_dot()draw it. The keywordsrecord,backend,dispatchanddeviceare the defaults ofbuild()’s.- __call__(n=1, /)[source]#
Replay
ntimes and wait; returnsresult(Nonewithout one).- Parameters:
n (int)
- add(bound, *, name=None, grad=True)[source]#
Append one plan launch (a
eagle.plan.BoundPlan).grad=Falsemarks the launch as not differentiated (a controller that writes a step size, say): a recorded run andeagle.diff.Reverseskip 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()withrecord=Truerefuses any other plane by name.- Return type:
- 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:
- add_node(node, *, name=None)[source]#
Append any registered-kind
Node, or an existingeagle.skippable/eagle.repeat_whileobject.- Return type:
- 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:
- build(*, backend=None, record=False, dispatch=None, device=None)[source]#
Derive the edges, refuse conflicts (always), and lower.
backendis 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=Truekeeps what a reverse pass needs (eagle.diff): after eachlaunch(),recordis that launch’sRecord.The graph runs on the GPU its planes live on (
device=nis checked against them); planes on two GPUs are refused.The keywords of
Graphare the defaults of the same-named ones here.dispatchlowers thepolicy="auto"dispatch groups of the graph’s hawk kernels (Noneor"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, ineagle.simulate().dispatchsays what was chosen.Example:
graph = eagle.Graph().add(bound_step).build(dispatch="switch") graph.dispatch # {"walker": {"dispatch0": "switch"}}
- Return type:
- classmethod builder(fn)[source]#
Decorate
fn: a parameter annotatedeagle.Graphmakes 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 takeslayout=("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(seeCudaGraphHandle); it carries every arraybind()swapped in. Refused withRuntimeErrornaming the node and the reason: a CPU graph, a segmented graph (a node outside thecapturetier), 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:
- property dispatch: dict#
{node label: {group: policy}}the lastbuild()lowered (empty when no node had an"auto"dispatch group).
- edges()[source]#
tuple[Edge]:Edge(src, dst, plane, kind)withkindin"RAW" | "WAR" | "WAW", indices intonode_labels().- Return type:
tuple
- enqueue(n=1)[source]#
Enqueue
nruns without waiting (CPU: same aslaunch()). A graph with a stream node stays non-blocking (each stage is fenced on the device); one with a host node waits aslaunch()does. As foreagle.GraphPipeline, write no plane of the graph betweenenqueueandsynchronize().- Return type:
- 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, withineagle.exec.host_threads(). Empty on the GPU and beforebuild().- 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
.handleis aconst eagle_host_table*(plugin/graph_handoff.h); the result holds this graph, and so its bound arrays, alive. It is a snapshot:bindor a rebuild makes it stale andeagle_host_table_runthen 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
ntimes and wait (enqueue(n)thensynchronize()). Arecord=Truegraph runs once per launch and keeps that run’sRecordinrecord.- Return type:
- 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
- parallel()[source]#
with g.parallel() as p:opens a fork in the builder; leaving thewithjoins.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 layoutshow()uses; returns theFigure.axdraws into an existing axes. A figure made here is a plainmatplotlib.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
Recordof the last launch of arecord=Truegraph (whateagle.diff.reverse()takes), elseNone.
- 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 beforebuild().- 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 afterbuild(). 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:
- update(values=None, /, **kw)[source]#
Change parameters of a
record=Truegraph between launches:g.update(k=0.3)sets every node’sk,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, orkeep()it, first).- Return type:
- class eagle.GraphPipeline(device=-1)[source]#
Bases:
objectA CUDA-graph wrapper: capture a sequence of launches once, replay cheaply. Backed by the
eagle._corebinding of theeagle::cudaC++ 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: afterbuild(),pipe.set_member_enabled(name, False)(or its registration-order index, always valid – seemember()) 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.
membersis a sequence of zero-arg callables,len(members) >= 2– each has the same contract asadd()’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 ofadd()/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 beforebuild()if you want that asserted.names(optional) aliases each member the same wayadd’snamedoes – a sequence the same length asmembers, entries may beNone. 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. ASkippableorRepeatWhilemember is marked non-toggleable structurally, from this layer’s own knowledge that it wove a conditional region, without ever driver-querying its nodes (cudaGraphNodeGetTypefails 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
nreplays on this pipeline’s own stream and return immediately – the non-blocking half oflaunch().launch(n)isenqueue(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 approximatesmaxover the pipelines rather than theirsum.The ordering (see
launch()) is applied here, not insynchronize(): an event is recorded on the caller’s current stream (and the legacyStream.nullwhen 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 modeeagle.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 secondenqueuebefore 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.
enqueuereturns 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 viapre_launchinstead. RaisesRuntimeErrorif called beforebuild().
- 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). Requiresbuild()to have run.- Return type:
bool
- launch(n=1)[source]#
Replay the captured graph
ntimes.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=Trueprecisely 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 legacyStream.null(when different) and wait on both, on the pipeline’s own stream, before the replay loop. This orders every consumer oflaunch()for free, at the facility seam, with no host block (~1-2us/call). Exactlyenqueue(n)followed bysynchronize()– same events, same order, same host block, same return value. The two halves are also available separately (seeenqueue()) 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 requirebuild()(onlyset_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 ofnode_labels(). A copy; mutating it has no effect. Requiresbuild()to have run.- Return type:
list
- node_labels()[source]#
Kernel function names of the captured nodes, in declaration order.
- Return type:
list
- 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 afterbuild(); 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 compiledeagle._coreextension). RaisesNonToggleableMemberErrorifbuild()recorded this member as non-toggleable (its node set contains something other than kernel/memcpy/memset – most commonly aSkippable’s conditional node).UnknownMemberErrorfor a bad name or index, andRuntimeErrorif called beforebuild().- Return type:
- 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 callset_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 (fromcapture_snapshot_nodes()).nodemust be a real handle from this pipeline’s own capture – passing a foreign or stale one is undefined at the driver level. Requiresbuild()to have run.- Return type:
- Parameters:
node (int)
enabled (bool)
- property stream: int#
This pipeline’s own
cudaStream_t, as a raw integer handle (the family’s sharedstreamname: 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 beforebuild()captures, needs this exact stream – launching on any other stream would race the graph. Read-only, valid for this pipeline’s entire lifetime.
- class eagle.KernelRegistry(kernels=None)[source]#
Bases:
objectA
name -> launchablemap for resolving a launchable by name.Values are any launchable sharing the
__call__+launchprotocol. Dict-like:reg[name],name in reg,len(reg), iteration over names,.get/.names.
- exception eagle.LayoutWarning[source]#
Bases:
UserWarningA 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:
UserWarningA 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
xas 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’slayout=. A shape that contradicts it is refused.
- eagle.samples_last(x)[source]#
Mark
xas 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’slayout=. A shape that contradicts it is refused.
- class eagle.LoadedKernel(ptx_path, *, abi_kind)[source]#
Bases:
LaunchMixinCommon 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 definelaunch/__call__over the inherited_dispatch(). The parsed sidecar is kept onself._meta.- function(device, name=None)[source]#
The function
name(default: the kernel) on CUDA devicedevice, 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 byeagle.plan.plan’s legacy-partition bridge.
- lane_space#
launch.lane_space(LaneSpace), the exactlaunch.block(Nonewhen the artifact states none), the sinks with named axes, theSortedinputs and the threadbox.
- block#
launch.lane_space(LaneSpace), the exactlaunch.block(Nonewhen the artifact states none), the sinks with named axes, theSortedinputs and the threadbox.
- plane_axes#
launch.lane_space(LaneSpace), the exactlaunch.block(Nonewhen the artifact states none), the sinks with named axes, theSortedinputs and the threadbox.
- sorted_inputs#
launch.lane_space(LaneSpace), the exactlaunch.block(Nonewhen the artifact states none), the sinks with named axes, theSortedinputs and the threadbox.
- box#
launch.lane_space(LaneSpace), the exactlaunch.block(Nonewhen the artifact states none), the sinks with named axes, theSortedinputs and the threadbox.
- 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:
LoadedKernelA precompiled pure kernel loaded from a PTX (+ sidecar) artifact – no nvcc. Drop-in equivalent to the in-process compiled pure launcher via
eagle.launch. TheMutablebuffers are the handoff (read-modify-written in place), so there is no separateout=.- __call__(**kw)[source]#
Launch the pure kernel and return the updated
Mutablebuffers 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
Mutablebuffers, any inputs, lookup tables, and theterminatedmask must be pre-allocated; read-modify-written in place.block=Nonedefers to eagle’s launch-policy resolver.
- class eagle.LoadedVector(ptx_path)[source]#
Bases:
LoadedKernelA 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 – seeas_out_buffer().
- class eagle.RepeatWhile(step, guard, max_iters=None, limit=None, brk=None)[source]#
Bases:
objectA zero-arg step repeated on the device while a
SkipGuardholds, at mostmax_iterstimes per replay (None: until the guard fails) – the loop sibling ofSkippable(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 onecudaGraphLaunchregardless of iteration count;launch(n)replays the whole loopntimes.max_itersisNoneor a plain Pythonint >= 1frozen at build as a kernel argument – a new cap needs a newbuild(). A reverse pass needs the cap.limit(auint32cell) is a runtime trip count (ran < limit[0]) andbrk(auint32cell the body writes) ends the loop after the iteration that leaves it nonzero;guardmay beNonewhen 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 soiterations()reads the same in every mode. The cell lives in the guard’s array module (cupy or numpy), allocated at construction;iteration_indexexposes itsranword to body kernels as the device-visible iteration index (0 on the first iteration).Composition: the body
stepmay be aSkippable, or a tuple of such parts run in order (e.g.(k_steps, skippable(compact, guard))); aRepeatWhile, aSkippableor a fork/join group nests in any of them, and aRepeatWhilemay be anadd_concurrentmember. 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, orUNCAPPED.- Type:
The device cap
- property iteration_index#
One-element
uint32view of theranword – 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:
objectWhat one
Runner.run()did.finishedcounts samples whose mask is set when the run ends,doneisfinished == n,launchesthe loop’s iteration count, andstepsthe steps the loop ran (launches * K, or the summedkfor an automatic artifact).exact_stepssaysstepsis exact (true forK=1, or an automatic artifact that launched nothing, hit the cap early, or ended on a one-step launch).compactions/reorderscount what ran,build_sthe one-time capture wall (0 on host),launches_by_keachk’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;Noneotherwise (every other mode, or a persist run that skipped the counter).modeis 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).probeis true for a fast-path run taken to time the entry the batch is not currently using (seeRunner._pick_entry());timedis 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 neitherprobenortimed.dispatchisNoneunless 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_sortscounts the sorts of samples by branch a split run made.mappedis the samples the launches ran over, summed over the launches:nfor a fast-path run (one launch over the whole batch), the live samples of each launch for a compacting run,launches * nfor one that does not compact;0for 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:
objectA bound, built run-until-done loop over one plan, or a step of several plans launched in order (see
until_done()).Attributes:
step(theeagle.plan.BoundPlan, or a tuple),loop,pipeline(the deviceeagle.GraphPipeline, built on firstrun()),active(theeagle.ActiveSet, orNone),finished/terminated,steps_per_launch(K, or"auto"),every/launches_per_compaction. For an automatic artifactfused_stepsis the device steps-per-launch word andpolicyreads the policy’s cells (a sync).host_policypicks how a host run paces automatic launches:"auto"(default:"tiled"when the entry’s fused side is tiled, else"measured"),"tiled"(steps_maxsteps per launch),"measured"(sweeps one step per launch until a timed fused probe wins) or"band"(the device’s band).host_threadsis 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 — seeeagle._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 (withon_no_event="zero");Nonewithoutevents="refine".
- property launch_policy: dict#
What the launch rules chose for this runner, for a probe report:
blockandgridof the persist launch (Nonewhen the runner has none),chunk(steps per fetch;Nonewhen the entry takes none),fill(the step fill the sizing last read, first run 0.5),rate(R) andk(the band’s current steps per launch;Noneoff the band). Pair it witheagle.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;Nonefor a fixed artifact.
- property record#
The
eagle.diff.Recordof the last run of arecord=Truerunner (Nonebefore the first run, or withoutrecord=True): pass it toeagle.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
nameafter 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_stepsreads, 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 (_compactionscan only ever be 0 without an active set, so it is never even read), and the POST snapshot foldsiterations/finished/compactions/reordersinto one.A fast mode (
_build_fast()) skips all of the above: one launch IS the run, so_run_fast()handles it entirely.- Return type:
- 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);Noneotherwise. 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:
objectWhat one
Simulation.run()produced.statemaps each state plane to its array (written in place, plus allocated ones, listed inallocated); each is also an attribute (result.x) and an item (result["x"]).finishedis the per-sample mask,donewhether every sample did,status"finished"/"max_steps",steps/report/wall_sthe loop’s steps, fulleagle.RunReportand wall time. Anevents="refine"run also fillst_stop(each sample’s event time) andevent_status(seeeagle.Runner.event_status); both areNoneotherwise. Ahistory=run fillshistory: each state plane’s rows (the state before the first step, then after every k-th),Noneotherwise.- 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"; seeeagle.Array.to());Nonekeeps theeagle.Arrays. 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:
objectA bound, built simulation (see
simulation()):run()runs it,reset()starts the batch over.runneris theeagle.Runnerdriving the model,loop/pipelineits loop and deviceeagle.GraphPipeline(Noneon host),plansthe plans per kernel,nthe batch size,namesthestate/params/allocatedplane names.- runner#
- loop#
- plans#
- n#
- names#
- active#
- finished#
- terminated#
- every#
- property pipeline#
The device
eagle.GraphPipeline(built on the firstrun());Noneon the host and before.
- property record#
The
eagle.diff.Recordof the lastrun()of arecord=Truesimulation (Noneotherwise): pass it toeagle.diff.reverse().Example:
sim.run(); grads = eagle.diff.reverse(sim.record, {"x": dJ_dx}).
- class eagle.SkipGuard(count_arr, count_idx=0, baseline_arr=None, baseline_idx=0, negate=False)[source]#
Bases:
objectRegion 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#
- classmethod intent(flags, index)[source]#
Router/user-owned intent flag:
flags[index] != 0.flagsis a uint32 array the caller owns and writes between graph replays, one lane per guarded region (e.g.SkipGuard.intent(expert_flags, e)for experte). No baseline: a plain on/off decision.Under
GraphPipeline.build()the predicate is read fresh from the device every replay, so flippingflags[index]takes effect with no recapture; in eager/numpy mode the same flag is read host-side byevaluate().indexhas no default (unlikenonzero()’s0): it is load-bearing at every call site.
- class eagle.Skippable(step, guard)[source]#
Bases:
objectA zero-arg step wrapped with a
SkipGuard. Works as aGraphPipeline.add()step or anadd_concurrentmember –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
GRefstructs (a matrix GRef composes the flat vector one); per-sample scalars, the termination mask, lookup tables, and a pure kernel’s scalar/intMutableslots are by-valueHandleTviews; broadcast constants arefloat64. A vector kernel’sGRefcarries its ownsamples_; a pure kernel takes an explicitnsamplesinstead.wide_in/wide_outare alsoHandleTviews, 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 whichmake_*helper builds it. An unrecognised role raises before any role-specific branch runs.plan(optional) is theLaunchPlanfor 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 (readLaunchPlan’s box-reuse note first). Omitplanfor fresh boxes per call, as always.
- eagle.check_aether_abi(meta, *, kind, name)[source]#
Reject an artifact whose
meta["aether_abi"]is not one ofACCEPTED_ABI_TAGS(absent/empty included).kindnames 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 runsstepeverytimes, then compactsactive– only whenfinishedmoved, if given, else unconditionally – and, for a set built withreorder=thetaover at leastMIN_REORDER_SPANsamples, reorders when the compaction fired (reorder=False/Trueoverrides this). The loop guard is checked once pereverysteps, so it may run up toevery - 1steps past the last sample finishing; sizemax_itersasceil(max_steps / every).steps_per_callis the steps onestep()call advances (a fused kernel’sK): the body then runsevery * Ksteps between compactions, and a cadence belowMIN_EVERYsteps is refused.- Return type:
tuple- Parameters:
active (ActiveSet)
every (int)
steps_per_call (int)
- eagle.copy(src, *, into, name=None)[source]#
into[...] = srcas 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.srcandintosharing their storage make a node that does nothing (the edges stay).Inside a builder the node is recorded and
intois returned, soh = eagle.copy(d, into=h)reads as the data flow. Elsewhere the node is returned, forGraph.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)#
selfasframework’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. RaisesImportErrorwith the install hint if the framework is missing.
- tolist#
- transpose#
- view#
- class eagle.IndexSet[source]#
Bases:
objectThe 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 lanesselectionnames out ofextent.selectionis a boolean mask over theextentlanes, 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 forcapacityentries (default: as many as selected; the unused tail is zero);active_countis oneuint32cell.widthis"auto"(32, or 64 past2**31 - 1lanes), 32 or 64. The planes are checked, and live ondevice(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 ofmap, each in[0, extent), none twice.mapandcountare arrays (aneagle.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. RaisesValueErrornaming 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
AutoPlanforplugin: run it where its data lives.eagle.deployis this same function.pluginis 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 undercache_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_dirandscalar_typeare refused for an already-built plugin.scalar_typeis 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 witheagle.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_kwareplan()’s keywords butstructure(inner/gatherdo not apply); a side the plugin lacks is refused when first selected.
- eagle.detect(x)[source]#
Identify
x’s framework adapter without importing the framework.Nonefor 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) viaeagle._core.device_props()and wrap the resulting dict in a frozenDeviceProps— 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 — importingeagleon a cuda-free box must not force-load it (the same disciplineeagle.pipeline. GraphPipeline.__init__()follows for the same reason).- Return type:
- 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 rideextra(a vector kernel’sout=, or a pure kernel’smutables_decl=, each with optionalmatrix_inputs=/wide_inputs=/wide_outputs=/wide_out_exempt=, named identically topure_prepare()’s). Every array argument must be pre-allocated cupy. Returns the vectorout, or the pureMutabledict merged with wide outputs.
- eagle.load_manifest(path)[source]#
Load a deployed
manifest.jsonby its top-levelpattern.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 intoLoadedVector/LoadedPureand keyed by its manifestidinto aKernelRegistry."graph_block"– a graph-block deployment unit: the inlineblocks[]compose one ordered layer whose exec references resolve against theplugins[]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
patternis a hard error. ReturnsKernelRegistry | LoadedBlockLayer.
- eagle.make_gref(arr, n)[source]#
Build a by-value
GRefover 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
HandleTover a contiguous(N,)device array;nis 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:
fnissues its device work on the current stream at build and is replayed with the graph (also inside groups, conditionals anduntil_donesteps). It must not allocate.stream=S– stream-ordered:fnruns on the host each launch withS(an int, a torch/Warp/CuPy stream or a__cuda_stream__object) as cupy’s current stream; issue its device work onS(torch.cuda.stream(S)for torch).Swaits for the stage before and the stage after waits forS; the host never waits. Keep what that work reads alive until it ran (torch:tensor.record_stream(S)).eager=True– host-synchronized:fnruns 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.schedulenames the tier per stage (capture/eager_stream/eager_host) andstr(g)tags the node. A reverse pass through it needsvjps={label: fn}(eagle.diff.reverse()): the label isnamewhen given (Graph.add(name=)wins over it), the kind otherwise.grad=Falsemarks the node as not differentiated (seeeagle.Graph.add()): a reverse skips it and needs no vjp for it.- Return type:
- 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.Arrayin 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 deployedLoadedPureso the two can never drift.State vectors ->
(3, N)f64; matrix inputs -> flat(R*C, N)f64; providedMutablearrays -> 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_exemptnames thewide_outputsthat are row-indexed destinations (e.g. an atomic by-key store output), skipping N-reconciliation. AMutableomitted fromkwis a broadcast scalar fill or its declared default. Returns theMutablebuffers merged with any wide gradient outputs (RMW in place). Meant to run inside the caller’s launch context (seeLaunchMixin._dispatch()).readonly_mask(defaultFalse) is the sidecar-declared opt-in letting an omittedterminatedmask be served from the cached all-false mask (seecoerce_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
xintoout.- 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"; aboolplane takes"all".out – a contiguous array of the same dtype on the same backend, shape
(1,)for a 1-Dxand(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 pairx + comp(rows of (hi, comp) partials), finished together.policy (
str) –"compensated"(default),"ordered"or"auto"(compensatedin 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:
- Returns:
A node for
eagle.Graph.add_node(). The edges to the nodes that producex(andcomp) and consumeoutare derived from the arrays.- Raises:
ValueError – for an unknown
oporpolicy, an emptyx, anoutof the wrong shape,compof another shape, or anoutthat overlaps an input.TypeError – for a dtype the operator does not take, a dtype mismatch, arrays on different backends, or
compon 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, aSkippable, or a tuple of such parts) whileguardholds, at mostmax_iterstimes (None: untilguardfails): one device-side WHILE node underGraphPipeline.build(), a host loop everywhere else. A refined run phase is refused: a phase count must be static.- Return type:
- 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()thenRunner.run(): the one-call form.- Return type:
- 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
modelon every sample until each one finishes (ormax_stepsis reached) and return theSimResult.modelis a hawk kernel, a list of them (one step, in list order), or plans fromeagle.deploy();untilis 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/**kwargsbind 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*argsoutright, naming the keyword call to use instead; keyword binding always works. AMutableplane is the state it updates (its initial value; one never read before it is written may be left out, zero-filled instead), aParama number shared by every sample, aScalar/Vector/Tableplane one value per sample (a number where the kernel allows it, an array otherwise);Terminatedis 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 iseagle.Array.max_stepsis required;every/reorderareeagle.until_done()’s compaction cadence and reorder threshold,scalar_typethe precision the kernels are built in ("float64", the default, or"float32"; seeeagle.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=Truerecords the run for a reverse pass: the result’s.recordgoes toeagle.diff.reverse()(windowandmemory_budgetareeagle.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_eventiseagle.until_done()’s); the result’sSimResult.t_stopis 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 intervalk) keeps the state of every step:res.history[name]holdsmax_steps // k + 1rows 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 isrows * n * planesand 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)
dispatchchooses how the model’spolicy="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 oneeagle.PerformanceWarning. What was decided is inresult.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:
- 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
modelonce; returns theSimulation, whoserun()runs it (again, afterreset(), without rebuilding).*args/**kwargsare the kernel’s own, bound exactly like a call to it; the rest aresimulate()’s own options.- Return type:
- 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 whileguardholds: one IF node underGraphPipeline.build(), an eager guard check everywhere else.
- eagle.stream(s, device=None)[source]#
with eagle.stream(s):runs eagle’s work onsuntil the block ends.sis a raw handle, a__cuda_stream__object, a torch or Warp stream (.cuda_stream) or a CuPy stream (.ptr);devicelimits 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/.ptrstream 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 capturablelaunchpath, 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
planand build the loop that runs it until every sample is done; returns theRunner(.run()runs it).**planesbinds every name of the plan’sarg_specbyeagle.plan.Plan.bind()’s rules, except the reservedFINISHED_PLANE,active_mapandactive_count(the runner allocates these); theterminatedmask is all-false when omitted.planmay be aneagle.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_stepscaps the steps a sample may take (a compacting loop may overrun by up toevery - 1steps;RunReport.stepscounts them).Guard(active_set=True)compacts everyeverysteps (a multiple ofK, at least 4, default the smallest at least 16), andreorder=thetaalso 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 withreorder=theta, and the runner owns theFUSED_STEPS_PLANEword.record=Truerecords each run for a reverse pass:Runner.recordafterRunner.run()goes toeagle.diff.reverse(). The run takes one step per launch and keeps the state everywindowsteps (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.chunkscounts 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_stopholds the event time andRunner.event_statushow it was located; underrecord=Truethe reverse includes the stop time’s sensitivity. A sample with no crossing in its stop step (it hitmax_steps) is refused unlesson_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:
- Parameters:
max_steps (int)
every (int | None)
record (bool)
memory_budget (int | None)
events (str)
on_no_event (str)