Skip to content

5 · Writing actions

The machines of chapter 4 name actions such as give_next_lecture, teach and lecture_finished. Each name is a method of the role class. A role acts only through its actions: sending a message, checking a condition, reading data, training a model. The machine decides when to call an action and the action decides whether the step succeeded. This chapter writes the actions of the teacher with the conventions that every action follows.

The @action decorator

src/teacher.py
from unaiverse.agent import Agent, action


class WAgent(Agent):

    @action
    async def reset_status(self) -> bool:
        """Resets the status of the teacher at the start of every round."""
        self.current_lecture_num = 1
        self.current_lecture_finished = False
        self.current_exam_finished = False
        self.current_feedback_provided = False
        self.current_students = set()
        self.sent_samples = {}
        self.received_samples = {}
        self.last_data_sent_at = -1.
        return True

An action is an async method decorated with @action that returns True or False. The decorator does three things:

  1. It marks the method as an action. Behaviors can name only marked methods and the world checks every name when it loads a behavior.
  2. It resolves names. Arguments called agent, agents, partner, partners, target or targets may hold a node name, an "owner/node" reference or a peer identifier. The decorator turns names into peer identifiers before the method runs. Arguments called stream or streams are resolved in the same way from a readable stream name, such as "images@lecture1", to the hash that identifies the stream on the network.
  3. It isolates errors. An exception raised inside the action is logged together with its traceback and the action counts as failed. The node keeps running.

An action must return a value. The machine treats a returned None as a programming error and logs it as critical. Any value that is not None and not False counts as success.

What True and False mean

True means that the step succeeded and the machine takes the transition. False means that the step did not happen yet. What the machine does next depends on the transition (chapter 4):

  • With a timeout, the action is called again at the next cycle until it succeeds or the timeout expires.
  • Without a timeout, the machine tries the next transition of the state.

This makes False the natural way to wait for a condition. lecture_finished waits for the end of a lecture and then for the last answers to travel back:

@action
async def lecture_finished(self) -> bool:
    """True once the lecture is over and the last answers had time to arrive."""
    if self.current_lecture_finished:
        if self.last_data_sent_at < 0:
            self.last_data_sent_at = self.clock.get_time()
        done = (self.clock.get_time() - self.last_data_sent_at) > self.LECTURE_RESPONSE_DELTA
        if done:
            self.current_lecture_num += 1
        return done
    return False

The transition from lecture_in_progress to in_class has no timeout. The state lecture_in_progress, however, has a single transition and is a blocking state. The machine therefore calls lecture_finished again at every cycle and leaves the state on the first True. self.clock.get_time() reads the clock of the node. Every node synchronizes this clock with time servers when it starts.

Where arguments come from

An action receives each argument from the first of three sources that holds it:

  1. the args of the transition in the behavior (action_kwargs in JSON)
  2. the action_kwargs of the interaction that requested the action, when another agent asked for it
  3. the default value of the parameter in the method

Before the call the machine replaces the wildcards of the behavior (<partner>, <agent>, <world>, <role>) in the values of the arguments.

The student action print shows the second source. The teacher sends action_kwargs={"msg": "..."} and the student receives msg:

src/student.py
from unaiverse.utils.logger import log
from unaiverse.agent import Agent, action
from unaiverse.interaction import Interaction


class WAgent(Agent):

    @action
    async def print(self, msg: str, interaction: Interaction | None = None) -> bool:
        """Prints a message that another agent asked this agent to show."""
        if interaction is None:
            return False
        log.user(msg)
        return True

log.user prints on the terminal of the member. It is the channel that the node always shows (see Launch a lone wolf).

Requested actions

An action with a parameter named interaction receives the Interaction that requested it. Such an action is requested by default. Like a transition with ready=False, it runs only when another agent asks for it. add_transit applies this default when it creates the transition in Python. In a JSON behavior an explicit "ready" field keeps its value.

print returns False when interaction is None and therefore never runs on the initiative of the student. The built-in learn and process follow the same pattern and a student runs them only when the teacher asks for them.

Actions that send

Most actions of the teacher talk to the students. give_next_lecture announces the next lecture by asking every student to run print:

