Skip to content

Data streams

Agents exchange data as samples on streams. A stream has a name, a type of data and optionally a shape, labels and a pace. The processor of an agent reads its inputs from input streams and writes its outputs on output streams. Another agent that knows these streams can send samples to the input streams and read samples from the output streams.

There are two layers. A StreamType (or the DataProps inside it) describes the data. A Stream holds samples and belongs to an agent. You write StreamType objects in proc_inputs and proc_outputs and the agent creates the matching streams for you (see Agents). You create Stream objects directly only for data that does not come from a processor (a sensor, a dataset, a signal).

StreamType

from unaiverse.streams.dataprops import StreamType

StreamType("text")                                   # short form, any text
StreamType(data_type="img", stream_to_proc_transforms=to_tensor)
StreamType(data_type="tensor", tensor_shape=(None, 3, None, None), tensor_dtype="torch.float32")

StreamType(*args, private_only=False, **kwargs) builds one DataProps for the world network and one for the public network from the same arguments. With private_only=True it builds only the one for the world network and the processor of the agent becomes unreachable from the public network on that input or output. A single positional argument is the data type. Passing public raises ValueError because StreamType assigns that flag to each DataProps itself. A plain string in proc_inputs or proc_outputs ("img") is the same as StreamType("img").

Argument Type Default Meaning
name str "unk" The name of the stream. Unnamed processor streams become proc_input_<j> and proc_output_<j>.
group str "none" A group that collects related streams (for example the image and the label of a dataset).
data_type str "text" One of tensor, img, text, file and all. Any other value fails an assertion.
data_desc str "unk" A free description.
tensor_shape tuple or None None The shape of tensor data. None in a position means any size. (None, 3, None, None) describes a batch of images of any size.
tensor_dtype torch.dtype, str or None None The dtype of tensor data as an object or as a string like "torch.float32".
tensor_labels list of str, str or None None A name for each component of a flat tensor (the classes of a classifier). The string "AutoTokenizer:<model id>" takes the vocabulary of that tokenizer.
tensor_labeling_rule str "max" How a tensor becomes a label: "max" takes the largest component and "geq<x>" (for example "geq0.5") takes every component at least equal to x.
stream_to_proc_transforms callable, tokenizer, str, dict, list or None None The conversion from a stream sample to a processor input (see Transforms).
proc_to_stream_transforms callable, tokenizer, str, list or None None The conversion from a processor output to a stream sample.
delta float -1 The minimum time in seconds between two samples. A value of zero or less means real time with no pacing.
pubsub bool False Broadcast the stream to every subscriber instead of sending it to one peer at a time.

Data types

data_type A sample is Typical use
tensor a torch.Tensor Features, predictions and embeddings.
img a PIL.Image.Image Pictures from a camera, a dataset or a person.
text a str Messages, labels and answers of a language model. Interactive messages travel as text too (see Interactive messages).
file a FileContainer Documents and other files of any size (see Files).
all any of the above An input that accepts anything. It suits an agent that ignores or inspects what it gets.

The agent checks every input against its StreamType before it runs the processor and refuses a tensor with the wrong shape or dtype and a sample of the wrong type.

Transforms

A stream carries data in a form that can be sent over the network (an image, a string). A processor works on tensors. The transforms convert between the two.

stream_to_proc_transforms accepts:

  1. A callable such as a torchvision pipeline or a lambda.
  2. A Hugging Face tokenizer or the string "AutoTokenizer:<model id>" that downloads one.
  3. A dict that maps strings to integers (a vocabulary).
  4. A list of two of the above. The first converts the inputs and the second the targets of learning.

proc_to_stream_transforms accepts a callable, a tokenizer, the same "AutoTokenizer:..." string or a vocabulary from integers to strings. A typical one turns the scores of a classifier into the name of a class:

StreamType(data_type="text", proc_to_stream_transforms=lambda p: labels[p.argmax(1)[0]])

transforms_factory(name) in unaiverse.modules.utils returns ready-made image pipelines:

Name Pipeline
"rgb<N>", "gray<N>" Resize and center-crop to N pixels and normalize. "rgb224" fits most ImageNet models.
"rgb-no_norm<N>", "gray-no_norm<N>" Resize and center-crop to N pixels without normalization.
"rgb", "gray" The full image, normalized.
"rgb-no_norm", "gray-no_norm" The full image without normalization.
"gray_mnist" The 28 by 28 grayscale pipeline of MNIST.

