unaiverse.streams.dataprops¶
A stream carries samples of one kind: text, images, tensors or files. Before a sample reaches a processor the node must know what to expect, how to turn the sample into a tensor and how to turn the output of the processor back into a sample that can be sent over the network. This module holds that description. A developer writes it when declaring the inputs and outputs of a processor (proc_inputs and proc_outputs of an agent) or when building a stream by hand. The node reads it to check every sample, to convert it and to name the stream on the network. The narrative guide is Data streams.
| Object | Role |
|---|---|
StreamType |
What a developer writes in proc_inputs and proc_outputs. It builds one DataProps for the world network and one for the public network from the same arguments. |
DataProps |
The description of the data of one stream: type, shape, dtype, labels, transforms, pace (delta), broadcast (pubsub) and network (public). Every Stream owns one in stream.props. |
TensorLabels |
The names of the components of a flat tensor and the rule that turns a tensor into one or more of these names. A DataProps creates it from tensor_labels. |
FileContainer |
A sample of a stream of type file. It holds the bytes of a file or the path of a file on disk together with its name and MIME type. |
StreamType takes the arguments of DataProps except public. A typical classifier reads images and writes the name of a class. Its declaration is the following:
import torch
from unaiverse.modules.utils import transforms_factory
from unaiverse.streams.dataprops import StreamType
classes = ["cat", "dog", "horse"]
proc_inputs = [StreamType(data_type="img", stream_to_proc_transforms=transforms_factory("rgb224"))]
proc_outputs = [StreamType(data_type="tensor", tensor_shape=(1, 3), tensor_dtype=torch.float32,
tensor_labels=classes)]
With these declarations the node accepts a PIL.Image.Image on the input stream, converts it to a (1, 3, 224, 224) float tensor for the processor and checks that the processor returns a (1, 3) float tensor. DataProps.to_text then reads such an output as the label with the largest score ("dog" for instance).
All the checks of this module are assert statements. A wrong argument raises AssertionError with a short message and Python skips every check when it runs with -O.
FileContainer
¶
FileContainer(content: bytes | str | None = None, filename: str = 'file', mime_type: str = 'application/octet-stream', path: str | None = None)
Source code in unaiverse/streams/dataprops.py
A sample of a stream of type file. The class exists to tell a file apart from a generic bytes or str sample. A container is backed either by its content (bytes or a string held in memory) or by a path on disk. A path-backed container reads the file only at the first access to its content property. Because the node sends such a container straight from the disk to a peer that accepts file messages, a file of any size never has to fit in memory. A received file arrives as a path-backed container that points into ~/.unaiverse/Downloads/ (see Networking).
| Argument | Type | Default | Meaning |
|---|---|---|---|
content |
bytes, str or None |
None |
The content of the file. None builds a path-backed container. |
filename |
str |
"file" |
The name of the file that the receiver sees. |
mime_type |
str |
"application/octet-stream" |
The MIME type of the content. |
path |
str or None |
None |
The file on disk of a path-backed container. |
The constructor raises ValueError("A FileContainer needs its content or its path") when both content and path are None. When both are given, content returns the content in memory and the path is only kept as an attribute.
Two containers compare equal (==) when their filename, mime_type and content are equal. The comparison therefore reads a path-backed file from disk. repr never prints the bytes:
>>> FileContainer(content=b"abc", filename="a.bin")
FileContainer(filename='a.bin', mime_type='application/octet-stream', 3 bytes)
from_path
classmethod
¶
from_path(file_path: str) -> FileContainer
Source code in unaiverse/streams/dataprops.py
Builds a path-backed container for the file at file_path without reading it. The filename is the base name of the path, the MIME type is guessed from the extension with mimetypes.guess_type ("application/octet-stream" when the extension is unknown) and the stored path is absolute. It raises FileNotFoundError when file_path is not an existing file.
>>> f = FileContainer.from_path("report.csv")
>>> f
FileContainer(filename='report.csv', mime_type='text/csv', path='/home/me/report.csv')
>>> f.has_content
False
The content of the file (bytes or str). On a path-backed container the first read opens the file in binary mode and keeps its bytes in memory. Later reads do not touch the disk and has_content becomes True. Assigning a new value replaces the content in memory and leaves path untouched.
True when the content is in memory. It is always True for a container built with content and False for a path-backed one until content is read.
The size of the file in bytes (int). A path-backed container that has not loaded its content takes the size from the file system without reading the file. A str content is measured on its UTF-8 encoding.
StreamType
¶
Source code in unaiverse/streams/dataprops.py
The object that a developer writes in proc_inputs and proc_outputs. An agent offers each processor stream twice: once on the private network of the world it joins and once on the public network. StreamType therefore builds two DataProps from the same arguments and keeps them in the list props. props[0] has public=False and props[1] has public=True.
| Argument | Type | Default | Meaning |
|---|---|---|---|
*args |
any | Positional arguments of DataProps. A single positional argument with no keyword argument is the data type (StreamType("text") is StreamType(data_type="text")). |
|
private_only |
bool |
False |
Keyword only. True builds only the private DataProps and makes the processor unreachable from the public network through this input or output. |
**kwargs |
any | Keyword arguments of DataProps (see the table of DataProps). |
Passing public raises ValueError("Invalid argument was provided to Stream: 'public' (it is an argument of DataProps)") because StreamType chooses that value itself. A plain string in proc_inputs or proc_outputs ("img") is read by the agent as StreamType("img").
StreamType forwards the access to every other attribute to its descriptions in two ways:
- A name that starts with
set_returns a function that calls that setter on everyDataPropsof the list.st.set_name("feat")therefore renames both descriptions. - Any other name is read from
props[0].st.data_type,st.is_text()andst.tensor_shapereturn the values of the private description.
>>> st = StreamType(data_type="tensor", tensor_shape=(1, 3), tensor_dtype="torch.float32")
>>> [p.public for p in st.props]
[False, True]
>>> st.set_name("features")
>>> [p.name for p in st.props]
['features', 'features']
>>> st.is_tensor()
True
str(st) lists the number of descriptions and the dictionary of each one.
to_list_of_dicts
¶
Source code in unaiverse/streams/dataprops.py
Returns the list [p.to_dict() for p in props] with one dictionary per description in the order of props (see DataProps.to_dict).
to_dict
¶
Source code in unaiverse/streams/dataprops.py
Always raises RuntimeError("This method can only be called on a DataProps object and not on Stream"). A StreamType holds up to two descriptions and has no single dictionary. Use to_list_of_dicts or call to_dict on one element of props.
from_dict
¶
Source code in unaiverse/streams/dataprops.py
Always raises RuntimeError with the same message as to_dict. Rebuild a description with DataProps.from_dict.
Returns a new StreamType whose props holds a clone of each description. The clones keep the transforms as they were given (an "AutoTokenizer:..." string is resolved again).
is_public
¶
Source code in unaiverse/streams/dataprops.py
Always raises RuntimeError with the same message as to_dict. The two descriptions give different answers because one is private and the other public. Ask props[0].is_public() or props[1].is_public().
DataProps
¶
DataProps(name: str = 'unk', group: str = 'none', data_type: str = 'text', data_desc: str = 'unk', tensor_shape: tuple[int | None, ...] | None = None, tensor_labels: list[str] | str | None = None, tensor_dtype: dtype | str | None = None, tensor_labeling_rule: str = 'max', stream_to_proc_transforms: Callable[..., Any] | PreTrainedTokenizerBase | str | dict | tuple[dict | Callable[..., Any] | PreTrainedTokenizerBase | str | None, dict | Callable[..., Any] | PreTrainedTokenizerBase | str | None] | list | None = None, proc_to_stream_transforms: Callable[..., Any] | PreTrainedTokenizerBase | str | list | None = None, delta: float = -1, pubsub: bool = False, public: bool = False)
Source code in unaiverse/streams/dataprops.py
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 | |
The description of the data of one stream. Every Stream holds one in stream.props and every StreamType holds one or two. The node uses it in four places: (1) it checks each sample that enters a processor with check_and_preprocess and each output with check_and_postprocess, (2) it converts samples with the transforms, (3) it names the stream on the network with net_hash and user_hash and (4) it publishes to_dict() in the profile of the node so that other agents can tell whether their streams are compatible (see is_compatible).
| Argument | Type | Default | Meaning |
|---|---|---|---|
name |
str |
"unk" |
The name of the stream. It must not contain ~. The agent renames unnamed processor streams proc_input_<j> and proc_output_<j>. |
group |
str |
"none" |
A group that collects related streams, for example the image and the label of one dataset. It must not contain ~. "none" means no group. When a group is present the network channel is named after the group (see name_or_group). |
data_type |
str |
"text" |
One of the values of VALID_DATA_TYPES: "tensor", "img", "text", "file" or "all". Any other value fails with AssertionError("Invalid data type"). |
data_desc |
str |
"unk" |
A free description. A value that is not a str fails an assertion. |
tensor_shape |
tuple[int \| None, ...], a list of the same entries or None |
None |
Required for "tensor" and forbidden for the other types. Each entry is an int or None. A None entry accepts any size in that position. The first entry is the batch dimension. (1, 10) is one vector of 10 features and (None, 3, None, None) is a batch of RGB images of any size. A list is stored as a tuple. |
tensor_dtype |
torch.dtype, str or None |
None |
Required for "tensor" and forbidden for the other types. A string must start with "torch." and name one attribute of torch, for example "torch.float32" or "torch.long". The string is converted to the matching dtype object. |
tensor_labels |
list[str], str or None |
None |
Only for "tensor". A list names each component of a flat tensor (the classes of a classifier for instance) and requires a shape of two entries (batch and features). The string "AutoTokenizer:<model id>" downloads that tokenizer and uses its vocabulary in id order as labels. Any other string fails an assertion. |
tensor_labeling_rule |
str |
"max" |
The rule that to_text uses to read a tensor as labels. "max" picks the component with the largest value and "geq<x>" (for example "geq0.5") picks every component at least equal to x. It is read only when tensor_labels is a list. |
stream_to_proc_transforms |
callable, tokenizer, str, dict, list, tuple 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 (see Transforms). |
delta |
float |
-1 |
The minimum time in seconds between two accepted samples of the stream. A value of zero or less means no pacing. The check is done by Stream.set. |
pubsub |
bool |
False |
True broadcasts the stream on a channel that every subscriber reads. False sends it to one peer at a time. |
public |
bool |
False |
True serves the stream on the public network and False on the private network of the world. StreamType chooses this value itself. |
The constructor validates the arguments against the type:
"tensor"requires a shape and a dtype. The labels are a list or an"AutoTokenizer:..."string. A list needs a shape of length 2 (AssertionError("Data attribute labels can only be specified for 2d arrays (batch size + data features)"))."img","text"and"file"requiretensor_shape,tensor_labelsandtensor_dtypeto beNone."text"resolves every"AutoTokenizer:<model id>"transform into the tokenizer object when the description is built. Building the description therefore downloads the tokenizer."all"accepts any sample and checks nothing.
A shape or a label list that arrives as another iterable (for example an array in the profile of a peer that runs in the browser) is converted to a list before the checks.
>>> p = DataProps(name="temperature", data_type="tensor", tensor_shape=(1, 1), tensor_dtype="torch.float32",
... delta=1.0, pubsub=True)
>>> p.to_dict()
{'name': 'temperature', 'group': 'none', 'data_type': 'tensor', 'data_desc': 'unk', 'tensor_shape': (1, 1),
'tensor_dtype': 'torch.float32', 'tensor_labels': None, 'delta': 1.0, 'pubsub': True, 'public': False}
str(p) is str(p.to_dict()).
Transforms¶
A stream carries data in a form that can be sent over the network (a string, an image). A processor works on tensors. The two transform arguments convert between the two forms.
stream_to_proc_transforms turns a sample into a processor input. It accepts:
- A callable such as a torchvision pipeline or a lambda.
- A tokenizer of Hugging Face (
PreTrainedTokenizerBase) or the string"AutoTokenizer:<model id>"that downloads one (text streams only). - A
dictvocabulary fromstrtoint. - A
listortupleof exactly two of the above. The first converts the inputs and the second the targets of learning (targets=Trueincheck_and_preprocess).
A single transform t is stored as [t, t] and serves both inputs and targets. A list or tuple of another length fails with AssertionError("Expected a list with two sets of transforms (input, target)").
proc_to_stream_transforms turns a processor output into a sample. It accepts a callable, a tokenizer, the string "AutoTokenizer:<model id>" (resolved for text streams) or a list that maps ids to strings (a vocabulary). A dict fails the assertion although the assertion message lists it among the accepted types.
Three behaviors of the current version matter when choosing a transform:
- A
dictvocabulary looks up the whole sample string as one key."the cat"is not split into words. A string that is not a key gets the idlen(vocabulary). - The checks that refuse a tokenizer on
"img"and"file"streams never fire forstream_to_proc_transformsbecause the transform is already wrapped in the list[t, t]when they run.DataProps(data_type="img", stream_to_proc_transforms="AutoTokenizer:gpt2")is accepted and keeps the string. to_textcalls alistvocabulary of a text stream as a function and raisesTypeError: 'list' object is not callable.check_and_postprocesshandles the same list correctly.
Ready-made image pipelines come from transforms_factory in unaiverse.modules.utils. The function returns a torchvision.transforms.Compose:
| Name | Pipeline |
|---|---|
"rgb<N>", "gray<N>" |
Convert to RGB or to one gray channel, resize and center-crop to N pixels, convert to a float tensor in [0, 1] and normalize (ImageNet statistics for RGB, mean 0.45 and std 0.225 for gray). "rgb224" fits most ImageNet models. |
"rgb-no_norm<N>", "gray-no_norm<N>" |
Resize and center-crop to N pixels into a uint8 tensor in [0, 255] with no normalization. |
"rgb", "gray" |
The full image, normalized. |
"rgb-no_norm", "gray-no_norm" |
The full image as a uint8 tensor. |
"gray_mnist" |
One gray channel of 28 by 28 pixels normalized with the MNIST statistics (mean 0.1307 and std 0.3081). |
transforms_factory(trans_type, add_batch_dim=True, return_inverse=False) appends a step that adds the batch dimension when add_batch_dim is True. With it "rgb224" produces a (1, 3, 224, 224) tensor. With return_inverse=True it returns the inverse pipeline. That pipeline removes the batch dimension, undoes the normalization and returns a PIL.Image.Image. It is therefore the natural proc_to_stream_transforms of an image output. Although the docstring of the function says that an unknown name returns None, the function raises ValueError.
VALID_DATA_TYPES
class-attribute
instance-attribute
¶
The tuple ('tensor', 'img', 'text', 'file', 'all') of the accepted values of data_type. The samples of the five types are respectively a torch.Tensor, a PIL.Image.Image, a str, a FileContainer and any object. The docstring of the class mentions a type 'tensor_token_id' that does not exist.
to_dict
¶
Source code in unaiverse/streams/dataprops.py
Returns the description as a plain dictionary that can travel in the profile of a node. The keys are name, group, data_type, data_desc, tensor_shape (a tuple or None), tensor_dtype (a string such as "torch.float32" or None), tensor_labels (the dictionary of TensorLabels.to_dict or None), delta, pubsub and public. The transforms are not included because they are code and the profile carries only data.
from_dict
staticmethod
¶
from_dict(d_props: dict) -> DataProps
Source code in unaiverse/streams/dataprops.py
A static method that rebuilds a DataProps from the dictionary of to_dict. Every key of to_dict must be present (KeyError otherwise). The labels and the original labeling rule come from the nested tensor_labels dictionary. The result has no transforms. The node calls it on the stream descriptions found in the profile of another peer.
clone
¶
clone() -> DataProps
Source code in unaiverse/streams/dataprops.py
Returns a new DataProps with the same arguments. The labels are copied into a new list and the transforms are the ones originally given to the constructor (or to the set_*_transforms methods). A tokenizer string is therefore resolved again. The clone does not carry over the changes made by interleave_with. It gets the current label list and no indices.
get_name
¶
Returns name (str).
get_group
¶
Returns group (str). "none" means that the stream belongs to no group.
get_description
¶
Returns data_desc (str).
get_tensor_labels
¶
Returns the list of labels of a tensor stream. It returns None when the stream has no labels.
set_name
¶
Source code in unaiverse/streams/dataprops.py
Replaces name. A name that contains ~ fails with AssertionError("Invalid chars in stream name"). The character ~ is reserved for the net hashes of direct channels (see normalize_net_hash).
set_group
¶
Source code in unaiverse/streams/dataprops.py
Replaces group. A group that contains ~ fails with AssertionError("Invalid chars in group name").
set_description
¶
Replaces data_desc with desc. The value is not checked.
set_public
¶
Replaces public with the given bool. It changes only the description and a stream that the node already serves keeps its channel.
set_pubsub
¶
Replaces pubsub with the given bool. As with set_public, a stream that the node already serves keeps its channel.
set_delta
¶
Replaces delta, the minimum time in seconds between two accepted samples. A value of zero or less disables the pacing.
set_stream_to_proc_transforms
¶
Replaces stream_to_proc_transforms with t and remembers t for clone. Unlike the constructor, it validates nothing, does not wrap a single transform into [t, t] and does not resolve an "AutoTokenizer:..." string. Pass a list of two transforms because check_and_preprocess indexes the stored value with 0 or 1. The image models of unaiverse.modules.networks call it on their descriptions with pipelines such as transforms_factory("gray_mnist").
set_proc_to_stream_transforms
¶
Replaces proc_to_stream_transforms with t and remembers t for clone. Nothing is validated or resolved.
is_tensor
¶
True when data_type is "tensor".
is_img
¶
True when data_type is "img".
is_text
¶
True when data_type is "text".
is_file
¶
True when data_type is "file".
is_tensor_long
¶
Source code in unaiverse/streams/dataprops.py
True when tensor_dtype is torch.long (torch.int64). False for a stream without a dtype.
is_tensor_float
¶
Source code in unaiverse/streams/dataprops.py
True when the string of tensor_dtype starts with "torch.float" (torch.float16, torch.float32, torch.float64). torch.half prints as torch.float16 and counts as float. torch.bfloat16 does not.
is_tensor_img
¶
Source code in unaiverse/streams/dataprops.py
True when the shape has four entries and the second (the channels) is 1 or 3 as in (1, 3, 224, 224). The dtype is not checked.
is_tensor_token_ids
¶
Source code in unaiverse/streams/dataprops.py
True for a sequence of token ids. The dtype must be torch.long and the shape must have two entries whose second is None or at least 1 (for example (1, None)). to_text then reads each id as a label.
is_tensor_target_id
¶
Source code in unaiverse/streams/dataprops.py
True for a batch of class ids used as targets. The dtype must be torch.long and the shape must have one entry (for example (None,)).
is_all
¶
True when data_type is "all". This type accepts any sample.
net_hash
¶
Source code in unaiverse/streams/dataprops.py
Returns the net hash of the stream for the peer id prefix. The net hash is the name of the network channel that carries the samples of the stream. It is "<prefix>::ps:<name or group>" for a broadcast stream and "<prefix>::dm:<name or group>" for a stream sent to one peer at a time. The last part comes from name_or_group. Streams of one group therefore share one channel.
user_hash
¶
Source code in unaiverse/streams/dataprops.py
Returns the user hash "<prefix>:<name>". It names the stream on the side of its owner and is unique per stream even inside a group. DataProps(name="x").user_hash("PEER") is 'PEER:x'.
peer_id_from_net_hash
staticmethod
¶
Source code in unaiverse/streams/dataprops.py
A static method that returns the part of a net hash before the first :: (the peer id). "PEER::ps:cams" gives "PEER".
peer_id_from_user_hash
staticmethod
¶
Source code in unaiverse/streams/dataprops.py
A static method that returns the part of a user hash before the last : (the peer id). "PEER:front@cams" gives "PEER".
name_or_group_from_net_hash
staticmethod
¶
Source code in unaiverse/streams/dataprops.py
A static method that returns the part of a net hash after ::ps: or ::dm:. "PEER::ps:cams" gives "cams". A string without either marker raises IndexError.
name_from_user_hash
staticmethod
¶
Source code in unaiverse/streams/dataprops.py
A static method that returns the part of a user hash after the last : (the stream name). "PEER:front@cams" gives "front@cams".
is_pubsub_from_net_hash
staticmethod
¶
Source code in unaiverse/streams/dataprops.py
A static method that returns True when the net hash contains ::ps: (the mark of a broadcast channel).
name_or_group
¶
Source code in unaiverse/streams/dataprops.py
Returns the group when it is not "none" and the name otherwise. This is the last part of the net hash.
build_net_hash
staticmethod
¶
Source code in unaiverse/streams/dataprops.py
A static method that builds "<prefix>::ps:<name_or_group>" when pubsub is True and "<prefix>::dm:<name_or_group>" otherwise. net_hash calls it.
build_user_hash
staticmethod
¶
Source code in unaiverse/streams/dataprops.py
A static method that builds "<prefix>:<name>". user_hash calls it.
user_hash_from_net_hash
staticmethod
¶
Source code in unaiverse/streams/dataprops.py
A static method that combines the peer id of net_hash with name into a user hash. ("PEER::ps:cams", "front@cams") gives "PEER:front@cams".
normalize_net_hash
staticmethod
¶
Source code in unaiverse/streams/dataprops.py
A static method that the node applies to the net hashes of direct channels. The last part of such a hash can start with a prefix added by the connection. A broadcast hash is returned unchanged. For a direct hash that contains ~ the method keeps what follows the ~. Otherwise it keeps the part of the name after the first -:
>>> DataProps.normalize_net_hash("PEER::dm:abc~feat")
'PEER::dm:feat'
>>> DataProps.normalize_net_hash("PEER::dm:abc-feat")
'PEER::dm:feat'
The second form keeps only the text between the first and the second -. "PEER::dm:abc-my-feat" therefore gives "PEER::dm:my". A direct hash with neither ~ nor - raises IndexError.
is_pubsub
¶
Returns pubsub.
is_public
¶
Returns public.
set_tensor_labels_from_auto_tokenizer
¶
Source code in unaiverse/streams/dataprops.py
Downloads the tokenizer model_id with AutoTokenizer.from_pretrained and replaces the labels with its vocabulary in id order (label i is the token with id i). The labeling rule becomes "max". The constructor calls it for tensor_labels="AutoTokenizer:<model id>" and ignores tensor_labeling_rule in that case. The stream must be a tensor stream with a shape of two entries.
set_tensor_labels
¶
Source code in unaiverse/streams/dataprops.py
Replaces the labels with a new TensorLabels built from labels (list[str] or None) and labeling_rule ("max" by default). The checks of TensorLabels apply. The stream must be a tensor stream and a non-empty list needs a shape of two entries.
adapt_tensor_to_tensor_labels
¶
Source code in unaiverse/streams/dataprops.py
Expands a tensor to a larger label set after TensorLabels.interleave_with has mapped the labels of this stream into a superset. When the stream is a tensor stream with labels and indices and the second dimension of data is smaller than the number of labels, the method returns a zero tensor of shape (batch, number of labels) and copies the columns of data into the columns given by the indices. In every other case it returns data unchanged. Stream.set calls it on every sample.
>>> p = DataProps(data_type="tensor", tensor_shape=(1, 2), tensor_dtype=torch.float32, tensor_labels=["b", "a"])
>>> p.tensor_labels.interleave_with(["a", "c", "b"])
>>> p.adapt_tensor_to_tensor_labels(torch.tensor([[0.3, 0.7]]))
tensor([[0.7000, 0.0000, 0.3000]])
clear_label_adaptation
¶
Source code in unaiverse/streams/dataprops.py
The inverse of adapt_tensor_to_tensor_labels. It returns data[:, indices] when the labels carry indices and data otherwise. On the example above it gives back tensor([[0.3000, 0.7000]]).
is_flat_tensor_with_labels
¶
Source code in unaiverse/streams/dataprops.py
True for a tensor stream with a shape of two entries and at least one label. A stream of token ids with labels counts too (a (1, None) shape with a vocabulary). Stream.create and BufferedStream.set use it to decide whether a sample has a text form.
has_tensor_labels
¶
True when the description has a non-empty label set.
to_text
¶
Source code in unaiverse/streams/dataprops.py
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 | |
Returns a readable text for one sample. The logs, the text buffer of a BufferedStream and the agent (when it shows data to a person) use it.
| Argument | Type | Default | Meaning |
|---|---|---|---|
data |
torch.Tensor, PIL.Image.Image, str or None |
The sample. | |
ignore_raw_tensors |
bool |
False |
True returns None for a tensor stream without labels instead of printing the tensor. |
The result depends on the sample and on the stream:
- A
stris returned as it is andNonegivesNone. Any other object that is not a tensor gives'<non-tensor and non-text>'. - On a tensor stream without labels, the result is the shape, the dtype and the values truncated to 110 characters and ending with
...:'1x3 tensor (torch.float32)\n[[1. 2. 3.]]'. - On a tensor stream with labels the method reads only a two-dimensional tensor with one row and returns
Nonefor any other shape. Token ids are joined with spaces (tensor([[0, 1, 2]])with labels["the", "cat", "sat"]gives'the cat sat'). A float tensor with rule"max"gives the label of the largest value and with rule"geq<x>"the labels of the values at leastxjoined by", ". Other dtypes giveNone. - On a text stream the tensor is decoded with
proc_to_stream_transforms. A tokenizer decodes the first row and a callable is called on the tensor. Without a transform the result isNone. - Images and files give
None.
>>> p = DataProps(data_type="tensor", tensor_shape=(1, 3), tensor_dtype=torch.float32,
... tensor_labels=["a", "b", "c"], tensor_labeling_rule="geq0.5")
>>> p.to_text(torch.tensor([[0.7, 0.1, 0.6]]))
'a, c'
Two inputs raise errors in the current version. The rule "geq" without a number leaves the threshold at None and the comparison raises TypeError. A list vocabulary of a text stream is called as a function and raises TypeError (see Transforms).
check_and_preprocess
¶
check_and_preprocess(data: str | Image | Tensor | None, allow_class_ids: bool = False, targets: bool = False, device: device = device('cpu'))
Source code in unaiverse/streams/dataprops.py
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 | |
Checks a sample that is about to enter a processor and converts it into the form that the processor expects. The agent calls it on each input before running the processor.
| Argument | Type | Default | Meaning |
|---|---|---|---|
data |
str, PIL.Image.Image, torch.Tensor, FileContainer, bytes or None |
The sample. None is returned as it is. |
|
allow_class_ids |
bool |
False |
True accepts a one-dimensional torch.long tensor (class ids) on a tensor stream without any further check. |
targets |
bool |
False |
True uses the second transform of the pair (the one for targets). |
device |
torch.device |
torch.device("cpu") |
The device of the returned tensor. |
What happens by type:
- tensor: a non-tensor raises
ValueError. The dtype must equaltensor_dtypeand the shape must have the same length astensor_shapeand match every entry that is notNone(ValueError("Expected data with shape (None, 3), got torch.Size([5, 4])")). With labels the tensor must have two dimensions. Its second dimension must equal the number of labels unless the stream holds token ids. The tensor is moved todevice. - text: a non-string raises
ValueError. Without a transform the string is returned. A tokenizer returnsinput_idsof shape(1, length). Adictvocabulary returns the id of the whole string as atorch.longtensor of shape(1, 1)((1,)for targets) and gives an unknown string the idlen(vocabulary). A callable is called on the string and its result is moved todevice. - img: a non-image raises
ValueError. The transform, if any, is applied and its result moved todevice. Without a transform the image is returned. - file: a
FileContaineris returned, astris taken as a path and wrapped withFileContainer.from_path,bytesbecome a container named"raw_bytes"and an object withcontent,filenameandmime_typeattributes is accepted as it is. Anything else raisesValueError. - all: the sample is returned as it is.
>>> t = DataProps(data_type="text", stream_to_proc_transforms={"hi": 0, "yo": 1})
>>> t.check_and_preprocess("yo"), t.check_and_preprocess("zz"), t.check_and_preprocess("yo", targets=True)
(tensor([[1]]), tensor([[2]]), tensor([1]))
check_and_postprocess
¶
Source code in unaiverse/streams/dataprops.py
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 | |
Converts the output of a processor into a sample of the stream and checks it. The agent calls it on each output before writing it on the output stream. None is returned as it is.
- tensor: a non-tensor raises
ValueError. Any output transform is applied first. The result is moved to the CPU and checked like an input (dtype, shape, labels). - text: a
stris returned. A tensor (moved to the CPU) needs a transform (ValueErrorotherwise) and a batch of exactly one row (AssertionErrorotherwise). A tokenizer decodes the row. Alistvocabulary reads a non-longtensor as scores and returns the label of the largest one. It reads alongtensor as token ids joined with spaces. A callable is called on the tensor. - img: an image is returned. A tensor needs a transform that produces the image and raises
ValueErrorwithout one. - file: a
FileContaineror an object with its three attributes is returned and anything else raisesValueError. - all: the output is returned as it is.
>>> t = DataProps(data_type="text", proc_to_stream_transforms=["hi", "yo"])
>>> t.check_and_postprocess(torch.tensor([[1, 0]])), t.check_and_postprocess(torch.tensor([[0.1, 0.9]]))
('yo hi', 'yo')
is_compatible
¶
is_compatible(props_to_compare: DataProps) -> bool
Source code in unaiverse/streams/dataprops.py
Returns True when the samples described by props_to_compare fit this description. The agent uses it to match its streams with the streams of another peer. The rules are:
- The data types must be equal unless this description is
"all". The test is not symmetric:DataProps(data_type="all").is_compatible(img)isTrueandimg.is_compatible(all_props)isFalse. - For tensors both shapes must exist with the same length. Each pair of entries that are both not
Nonemust be equal. - When both tensor descriptions have labels, the labels must be equal in the same order (see
TensorLabels). A description without labels matches any labels.
The dtype is not compared. A (None, 3) float description is therefore compatible with a (2, 3) long one. Types other than tensors are compatible as soon as rule 1 passes.
TensorLabels
¶
TensorLabels(data_props: DataProps, labels: list[str] | None, labeling_rule: str = 'max')
Source code in unaiverse/streams/dataprops.py
The labels of a flat tensor stream. The class holds one name per component of the second dimension and the rule that reads a tensor as labels. A DataProps creates it from tensor_labels. A developer reads it through props.tensor_labels or props.get_tensor_labels().
| Argument | Type | Default | Meaning |
|---|---|---|---|
data_props |
DataProps |
The owner. It must be a tensor description with a shape. | |
labels |
list[str] or None |
The names, in component order. A non-empty list requires a shape of two entries. | |
labeling_rule |
str |
"max" |
"max" or "geq" followed by a number. The first three characters must be one of VALID_LABELING_RULES and what follows them is parsed as a float threshold (AssertionError("Invalid labeling rule") when it is not a number). |
The attributes are labels (the list), labeling_rule ("max" or "geq"), labeling_rule_thres (the float, or None), original_labeling_rule (the string as given), num_labels and indices (a torch.long tensor after interleave_with, None otherwise).
The threshold is everything after the first three characters. The docstrings write the rule as "geq-X". In the current version "geq-0.5" gives the threshold -0.5 and then every component is selected. Write "geq0.5". A number after "max" is parsed and never used.
The object behaves like a sequence. len(labels) is num_labels and iteration yields the labels (nothing when they are None). labels[i] returns one label and raises ValueError for an index outside 0 to num_labels - 1 or when there are no labels. labels[i] = "name" replaces one label, raises TypeError for a value that is not a str and clears indices. Two TensorLabels are equal (==) when they hold the same labels in the same order. The rules are not compared. str prints the labels, the rule and the indices.
The tuple ('max', 'geq') of the accepted rule prefixes.
to_dict
¶
Source code in unaiverse/streams/dataprops.py
Returns the dictionary {"labels": labels, "labeling_rule": original_labeling_rule} that DataProps.to_dict embeds.
clear_indices
¶
Source code in unaiverse/streams/dataprops.py
Clears indices (back to None). The labels remain the superset installed by interleave_with but the tensors are no longer expanded onto it.
interleave_with
¶
Source code in unaiverse/streams/dataprops.py
Maps the labels of this stream into superset_labels, a list that contains each of them. The agent uses it when it merges streams whose classes are a subset of a larger class list. Every current label must appear in the superset and the superset must be at least as long as the labels (AssertionError otherwise). When the superset holds the same labels in the same order the method only clears indices. Otherwise it replaces labels with the superset, stores in indices the position of each original label in it and widens the shape of the owner to (shape[0], len(superset_labels)). From then on DataProps.adapt_tensor_to_tensor_labels expands each sample onto the superset. A second call starts from the original labels recovered through the indices.