matrix-compute-node 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,213 @@
1
+ """Preemptive Two-Level Priority Compute Scheduler for matrix-compute-node."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import deque
6
+ from enum import Enum
7
+ import logging
8
+ import threading
9
+ import time
10
+ from typing import Any, Callable, Deque, Optional, Tuple, TypeVar, Union
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ T = TypeVar("T")
15
+
16
+
17
+ class PriorityTier(str, Enum):
18
+ """Execution priority tiers for compute tasks."""
19
+
20
+ PAID_MAINNET = "PAID_MAINNET"
21
+ FREE_TRIAL = "FREE_TRIAL"
22
+
23
+
24
+ class PreemptiveComputeScheduler:
25
+ """
26
+ Two-level preemptive compute scheduler enforcing:
27
+ - Priority 1 (`PAID_MAINNET`): Executes immediately with 100% GPU allocation.
28
+ Wakes any sleeping condition immediately upon arrival.
29
+ - Priority 2 (`FREE_TRIAL`): Executes strictly when `paid_queue_depth == 0`.
30
+ Enforces a <= 5% GPU duty cycle via:
31
+ 1. Sliding window cap (`<= 50ms` per `1.0s` rolling window).
32
+ 2. Proportional cooldown (`T_cooldown >= 19 * T_exec` for 5% duty cycle).
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ sliding_window_seconds: float = 1.0,
38
+ max_trial_ms_per_window: float = 50.0,
39
+ max_trial_duty_cycle: float = 0.05,
40
+ max_trial_ms_per_second: Optional[float] = None,
41
+ window_seconds: Optional[float] = None,
42
+ max_wait_seconds: float = 5.0,
43
+ ) -> None:
44
+ win_sec = float(window_seconds if window_seconds is not None else sliding_window_seconds)
45
+ max_ms = float(
46
+ max_trial_ms_per_second if max_trial_ms_per_second is not None else max_trial_ms_per_window
47
+ )
48
+ duty = float(max_trial_duty_cycle)
49
+ if win_sec <= 0:
50
+ raise ValueError(f"sliding_window_seconds must be positive, got {win_sec}")
51
+ if max_ms <= 0:
52
+ raise ValueError(f"max_trial_ms_per_window must be positive, got {max_ms}")
53
+ if not (0.0 < duty <= 1.0):
54
+ raise ValueError(f"max_trial_duty_cycle must be in (0.0, 1.0], got {duty}")
55
+
56
+ self.sliding_window_seconds: float = win_sec
57
+ self.window_seconds: float = win_sec
58
+ self.max_trial_ms_per_window: float = max_ms
59
+ self.max_trial_ms_per_second: float = max_ms
60
+ self.max_trial_duty_cycle: float = duty
61
+ self.max_wait_seconds: float = float(max_wait_seconds)
62
+
63
+ self.lock = threading.RLock()
64
+ self._condition = threading.Condition(self.lock)
65
+
66
+ self.paid_queue_depth: int = 0
67
+ self.trial_queue_depth: int = 0
68
+ self._active_paid: int = 0
69
+ self._active_trial: int = 0
70
+
71
+ # Sliding window history of (finish_timestamp_sec, duration_ms)
72
+ self._trial_execution_history: Deque[Tuple[float, float]] = deque()
73
+ self._last_trial_finish_time: float = 0.0
74
+ self._last_trial_cooldown_required: float = 0.0
75
+
76
+ def get_window_trial_usage_ms(self, now: Optional[float] = None) -> float:
77
+ """Calculates trial compute time (ms) used within the sliding window."""
78
+ current_time = float(now if now is not None else time.time())
79
+ with self.lock:
80
+ cutoff = current_time - self.sliding_window_seconds
81
+ while self._trial_execution_history and self._trial_execution_history[0][0] < cutoff:
82
+ self._trial_execution_history.popleft()
83
+ return sum(duration_ms for _, duration_ms in self._trial_execution_history)
84
+
85
+ def can_execute_trial(
86
+ self,
87
+ estimated_exec_ms: float = 1.0,
88
+ now: Optional[float] = None,
89
+ ) -> Tuple[bool, str]:
90
+ """
91
+ Determines whether a FREE_TRIAL task can execute right now.
92
+ Must satisfy:
93
+ 1. `paid_queue_depth == 0`
94
+ 2. Cooldown from previous trial execution has expired (`T_cooldown >= 19 * T_exec`)
95
+ 3. Sliding window usage + `estimated_exec_ms <= max_trial_ms_per_window` (50ms)
96
+ """
97
+ with self.lock:
98
+ if self.paid_queue_depth > 0 or self._active_paid > 0:
99
+ return False, f"PAID_QUEUE_ACTIVE: {self.paid_queue_depth} paid tasks waiting"
100
+
101
+ current_time = float(now if now is not None else time.time())
102
+ time_since_last = current_time - self._last_trial_finish_time
103
+ if time_since_last < self._last_trial_cooldown_required:
104
+ rem_cooldown = self._last_trial_cooldown_required - time_since_last
105
+ return False, f"COOLDOWN_ACTIVE: {rem_cooldown:.4f}s cooldown remaining"
106
+
107
+ used_ms = self.get_window_trial_usage_ms(current_time)
108
+ if used_ms + float(estimated_exec_ms) > self.max_trial_ms_per_window:
109
+ return (
110
+ False,
111
+ f"WINDOW_QUOTA_EXCEEDED: {used_ms:.2f}ms used, quota {self.max_trial_ms_per_window}ms",
112
+ )
113
+
114
+ return True, "OK"
115
+
116
+ def execute_paid(self, compute_fn: Callable[..., T], *args: Any, **kwargs: Any) -> T:
117
+ """
118
+ Executes a `PAID_MAINNET` task immediately with Priority 1.
119
+ Preempts waiting trial tasks and wakes condition variables immediately.
120
+ """
121
+ if not callable(compute_fn):
122
+ raise TypeError("compute_fn must be callable")
123
+
124
+ with self.lock:
125
+ self.paid_queue_depth += 1
126
+ self._active_paid += 1
127
+ self._condition.notify_all()
128
+
129
+ try:
130
+ return compute_fn(*args, **kwargs)
131
+ finally:
132
+ with self.lock:
133
+ self._active_paid = max(0, self._active_paid - 1)
134
+ self.paid_queue_depth = max(0, self.paid_queue_depth - 1)
135
+ self._condition.notify_all()
136
+
137
+ def execute_trial(
138
+ self,
139
+ compute_fn: Callable[..., T],
140
+ *args: Any,
141
+ max_wait_seconds: Optional[float] = None,
142
+ **kwargs: Any,
143
+ ) -> T:
144
+ """
145
+ Executes a `FREE_TRIAL` task with Priority 2 and <= 5% duty cycle throttle.
146
+ """
147
+ if not callable(compute_fn):
148
+ raise TypeError("compute_fn must be callable")
149
+
150
+ wait_budget = float(max_wait_seconds if max_wait_seconds is not None else self.max_wait_seconds)
151
+
152
+ with self.lock:
153
+ self.trial_queue_depth += 1
154
+
155
+ try:
156
+ start_wait = time.time()
157
+ can_run = False
158
+ reason = ""
159
+
160
+ while True:
161
+ with self.lock:
162
+ can_run, reason = self.can_execute_trial(estimated_exec_ms=1.0)
163
+ if can_run and self._active_trial == 0:
164
+ self._active_trial += 1
165
+ break
166
+
167
+ elapsed = time.time() - start_wait
168
+ if elapsed >= wait_budget:
169
+ break
170
+
171
+ rem_wait = min(0.005, max(0.001, wait_budget - elapsed))
172
+ self._condition.wait(timeout=rem_wait)
173
+
174
+ if not can_run:
175
+ raise RuntimeError(f"Trial execution throttled or preempted: {reason}")
176
+
177
+ t0 = time.time()
178
+ try:
179
+ result = compute_fn(*args, **kwargs)
180
+ finally:
181
+ t1 = time.time()
182
+ exec_duration = max(0.0001, t1 - t0)
183
+ with self.lock:
184
+ self._active_trial = max(0, self._active_trial - 1)
185
+ exec_ms = exec_duration * 1000.0
186
+ self._trial_execution_history.append((t1, exec_ms))
187
+ self._last_trial_finish_time = t1
188
+ cooldown_mult = (1.0 - self.max_trial_duty_cycle) / self.max_trial_duty_cycle
189
+ self._last_trial_cooldown_required = cooldown_mult * exec_duration
190
+ self._condition.notify_all()
191
+
192
+ return result
193
+ finally:
194
+ with self.lock:
195
+ self.trial_queue_depth = max(0, self.trial_queue_depth - 1)
196
+
197
+ def execute(
198
+ self,
199
+ tier: Union[PriorityTier, str],
200
+ compute_fn: Callable[..., T],
201
+ *args: Any,
202
+ **kwargs: Any,
203
+ ) -> T:
204
+ """
205
+ Schedules and executes `compute_fn` according to priority tier (`PAID_MAINNET` vs `FREE_TRIAL`).
206
+ """
207
+ tier_str = tier.value if isinstance(tier, PriorityTier) else str(tier).strip().upper()
208
+ if tier_str == PriorityTier.PAID_MAINNET.value:
209
+ return self.execute_paid(compute_fn, *args, **kwargs)
210
+ elif tier_str == PriorityTier.FREE_TRIAL.value:
211
+ return self.execute_trial(compute_fn, *args, **kwargs)
212
+ else:
213
+ raise ValueError(f"Unsupported PriorityTier: {tier}")