@action
async def give_next_lecture(self) -> bool:
    """Announces the next lecture, or fails when all three lectures were given."""
    if self.current_lecture_num > 3:
        return False
    self.current_lecture_finished = False
    return await self.send(action_name="print",
                           action_kwargs={"msg": f"📚 **Lecture {self.current_lecture_num}/3**\n\n"
                                                 "*Watch the following pictures and learn!*"},
                           from_state="in_class",
                           target=self.get_agents_by_role("student"),
                           volatile=True)

After the three lectures the action fails. The machine then tries the next candidate of in_class (start_exam_session). send returns True when at least one target was reached. Chapter 6 explains every argument of send.

The hooks of a role class

Besides actions, a role class can override methods that the node calls at fixed moments:

Method When it runs Used for
accept_new_role(role) when the world assigns or changes the role creating streams, loading local resources (chapter 3)
async on_tick() inside a world, at every cycle of the node, right before the behavior acts checks that do not belong to a single state, such as an empty class
hook_before_sending_sample(data, data_tag, net_hash, stream_name, recipient) right before a sample of an owned stream leaves the node rewriting a sample for its receiver (chapter 7)

The teacher uses on_tick for three jobs: it returns to init when no student is left, pauses the class when the space bar is pressed in its terminal and prints a summary of the class. An override of on_tick must call await super().on_tick() first.

Methods without the decorator are ordinary helpers. The student defines one_at_random, a static method that picks one teacher at random when several exist. connect_by_role receives its name as filter_fcn and calls it.

Long computations: stepwise

All the actions of a node run on its main asyncio task and share it with the sessions of the node. An action that computes for ten seconds blocks the keep-alive answers of every session for ten seconds. Processors avoid this problem by running in a worker thread during process and learn. For a long computation inside an action, stepwise slices the work into chunks, one per cycle of the node:

def score_buffer(self, samples):
    """A generator: every yield ends a chunk, the return value is the result."""
    total = 0.
    for i, s in enumerate(samples):
        total += self.expensive_score(s)
        if i % 100 == 99:
            yield
    return total / max(1, len(samples))

@action
async def evaluate_buffer(self, interaction: Interaction | None = None) -> bool:
    done, result = self.stepwise(interaction, self.score_buffer, self.buffer)
    if not done:
        return False          # come back at the next cycle for the next chunk
    self.last_score = result
    return True

stepwise(interaction, make_gen, *args, retry_timeout=..., **kwargs) builds the generator at the first call, makes the action pedantic and advances one chunk. Every later call advances one more chunk. It returns (False, None) until the generator returns and then (True, result). When the deadline given by retry_timeout passes, it cleans up and raises an exception. The decorator turns that exception into one failure of the action. An abandoned interaction drops the generator and a later request starts a new one. The generator must therefore be safe to run again from scratch. A chunk must never yield while it holds a global mode (enter and exit torch.no_grad() within the chunk) and must restore in a finally block any state it changes on shared objects. When interaction is None (a direct call from code), stepwise runs the generator to the end at once.

Because evaluate_buffer takes an interaction parameter, it is a requested action. It runs when another agent asks for it.

Built-in actions

Every agent inherits a set of actions from Agent. The behaviors of the examples use them all the time:

Group Actions
Processor process, learn
Sending send, all_sent_completed, on_received, show
Finding and connecting find_agents, connect_by_role, connect_to, connected, disconnected, disconnect, disconnect_by_role
Engagement engage, send_engage, disengage, send_disengage, disengage_all, set_engaged_partner, all_engagements_completed, agents_are_waiting
Streams subscribe, send_subscribe, record, set_pref_streams, first_pref_stream, next_pref_stream, check_pref_stream
Evaluation evaluate, compare_eval
World ask_world_stats, suggest_role_to_world, suggest_badges_to_world
Control nop

Actions documents the arguments and the return value of each one.

Run it

tutorial_steps/step3 declares every action of the teacher as a stub that returns True. Replace the stubs one at a time with the implementations of this chapter and of the next ones and watch how the loop of the teacher changes. The complete implementations are in tutorial_steps/step4/src/teacher.py.

Where next

Chapter 6 opens send, the call that connects the actions of different agents.

6 · How interactions travel