ssapling 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.
Files changed (61) hide show
  1. ssapling/__init__.py +12 -0
  2. ssapling/core/__init__.py +53 -0
  3. ssapling/core/_declarations.py +139 -0
  4. ssapling/core/_execution.py +155 -0
  5. ssapling/core/_plain.py +37 -0
  6. ssapling/core/_text.py +42 -0
  7. ssapling/core/errors.py +175 -0
  8. ssapling/core/loading.py +205 -0
  9. ssapling/core/registry.py +345 -0
  10. ssapling/core/settings.py +698 -0
  11. ssapling/core/spec.py +98 -0
  12. ssapling/data/__init__.py +89 -0
  13. ssapling/data/_matching.py +22 -0
  14. ssapling/data/batching.py +166 -0
  15. ssapling/data/collections.py +335 -0
  16. ssapling/data/encoding.py +107 -0
  17. ssapling/data/errors.py +104 -0
  18. ssapling/data/provenance.py +94 -0
  19. ssapling/data/records.py +546 -0
  20. ssapling/data/sampling.py +339 -0
  21. ssapling/data/storage.py +569 -0
  22. ssapling/environments/__init__.py +43 -0
  23. ssapling/environments/contracts.py +168 -0
  24. ssapling/environments/errors.py +53 -0
  25. ssapling/environments/runner.py +153 -0
  26. ssapling/environments/types.py +173 -0
  27. ssapling/evaluate/__init__.py +40 -0
  28. ssapling/evaluate/aggregation.py +173 -0
  29. ssapling/evaluate/assessment.py +429 -0
  30. ssapling/evaluate/measurement.py +165 -0
  31. ssapling/interaction/__init__.py +24 -0
  32. ssapling/interaction/episode.py +713 -0
  33. ssapling/interaction/errors.py +21 -0
  34. ssapling/interaction/hosting.py +287 -0
  35. ssapling/models/__init__.py +44 -0
  36. ssapling/models/buffering.py +189 -0
  37. ssapling/models/contracts.py +181 -0
  38. ssapling/models/errors.py +27 -0
  39. ssapling/models/types.py +75 -0
  40. ssapling/py.typed +0 -0
  41. ssapling/registries.py +37 -0
  42. ssapling/tasks/__init__.py +49 -0
  43. ssapling/tasks/contracts.py +137 -0
  44. ssapling/tasks/errors.py +37 -0
  45. ssapling/tasks/types.py +172 -0
  46. ssapling/teachers/__init__.py +34 -0
  47. ssapling/teachers/contracts.py +145 -0
  48. ssapling/teachers/errors.py +80 -0
  49. ssapling/teachers/runner.py +142 -0
  50. ssapling/teachers/types.py +178 -0
  51. ssapling/train/__init__.py +43 -0
  52. ssapling/train/components.py +194 -0
  53. ssapling/train/context.py +169 -0
  54. ssapling/train/errors.py +24 -0
  55. ssapling/train/procedure.py +316 -0
  56. ssapling/train/runner.py +398 -0
  57. ssapling/train/stages.py +463 -0
  58. ssapling-0.1.0.dist-info/METADATA +113 -0
  59. ssapling-0.1.0.dist-info/RECORD +61 -0
  60. ssapling-0.1.0.dist-info/WHEEL +4 -0
  61. ssapling-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,713 @@
