Repository navigation
Experimental ContinuousState descriptor for state handling - #3755
codebreaker32 wants to merge 13 commits into
Conversation
|
Some architectural challenges that I faced worth noting while reaching to this implementation are Priority Queue Tombstone Bloat Execution Order vs. Continuous Decay Stale Object References |
|
Please see #3721 (reply in thread) also |
|
Performance benchmarks:
|
|
Performance benchmarks:
|
|
Cool! Will try to dive in tomorrow or Tuesday. |
|
Columnar Memory Layout # L26-30
self.values = np.zeros(capacity, dtype=np.float64)
self.rates = np.zeros(capacity, dtype=np.float64)
self.last_update_times = np.zeros(capacity, dtype=np.float64)
self.limits = np.full(capacity, np.inf, dtype=np.float64)
self.projected_times = np.full(capacity, np.inf, dtype=np.float64)To eliminate the severe performance penalty of resizing arrays mid-simulation, the tensor pre-allocates these arrays to a fixed capacity upfront (size=10_000) and manages active rows via a # L26
def __init__(self, capacity: int = 10_000) -> None:
# L49
# O(1) allocation stack
self.free_indices = list(range(capacity - 1, -1, -1))The Projection Engine # Lines 129-130
with np.errstate(divide="ignore", invalid="ignore"):
delta_t = (l - v) / rOnce the raw time-deltas are computed, the engine applies an # Lines 143-145
invalid_mask = np.isnan(delta_t) | (~active)
invalid_mask |= (d == DIR_RISING) & (r <= 0)
invalid_mask |= (d == DIR_FALLING) & (r >= 0)
# L150
projected[invalid_mask] = np.infBeyond raw projection, the implementation relies heavily on an # L132-135
# Flags agents already mathematically past their threshold bounds
already_past = (d == DIR_FALLING) & (v <= l)
already_past |= (d == DIR_RISING) & (v >= l)
already_past |= (d == DIR_BOTH) & ((v <= l) | (v >= l))
delta_t[already_past] = 0.0A bitwise guard ( # L148
invalid_mask &= ~already_pastFor targeted writes, this bulk array logic is mirrored by def update_single_projection(self, idx: int, current_time: float) -> None:
...
# The Single-Row Fallback
if (
(d == DIR_FALLING and val <= limit)
or (d == DIR_RISING and val >= limit)
or (d == DIR_BOTH and (val <= limit or val >= limit))
):
self.projected_times[idx] = current_time
returnEager vs. Lazy Reactivity (Interrupts vs. Polling) # Inside ContinuousState.__set__
if self._has_thresholds:
tensor.update_single_projection(idx, instance.model.time)
instance.model.continuous_scheduler.check_and_reschedule(
tensor.projected_times[idx]
)Conversely, lazy thresholds operate via polling and are evaluated strictly on read. Writes bypass the scheduler entirely, and the descriptor mathematically extrapolates the current value on the fly, checking if a crossing occurred since the last cached read to prevent spamming the queue with false-positive projections. Inside ContinuousState.__get__
if self.lazy_thresholds:
# Prevents trigger spam by requiring an actual crossing between reads
last_read_attr = self._lazy_cache_attr + "_last_val"
old_val = getattr(instance, last_read_attr, base_val)
lazy_list = getattr(instance, self._lazy_cache_attr, self.lazy_thresholds)
for t in lazy_list:
if self._check_triggered(t, old_val, current_val):
...Deferred Execution # Inside ContinuousState.__get__
if not getattr(instance, t._queued_flag, False):
setattr(instance, t._queued_flag, True)
tensor.deferred_callbacks.append(
(instance, t.callback, t._queued_flag)
)
if not tensor._flush_scheduled:
tensor._flush_scheduled = True
instance.model.schedule_event(
tensor.process_deferred_callbacks, after=1e-9
) |
|
Thanks for this PR. You're trying to solve a real problem in Mesa, and the architectural notes in your description show careful thinking. The eager/lazy insight in particular is useful. That said, I think the implementation can be significantly simplified by building on what Mesa 3.5 already provides, and I'd like to suggest an alternative direction before this moves forward. The core need
What Mesa 3.5 already gives us model.schedule_event(self.die, at=current_time + self.sugar / self.metabolism)That's essentially what Similarly, The problem with the current approach The PR introduces a parallel execution engine:
What I think we should be built instead
This covers the piecewise-constant-rate case, which is the vast majority of ABM use cases: metabolism, resource decay, disease progression. Rates generally change at discrete events (eating, trading, moving), not continuously. Except if you have continuous rates depending on other continuous rates, but let's not get into that rabbit hole (okay not now at least, at some point we might want to do step-level approximation or something). Between those events the trajectory is a straight line, the crossing time is analytically exact, and The case this deliberately doesn't cover is rates that depend on other Suggested direction So we basically want to try to catch 80% of the use-cases with 20% of the complexity/code. The easiest way to do that is by building on to the current event/signals code already in place. |
|
@quaquel also curious what you think. |
|
I appreciate all the work and thought that has gone into this PR. However, I also have some reservations. I like the seperation between threshold and the evolving state. I also appreciate the use of a descriptor for the state. Together this nicely encapsulates the relevant behavior. I am less sure about the tensor. The impression I have, but please correct me if I am wrong, is that you went down this route because of the poor performance on sugarscape. However, I am not sure whether sugarscape is the most appropriate model to test this kind of mechanism with. As indicated in the conceptual discussion, I see a lot of potential for this approach in more discrete event style simulations. For example, imagine simulating trams or train. Here the acceleration and braking could nicely be expressed using continuous state and thresholds. Since the frequency of event cancelation is small, you don't get the bloat problem. And so, there is no need for the added complexity of the tensor stuff. In contrast, in sugarscape, every trade invalidates the set thresholds. Since there are many trades each time step, event cancelation explodes. |
|
CLosing in favour of #3766 |
This PR introduces an experimental Entity-Component-System (ECS) backend for modeling continuously evolving agent properties using a columnar NumPy architecture.
Architecture
StateTensor: Provides vectorized NumPy arrays to track values, rates, limits, andprojections for
ContinuousStateattributes across all agents. Eagerthresholds receive dedicated rows; lazy thresholds are evaluated on-read.
ContinuousScheduler: A priority-based scheduler that maintains a single master event pointed at the earliest projected crossing time across the entire tensor, re-targeting dynamically as writes occur.ContinuousState: Descriptor for an agent attribute that evolves continuously.Extrapolates state based on elapsed model time and rate. Eager thresholds
are projected and managed by the scheduler. Lazy thresholds are evaluated
on read.
Threshold: A trigger condition attached to aContinuousStateattribute.Notes
ContinuousStatefor sugar and spice metabolism.