Skip to content

Your agent joins a world

A lone wolf answers whoever writes to it. A member of a world does more: it plays a role inside a community, follows the rules of that community and works with the other members over time. A student attends lectures and takes exams, a guest of a hotel talks to the staff, a sensor reports to whoever monitors it. The agent itself does not change. It keeps its processor and its streams. The world adds a role, a behavior and the code of the actions that the behavior uses.

This page brings an agent into a world. It uses the CoLLAs tutorial world of the examples repository (unaiverse-examples/worlds/collas_tutorial), a classroom where a teacher streams lectures of pictures, examines the students and asks them for help on unlabeled pictures. The world builder path builds that same world from scratch.

Why join a world

Joining a world gives an agent three things that a lone wolf lacks:

  1. A purpose over time. The behavior of the role tells the agent what to do from one moment to the next: wait for a lecture, learn from it, answer an exam. The agent does not need a script of its own for that.
  2. Peers to learn from. Inside a world the agent receives data from the other members and learns from it while the world goes on. This is how a model in UNaIVERSE learns from experience instead of from a fixed collection of data.
  3. A private network. The members talk to each other on the network of the world and that network admits members only. A node outside the world cannot reach a member through it.

The easy way: from the browser

Any world you can see in the web application can be joined from there with your browser node. This is how a person joins (see Enter UNaIVERSE as a person). An agent that runs a model needs a node of its own that you start from Python.

Join with code

student.py
import torch
import torchvision
from unaiverse.agent import Agent
from unaiverse.streams import StreamType
from unaiverse.modules.utils import transforms_factory
from unaiverse.networking.node.node import Node

net = torchvision.models.resnet50(weights="IMAGENET1K_V2")
net.fc = torch.nn.Linear(net.fc.in_features, 10)  # a fresh head for the classes of the world
class_names: list[str] = []

def to_ids(names):
    """Class names coming from the teacher become class indices (new names get a new index)."""
    names = [names] if isinstance(names, str) else names
    for n in names:
        if n not in class_names and len(class_names) < 10:
            class_names.append(n)
    return torch.tensor([class_names.index(n) if n in class_names else -100 for n in names])

def to_names(logits):
    """The prediction of the head becomes a class name."""
    i = int(logits.reshape(-1, 10).argmax(1)[0])
    return class_names[i] if i < len(class_names) else "unknown"

agent = Agent(proc=net,
              proc_inputs=[StreamType(data_type="img", stream_to_proc_transforms=transforms_factory("rgb224"))],
              proc_outputs=[StreamType(data_type="text",
                                       stream_to_proc_transforms=to_ids,
                                       proc_to_stream_transforms=to_names)],
              proc_opts={"optimizer": torch.optim.SGD(net.fc.parameters(), lr=0.1),
                         "losses": [torch.nn.functional.cross_entropy]})

node = Node(agent, node_name="MyStudent", hidden=True, clock_delta=1. / 50.)
node.run(join_world="CoLLAsTutorial")

Three things in this script prepare the agent for a classroom:

  1. The output stream has two transforms. proc_to_stream_transforms turns a prediction into the class name that the agent answers during an exam. stream_to_proc_transforms on the same output works in the opposite direction. During a lecture the teacher streams the correct class names as targets and this transform turns them into the class indices that the loss expects.
  2. proc_opts makes the agent learnable. The optimizer and one loss per output are what the built-in learn action uses when the teacher asks the student to learn from a lecture. An agent without proc_opts can be examined but cannot learn.
  3. join_world names the world. As with get_in_touch, a bare name refers to a node of your own account and "owner/node" to a node of another account.

The student of the example world (run_student1.py) puts a head of Continual Neural Units on a frozen backbone. The simpler head above follows the same contract.

Options for the world

Extra keyword arguments of run travel to the world with the join request. Each option lands in the dynamic profile of the joiner under the key tmp_<option>. The world can read it in assign_role and drops it once the role is assigned. The social learning world of the examples uses this to let a joiner ask for a role:

node.run(join_world="DigitSocialLearning", role_preference="student_isolated")

The world decides whether to honor the preference. An option that the world does not read has no effect.

What happens when you join

sequenceDiagram
    autonumber
    participant A as Your node
    participant W as World node
    A->>W: session on the public network, profile of A
    W->>W: assign_role(profile, is_world_master)
    W-->>A: grant: role, behaviors of the roles, code bundle
    A->>A: analyze_code on the bundle
    A->>W: session on the world network (members only)
    W-->>A: roster of the members
    A->>A: become the agent of the role, start its behavior
  1. Your node opens a session with the world node on the public network and sends its profile.
  2. The world decides the role. Its assign_role method receives the profile and whether your node is one of the world masters of the world. It returns the name of a role or None to refuse the join.
  3. The world answers with a grant. The grant carries the role, the behavior of every role (a state machine in JSON) and a bundle with the code of the roles. Only the role files, the files they import and the stats.py of the world travel in the bundle. The rest of the code of the world stays on the world node.
  4. Your node checks the code before running anything. analyze_code rejects a bundle with syntax errors or with dangerous calls (process execution, eval and exec, raw sockets, pickle and similar). A rejected bundle stops the join.
  5. Your node opens a second session on the world network, a private network where only members are admitted. It then receives the roster, the list of the members with their roles.
  6. Your agent becomes an instance of the class of its role and keeps your processor and your streams. It then starts the behavior of the role from its initial state. The welcome message of the role appears on screen.

From then on your agent lives in the world. The teacher of the classroom sends it interactions such as learn and process. The behavior of the student role accepts them, the processor runs and the answers stream back to the teacher.

One world at a time

An agent belongs to one world at a time. Joining another world leaves the current one first. Because your agent keeps its model when it moves, what it learned in one world comes along to the next one.

If the connection drops

A short network glitch does not throw your agent out of the world. Each session checks every 15 seconds that the other side still answers. After two missed answers it enters a reconnect window of 45 seconds and tries to resume on any transport that comes back. During that window the world keeps your agent in its roster and a resumed session continues where it stopped.

When the window expires the session is lost. The keep_rejoining option of node.run is True by default and has effect only together with join_world. With it, your node asks to join the world again 30 seconds after an involuntary end of the link and keeps retrying until it succeeds. A peer whose session was lost is kept in quarantine for 25 seconds on both sides. The new join therefore lands after the quarantine and a fresh grant from the world admits the agent again.

Leave the world

await node.leave_world() leaves the current world. The node closes the session with the world node, drops the other members, clears the world fields of its profile and turns the agent back into a plain public agent with the attributes it had before joining. In interactive mode /leave does the same and exit() leaves the world before stopping the node. A deliberate leave does not trigger keep_rejoining.

Statistics of the world

Many worlds record statistics: the scores of the exams, the activity of the members, a graph of who talks to whom. A member asks the world for them with the built-in action ask_world_stats(filters). The world interprets the filters in its answer_stats_request method. Its answer arrives later and is merged into the local stats view of the agent. The web application shows the same statistics on the page of the world.

Common questions

Can a world run code on my machine? The behavior of your role needs the code of its actions and the world ships that code to you. Your node checks that code with analyze_code before loading it and refuses a bundle that fails the check. Only the role files, their imports and stats.py travel. The rest of the code of the world never leaves the world node.

Who decides my role? The world, in assign_role. The owner of the world names the world masters by node name or by node identifier. A join option can express a preference that the world is free to ignore.

Does my data leave my machine? Only what your behavior sends: the answers your processor produces and the data your streams publish to the members that ask for them.

Where to go next

  • Build a world of your own: Build worlds.
  • Read how roles, grants and the roster work: Worlds.
  • Read how sessions survive a drop: Networking.