1
+ """Running attempts: the episode loop and static solving, each recorded step by step.
2
+
3
+ ``run_episode`` resets an environment with an instance's inputs, then, step
4
+ by step: asks the model controlling each agent whose turn it is for an
5
+ action, consults the teacher if there is one, steps the environment, and
6
+ appends the step to the record. ``solve`` is the same without an
7
+ environment: it presents the instance's inputs to a model and records its
8
+ predictions. Train and Evaluate both run attempts through these, so an
9
+ attempt behaves the same in training and assessment.
10
+
11
+ How long the loop waits for a model's output is the **timing mode**,
12
+ measured on a **clock**. On the simulated clock, time is counted in calls to
13
+ the model's ``advance``, made by the loop, so runs are reproducible. On the
14
+ wall clock, it is counted in seconds.
15
+ """
16
+
17
+ import asyncio
18
+ import time
19
+ from collections import Counter
20
+ from collections.abc import AsyncIterator, Callable, Hashable, Mapping
21
+ from concurrent.futures import ThreadPoolExecutor
22
+ from contextlib import asynccontextmanager
23
+ from dataclasses import dataclass
24
+ from typing import Any, Literal
25
+
26
+ from ..core import setting, validate_settings
27
+ from ..core._declarations import check_int, name_of
28
+ from ..core._execution import Execution
29
+ from ..data import (
30
+ AgentTiming,
31
+ Clock,
32
+ LateOutput,
33
+ Provenance,
34
+ Record,
35
+ RecordBuilder,
36
+ RecordHeader,
37
+ RecordStep,
38
+ RecordSummary,
39
+ Store,
40
+ TeacherPlacement,
41
+ )
42
+ from ..environments import (
43
+ EnvironmentCommunicationError,
44
+ EnvironmentRunner,
45
+ ResetResult,
46
+ StepResult,
47
+ agents,
48
+ next_agents,
49
+ )
50
+ from ..models import NOTHING, as_buffered
51
+ from ..tasks import Instance
52
+ from ..teachers import TeacherRequest, TeacherResponse, TeacherRunner
53
+
54
+ __all__ = ["EpisodeSettings", "run_episode", "solve"]
55
+
56
+ Role = Literal["environment", "model", "teacher"]
57
+
58
+ TeacherContext = Callable[[Instance, Mapping[str, Any]], Mapping[str, Any]]
59
+ """Builds a teacher request's context from the instance and the acting agents' observations."""
60
+
61
+ OnStep = Callable[[RecordStep], Any]
62
+ """Called with each step of an attempt once it is recorded; it may be ``async def``."""
63
+
64
+ _POLL_INTERVAL = 0.001
65
+ """Seconds between polls of a model that works on its own, on the wall clock."""
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class EpisodeSettings:
70
+ """How an attempt is run. Plain values, so a run file can set them.
71
+
72
+ ``solve`` uses the timing settings and ``threads``; the others are for
73
+ episodes with an environment.
74
+ """
75
+
76
+ timing: Literal["turn_based", "deadline", "real_time"] = setting(
77
+ "turn_based",
78
+ description=(
79
+ "How long a model has to act. turn_based: as long as it needs. deadline: up to "
80
+ "budget, acting as soon as it has an output. real_time: exactly budget, a tick, "
81
+ "acting at its end."
82
+ ),
83
+ )
84
+ clock: Clock = setting(
85
+ "simulated",
86
+ description=(
87
+ "simulated: time is counted in calls to the model's advance, made by the loop, so "
88
+ "runs are reproducible. wall: time is counted in seconds."
89
+ ),
90
+ )
91
+ budget: float | None = setting(
92
+ None,
93
+ gt=0,
94
+ description=(
95
+ "For deadline and real_time: the time a model has per action, in calls to advance "
96
+ "on the simulated clock or seconds on the wall clock."
97
+ ),
98
+ )
99
+ late_outputs: Literal["discard", "use"] = setting(
100
+ "discard",
101
+ description=(
102
+ "What to do with an output that arrives after its deadline: discard it, or use it "
103
+ "as the agent's next action."
104
+ ),
105
+ )
106
+ default_actions: dict[str, Any] = setting(
107
+ default_factory=dict,
108
+ description=(
109
+ "Each agent's action when its model gives none in time. An agent not listed is left "
110
+ "out of the step, so the environment applies its own default."
111
+ ),
112
+ )
113
+ max_steps: int | None = setting(
114
+ None, ge=1, description="Cut the episode off after this many steps, as truncated."
115
+ )
116
+ intervene: bool = setting(
117
+ False,
118
+ description=(
119
+ "Apply the teacher's interventions to the actions. Otherwise the teacher only "
120
+ "observes: its responses are recorded, not applied."
121
+ ),
122
+ )
123
+ teacher_operation: str = setting(
124
+ "review_action", min_length=1, description="The operation asked of the teacher each step."
125
+ )
126
+ threads: list[Role] = setting(
127
+ default_factory=list,
128
+ description=(
129
+ "The components whose synchronous calls run in a worker thread of their own, so "
130
+ "they do not block the loop and can have a timeout: 'environment', 'model', "
131
+ "'teacher'."
132
+ ),
133
+ )
134
+ environment_timeout: float | None = setting(
135
+ None, gt=0, description="Seconds to wait for the environment's reset or step."
136
+ )
137
+ teacher_timeout: float | None = setting(
138
+ None, gt=0, description="Seconds to wait for the teacher; then its response is cancelled."
139
+ )
140
+
141
+ def validate(self) -> None:
142
+ if (self.timing == "turn_based") != (self.budget is None):
143
+ raise ValueError("deadline and real_time timing need a budget; turn_based has none")
144
+ if self.clock == "simulated" and self.budget is not None and self.budget % 1:
145
+ raise ValueError(
146
+ f"on the simulated clock the budget counts calls to advance, so it must be a "
147
+ f"whole number, not {self.budget}"
148
+ )
149
+
150
+
151
+ async def run_episode(
152
+ env: object,
153
+ model: object,
154
+ instance: Instance,
155
+ *,
156
+ record_id: str,
157
+ seed: int | None = None,
158
+ teacher: object | None = None,
159
+ teacher_context: TeacherContext | None = None,
160
+ teacher_placement: TeacherPlacement | None = None,
161
+ lane: Hashable | None = None,
162
+ provenance: Provenance | None = None,
163
+ store: Store | None = None,
164
+ settings: EpisodeSettings | Mapping[str, Any] | None = None,
165
+ on_step: OnStep | None = None,
166
+ ) -> Record:
167
+ """Run one episode of ``env`` on ``instance`` and return its record.
168
+
169
+ Example::
170
+
171
+ record = await run_episode(env, model, instance, record_id="ep-1", seed=7)
172
+ record = await run_episode(
173
+ env, {"player_1": alice, "player_2": bob}, instance, record_id="ep-2",
174
+ teacher=tutor, store=store, settings={"timing": "deadline", "budget": 3},
175
+ )
176
+
177
+ The environment is reset with ``options=instance.inputs`` (nothing, if
178
+ the inputs are ``None``), so the instance's reference never reaches it.
179
+ The models' and the teacher's episode state is reset too. Then, until
180
+ the episode is over:
181
+
182
+ 1. The agents whose turn it is (``environments.next_agents``) each give
183
+ an action: their model perceives the agent's latest observation
184
+ (``None`` if it has had none), and the loop waits for its output, as
185
+ the timing mode allows. With no output in time, the agent's default
186
+ action is used, or, without one, it is left out of the step.
187
+ 2. If there is a teacher, it is asked to review the proposals. Its
188
+ interventions replace actions only with ``intervene``.
189
+ 3. The environment steps, and the step is appended to the record. What
190
+ was executed, and any teacher responses, come from the environment's
191
+ report when it gives them, and otherwise from the loop.
192
+
193
+ The summary is the environment's: terminated or truncated. With
194
+ ``max_steps``, an episode still going after that many steps is
195
+ truncated, with ``"step limit"`` as the detail.
196
+
197
+ Args:
198
+ env: The environment.
199
+ model: The model controlling every participant, or a mapping from
200
+ each participant's agent id to its model. A model that controls
201
+ several participants is given each one's id as ``key``.
202
+ instance: What the episode attempts.
203
+ record_id: The record's id.
204
+ seed: Optional. Passed to the environment's reset.
205
+ teacher: Optional. A teacher the loop consults at each step, so its
206
+ placement is ``"coordinator"``.
207
+ teacher_context: Optional. Builds each request's context from the
208
+ instance and the acting agents' observations. By default the
209
+ context is ``{"instance": instance, "observations": ...}``.
210
+ teacher_placement: For the record's header, where a teacher the loop
211
+ does not consult sits: ``"environment"`` (the environment owns
212
+ it) or ``"participant"`` (it is one of the models).
213
+ lane: Optional. For several episodes at once that share a model:
214
+ each episode's lane, given to the model as its ``key`` (with the
215
+ agent id, as ``(lane, agent)``, when it controls several
216
+ participants), so each keeps its own episode state.
217
+ provenance: Optional. Where the instance came from, for the header.
218
+ store: Optional. Where the record is written, step by step.
219
+ settings: ``EpisodeSettings``, or a mapping of them.
220
+ on_step: Optional. Called with each step once it is recorded, before
221
+ the next one, for example to learn online. It may be ``async
222
+ def``.
223
+
224
+ Returns:
225
+ The record. When the environment cannot be reached during a step,
226
+ the record says so: that step has no transition, and the summary is
227
+ ``failed``.
228
+
229
+ Raises:
230
+ Exception: Whatever else goes wrong, such as a model's error or the
231
+ environment's own, as itself. A record already begun is first
232
+ finished as ``failed``, with the error as the reason, so it is
233
+ kept.
234
+ ValueError: A participant with no model; a teacher with a placement
235
+ other than ``"coordinator"``; or a timeout for a synchronous
236
+ component that does not run in a thread, which could never
237
+ interrupt it. Raised before any record is begun. Also an agent
238
+ named to act that is not a participant.
239
+ TypeError: A model without ``advance`` on the simulated clock.
240
+ """
241
+ settings = validate_settings(EpisodeSettings, settings)
242
+ if teacher is not None and teacher_placement not in (None, "coordinator"):
243
+ raise ValueError(
244
+ f"the loop consults a teacher only as 'coordinator', not {teacher_placement!r}; a "
245
+ "teacher in the environment or controlling a participant is not passed as teacher"
246
+ )
247
+ attempt = _Attempt(
248
+ settings, lane, on_step, env=env, teacher=teacher, teacher_context=teacher_context
249
+ )
250
+ try:
251
+ return await attempt.interact(
252
+ model,
253
+ instance,
254
+ record_id=record_id,
255
+ seed=seed,
256
+ placement="coordinator" if teacher is not None else teacher_placement,
257
+ provenance=provenance,
258
+ store=store,
259
+ )
260
+ finally:
261
+ attempt.close()
262
+
263
+
264
+ async def solve(
265
+ model: object,
266
+ instance: Instance,
267
+ *,
268
+ record_id: str,
269
+ attempts: int = 1,
270
+ participant: str = "solver",
271
+ lane: Hashable | None = None,
272
+ provenance: Provenance | None = None,
273
+ store: Store | None = None,
274
+ settings: EpisodeSettings | Mapping[str, Any] | None = None,
275
+ on_step: OnStep | None = None,
276
+ ) -> Record:
277
+ """Present ``instance``'s inputs to ``model``, with no environment, and record its predictions.
278
+
279
+ Example::
280
+
281
+ record = await solve(model, puzzle, record_id="p-1", attempts=2)
282
+ record.steps[0].predictions["solver"]
283
+
284
+ Each attempt is one step: the model perceives the whole of
285
+ ``instance.inputs``, never the reference, and the loop waits for its
286
+ prediction, as the timing mode allows. A prediction that does not come
287
+ in time is left out of the step, and the step's timing says so. The
288
+ summary is ``terminated``.
289
+
290
+ Args:
291
+ model: The model.
292
+ instance: What is solved.
293
+ record_id: The record's id.
294
+ attempts: How many times the inputs are presented: one step each.
295
+ participant: The model's agent id in the record.
296
+ lane: Optional. As for ``run_episode``.
297
+ provenance: Optional. Where the instance came from, for the header.
298
+ store: Optional. Where the record is written, step by step.
299
+ settings: ``EpisodeSettings``, or a mapping of them. The timing
300
+ settings and ``threads`` apply.
301
+ on_step: Optional. As for ``run_episode``.
302
+
303
+ Raises:
304
+ As for ``run_episode``.
305
+ """
306
+ settings = validate_settings(EpisodeSettings, settings)
307
+ check_int(attempts, "attempts", minimum=1)
308
+ attempt = _Attempt(settings, lane, on_step)
309
+ try:
310
+ return await attempt.present(
311
+ model,
312
+ instance,
313
+ record_id=record_id,
314
+ attempts=attempts,
315
+ participant=participant,
316
+ provenance=provenance,
317
+ store=store,
318
+ )
319
+ finally:
320
+ attempt.close()
321
+
322
+
323
+ class _Attempt:
324
+ """What one attempt's steps share: the components, how each is called, and its timing."""
325
+
326
+ def __init__(
327
+ self,
328
+ settings: EpisodeSettings,
329
+ lane: Hashable | None,
330
+ on_step: OnStep | None,
331
+ *,
332
+ env: object = None,
333
+ teacher: object = None,
334
+ teacher_context: TeacherContext | None = None,
335
+ ) -> None:
336
+ self.settings, self.lane, self.on_step = settings, lane, on_step
337
+ self.env, self.teacher = env, teacher
338
+ self.context = teacher_context or _default_context
339
+ self.threads = {role: ThreadPoolExecutor(max_workers=1) for role in settings.threads}
340
+
341
+ def placement(role: Role) -> dict[str, Any]:
342
+ if role in self.threads:
343
+ return {"placement": "thread", "executor": self.threads[role]}
344
+ return {}
345
+
346
+ self.environment = EnvironmentRunner(**placement("environment"))
347
+ self.teachers = TeacherRunner(**placement("teacher"))
348
+ self.teacher_calls = Execution(**placement("teacher"))
349
+ self.model_calls = Execution(**placement("model")) # advance and reset_episode
350
+ self.direct = Execution() # perceive and poll, which return at once
351
+ self.controllers: dict[str, tuple[Any, Hashable | None]] = {} # agent: model, key
352
+ self.owed: Counter[str] = Counter() # each agent's observations not yet answered
353
+ self.advancing: dict[str, asyncio.Task[Any]] = {} # wall clock: advance calls running
354
+ # The teacher is first asked mid-episode, so a timeout that could never
355
+ # interrupt it is refused now. The environment's is refused by its reset.
356
+ respond = getattr(teacher, "respond", None)
357
+ if settings.teacher_timeout is not None and callable(respond):
358
+ _check_interruptible(self.teacher_calls, settings.teacher_timeout, respond, "teacher")
359
+
360
+ def close(self) -> None:
361
+ for task in self.advancing.values():
362
+ task.cancel()
363
+ for thread in self.threads.values(): # a call past its time may still be running
364
+ thread.shutdown(wait=False, cancel_futures=True)
365
+
366
+ # The two kinds of attempt
367
+
368
+ async def interact(
369
+ self,
370
+ model: object,
371
+ instance: Instance,
372
+ *,
373
+ record_id: str,
374
+ seed: int | None,
375
+ placement: TeacherPlacement | None,
376
+ provenance: Provenance | None,
377
+ store: Store | None,
378
+ ) -> Record:
379
+ reset = await self.environment.reset(
380
+ self.env, seed=seed, options=instance.inputs, timeout=self.settings.environment_timeout
381
+ )
382
+ participants = agents(self.env, reset)
383
+ self._control(model, participants)
384
+ header = RecordHeader(
385
+ id=record_id,
386
+ instance_id=instance.id,
387
+ participants=participants,
388
+ reset=reset,
389
+ provenance=provenance,
390
+ seeds={} if seed is None else {"reset": seed},
391
+ clock=self.settings.clock,
392
+ teacher_placement=placement,
393
+ )
394
+ async with self._recording(header, store) as writer:
395
+ return await self._play(instance, reset, writer)
396
+
397
+ async def present(
398
+ self,
399
+ model: object,
400
+ instance: Instance,
401
+ *,
402
+ record_id: str,
403
+ attempts: int,
404
+ participant: str,
405
+ provenance: Provenance | None,
406
+ store: Store | None,
407
+ ) -> Record:
408
+ self._control(model, (participant,))
409
+ header = RecordHeader(
410
+ id=record_id,
411
+ instance_id=instance.id,
412
+ participants=(participant,),
413
+ provenance=provenance,
414
+ clock=self.settings.clock,
415
+ )
416
+ async with self._recording(header, store) as writer:
417
+ for index in range(attempts):
418
+ output, timing, report = await self._decide(participant, instance.inputs)
419
+ await writer.append(
420
+ RecordStep(
421
+ index=index,
422
+ acting=(participant,),
423
+ presented={participant: instance.inputs},
424
+ predictions={} if output is NOTHING else {participant: output},
425
+ timing={participant: timing},
426
+ diagnostics={} if report is None else {participant: report},
427
+ )
428
+ )
429
+ return writer.finish(RecordSummary.terminated())
430
+
431
+ @asynccontextmanager
432
+ async def _recording(
433
+ self, header: RecordHeader, store: Store | None
434
+ ) -> AsyncIterator["_Writer"]:
435
+ """Begin the record and reset episode state; if what follows fails, keep the record."""
436
+ writer = _Writer(header, store, self.on_step)
437
+ try:
438
+ for controller, key in self.controllers.values():
439
+ if callable(getattr(controller, "reset_episode", None)):
440
+ await _call(self.model_calls, controller.reset_episode, key)
441
+ if callable(getattr(self.teacher, "reset", None)):
442
+ await self.teacher_calls.call(self.teacher.reset) # type: ignore[attr-defined]
443
+ yield writer
444
+ except BaseException as error:
445
+ if writer.record is None: # keep what happened, marked failed
446
+ writer.finish(RecordSummary.failed(f"{type(error).__name__}: {error}"))
447
+ raise
448
+
449
+ async def _play(self, instance: Instance, reset: ResetResult, writer: "_Writer") -> Record:
450
+ observations = dict(reset.observations) # each agent's latest
451
+ last: ResetResult | StepResult = reset
452
+ index = 0
453
+ while True:
454
+ if self.settings.max_steps is not None and index == self.settings.max_steps:
455
+ return writer.finish(RecordSummary.truncated("step limit"))
456
+ acting = next_agents(self.env, last)
457
+ unknown = [agent for agent in acting if agent not in self.controllers]
458
+ if unknown:
459
+ raise ValueError(f"{name_of(self.env)} names {unknown} to act: not participants")
460
+ seen = {agent: observations.get(agent) for agent in acting} # None if never observed
461
+ decided = await asyncio.gather(*(self._decide(agent, seen[agent]) for agent in acting))
462
+ proposals: dict[str, Any] = {}
463
+ actions: dict[str, Any] = {} # the proposals, and default actions where none came
464
+ timing: dict[str, AgentTiming] = {}
465
+ diagnostics: dict[str, Any] = {}
466
+ for agent, (output, when, report) in zip(acting, decided, strict=True):
467
+ timing[agent] = when
468
+ if report is not None:
469
+ diagnostics[agent] = report
470
+ if output is not NOTHING:
471
+ proposals[agent] = actions[agent] = output
472
+ elif agent in self.settings.default_actions:
473
+ actions[agent] = self.settings.default_actions[agent]
474
+
475
+ responses: tuple[TeacherResponse, ...] = ()
476
+ if self.teacher is not None:
477
+ request = TeacherRequest(
478
+ id=f"{writer.id}:{index}",
479
+ operation=self.settings.teacher_operation,
480
+ context=self.context(instance, seen),
481
+ proposals=proposals,
482
+ episode=writer.id,
483
+ step=index,
484
+ )
485
+ response = await self.teachers.request(
486
+ self.teacher, # type: ignore[arg-type]
487
+ request,
488
+ timeout=self.settings.teacher_timeout,
489
+ )
490
+ responses = (response,)
491
+ if self.settings.intervene:
492
+ actions = _intervene(actions, response)
493
+
494
+ try:
495
+ result = await self.environment.step(
496
+ self.env, actions, timeout=self.settings.environment_timeout
497
+ )
498
+ except EnvironmentCommunicationError as error:
499
+ await writer.append(
500
+ RecordStep(
501
+ index=index,
502
+ acting=acting,
503
+ proposals=proposals,
504
+ teacher_responses=responses,
505
+ timing=timing,
506
+ diagnostics=diagnostics,
507
+ )
508
+ )
509
+ return writer.finish(RecordSummary.failed(str(error)))
510
+ await writer.append(
511
+ RecordStep(
512
+ index=index,
513
+ acting=acting,
514
+ proposals=proposals,
515
+ teacher_responses=responses + tuple(result.teacher_responses or ()),
516
+ executed_actions=(
517
+ actions if result.executed_actions is None else result.executed_actions
518
+ ),
519
+ transition=result,
520
+ timing=timing,
521
+ diagnostics=diagnostics,
522
+ )
523
+ )
524
+ if result.episode_over:
525
+ ended = (
526
+ RecordSummary.terminated
527
+ if result.episode_terminated
528
+ else RecordSummary.truncated
529
+ )
530
+ return writer.finish(ended())
531
+ observations.update(result.observations)
532
+ last = result
533
+ index += 1
534
+
535
+ # Models and timing
536
+
537
+ def _control(self, model: object, participants: tuple[str, ...]) -> None:
538
+ """Find each participant's model, seen through buffers, and the key it is called with."""
539
+ chosen: Mapping[str, Any] = (
540
+ model if isinstance(model, Mapping) else dict.fromkeys(participants, model)
541
+ )
542
+ missing = [agent for agent in participants if agent not in chosen]
543
+ if missing:
544
+ names = ", ".join(repr(agent) for agent in missing)
545
+ raise ValueError(f"no model controls {names}; give a model for every participant")
546
+ buffered = {id(each): as_buffered(each) for each in chosen.values()}
547
+ for controller in buffered.values():
548
+ advance = getattr(controller, "advance", None)
549
+ if not callable(advance):
550
+ if self.settings.clock == "simulated":
551
+ raise TypeError(
552
+ f"{name_of(controller)} has perceive and poll but no advance, so it "
553
+ "cannot be driven on the simulated clock; use the wall clock"
554
+ )
555
+ elif self.settings.clock == "wall" and self.settings.budget is not None:
556
+ _check_interruptible(self.model_calls, self.settings.budget, advance, "model")
557
+
558
+ serving = Counter(id(chosen[agent]) for agent in participants)
559
+
560
+ def key(agent: str) -> Hashable | None:
561
+ shared = serving[id(chosen[agent])] > 1
562
+ if self.lane is None:
563
+ return agent if shared else None
564
+ return (self.lane, agent) if shared else self.lane
565
+
566
+ self.controllers = {
567
+ agent: (buffered[id(chosen[agent])], key(agent)) for agent in participants
568
+ }
569
+
570
+ async def _decide(self, agent: str, observation: Any) -> tuple[Any, AgentTiming, Any]:
571
+ """Give ``agent``'s model the observation, and wait for its output as timing allows.
572
+
573
+ Returns the output, or ``NOTHING`` when none came in time; the
574
+ agent's timing; and the model's report about its decision, from its
575
+ ``diagnostics`` method, or ``None`` when it has none.
576
+ """
577
+ output, timing = await self._wait(agent, observation)
578
+ model, key = self.controllers[agent]
579
+ diagnostics = getattr(model, "diagnostics", None)
580
+ report = None if diagnostics is None else await _call(self.direct, diagnostics, key)
581
+ return output, timing, report
582
+
583
+ async def _wait(self, agent: str, observation: Any) -> tuple[Any, AgentTiming]:
584
+ model, key = self.controllers[agent]
585
+ await _call(self.direct, model.perceive, key, observation)
586
+ self.owed[agent] += 1
587
+ clock = _Clock(self.settings)
588
+ late: LateOutput | None = None
589
+ while True:
590
+ output = await _call(self.direct, model.poll, key)
591
+ if output is not NOTHING:
592
+ self.owed[agent] -= 1
593
+ if self.owed[agent] > 0: # it answers an earlier observation
594
+ late = "used" if self.settings.late_outputs == "use" else "discarded"
595
+ if late == "discarded":
596
+ continue
597
+ if self.settings.timing == "real_time": # act at the end of the tick
598
+ await self._wait_out(agent, clock)
599
+ return output, AgentTiming(elapsed=clock.elapsed(), late=late)
600
+ if clock.done():
601
+ return NOTHING, AgentTiming(elapsed=clock.elapsed(), defaulted=True, late=late)
602
+ await self._advance(agent, clock)
603
+
604
+ async def _advance(self, agent: str, clock: "_Clock") -> None:
605
+ """Let ``agent``'s model work for one call to ``advance``, or until time runs out.
606
+
607
+ On the simulated clock, the call is one unit of time. On the wall
608
+ clock, a call still running when time runs out keeps running, and
609
+ the agent's next wait continues it, so its output arrives late.
610
+ """
611
+ model, key = self.controllers[agent]
612
+ advance = getattr(model, "advance", None)
613
+ if not clock.wall:
614
+ await _call(self.model_calls, advance, key) # type: ignore[arg-type]
615
+ clock.steps += 1
616
+ elif advance is None: # the model works on its own: look again shortly
617
+ remaining = clock.remaining()
618
+ await asyncio.sleep(
619
+ _POLL_INTERVAL if remaining is None else min(_POLL_INTERVAL, remaining)
620
+ )
621
+ else:
622
+ task = self.advancing.get(agent) or asyncio.create_task(
623
+ _call(self.model_calls, advance, key)
624
+ )
625
+ self.advancing[agent] = task
626
+ done, _ = await asyncio.wait({task}, timeout=clock.remaining())
627
+ if done:
628
+ del self.advancing[agent]
629
+ task.result() # its error, if it raised one
630
+
631
+ async def _wait_out(self, agent: str, clock: "_Clock") -> None:
632
+ """Let the rest of ``agent``'s tick pass; on the simulated clock its model advances."""
633
+ while not clock.done():
634
+ if clock.wall:
635
+ await asyncio.sleep(clock.remaining() or 0)
636
+ else:
637
+ await self._advance(agent, clock)
638
+
639
+
640
+ class _Clock:
641
+ """Measures one wait: calls to ``advance`` on the simulated clock, seconds on the wall clock."""
642
+
643
+ def __init__(self, settings: EpisodeSettings) -> None:
644
+ self.wall = settings.clock == "wall"
645
+ self.budget = settings.budget
646
+ self.start = time.monotonic()
647
+ self.steps = 0
648
+
649
+ def elapsed(self) -> float:
650
+ return time.monotonic() - self.start if self.wall else self.steps
651
+
652
+ def remaining(self) -> float | None:
653
+ return None if self.budget is None else max(0.0, self.budget - self.elapsed())
654
+
655
+ def done(self) -> bool:
656
+ return self.remaining() == 0
657
+
658
+
659
+ class _Writer:
660
+ """Builds the record, writes it to the store, if there is one, and passes on each step."""
661
+
662
+ def __init__(self, header: RecordHeader, store: Store | None, on_step: OnStep | None) -> None:
663
+ self.id = header.id
664
+ self.builder = RecordBuilder(header)
665
+ self.store, self.on_step = store, on_step
666
+ self.record: Record | None = None # once finished
667
+ if store is not None:
668
+ store.begin(header)
669
+
670
+ async def append(self, step: RecordStep) -> None:
671
+ self.builder.append(step)
672
+ if self.store is not None:
673
+ self.store.append(self.id, step)
674
+ if self.on_step is not None:
675
+ await Execution().call(self.on_step, step)
676
+
677
+ def finish(self, summary: RecordSummary) -> Record:
678
+ self.record = self.builder.finish(summary)
679
+ if self.store is not None:
680
+ self.store.finish(self.id, summary)
681
+ return self.record
682
+
683
+
684
+ async def _call(
685
+ execution: Execution, method: Callable[..., Any], key: Hashable | None, *args: Any
686
+ ) -> Any:
687
+ """Call a model's method, passing ``key`` only when there is one."""
688
+ if key is None:
689
+ return await execution.call(method, *args)
690
+ return await execution.call(method, *args, key=key)
691
+
692
+
693
+ def _intervene(actions: Mapping[str, Any], response: TeacherResponse) -> dict[str, Any]:
694
+ """``actions`` with the interventions of an answered response applied."""
695
+ if response.status != "answered":
696
+ return dict(actions)
697
+ interventions = response.contributions.get("intervention", {})
698
+ return {agent: interventions.get(agent, action) for agent, action in actions.items()}
699
+
700
+
701
+ def _default_context(instance: Instance, observations: Mapping[str, Any]) -> dict[str, Any]:
702
+ return {"instance": instance, "observations": dict(observations)}
703
+
704
+
705
+ def _check_interruptible(
706
+ execution: Execution, timeout: float, method: Callable[..., Any], role: Role
707
+ ) -> None:
708
+ """Refuse a time limit that could never interrupt ``method``, before the attempt begins."""
709
+ try:
710
+ execution.check_timeout(timeout, method)
711
+ except ValueError as error:
712
+ error.add_note(f"In the episode loop, list {role!r} in settings.threads.")
713
+ raise