Image classifier¶
A pretrained ResNet-50 from torchvision becomes an agent of the network that anyone you allow can reach. It takes a picture and answers with one of the 1000 ImageNet labels. The example has two scripts: server.py serves the model as a lone wolf and client.py is a second agent that sends it one picture and prints the label. Both run on the same account. While the server runs, you can also open it from the webapp and send it a photo from your phone.
The sources are in examples-src/image-classifier/.
The server¶
"""Serves a pretrained ResNet-50 as a lone wolf: a picture in, the ImageNet label out."""
import torchvision
from unaiverse.agent import Agent
from unaiverse.streams import StreamType
from unaiverse.networking.node.node import Node
weights = torchvision.models.ResNet50_Weights.IMAGENET1K_V1
net = torchvision.models.resnet50(weights=weights).eval()
labels = weights.meta["categories"]
# From the PIL image that arrives to the batch of one tensor that ResNet expects
to_tensor = torchvision.transforms.Compose([
torchvision.transforms.Lambda(lambda img: img.convert("RGB")),
weights.transforms(),
torchvision.transforms.Lambda(lambda x: x.unsqueeze(0)),
])
agent = Agent(proc=net,
proc_inputs=[StreamType(data_type="img", stream_to_proc_transforms=to_tensor)],
proc_outputs=[StreamType(data_type="text",
proc_to_stream_transforms=lambda logits: labels[logits.argmax(1)[0]])])
node = Node(agent, node_name="ResNetAgent", hidden=True, clock_delta=1. / 10.)
node.run()
The agent declares what its processor takes and returns with one StreamType per side. Pictures travel between nodes as img data and reach the processor side as PIL images. Before the forward pass, stream_to_proc_transforms applies the normalization that comes with the weights and turns each picture into the (1, 3, 224, 224) tensor that ResNet expects. After the forward pass, proc_to_stream_transforms turns the (1, 1000) logits into the text of the winning label. The network itself stays an ordinary torch.nn.Module in evaluation mode and knows nothing of UNaIVERSE.
Node registers the node on your account under the name ResNetAgent the first time and reuses it afterwards. hidden=True keeps it visible to you only. clock_delta=1/10 makes the node tick at most ten times per second. With no join_world and no get_in_touch, run() keeps the node in the public network as a lone wolf until you stop it with Ctrl+C.
A lone wolf needs no behavior of its own. Every agent loads a default public behavior that waits in state ready. When another agent asks for process, the behavior runs the processor on the sample that came with the request and sends the output back to the requester.
The client¶
"""Sends one picture to the ResNetAgent node of the same account and prints the label it answers with."""
import sys
from PIL import Image
from unaiverse.agent import Agent
from unaiverse.streams import StreamType
from unaiverse.interaction import CompletionReason
from unaiverse.networking.node.node import Node
PICTURE = sys.argv[1] if len(sys.argv) > 1 else "cat.jpg"
class Asker(Agent):
"""An agent without a processor that asks ResNetAgent to label one picture."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.request = None
self.answered = False
async def behave(self):
await super().behave()
# Ask once, as soon as the other node is connected
if self.request is None and self.resolve_agent_ref("ResNetAgent") is not None:
if await self.send(action_name="process",
target="ResNetAgent",
data_samples={"proc_output_0": Image.open(PICTURE)},
callback="on_done"):
self.request = self.get_last_sent_interaction()
# Read the answer when it arrives on the processor stream of ResNetAgent
if self.request is not None and not self.answered:
label = self.answer_of(self.request)
if label is not None:
self.answered = True
print(f"ResNetAgent says: {label}")
def answer_of(self, interaction):
"""The sample that the target wrote for this interaction on its processor stream, or None."""
for streams in self.find_streams(interaction.target[0], "processor").values():
for stream in streams.values():
sample = stream.get(uuid=interaction.uuid)
if sample is not None:
return sample
return None
async def on_done(self, interaction=None):
if interaction.completion_reason != CompletionReason.OK:
print(f"No answer: {interaction.completion_reason}")
return True
agent = Asker(proc=None, proc_inputs=[StreamType(data_type="text")], proc_outputs=[StreamType(data_type="img")])
node = Node(agent, node_name="Asker", hidden=True, clock_delta=1. / 10.)
node.run(get_in_touch="ResNetAgent", max_time=60.)
run(get_in_touch="ResNetAgent", max_time=60.) connects to the node with that name in your account and stops the client after 60 seconds. A name without a slash always refers to your own account. For a node of another account write owner/node.
The node awaits behave() at every tick. Asker overrides it and calls the inherited version first in order to keep the default behavior running. The first time resolve_agent_ref("ResNetAgent") returns a peer ID, the connection is up and the client sends the request. Agent.send is the one call for every request to other agents:
action_name="process"names the action that the receiver must run.targetis a peer ID, a node name of your account, anowner/nodereference or a list of them.data_samplesmaps a stream of the sender to the sample that travels with the request.proc_output_0is the name that the SDK gives to the first processor output of an agent whose output streams have no name of their own. This is why the client declaresproc_outputs=[StreamType(data_type="img")]even though it has no processor.callbacknames an async method of the agent that the SDK calls when the request completes for any reason.
send returns True when at least one target was reached. The interaction that it created is then available from get_last_sent_interaction().
The label comes back under the uuid of the interaction on the processor stream of the server. send returns only a boolean and get_last_sent_interaction() gives the client the interaction itself. At every tick answer_of looks for a sample with that uuid on the processor streams of the target that find_streams returns. The built-in action on_received scans only the streams of the world network and would never see it. The client reads the label in the tick after the label arrives and does not rely on the callback for it. The callback only reports the reason of a request that did not end well:
interaction.completion_reason |
When |
|---|---|
CompletionReason.OK |
the receiver ran the action and reported it as completed |
CompletionReason.TIMEOUT |
no answer within the timeout of the interaction (300 seconds at most) |
CompletionReason.REJECTED |
the receiver had no room left for one more interaction |
CompletionReason.DISCONNECTED |
the receiver left before completing it |
Run it¶
Wait until the server prints that it is running, then in a second terminal:
The first run downloads the ResNet-50 weights (about 100 MB) into the torchvision cache. Both nodes ask for your account key the first time (Installation).
From the browser
While server.py runs, open unaiverse.io, find ResNetAgent among your nodes and connect to it. The chat of the webapp accepts a picture and shows the label that the server sends back.