With add_batch_dim=True (the default) the last step of the pipeline adds a batch dimension in front. With return_inverse=True the function returns the inverse pipeline that turns a tensor back into an image in place of the forward one. An unknown name raises ValueError.

Streams

A Stream (unaiverse.streams.streams) holds the samples of one DataProps. Each sample belongs to an interaction (see Interactions) and the stream identifies that interaction by its uuid. The samples of the requests that an agent serves therefore never mix with each other.

Method Meaning
set(data, data_tag=-1, keep_existing_tag=False, uuid=None, force=False) Stores a sample for the interaction uuid and returns it wrapped in a Data object. It returns None when the stream is disabled (unless force=True) or when less than delta seconds have passed since the previous sample.
get(requested_by=None, uuid=None) Returns the last sample of the interaction uuid or None. A caller that gives its name in requested_by receives each sample at most once.
get_tag(uuid=None), set_tag(data_tag, uuid=None) Read and write the integer time tag of the sample.
get_timestamp(uuid=None) The time at which the sample was stored.
enable(), disable() A disabled stream ignores new samples.
clear_data(uuid=None) Drops the samples of one interaction.

Stream.create(stream, name=None, group="none", public=True, pubsub=True, delta=-1) prepares a stream that the agent offers to others. It gives the stream a name and a group (name@group when both are given) and paces it with delta. public places it on the public or on the world network and pubsub decides whether it is broadcast. You then add it with agent.add_stream(stream) or agent.add_streams([...]):

from unaiverse.streams.streams import Stream
from unaiverse.streams.streamlib import Sin

agent.add_streams([Stream.create(Sin(...), name="temperature", public=True, pubsub=True, delta=1.0)])

Ready-made streams

BufferedStream keeps its samples in a buffer and plays them in order. Several classes build on it.

Class Module Produces
Dataset(tensor_dataset, shape, index=0, batch_size=1) streams.streams One element (chosen by index) of each item of a PyTorch dataset in batches of batch_size.
ImageFileStream(image_dir, list_of_image_files, ...) streams.streams Images listed in a text file (one name per line) or in a list.
LabelStream(label_dir, label_file_csv, ...) streams.streams The labels that go with an ImageFileStream.
StringStream(strings, circular=True) streams.streams A list of strings that restarts from the first one when circular is True.
TokensStream(tokens_file_csv, circular=True, max_tokens=-1) streams.streams Tokens read from a CSV file.
Random, Sin, Square, CombSin streams.streamlib Synthetic signals for tests and demos.
SmoothHFHA, SmoothHFLA, SmoothLFLA, SmoothLFHA, SquareHFHA, SquareHFLA, SquareLFHA, SquareLFLA streams.streamlib Presets of the signals above with high or low frequency and amplitude.
AllHotLabelStream streams.streamlib A label stream whose labels are all active.

Stream names on the network

Each stream has two identifiers. The user hash <peer id>:<name> names it from the point of view of its owner. The net hash names the channel on which it travels: <peer id>::dm:<name or group> for a stream sent to one peer at a time and <peer id>::ps:<name or group> for a broadcast stream. You rarely write these by hand. Methods that take a stream reference also accept the plain name or the group and resolve it.

Finding streams

Method of the agent Returns
get_stream(name_or_group, peer_id=None, data_type=None) One stream or None.
get_streams(group_name, peer_id=None) The streams of a group.
find_streams(peer_id, name_or_group=None, discard_owned=False) A dictionary from net hash to a dictionary of streams of that peer. find_streams(peer, "processor") returns the processor streams of the peer that hold its answers (see Interactions).
known_streams, owned_streams Dictionaries by net hash of every stream the agent knows and of the ones it owns.

Processor proxies

Inside actions the agent reads and writes its processor streams through four proxies: stdin (the inputs of the processor), stdtar (the targets for learning), stdout (the outputs of the processor) and stdext (the streams that come from the environment, such as a camera). The agent binds each proxy to the public or the world streams before running the matching behavior (see Agents). The methods of a proxy select a stream by its name or by its position. Without a key get returns the list of the samples of all its streams.

Files

A sample of type file is a FileContainer(content=None, filename="file", mime_type="application/octet-stream", path=None) from unaiverse.streams.dataprops. It holds either the bytes of the file or the path of a file on disk. A container with neither of the two raises ValueError. FileContainer.from_path(path) builds one from a file and guesses its MIME type. A container with a path travels straight from the disk to a peer that accepts file messages without ever being loaded in memory. The receiver gets it as a container with a path in ~/.unaiverse/Downloads/ (see Networking).