Skip to content

unaiverse.modules.utils

An agent runs every processor through a ModuleWrapper. The wrapper sits between the streams of the agent and the model: it converts each input sample into what the model reads (a PIL picture into a normalized tensor, a tensor onto the right device), calls the model, checks and converts each output back into a stream sample and runs the backward step when the agent learns. It also runs the model in a worker thread of its own so that the node keeps answering its peers during a long call (see Agents). When the agent is built, AgentProcessorChecker wraps the processor in a ModuleWrapper and fills in what the developer did not describe: the input and output streams and the learning options.

The module also holds HumanModule (the processor of a person), the image transforms used by the ready-made classifiers, a few helpers for training and testing and the local gateway that the FeatherlessAPI processors of one machine share (see networks).

import torch
from unaiverse.agent import Agent

net = torch.nn.Sequential(torch.nn.Linear(4, 16), torch.nn.ReLU(), torch.nn.Linear(16, 3))
agent = Agent(proc=net)              # The checker wraps net and guesses its streams
print(agent.proc_inputs[0].get_name(), agent.proc_outputs[0].get_name())   # proc_input_0 proc_output_0

Stream names

The streams of a processor whose StreamType has no name (the name "unk") are named after their position: proc_input_0, proc_input_1, ... for the inputs and proc_output_0, proc_output_1, ... for the outputs. AgentProcessorChecker gives these names. An interaction addresses the streams of a processor by these names (see Interactions). In data_samples={"proc_output_0": picture} the key names the first output stream of the requester.

Wrapping and checking

ModuleWrapper

ModuleWrapper(module: Module | Callable, proc_inputs: list[StreamType] | None = None, proc_outputs: list[StreamType] | None = None, proc_opts: dict | None = None, seed: int = -1, agent: object = None, device: str | device | None = None)

Bases: Module

Source code in unaiverse/modules/utils.py
def __init__(self,
             module: torch.nn.Module | Callable,
             proc_inputs: list[StreamType] | None = None,
             proc_outputs: list[StreamType] | None = None,
             proc_opts: dict | None = None,
             seed: int = -1,
             agent: object = None,
             device: str | torch.device | None = None) -> None:
    """Initializes the ModuleWrapper.

    Args:
        module: The torch.nn.Module or callable object to wrap (default: None).
        proc_inputs: List of Stream objects describing the input types (default: None).
        proc_outputs: List of Stream objects describing the output types (default: None).
        proc_opts: Dictionary with keys ``"optimizer"`` and ``"losses"`` (default: None).
        seed: Random seed to fix before instantiation; negative values are ignored (default: -1).
        agent: The agent who owns this processor.
        device: The device on which to run the processor (default: None).
    """
    super(ModuleWrapper, self).__init__()
    self.device = None
    self.module: Callable | None = None
    self.proc_inputs = None  # The list of Stream objects describing the input types of the module
    self.proc_outputs = None  # The list of Stream objects describing the output types of the module
    self.proc_opts = None
    self.proc_optional_inputs = []
    self.agent = None
    self._has_first = False
    self._has_last = False
    self._sig_defaults = []
    self._last_raw_outputs = None
    self._last_module_s = None  # Seconds the last module call blocked its thread (see runs_long)

    # Working
    set_seed(seed)

    self.guess_device(device)
    self.set_module(module)
    self.set_proc_inputs_and_outputs(proc_inputs, proc_outputs)
    self.set_proc_opts(proc_opts)
    self.set_agent(agent)

A torch.nn.Module that wraps a model and the description of its streams.

Argument Type Default Meaning
module torch.nn.Module or callable required The model. A torch.nn.Module moves to device. A plain callable stays as it is.
proc_inputs list[StreamType] or None None One descriptor per input of the model, in the order of its positional arguments.
proc_outputs list[StreamType] or None None One descriptor per output of the model, in the order of the returned tuple.
proc_opts dict or None None The learning options: {"optimizer": torch.optim.Optimizer, "losses": [loss, ...]} (see Learning over time).
seed int -1 A non-negative value seeds torch, random and numpy (see set_seed). The seeding happens after the model is built and before it moves to device.
agent object or None None The agent that owns the processor. With an agent the wrapper renders interactive messages for the model and checks the answers (see Interactive messages).
device str, torch.device or None None The device of the model and of the input tensors (see guess_device).

The wrapper accepts only StreamType objects in proc_inputs and proc_outputs. AgentProcessorChecker converts the strings such as "text" before the wrapper sees them.

Attribute Type Content
module torch.nn.Module or callable The wrapped model.
device torch.device The device of the model.
proc_inputs, proc_outputs list[StreamType] The descriptors of the streams.
proc_opts dict The learning options.
proc_optional_inputs list[dict] One entry per input, parallel to proc_inputs: {"has_default": bool, "default_value": ...} read from the signature of the model. The agent uses it to call the model when an optional input has no sample.
agent object The owner of the processor.

The model may declare the class attributes UAI_ECHOES_INPUT = True (it gives back its input, as HumanModule and MultiIdentity do) and UAI_OFFLOAD = False (it must run on the event loop). A subclass of the wrapper may declare UAI_OFFLOAD = False as well.

UAI_HARD_CAP class-attribute instance-attribute

UAI_HARD_CAP = 8

8. The maximum number of times that the answer check of an interactive message asks the model again within one call. A policy of the agent that allows more retries is capped at this value.

forward

forward(*args: Any, **kwargs: Any) -> tuple
Source code in unaiverse/modules/utils.py
def forward(self, *args: Any, **kwargs: Any) -> tuple:
    """Preprocesses inputs, runs the wrapped module, and post-processes the outputs.

    Args:
        *args: Positional inputs; each element is preprocessed via the corresponding ``proc_inputs`` Stream.
        **kwargs: Extra keyword arguments forwarded to the module.  The ``first`` and ``last``
            keys are silently removed before the call.

    Returns:
        A tuple of post-processed outputs, one per entry in ``proc_outputs``.
    """
    return _run_to_end(self.__forward(list(args), kwargs, offload=False))

Runs one call of the model synchronously and returns a tuple with one element per entry of proc_outputs. The steps are these:

  1. It drops the keyword arguments first and last when the signature of the model has no parameter with that name. The agent always passes both.
  2. When the wrapper has an agent and the model does not echo its input, every string input that contains an interactive block becomes the plain text of that block for the model.
  3. Each input args[i] goes through proc_inputs[i].check_and_preprocess(..., device=device). That method checks its type and shape and applies the stream-to-processor transform. Positional arguments beyond len(proc_inputs) are dropped. Fewer arguments raise IndexError.
  4. It calls the model. A result that is not a tuple becomes a tuple of one element. The raw result stays available to learn_backward.
  5. Each output outputs[i] goes through proc_outputs[i].check_and_postprocess(...). Outputs beyond len(proc_outputs) are dropped.
  6. When the wrapper has an agent, the answer check of interactive messages runs on the first text output. It may ask the model again (up to UAI_HARD_CAP times), replace the text or raise unaiverse.uai.AnswerWithheld when no answer may leave the agent.

A check that fails in step 3 or 5 raises ValueError or TypeError from the stream. The method raises AssertionError when module, proc_inputs or proc_outputs is None. An async model works only when it returns without waiting. A model that suspends makes the method raise RuntimeError("A coroutine run without an event loop suspended") and needs aforward instead.

aforward async

aforward(*args: Any, offload: bool = True, **kwargs: Any) -> tuple
Source code in unaiverse/modules/utils.py
async def aforward(self, *args: Any, offload: bool = True, **kwargs: Any) -> tuple:
    """forward(), with the module and its pre/postprocessing in the worker thread of this wrapper (async).

    What concerns the agent (the rendering of interactive blocks before the call, the answer gate after it) stays
    on the event loop; the module calls (the first one and every re-ask of the gate) run in the worker, one at a
    time. Inline instead, as forward(), in the browser, with Custom.OFFLOAD_ENABLED off, for modules that echo
    their input or say UAI_OFFLOAD = False, and when a subclass overrides forward().

    Args:
        *args: As for forward().
        offload: False to run on the event loop even where the worker would be used (the steps of a multistep
            interaction, which must take their samples one per tick). An async module is awaited either way.
        **kwargs: As for forward().

    Returns:
        As forward().
    """
    if type(self).forward is not ModuleWrapper.forward:
        return self.forward(*args, **kwargs)
    return await self.__forward(list(args), kwargs, offload=offload and self.__offloads())

The coroutine that the agent awaits in process and learn. It does what forward does with the same arguments and returns the same tuple. The calls of the model run in the worker thread of the wrapper. The rendering of interactive messages and the answer check stay on the event loop.

Argument Type Default Meaning
*args, **kwargs As for forward.
offload bool True False runs the model on the event loop. The agent passes False for the steps of a multi-step interaction unless runs_long() is True.

The calls run inline (on the event loop) also in these cases: NODE_OFFLOAD=0, the browser runtime (no threads), a model with UAI_ECHOES_INPUT = True or UAI_OFFLOAD = False and a wrapper with UAI_OFFLOAD = False. A subclass that overrides forward is called synchronously through its own forward. An async model is awaited on the event loop in every case.

Each wrapper owns one worker thread (ThreadPoolExecutor(max_workers=1), thread name unaiverse-proc). Two calls of the same wrapper therefore never overlap. On the other hand the wrappers of different agents run their models in parallel. The worker runs with the grad mode, the inference mode and the context variables of the caller.

runs_long

runs_long() -> bool
Source code in unaiverse/modules/utils.py
def runs_long(self) -> bool:
    """Tells whether the last call of the module was long, at least Custom.OFFLOAD_SLOW_S seconds of work on its
    thread (the wait of an async module is not counted: it blocks nothing).

    Returns:
        True when it was long; False when it was short, or before the first call.
    """
    return self._last_module_s is not None and self._last_module_s >= Custom.OFFLOAD_SLOW_S

Returns True when the last call took at least Custom.OFFLOAD_SLOW_S seconds (environment variable NODE_OFFLOAD_SLOW, default 0.5) on its thread. The time covers the preprocessing, the model call and the postprocessing. The wait of an async model is not counted. Before the first call the method returns False. The agent reads it to decide whether the steps of a multi-step interaction go to the worker thread.

learn_backward

learn_backward(targets: list | None = None) -> list
Source code in unaiverse/modules/utils.py
def learn_backward(self, targets: list | None = None) -> list:
    """Runs a supervised or unsupervised backward pass and optimizer step.

    Args:
        targets: Optional list of target tensors, one per processor output.  Individual
            entries may be ``None`` (treated as unsupervised for that slot).

    Returns:
        A list of per-output loss values if a backward pass was performed.
    """
    if (self.proc_opts is None or len(self.proc_opts) == 0 or
            ('losses' not in self.proc_opts and 'optimizer' not in self.proc_opts) or self.proc_outputs is None):
        return []

    loss_functions: list = self.proc_opts['losses']
    optimizer: torch.optim.optimizer.Optimizer = self.proc_opts['optimizer']

    # Evaluating loss function(s), one for each processor output slot (they are set to 0. if no targets are there)
    if targets is not None and len(targets) > 0 and any(x is not None for x in targets):

        # Preprocessing targets
        targets = [self.proc_outputs[i].check_and_preprocess(targets[i], device=self.device,
                                                             allow_class_ids=True, targets=True)
                   for i in range(0, len(self.proc_outputs))]

        # Supervised or partly supervised learning
        loss_values = [loss_fcn(self._last_raw_outputs[i], targets[i]) if targets[i] is not None else
                       torch.tensor(0., device=self.device)
                       for i, loss_fcn in enumerate(loss_functions)]
        loss = torch.stack(loss_values).sum()  # Sum of losses
    else:

        # Unsupervised learning
        loss_values = [loss_fcn(self._last_raw_outputs[i]) for i, loss_fcn in enumerate(loss_functions)]
        loss = torch.stack(loss_values).sum()  # Sum of losses

    # Learning step
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    # Teaching (for autoregressive models, expected to have attribute "y")
    if targets is not None and hasattr(self.module, 'y'):
        self.module.y = targets[0]

    return loss_values

Runs one optimization step on the outputs of the last call and returns the list of the loss tensors in the order of the outputs.

Argument Type Default Meaning
targets list or None None One target per output. None entries give a loss of zero for that output.

With at least one target, each target goes through proc_outputs[i].check_and_preprocess(..., allow_class_ids=True, targets=True) and the loss of output i is losses[i](raw_output[i], target[i]). Without targets the step is unsupervised and the loss is losses[i](raw_output[i]). The method sums the losses and runs optimizer.zero_grad(), loss.backward() and optimizer.step(). When targets are given and the model has an attribute y, the first target replaces module.y for the next step.

The method returns [] without learning when proc_opts is empty, has neither optimizer nor losses or when proc_outputs is None. An optimizer equal to None makes it raise AttributeError. A None loss raises TypeError when its output has a target or the step is unsupervised. Agent.learn checks the optimizer and the losses before it calls the method.

alearn_backward async

alearn_backward(targets: list | None = None, offload: bool = True) -> list
Source code in unaiverse/modules/utils.py
async def alearn_backward(self, targets: list | None = None, offload: bool = True) -> list:
    """learn_backward(), in the worker thread of this wrapper, after the forward pass it learns from (async).

    Inline in the same cases as aforward().

    Args:
        targets: As for learn_backward().
        offload: False to run on the event loop even where the worker would be used (as for aforward()).

    Returns:
        As learn_backward().
    """
    if type(self).learn_backward is not ModuleWrapper.learn_backward or not (offload and self.__offloads()):
        return self.learn_backward(targets)
    return await self.__in_worker(self.learn_backward, targets)

The coroutine that the agent awaits in learn. It runs learn_backward(targets) in the worker thread under the rules of aforward and returns its result. offload=False runs it inline. A subclass that overrides learn_backward is called inline.

guess_device

guess_device(device: str | device | None) -> None
Source code in unaiverse/modules/utils.py
def guess_device(self, device: str | torch.device | None) -> None:
    """Sets the device of the processor: the given one, else the PROC_DEVICE environment variable, else CPU.

    Args:
        device: The device to use, or None to guess it.
    """
    device_env = os.getenv("PROC_DEVICE", None)
    self.device = torch.device("cpu") if device_env is None else torch.device(device_env)

    # Override if it was given
    if device is not None:
        self.device = torch.device(device) if isinstance(device, str) else device

Stores the device of the wrapper in device: the argument when it is not None (a string becomes a torch.device), else the environment variable PROC_DEVICE, else cpu. It moves nothing. The constructor calls it before set_module moves the model.

set_agent

set_agent(agent: object) -> None
Source code in unaiverse/modules/utils.py
def set_agent(self, agent: object) -> None:
    """Sets the agent that owns this processor.

    Args:
        agent: The owning agent (or None).
    """
    self.agent = agent

Stores the owner of the processor. AgentProcessorChecker calls it.

set_proc_inputs_and_outputs

set_proc_inputs_and_outputs(proc_inputs: list[StreamType] | None, proc_outputs: list[StreamType] | None) -> None
Source code in unaiverse/modules/utils.py
def set_proc_inputs_and_outputs(self, proc_inputs: list[StreamType] | None,
                                proc_outputs: list[StreamType] | None) -> None:
    """Sets the descriptors of the inputs and of the outputs of the processor (None leaves them unchanged).

    Args:
        proc_inputs: The list of the input stream descriptors, or None.
        proc_outputs: The list of the output stream descriptors, or None.
    """
    if proc_inputs is not None:
        self.proc_inputs = proc_inputs
        self.__refresh_proc_optional_inputs()  # rebuilds, truncating or padding as needed
    if proc_outputs is not None:
        self.proc_outputs = proc_outputs

Replaces proc_inputs and proc_outputs. A None argument leaves that list unchanged. A new proc_inputs also rebuilds proc_optional_inputs with the same length. The inputs beyond the parameters of the model get no default.

set_proc_opts

set_proc_opts(proc_opts: dict | None) -> None
Source code in unaiverse/modules/utils.py
def set_proc_opts(self, proc_opts: dict | None) -> None:
    """Sets the learning options of the processor (None leaves them unchanged).

    Args:
        proc_opts: Dictionary with keys ``"optimizer"`` and ``"losses"``, or None.
    """
    if proc_opts is not None:
        self.proc_opts = proc_opts

Replaces proc_opts. None leaves it unchanged.

set_module

set_module(mod: Callable | Module) -> None
Source code in unaiverse/modules/utils.py
def set_module(self, mod: Callable | torch.nn.Module) -> None:
    """Sets the wrapped module, caching what its signature tells (first/last flags, defaults of the inputs).

    Args:
        mod: The torch.nn.Module or callable object to wrap.

    Raises:
        GenException: If the signature of the module cannot be guessed.
    """

    # Case 1: torch.nn.Module / object with .forward
    if hasattr(mod, "forward") and callable(getattr(mod, "forward")):
        sig = inspect.signature(mod.forward)
    elif callable(mod):
        sig = inspect.signature(mod)
    else:
        raise GenException("Invalid processor module, cannot guess the signature of the callable method, if any")

    self.module = mod.to(self.device) if isinstance(mod, torch.nn.Module) else mod
    self._has_first = "first" in sig.parameters  # B8: rename below
    self._has_last = "last" in sig.parameters

    # Cache the signature-derived defaults ONCE, excluding framework-handled kwargs and *args/**kwargs
    # catch-alls. This is the canonical per-positional-data-arg default list of the wrapped module's forward.
    framework_kwargs = {"first", "last"}
    self._sig_defaults: list[dict] = []
    for name, param in sig.parameters.items():
        if name in framework_kwargs:
            continue
        if param.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD):
            continue
        if param.default is not inspect.Parameter.empty:
            self._sig_defaults.append({"has_default": True, "default_value": param.default})
        else:
            self._sig_defaults.append({"has_default": False, "default_value": None})

    # Align proc_optional_inputs to current proc_inputs (if already known)
    self.__refresh_proc_optional_inputs()

Replaces the model. The method reads the signature of mod.forward (or of mod itself for a plain callable), notes whether it accepts first and last and records the default of each other parameter for proc_optional_inputs. A torch.nn.Module moves to device. An object that is not callable raises unaiverse.custom.GenException.

AgentProcessorChecker

AgentProcessorChecker(agent: object)
Source code in unaiverse/modules/utils.py
def __init__(self, agent: object) -> None:
    """Validates and normalizes processor attributes on the given container.

    Checks that ``processor_container`` exposes the required processor attributes, performs
    type validation, auto-wraps plain ``torch.nn.Module`` objects in ``ModuleWrapper``,
    and infers missing ``proc_inputs``, ``proc_outputs``, and ``proc_opts`` heuristically.
    The validated and completed values are written back onto ``processor_container``.

    Args:
        agent: Any object that exposes ``proc``, ``proc_inputs``,
            ``proc_outputs``, ``proc_opts``, and ``proc_optional_inputs`` attributes.
    """

    # Right now, the processor has its own attributes, but they are also directly referenced from the agent object.
    # In the future, we might drop the ones on the agent side.
    assert hasattr(agent, 'proc'), "Invalid processor container (agent) object"
    assert hasattr(agent, 'proc_inputs'), "Invalid processor container (agent) object"
    assert hasattr(agent, 'proc_outputs'), "Invalid processor container (agent) object"
    assert hasattr(agent, 'proc_opts'), "Invalid processor container (agent) object"
    assert hasattr(agent, 'proc_optional_inputs'), "Invalid processor container (agent) object"

    # Getting processor-related info from the main object which collects processor and its properties
    proc: torch.nn.Module | ModuleWrapper | Callable | None = agent.proc
    proc_inputs: list[StreamType] | list[str] | None = agent.proc_inputs
    proc_outputs: list[StreamType] | list[str] | None = agent.proc_outputs
    proc_opts: dict | None = agent.proc_opts

    # The agent itself could be a processor
    if proc is None and callable(agent):
        proc = agent

    if not (proc is None or isinstance_fcn(proc, torch.nn.Module) or isinstance_fcn(proc, ModuleWrapper) or
            callable(proc) or (isinstance(proc, str) and proc == "human")):
        raise GenException("Processor (proc) must be either None or a torch.nn.Module, "
                           "or a ModuleWrapper, or a callable object")
    if not ((proc_inputs is None or (
            isinstance_fcn(proc_inputs, list) and (len(proc_inputs) == 0 or
                                                   (len(proc_inputs) > 0 and
                                                    isinstance_fcn(proc_inputs[0],
                                                                   (StreamType, str))))))):
        raise GenException("Invalid proc_inputs: it must be None or a list of StreamType/str")
    if not ((proc_outputs is None or (
            isinstance_fcn(proc_outputs, list) and (len(proc_outputs) == 0 or
                                                    (len(proc_outputs) > 0 and
                                                     isinstance_fcn(proc_outputs[0],
                                                                    (StreamType, str))))))):
        raise GenException("Invalid proc_outputs: it must be None or a list of StreamType/str")
    if not (proc_opts is None or isinstance_fcn(proc_opts, dict)):
        raise GenException("Invalid proc_opts: it must be None or a dictionary")

    # From strings to StreamType (proc_inputs)
    if proc_inputs is not None:
        proc_inputs_copy = proc_inputs.copy()
        for i, p in enumerate(proc_inputs_copy):
            if isinstance(p, str):
                try:
                    proc_inputs_copy[i] = StreamType(data_type=p, pubsub=False, private_only=False)
                except Exception as e:
                    raise GenException(f"Invalid stream type {p}: {e}")
        proc_inputs = proc_inputs_copy

    # From strings to StreamType (proc_outputs)
    if proc_outputs is not None:
        proc_outputs_copy = proc_outputs.copy()
        for i, p in enumerate(proc_outputs_copy):
            if isinstance(p, str):
                try:
                    proc_outputs_copy[i] = StreamType(data_type=p, pubsub=False, private_only=False)
                except Exception as e:
                    raise GenException(f"Invalid stream type {p}: {e}")
        proc_outputs = proc_outputs_copy

    # From None to empty dictionary (proc_opts)
    if proc_opts is None:
        proc_opts = {}

    # Type checking
    if proc_inputs is not None:
        proc_inputs: list[StreamType]
    if proc_outputs is not None:
        proc_outputs: list[StreamType]

    # Dummy processor (if no processor was provided)
    if proc is None:
        if proc_inputs is None:
            proc_inputs: list[StreamType] = [StreamType(data_type="all", pubsub=False, private_only=False)]
        if proc_outputs is None:
            proc_outputs: list[StreamType] = [StreamType(data_type="all", pubsub=False, private_only=False)]
        assert proc_outputs is not None
        proc_opts = {'optimizer': None, 'losses': [None] * len(proc_outputs)}
        proc = ModuleWrapper(module=MultiIdentity(), proc_inputs=proc_inputs,
                             proc_outputs=proc_outputs, proc_opts=proc_opts,
                             agent=agent, device=torch.device("cpu"))
    else:

        if isinstance(proc, str) and proc.lower().strip() == "human":
            proc_inputs: list[StreamType] = [StreamType(data_type="text", pubsub=False, private_only=False),
                                             StreamType(data_type="img", pubsub=False, private_only=False)]
            proc_outputs: list[StreamType] = [StreamType(data_type="text", pubsub=False, private_only=False),
                                              StreamType(data_type="img", pubsub=False, private_only=False)]
            proc = ModuleWrapper(module=HumanModule(), proc_inputs=proc_inputs,
                                 proc_outputs=proc_outputs, agent=agent, device=torch.device("cpu"))

        # Creating a ModuleWrapper with the given processor
        elif not isinstance(proc, ModuleWrapper):
            proc: torch.Module | Callable
            proc = ModuleWrapper(module=proc, proc_opts=proc_opts, proc_inputs=proc_inputs,
                                 proc_outputs=proc_outputs, agent=agent, device=torch.device("cpu"))
        else:

            # If it is already a ModuleWrapper, we force the reference to the agent and the references to the
            # types of inputs and outputs: actually, the inputs/outpus/opts might have been already defined by the
            # wrapper creator, but we give priority to the user options
            proc.set_proc_inputs_and_outputs(proc_inputs, proc_outputs)
            proc.set_proc_opts(proc_opts)
            proc.set_agent(agent)

    # From here after, the proc is not None, and it is a ModuleWrapper.
    # However, proc_inputs, proc_outputs, and proc_opts might still not be specified
    assert proc is not None
    assert isinstance(proc, ModuleWrapper)

    # Guessing inputs, fixing attributes
    AgentProcessorChecker.__guess_proc_inputs(proc)
    if proc.proc_inputs is None:
        raise GenException("The inputs of the processor were not described and cannot be automatically guessed")

    # Fixing naming conventions
    AgentProcessorChecker.__fix_proc_inputs(proc)

    # Guessing outputs, fixing attributes
    AgentProcessorChecker.__guess_proc_outputs(proc)
    if proc.proc_outputs is None:
        raise GenException("The outputs of the processor were not described and cannot be automatically guessed")

    # Fixing naming conventions (should not be needed)
    AgentProcessorChecker.__fix_proc_outputs(proc)

    # Guessing optimization-related options and stuff, fixing attributes
    AgentProcessorChecker.__guess_proc_opts(proc)

    # Fixing attribute-presence conventions
    AgentProcessorChecker.__fix_proc_opts(proc)

    # Ensuring all is OK
    assert proc.proc_inputs is not None
    assert proc.proc_outputs is not None
    assert proc.proc_opts is not None
    assert proc.proc_optional_inputs is not None

    # Updating processor container object (agent)
    agent.proc = proc
    agent.proc_inputs = proc.proc_inputs
    agent.proc_outputs = proc.proc_outputs
    agent.proc_opts = proc.proc_opts
    agent.proc_optional_inputs = proc.proc_optional_inputs

Checks and completes the processor of an agent. The constructor does all the work and writes the result back to the agent. AgentBasics.__init__ calls it once per agent. The argument is any object with the attributes proc, proc_inputs, proc_outputs, proc_opts and proc_optional_inputs. An object without them raises AssertionError. The steps are these:

  1. A proc that is None on a callable agent becomes the agent itself.
  2. proc must be None, a torch.nn.Module, a callable or the string "human". proc_inputs and proc_outputs must be None or lists of StreamType or str. proc_opts must be None or a dict. A violation raises GenException.
  3. Each string in proc_inputs and proc_outputs becomes StreamType(data_type=s). An unknown type raises GenException.
  4. The processor becomes a ModuleWrapper on the CPU:

    proc Result
    None MultiIdentity with one input and one output of type "all" unless the lists are given.
    "human" HumanModule with the inputs and outputs text and img. The given lists are ignored.
    a ModuleWrapper Kept. The given lists and options replace its own and the agent becomes its owner.
    anything else A new ModuleWrapper around it with device=torch.device("cpu"). PROC_DEVICE does not apply.
  5. Without proc_inputs the checker guesses one input from the first Conv2d, Linear, Conv1d or Embedding layer of the module (table below). A module without such a layer is guessed from the annotation of the first data parameter of its forward: str gives text and PIL.Image.Image gives img. A module that cannot be guessed raises ValueError and a callable that cannot be guessed raises GenException.

  6. The unnamed inputs take the names proc_input_<j>.
  7. Without proc_outputs the checker calls the module once on dummy inputs (a random tensor with batch size 1 and 8 for every unknown size, a random 224 × 224 RGB picture or the text "test text as input") and describes each output it receives (table below). An output of another type raises ValueError("Unsupported output type ...").
  8. The unnamed outputs take the names proc_output_<j>.
  9. proc_opts gains optimizer: None and losses: [None] * len(proc_outputs) when they are missing. Each torch.nn.functional.cross_entropy or torch.nn.CrossEntropyLoss among the losses becomes target_shape_fixed_cross_entropy.
  10. The agent receives proc, proc_inputs, proc_outputs, proc_opts and proc_optional_inputs from the wrapper.
First layer Guessed input
Conv2d with 1 or 3 channels img. The checker tries the module on an RGB and a grayscale picture. When it accepts both there is no transform. When it accepts only RGB the transform converts to 3 channels. When it accepts only grayscale the transform converts to 1 channel. When it accepts neither the transform is transforms_factory("rgb") or transforms_factory("gray").
Conv2d with another number of channels tensor of torch.float32 with shape (None, C, None, None).
Conv1d tensor of torch.float32 with shape (None, C, None).
Linear tensor of torch.float32 with shape (None, in_features).
Embedding text when the module accepts a string. Otherwise a torch.long tensor of token ids with labels token0, token1, ... of shape (None, None) or (None, 1).
Output of the dummy call Guessed output
PIL.Image.Image img.
tensor of shape [b, 3, H, W] or [b, 1, H, W] img with the inverse of transforms_factory("rgb") or transforms_factory("gray").
other tensor tensor with its dtype and the shape (None, *shape[1:]). A 0-dimensional tensor gives the shape ().
str text.

The probes of steps 5 and 7 restore the state_dict of the module afterwards. The dummy call of step 7 is a real call of the model. An explicit proc_outputs skips it. A slow model or a model behind a paid API should therefore always get one.

proc_opts must use the keys optimizer and losses. Because step 9 always adds both keys, an optimizer or a known loss function stored under any other key makes the checker raise AssertionError (About proc_opts: cannot find required keys ...). A key lr creates no optimizer.

has_human_processor

has_human_processor(agent: object) -> bool
Source code in unaiverse/modules/utils.py
def has_human_processor(agent: object) -> bool:
    """Checks whether the given agent has a human processor module.

    Args:
        agent: The agent object to inspect; expected to have a ``proc`` attribute.

    Returns:
        True if the agent's processor module is a HumanModule, False otherwise.
    """
    assert hasattr(agent, "proc")
    return getattr(agent, "proc") is not None and isinstance(getattr(agent, "proc").module, HumanModule)

Returns True when agent.proc is a wrapper around a HumanModule. The agent must have the attribute proc (otherwise AssertionError). AgentBasics calls it to know whether a person drives the agent.

Processor modules

HumanModule

HumanModule()

Bases: Module

Source code in unaiverse/modules/utils.py
def __init__(self) -> None:
    """Initializes the human module."""
    super().__init__()

The processor of a person. Because a person writes the output by hand, the module gives back what it receives (see People).

UAI_ECHOES_INPUT class-attribute instance-attribute

UAI_ECHOES_INPUT = True

True. The wrapper neither rewrites the interactive blocks of the input nor runs the module in the worker thread.

forward

forward(text: str | None = None, img: Image | None = None, file: object | None = None, whatever: object | None = None) -> tuple[str | None, Image | None, object | None]
Source code in unaiverse/modules/utils.py
def forward(self, text: str | None = None, img: Image.Image | None = None, file: object | None = None,
            whatever: object | None = None) -> tuple[str | None, Image.Image | None, object | None]:
    """Returns the text, image and file inputs as-is (placeholder for human interaction).

    The person's inputs are text, img, file and all; the outputs that a node declares take these in order (a node
    with outputs text and img gives back the text and the image only).

    Args:
        text: Optional text input.
        img: Optional PIL image input.
        file: Optional file input (a FileContainer).
        whatever: Optional additional input (ignored).

    Returns:
        A tuple ``(text, img, file)`` with the unchanged inputs.
    """
    return text, img, file

Returns (text, img, file) unchanged. The four parameters text, img, file and whatever default to None. whatever is accepted and ignored. A node with proc_outputs=["text"] keeps the text only because the wrapper drops the outputs beyond proc_outputs. Pass proc_inputs and proc_outputs explicitly because the guess of the outputs fails on the None elements of the tuple. proc="human" builds the same module with the streams text and img.

from unaiverse.agent import Agent
from unaiverse.modules.utils import HumanModule

agent = Agent(proc=HumanModule(), proc_inputs=["text", "img", "file"], proc_outputs=["text", "img", "file"])

MultiIdentity

MultiIdentity()

Bases: Module

Source code in unaiverse/modules/utils.py
def __init__(self) -> None:
    """Initializes the identity module."""
    super().__init__()

The processor of an agent without a model. AgentProcessorChecker uses it when proc is None.

UAI_ECHOES_INPUT class-attribute instance-attribute

UAI_ECHOES_INPUT = True

True. The effects are those described for HumanModule.

forward

forward(*args: object, **kwargs: object) -> object
Source code in unaiverse/modules/utils.py
def forward(self, *args: object, **kwargs: object) -> object:
    """Returns the single input unchanged, or all positional inputs as a tuple.

    Args:
        *args: One or more input tensors / objects.
        **kwargs: Unused.

    Returns:
        The single input if exactly one positional argument is given, otherwise the
        full ``args`` tuple.
    """
    if len(args) == 1:
        return args[0]
    return args

Returns its single positional argument. With zero or more than one positional argument it returns their tuple. Keyword arguments are ignored.

LoggerModule

LoggerModule(log_file: str | None = None)

Bases: Module

Source code in unaiverse/modules/utils.py
def __init__(self, log_file: str | None = None) -> None:
    """Initializes the LoggerModule.

    Args:
        log_file: Path to the log file that records inputs and outputs (default: ``"app_log.txt"``).
    """
    super().__init__()
    self.log_file = log_file
    self._initialized = False
    self._logger = logging.getLogger("CallableLogger")
    self._logger.setLevel(logging.INFO)
    self.__handler = None
    self._idx = 0
    self._objects = ["telescope", "hammer", "compass", "anchor", "lantern", "keyboard", "cat", "dog", "tiger",
                     "zebra", "batman", "superman", "candy", "table", "chair", "balloon", "kitchen", "sofa", "lamp",
                     "arrow", "green", "red", "blue", "yellow", "magenta", "brown", "pink", "orange", "white",
                     "paris", "rome", "boston", "york", "berlin", "singapore", "taiwan", "japan", "china",
                     "turkey", "italy", "france", "germany", "spain", "madrid", "barcelona", "portugal",
                     "norway", "sweden", "belgium", "romania", "sunny", "snowy", "rainy"]
    random.shuffle(self._objects)

A test processor that logs what it receives and answers with a word from a list. The constructor takes log_file (str or None, default None) and shuffles a list of 53 words (objects, animals, colors, cities, weather).

forward

forward(text: str, img: Image | None = None) -> tuple[str | None, Image | None]
Source code in unaiverse/modules/utils.py
def forward(self, text: str, img: Image.Image | None = None) -> tuple[str | None, Image.Image | None]:
    """Logs the received inputs and returns a cycling dummy text response with no image output.

    Args:
        text: The text input to log.
        img: An optional PIL image input to log (not forwarded to the output).

    Returns:
        A tuple ``(response_text, None)`` where ``response_text`` is the next item from
        the internal word cycle.
    """
    if self.log_file is not None:
        if not self._initialized:
            self.__setup_logger()
        self._logger.info("-------------------------------------------------------------------------------")
        self._logger.info(f"[INPUT] text={text if text is not None else None}, "
                          f"img={img.size if img is not None else None}")
    else:
        log.user(f"[INPUT] text={text if text is not None else None}, "
                 f"img={img.size if img is not None else None}")

    text = f"{self._idx}_{self._objects[self._idx]}"
    self._idx = (self._idx + 1) % len(self._objects)
    img = None

    if self.log_file is not None:
        self._logger.info(f"[OUTPUT] text={text}, img={None}")
        self._logger.info("-------------------------------------------------------------------------------")
        self.__handler.flush()
    else:
        log.user(f"[OUTPUT] text={text}, img={None}")
    return text, img

Takes text and an optional picture img and returns (f"{i}_{word}", None) with i the position in the list. The position cycles over the list. With log_file=None the input and the answer go to the USER channel of the logger. With a path the first call creates its folders and truncates the file. Every call then writes the input (the text and the size of the picture) and the answer to it. Because all the instances share the Python logger "CallableLogger", two instances with two files write each line to both files.

Transforms

transforms_factory

transforms_factory(trans_type: str, add_batch_dim: bool = True, return_inverse: bool = False) -> Compose | None
Source code in unaiverse/modules/utils.py
def transforms_factory(trans_type: str, add_batch_dim: bool = True,
                       return_inverse: bool = False) -> transforms.Compose | None:
    """Builds and returns a torchvision transform pipeline for the given type.

    Args:
        trans_type: A string identifying the desired transform.  Supported values are
            ``"rgb<N>"`` / ``"gray<N>"`` (resize + center-crop to ``<N>`` pixels, with normalization).
            ``"rgb-no_norm<N>"`` / ``"gray-no_norm<N>"`` (resize + center-crop, no normalization).
            ``"rgb"`` / ``"gray"`` (full-image with normalization).
            ``"rgb-no_norm"`` / ``"gray-no_norm"`` (full-image, no normalization).
            ``"gray_mnist"`` (MNIST-specific 28×28 grayscale pipeline).
        add_batch_dim: If True, appends an ``unsqueeze(0)`` step to the forward transform and
            inserts a ``squeeze(0)`` step at the start of the inverse transform (default: True).
        return_inverse: If True, returns the inverse (de-normalization) transform instead of the
            forward transform (default: False).

    Returns:
        The requested ``transforms.Compose`` pipeline (or None, if the type is unknown).
    """
    supported_types = {"rgb*",          "gray*",
                       "rgb-no_norm*",  "gray-no_norm*",
                       "rgb",           "gray",
                       "rgb-no_norm",   "gray-no_norm",
                                        "gray_mnist"}

    found = False
    num = -1
    for _type in supported_types:
        if _type.endswith("*"):
            has_star = True
            __type = _type[0:-1]
        else:
            has_star = False
            __type = _type

        if has_star and trans_type.startswith(__type) and len(trans_type) > len(__type):
            try:
                num = int(trans_type[len(__type):])
                trans_type = _type
                found = True
                break
            except ValueError:
                pass
        elif trans_type == _type:
            found = True
            break

    if not found:
        raise ValueError(f"Invalid transformation type '{trans_type}': must be one of {supported_types}, "
                         f"where * is an integer number")

    trans = None
    inverse_trans = None

    if trans_type == "rgb*":
        trans = transforms.Compose([
            transforms.Lambda(lambda img: img.convert("RGB") if img.mode != "RGB" else img),  # Ensure 3 chans
            transforms.Resize(num),
            transforms.CenterCrop(num),
            transforms.ToTensor(),  # Convert PIL to tensor (3, H, W), float [0,1]
            transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                 std=[0.229, 0.224, 0.225]),
        ])
        inverse_trans = transforms.Compose([
            transforms.Normalize(mean=[0., 0., 0.],
                                 std=[1. / 0.229, 1. / 0.224, 1. / 0.225]),
            transforms.Lambda(lambda x: torch.clamp(x + torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1),
                                                    min=0.0, max=1.0)),
            transforms.ToPILImage()
        ])
    elif trans_type == "gray*":
        trans = transforms.Compose([
            transforms.Lambda(lambda img: img.convert("L") if img.mode != "L" else img),  # Ensure 1 channel
            transforms.Resize(num),
            transforms.CenterCrop(num),
            transforms.ToTensor(),  # Convert PIL to tensor (1, H, W), float [0,1]
            transforms.Normalize(mean=[0.45],
                                 std=[0.225])
        ])
        inverse_trans = transforms.Compose([
            transforms.Normalize(mean=[0.],
                                 std=[1. / 0.225]),
            transforms.Lambda(lambda x: torch.clamp(x + 0.45, min=0.0, max=1.0)),
            transforms.ToPILImage()
        ])
    elif trans_type == "rgb-no_norm*":
        trans = transforms.Compose([
            transforms.Lambda(lambda img: img.convert("RGB") if img.mode != "RGB" else img),  # Ensure 3 channels
            transforms.Resize(num),
            transforms.CenterCrop(num),
            transforms.PILToTensor(),  # Convert PIL to tensor (3, H, W), uint [0,255]
        ])
        inverse_trans = transforms.Compose([transforms.ToPILImage()])
    elif trans_type == "gray-no_norm*":
        trans = transforms.Compose([
            transforms.Lambda(lambda img: img.convert("L") if img.mode != "L" else img),  # Ensure 1 channel
            transforms.Resize(num),
            transforms.CenterCrop(num),
            transforms.PILToTensor(),  # Convert PIL to tensor (1, H, W), uint [0,255]
        ])
        inverse_trans = transforms.Compose([transforms.ToPILImage()])
    elif trans_type == "rgb":
        trans = transforms.Compose([
            transforms.Lambda(lambda img: img.convert("RGB") if img.mode != "RGB" else img),  # Ensure 3 channels
            transforms.ToTensor(),  # Convert PIL to tensor (3, H, W), float [0,1]
            transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                 std=[0.229, 0.224, 0.225])
        ])
        inverse_trans = transforms.Compose([
            transforms.Normalize(mean=[0., 0., 0.],
                                 std=[1. / 0.229, 1. / 0.224, 1. / 0.225]),
            transforms.Lambda(lambda x: torch.clamp(x + torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1),
                                                    min=0.0, max=1.0)),
            transforms.ToPILImage()
        ])
    elif trans_type == "gray":
        trans = transforms.Compose([
            transforms.Lambda(lambda img: img.convert("L") if img.mode != "L" else img),  # Ensure 1 channel
            transforms.ToTensor(),  # Convert PIL to tensor (1, H, W), float [0,1]
            transforms.Normalize(mean=[0.45],
                                 std=[0.225])
        ])
        inverse_trans = transforms.Compose([
            transforms.Normalize(mean=[0.],
                                 std=[1. / 0.225]),
            transforms.Lambda(lambda x: torch.clamp(x + 0.45, min=0.0, max=1.0)),
            transforms.ToPILImage()
        ])
    elif trans_type == "rgb-no_norm":
        trans = transforms.Compose([
            transforms.Lambda(lambda img: img.convert("RGB") if img.mode != "RGB" else img),  # Ensure 3 channels
            transforms.PILToTensor(),  # Convert PIL to tensor (3, H, W), uint [0,255]
        ])
        inverse_trans = transforms.Compose([transforms.ToPILImage()])
    elif trans_type == "gray-no_norm":
        trans = transforms.Compose([
            transforms.Lambda(lambda img: img.convert("L") if img.mode != "L" else img),  # Ensure 1 channel
            transforms.PILToTensor(),  # Convert PIL to tensor (1, H, W), uint [0,255]
        ])
        inverse_trans = transforms.Compose([transforms.ToPILImage()])
    elif trans_type == "gray_mnist":
        trans = transforms.Compose([
            transforms.Lambda(lambda img: img.convert("L") if img.mode != "L" else img),  # Ensure 1 channel
            transforms.Resize(28),
            transforms.CenterCrop(28),
            transforms.ToTensor(),  # Convert PIL to tensor (1, H, W), float [0,1]
            transforms.Normalize(mean=[0.1307],  # MNIST
                                 std=[0.3081])  # MNIST
        ])
        inverse_trans = transforms.Compose([
            transforms.Normalize(mean=[0.],
                                 std=[1. / 0.3081]),
            transforms.Lambda(lambda x: torch.clamp(x + 0.1307, min=0.0, max=1.0)),
            transforms.ToPILImage()
        ])

    if add_batch_dim and (trans is not None and inverse_trans is not None):
        trans.transforms.append(transforms.Lambda(lambda x: x.unsqueeze(0)))
        inverse_trans.transforms.insert(0, transforms.Lambda(lambda x: x.squeeze(0)))

    return trans if not return_inverse else inverse_trans

Returns a torchvision.transforms.Compose that turns a PIL picture into a tensor or the inverse transform.

Argument Type Default Meaning
trans_type str required One of the types below. <N> is an integer.
add_batch_dim bool True True appends unsqueeze(0) to the forward transform and puts squeeze(0) first in the inverse.
return_inverse bool False True returns the inverse transform (tensor to PIL picture).
trans_type Forward transform Output (with the batch dimension)
"rgb<N>" RGB, resize of the shorter side to N, center crop N × N, ToTensor, ImageNet normalization (mean 0.485, 0.456, 0.406, std 0.229, 0.224, 0.225) [1, 3, N, N], float32
"gray<N>" Grayscale, resize, center crop, ToTensor, normalization (mean 0.45, std 0.225) [1, 1, N, N], float32
"rgb-no_norm<N>", "gray-no_norm<N>" As above without ToTensor and normalization, with PILToTensor [1, C, N, N], uint8 in [0, 255]
"rgb", "gray" As "rgb<N>" and "gray<N>" without resize and crop [1, C, H, W], float32
"rgb-no_norm", "gray-no_norm" Conversion and PILToTensor only [1, C, H, W], uint8
"gray_mnist" Grayscale, resize and crop to 28, ToTensor, MNIST normalization (mean 0.1307, std 0.3081) [1, 1, 28, 28], float32

The inverse of a normalized type undoes the normalization, clamps to [0, 1] and converts to a PIL picture. The inverse of a no_norm type only converts. Another trans_type raises ValueError.

from PIL import Image
from unaiverse.modules.utils import transforms_factory

t = transforms_factory("rgb224")
x = t(Image.open("cat.jpg"))                                # [1, 3, 224, 224]
back = transforms_factory("rgb224", return_inverse=True)(x)  # A PIL picture again

get_proc_inputs_and_proc_outputs_for_rnn

get_proc_inputs_and_proc_outputs_for_rnn(u_shape: Size | tuple, du_dim: int, y_dim: int) -> tuple[list, list]
Source code in unaiverse/modules/utils.py
def get_proc_inputs_and_proc_outputs_for_rnn(u_shape: torch.Size | tuple, du_dim: int,
                                             y_dim: int) -> tuple[list, list]:
    """Creates Stream descriptors for the inputs and output of an RNN-style processor.

    Args:
        u_shape: Shape of the main input tensor (excluding the batch dimension).
        du_dim: Dimensionality of the secondary (delta-u) input.
        y_dim: Dimensionality of the output.

    Returns:
        A tuple ``(proc_inputs, proc_outputs)`` where each element is a list of
        ``Stream`` objects describing the processor's I/O signature.
    """
    if isinstance(u_shape, torch.Size):
        u_shape = tuple(u_shape)
    proc_inputs = [
        StreamType(data_type="tensor", tensor_shape=(None,) + u_shape, tensor_dtype=torch.float32,
                   pubsub=False, private_only=False),
        StreamType(data_type="tensor", tensor_shape=(None, du_dim,), tensor_dtype=torch.float32,
                   pubsub=False, private_only=False)
    ]
    proc_outputs = [
        StreamType(data_type="tensor", tensor_shape=(None, y_dim), tensor_dtype=torch.float32,
                   pubsub=False, private_only=False)
    ]
    return proc_inputs, proc_outputs

Returns (proc_inputs, proc_outputs) for a network that reads a signal and a descriptor: two torch.float32 tensor inputs of shape (None, *u_shape) and (None, du_dim) and one torch.float32 tensor output of shape (None, y_dim). u_shape is a tuple or a torch.Size. The recurrent and state-space networks of networks use it.

get_proc_inputs_and_proc_outputs_for_image_classification

get_proc_inputs_and_proc_outputs_for_image_classification(y_dim: int = -1, trans_forms: Callable | None = None) -> tuple[list[StreamType], list[StreamType]]
Source code in unaiverse/modules/utils.py
def get_proc_inputs_and_proc_outputs_for_image_classification(y_dim: int = -1, trans_forms: Callable | None = None) \
        -> tuple[list[StreamType], list[StreamType]]:
    """Creates Stream descriptors for the inputs and output of an image-classification processor.

    Args:
        y_dim: Number of output classes.  Pass ``-1`` to default to 1000 (ImageNet).
        trans_forms: Stream to processor transforms, if any (Default: None).

    Returns:
        A tuple ``(proc_inputs, proc_outputs)`` where each element is a list of
        ``Stream`` objects describing the processor's I/O signature.
    """
    if y_dim == -1:
        y_dim = 1000  # Assuming ImageNet-trained models
    proc_inputs = [StreamType(data_type="img", pubsub=False, private_only=False, stream_to_proc_transforms=trans_forms)]
    proc_outputs = [StreamType(data_type="tensor", tensor_shape=(None, y_dim), tensor_dtype=torch.float32,
                               pubsub=False, private_only=False)]
    return proc_inputs, proc_outputs

Returns (proc_inputs, proc_outputs) for an image classifier: one img input with the stream-to-processor transform trans_forms (default None) and one torch.float32 tensor output of shape (None, y_dim). y_dim=-1 (the default) stands for 1000 classes. The classifiers of networks use it.

Training helpers

set_seed

set_seed(seed: int) -> None
Source code in unaiverse/modules/utils.py
def set_seed(seed: int) -> None:
    """Seeds all relevant random-number generators for reproducibility.

    Args:
        seed: The integer seed value.  If negative, no seeding is performed.
    """
    if seed >= 0:
        torch.manual_seed(seed)
        random.seed(seed)
        np.random.seed(seed)

Seeds torch.manual_seed, random.seed and numpy.random.seed with seed. A negative seed does nothing. ModuleWrapper.__init__ calls it with its seed argument.

hard_tanh

hard_tanh(x: Tensor) -> Tensor
Source code in unaiverse/modules/utils.py
def hard_tanh(x: torch.Tensor) -> torch.Tensor:
    """Clamps tensor values to the range [-1, 1] (hard tanh activation).

    Args:
        x: Input tensor.

    Returns:
        Tensor with all values clamped to ``[-1, 1]``.
    """
    return torch.clamp(x, min=-1., max=1.)

Returns torch.clamp(x, -1, 1).

target_shape_fixed_cross_entropy

target_shape_fixed_cross_entropy(output: Tensor, target: Tensor, *args: Any, **kwargs: Any) -> Tensor
Source code in unaiverse/modules/utils.py
def target_shape_fixed_cross_entropy(output: torch.Tensor, target: torch.Tensor,
                                     *args: Any, **kwargs: Any) -> torch.Tensor:
    """Computes cross-entropy loss, squeezing a leading batch dimension from the target if present.

    Args:
        output: The model output logits tensor.
        target: The target class-index tensor; if it has more than one dimension the first
            dimension is squeezed before calling ``cross_entropy``.
        *args: Additional positional arguments forwarded to ``torch.nn.functional.cross_entropy``.
        **kwargs: Additional keyword arguments forwarded to ``torch.nn.functional.cross_entropy``.

    Returns:
        The scalar cross-entropy loss tensor.
    """
    if len(target.shape) > 1:
        target = target.squeeze(0)
    return torch.nn.functional.cross_entropy(output, target, *args, **kwargs)

Calls torch.nn.functional.cross_entropy(output, target, *args, **kwargs) after removing the first dimension of target when target has more than one dimension. A target stream sample of shape [1, b] thus reaches the loss as [b]. AgentProcessorChecker puts it in place of every cross-entropy loss of proc_opts.

isinstance_fcn

isinstance_fcn(obj: object, class_to_check: type | tuple) -> bool
Source code in unaiverse/modules/utils.py
def isinstance_fcn(obj: object, class_to_check: type | tuple) -> bool:
    """Thin wrapper around the built-in ``isinstance`` function.

    Args:
        obj: The object to test.
        class_to_check: A type or tuple of types to check against.

    Returns:
        True if ``obj`` is an instance of ``class_to_check``, False otherwise.
    """
    return isinstance(obj, class_to_check)

Returns isinstance(obj, class_to_check).

error_rate_mnist_test_set

error_rate_mnist_test_set(network: Module, mnist_data_save_path: str) -> float
Source code in unaiverse/modules/utils.py
def error_rate_mnist_test_set(network: torch.nn.Module, mnist_data_save_path: str) -> float:
    """Evaluates a network's classification error rate on the MNIST test set, in one
    blocking call (drains the stepwise generator above).

    Args:
        network: The PyTorch module to evaluate.
        mnist_data_save_path: Path where the MNIST dataset will be downloaded and cached.

    Returns:
        The fraction of misclassified test samples (in [0, 1]).
    """
    gen = error_rate_mnist_test_set_steps(network, mnist_data_save_path)
    while True:
        try:
            next(gen)
        except StopIteration as stop:
            return stop.value

Returns the error rate (a float in [0, 1]) of network on the 10000 pictures of the MNIST test set. The function downloads the dataset into mnist_data_save_path when it is not there, normalizes the pictures (mean 0.1307, std 0.3081) and feeds batches of 200 tensors of shape [200, 1, 28, 28] to the module on the device of its first parameter. The prediction is the argmax over dimension 1. The module runs in evaluation mode and gets its previous mode back at the end. The function needs the PyTorch module itself in place of the wrapper.

error_rate_mnist_test_set_steps

error_rate_mnist_test_set_steps(network: Module, mnist_data_save_path: str) -> Generator[None, None, float]
Source code in unaiverse/modules/utils.py
def error_rate_mnist_test_set_steps(network: torch.nn.Module, mnist_data_save_path: str) \
        -> Generator[None, None, float]:
    """Generator variant of error_rate_mnist_test_set, one chunk of work per yield: the
    dataset setup is a chunk of its own (it may touch the disk), then one test batch per
    chunk. Built for AgentBasics.stepwise, so the node loop keeps pumping during the
    evaluation. torch.no_grad() is entered and exited within each chunk (grad mode is
    thread-global: it must never stay flipped across a yield), and the train-mode
    restore lives in a finally block, which also runs if an abandoned generator is
    garbage-collected. Returns the error rate like the plain function.

    Args:
        network: The PyTorch module to evaluate.
        mnist_data_save_path: Path where the MNIST dataset will be downloaded and cached.

    Returns:
        The fraction of misclassified test samples (in [0, 1]).
    """

    # Getting MNIST test set
    mnist_test = datasets.MNIST(root=mnist_data_save_path,
                                train=False, download=True,
                                transform=transforms.Compose([
                                    transforms.ToTensor(),
                                    transforms.Normalize((0.1307,), (0.3081,))
                                ]))
    mnist_test = DataLoader(mnist_test, batch_size=200, shuffle=False)
    yield

    # Checking error rate
    error_rate = 0.
    n = 0
    training_flag_backup = network.training
    network.eval()
    try:
        device = next(network.parameters()).device
        for x, y in mnist_test:
            with torch.no_grad():
                x = x.to(device)
                y = y.to(device)
                o = network(x)
                c = torch.argmax(o, dim=1)
                error_rate += float(torch.sum(c != y).item())
                n += x.shape[0]
            yield
    finally:
        network.train(training_flag_backup)

    return error_rate / n

The same evaluation as a generator. It yields None once after loading the dataset and once after every batch. Its return value (the value of StopIteration) is the error rate. torch.no_grad() covers each batch only and the evaluation mode is restored in a finally block. A role that evaluates during the life of a node uses it through AgentBasics.stepwise. That method advances the generator one chunk per tick and keeps the node running.

Gateway of the Featherless clients

The FeatherlessAPI processors of one machine share one gateway process. The gateway owns the connection to Featherless, keeps one budget of units per API key and serves the requests in strict round robin between processes. The environment variables of this section are read when the module is imported (see Configuration).

OPENAI_NATIVE_SAMPLER_PARAMS module-attribute

OPENAI_NATIVE_SAMPLER_PARAMS: frozenset[str] = frozenset({'max_tokens', 'temperature', 'top_p', 'frequency_penalty', 'presence_penalty', 'stop', 'seed', 'n', 'logit_bias', 'logprobs', 'top_logprobs', 'response_format'})

The frozenset of the sampling options that the chat-completions API of OpenAI takes as fields: max_tokens, temperature, top_p, frequency_penalty, presence_penalty, stop, seed, n, logit_bias, logprobs, top_logprobs and response_format. featherless_call and OpenRouterAPI send these as fields and every other option in the extra body of the request.

featherless_call async

featherless_call(sys_prompt: str, prompt: str, sampler: dict | None = None, model: str | None = None, api_key: str | None = None) -> str | None
Source code in unaiverse/modules/utils.py
async def featherless_call(sys_prompt: str, prompt: str, sampler: dict | None = None,
                           model: str | None = None, api_key: str | None = None) -> str | None:
    """Perform the actual call to the Featherless API and return the generated text (async).

    Args:
        sys_prompt: The system prompt, if any (can be empty).
        prompt: The prompt string to send to the model.
        sampler: Sampling parameters to send (e.g. ``temperature``, ``max_tokens``, ``top_p``, ``top_k``,
            ``frequency_penalty``, ``presence_penalty``, ``repetition_penalty``, ``min_p``). OpenAI-native keys are
            passed as top-level fields; any other key is forwarded via ``extra_body``. None/empty uses API defaults.
        model: The model identifier to use; if None, falls back to the MODEL_ID environment variable.
        api_key: The Featherless API key to authenticate with (None falls back to FEATHERLESS_API_KEY).

    Returns:
        The text generated by the model.
    """
    client = _get_featherless_client(api_key)
    model = model or os.environ.get("MODEL_ID", "MOD")

    if model == "MOD":
        log.critical("Calling Featherless API: the model argument was not set; "
                     "the MODEL_ID environment variable was not set!")

    # Split the requested sampler params: OpenAI-native ones go top-level, the rest ride along in extra_body
    sampler = sampler or {}
    extra_body = {k: v for k, v in sampler.items() if k not in OPENAI_NATIVE_SAMPLER_PARAMS}
    native = {k: v for k, v in sampler.items() if k in OPENAI_NATIVE_SAMPLER_PARAMS}

    def _account_log(row_to_add: str) -> None:
        """Append a row to the per-account usage log, if the flag file enables it (crash-durable append)."""
        flag_file = os.path.expanduser("~/DO_LOG_FEATHERLESS_AI")
        if os.path.exists(flag_file):
            file_path = os.path.join(os.path.expanduser("~"), f"featherless_ai_account_{(api_key or 'env')[-6:]}.log")
            with open(file_path, "a") as f:
                f.write(row_to_add + " \n")
                f.flush()  # Flushes Python's internal buffer to OS buffer
                os.fsync(f.fileno())  # Forces OS buffer to write to physical storage

    # Retry with exponential backoff, keeping the last error so a final failure reports its cause
    last_err = None

    for attempt in range(3):
        current_time = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
        t0 = time.perf_counter()
        try:

            # Always use chat completions; include the system message only when a system prompt is given
            msgs = [{"role": "system", "content": sys_prompt}] if sys_prompt else []
            msgs.append({"role": "user", "content": prompt})

            # The dict is typed dict[str, object] so PyCharm accepts the mixed value types (str / list / int / float)
            kwargs: dict[str, object] = {"model": model, "messages": msgs, **native}
            if extra_body:
                kwargs["extra_body"] = extra_body

            resp = await client.chat.completions.create(**kwargs)  # type: ignore
            elapsed = time.perf_counter() - t0

            # Diagnostics: wall time, throughput, completion length + stop reason. A large completion_tokens count
            # suggests thinking is still on; a low tokens/sec on a warm model points at a slow/cold API replica.
            usage = getattr(resp, "usage", None)
            c_toks = getattr(usage, "completion_tokens", 0)
            finish_reason = resp.choices[0].finish_reason if resp.choices else "n/a"
            tps = f"{c_toks / elapsed:.1f}" if (c_toks and elapsed > 0) else "n/a"

            _account_log(f"{current_time} model={model} finish_reason={finish_reason} "
                         f"completion_tokens={c_toks if c_toks is not None else 'n/a'} "
                         f"elapsed={elapsed:.2f}s tokens/sec={tps}")

            # Return the first choice that carries non-empty text (content may be None)
            for choice in resp.choices:
                content = choice.message.content
                if content is not None and content.strip():
                    return content

            # Empty/blank content: treat it as a transient failure so the loop retries instead of returning ""
            finish = resp.choices[0].finish_reason if resp.choices else "n/a"
            last_err = RuntimeError(f"Empty content from model (finish_reason={finish})")
        except Exception as e:
            last_err = e
            elapsed = time.perf_counter() - t0
            _account_log(f"{current_time} model={model} FAILED attempt={attempt + 1} "
                         f"elapsed={elapsed:.2f}s error={e!r}")

        # Retry on either an exception or empty content
        log.error(f"Empty response or exception! (prompt={prompt}, attempt={attempt + 1}, last_err={last_err!r}), "
                  f"waiting {2 ** attempt} seconds before trying again...")
        await asyncio.sleep(2 ** attempt)

    log.critical(f"Featherless AI call failed after retries: {last_err!r}")  # This will raise an exception
    return ""  # Never reached

The coroutine that the gateway uses for one generation. It returns the text of the answer.

Argument Type Default Meaning
sys_prompt str required The system message. "" sends none.
prompt str required The user message.
sampler dict or None None The sampling options.
model str or None None The model. None reads the environment variable MODEL_ID.
api_key str or None None The key. None reads FEATHERLESS_API_KEY.

The function creates one openai.AsyncOpenAI client per key on https://api.featherless.ai/v1 on first use and keeps it. It raises GenException without a model or a key. An exception or an answer without text counts as a failed attempt. The function logs each failed attempt on the ERROR channel with the whole prompt and then sleeps 2 ** attempt seconds (1 after the first, 2 after the second and 4 after the third). After the third failure and its sleep it raises GenException. When the file ~/DO_LOG_FEATHERLESS_AI exists, every attempt appends a line (time, model, stop reason, tokens, duration) to ~/featherless_ai_account_<last 6 characters of the key>.log.

APIGatewayServer

APIGatewayServer(call: Callable = featherless_call)
Source code in unaiverse/modules/utils.py
def __init__(self, call: Callable = featherless_call) -> None:
    """Create a Server.

    Args:
        call: The asynchronous function performing the actual model call (Default: featherless_call).
    """
    self.scheds: dict[str, APIGatewayScheduler] = {}  # API key -> scheduler (own queues/budget/dispatcher)
    self.call: Callable = call
    self.live: set = set()  # Set of registration writers (one per live client)
    self.shutdown: asyncio.Event = asyncio.Event()

The gateway. It listens on TCP and speaks newline-delimited JSON:

Message Direction Meaning
{"op": "hello"} client to server Registers the connection that carries it. The registration lasts as long as the connection.
{"op": "generate", "process_id": ..., "sys_prompt": ..., "prompt": ..., "cost": ..., "model": ..., "sampler": ..., "api_key": ..., "key_units": ...} client to server One request.
{"ok": true, "result": "..."} or {"ok": false, "error": "..."} server to client The answer to a request on the same connection.

The constructor takes the coroutine call that performs a generation (default featherless_call). It creates the attributes scheds (one APIGatewayScheduler per API key), live (the registered connections) and shutdown (an asyncio.Event).

HOST class-attribute instance-attribute

HOST: str = os.environ.get('GW_HOST', '127.0.0.1')

The address of the gateway: the environment variable GW_HOST, default "127.0.0.1".

PORT class-attribute instance-attribute

PORT: int = int(os.environ.get('GW_PORT', '11321'))

The port of the gateway: GW_PORT, default 11321.

TOTAL_UNITS class-attribute instance-attribute

TOTAL_UNITS = int(os.environ.get('GW_UNITS', '8'))

The budget of a key whose requests declare none: GW_UNITS, default 8.

VALID_COSTS class-attribute instance-attribute

VALID_COSTS = tuple(int(x) for x in os.environ.get('GW_VALID_COSTS', '1,2,4').split(','))

The accepted costs of a request: the comma-separated integers of GW_VALID_COSTS, default (1, 2, 4).

LOCKFILE class-attribute instance-attribute

LOCKFILE: str = os.environ.get('GW_LOCKFILE', os.path.join(tempfile.gettempdir(), 'llm_api_gateway.lock'))

The lock file that lets one process at a time start the gateway: GW_LOCKFILE, default llm_api_gateway.lock in the temporary folder of the system.

handle async

handle(reader: StreamReader, writer: StreamWriter) -> None
Source code in unaiverse/modules/utils.py
async def handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
    """Serve a single client connection until it closes (async).

    A connection that sends ``{"op": "hello"}`` is treated as that client's liveness registration; a connection
    that sends ``{"op": "generate", ...}`` has its query scheduled and the result written back.

    Args:
        reader: The stream reader for the client connection.
        writer: The stream writer for the client connection.
    """
    registered = False
    try:
        while True:
            line = await reader.readline()
            if not line:
                break  # Connection closed by the client (or it died)
            try:
                msg = json.loads(line)
            except json.JSONDecodeError:
                continue
            op = msg.get("op")
            if op == "hello":

                # This connection is the client's liveness registration
                registered = True
                self.live.add(writer)
            elif op == "generate":
                pid = msg["process_id"]
                sys_prompt = msg.get("sys_prompt", "")
                prompt = msg["prompt"]
                cost = int(msg.get("cost", 1))
                model = msg.get("model")
                sampler = msg.get("sampler") or {}
                api_key = msg.get("api_key") or os.environ.get("FEATHERLESS_API_KEY", "")
                key_units = int(msg.get("key_units", APIGatewayServer.TOTAL_UNITS))
                if cost not in APIGatewayServer.VALID_COSTS:
                    out = {"ok": False, "error": f"bad cost {cost}"}
                elif not api_key:
                    out = {"ok": False, "error": "no API key: not in the request, and no FEATHERLESS_API_KEY"}
                else:
                    try:
                        sched = self._sched_for(api_key, key_units)
                        result = await sched.submit(pid, sys_prompt, prompt, cost, model, sampler)
                        out = {"ok": True, "result": result}
                    except Exception as e:
                        out = {"ok": False, "error": str(e)}
                writer.write((json.dumps(out) + "\n").encode())
                await writer.drain()
    except (ConnectionResetError, asyncio.IncompleteReadError):
        pass
    finally:
        if registered:
            self.live.discard(writer)

            # When the last interested client disconnects, shut down
            if not self.live:
                self.shutdown.set()
        try:
            writer.close()
        except Exception:
            pass

Serves one connection until it closes. A line that is not JSON is ignored. A generate request with a cost outside VALID_COSTS or without a key (in the request or in FEATHERLESS_API_KEY) gets an error answer. Every other request goes to the scheduler of its key and the coroutine writes the answer when the generation ends. An exception of the generation becomes an error answer with its message. When a registered connection closes and no registration is left, the gateway shuts down.

run async

run() -> None
Source code in unaiverse/modules/utils.py
async def run(self) -> None:
    """Bind the listening socket, start the dispatcher, and run until shutdown is requested (async).

    Binding also arbitrates the startup race: if the port is already taken, ``start_server`` raises and this process
    is not the server. A grace period guards against an orphan server whose starter died before registering.
    """

    # Bind first (this is also the startup-race arbiter): if the port is taken, bind() raises and we are NOT
    # the server. Dispatchers are started lazily, one per API key, on the first request mentioning each key
    server = await asyncio.start_server(self.handle, APIGatewayServer.HOST, APIGatewayServer.PORT)

    # Grace period: if no client registers shortly after boot, exit, so a server spawned by a starter that
    # immediately died does not linger
    grace_secs = float(os.environ.get("GW_GRACE", "10"))

    async def grace():
        await asyncio.sleep(grace_secs)
        if not self.live:
            self.shutdown.set()
    asyncio.create_task(grace())

    async with server:
        await self.shutdown.wait()

Binds HOST:PORT and serves until shutdown. Binding fails with OSError when another gateway holds the port. When no client has registered GW_GRACE seconds (default 10) after the start, the gateway shuts down. This handles a starter process that died before registering. The scheduler of a key and its dispatcher task start with the first request that mentions the key. That request also fixes the budget of the key. A later request that declares another budget is served under the first one and the mismatch is logged.

APIGatewayScheduler

APIGatewayScheduler(total_units: int = -1)
Source code in unaiverse/modules/utils.py
def __init__(self, total_units: int = -1) -> None:
    """Create a Scheduler.

    Args:
        total_units: The total unit budget this scheduler admits (negative falls back to GW_UNITS) (Default: -1).
    """
    self.total_units: int = total_units if total_units > 0 else APIGatewayServer.TOTAL_UNITS
    self.available: int = self.total_units
    self.cond: asyncio.Condition = asyncio.Condition()
    self.queues: dict[str, asyncio.Queue] = {}  # Process ID -> queue of (prompt, cost, model, fut) - ORDERED
    self.rr: int = 0  # Round-robin cursor into the (insertion-ordered) list of process IDs

The queue of the requests of one API key. The constructor takes total_units. Its default -1 stands for APIGatewayServer.TOTAL_UNITS. The attributes are total_units, available (the units not in use), queues (one FIFO queue per process id) and rr (the round-robin cursor).

The scheduler serves one request per process per turn whatever its cost. When the turn comes to a process whose next request does not fit in the available units, the dispatcher holds it and waits for units without serving anybody else. A request whose cost exceeds total_units can never be served and stalls the scheduler of its key forever.

submit async

submit(pid: str, sys_prompt: str, prompt: str, cost: int, model: str | None, sampler: dict | None = None) -> str
Source code in unaiverse/modules/utils.py
async def submit(self, pid: str, sys_prompt: str, prompt: str, cost: int, model: str | None,
                 sampler: dict | None = None) -> str:
    """Enqueue a query for a process and wait until the dispatcher runs it (async).

    Args:
        pid: The process ID the query belongs to (round-robin fairness is per process).
        sys_prompt: The system prompt string (can be "").
        prompt: The prompt string to send to the model.
        cost: The query's unit cost (one of VALID_COSTS).
        model: The model identifier to use (None lets the call fall back to its own default).
        sampler: Sampling parameters to forward to the model call (None means use API defaults).

    Returns:
        The model's textual result.
    """
    fut: asyncio.Future = asyncio.get_running_loop().create_future()
    await self._queue(pid).put((sys_prompt, prompt, cost, model, sampler, fut))
    async with self.cond:
        self.cond.notify_all()  # Wake the dispatcher: there is new work
    return await fut

Queues a request of process pid and waits for the string of its result. The arguments are pid, sys_prompt, prompt, cost, model and sampler (default None). An exception of the generation is raised here.

dispatcher async

dispatcher(call: Callable) -> None
Source code in unaiverse/modules/utils.py
async def dispatcher(self, call: Callable) -> None:
    """Forever serve queued queries in strict round-robin order under the unit budget (async).

    Args:
        call: The asynchronous function performing the actual model call (passed on to each job).
    """

    # held[pid] holds a (prompt, cost, model, fut) we popped for a process but could not launch yet (its turn came
    # but the budget did not fit). Strict hold keeps it here until it can run; never put it back nor skip past it.
    held: dict = {}
    while True:
        async with self.cond:
            pids = list(self.queues.keys())
            if not pids:
                await self._wait_locked()
                continue

            pid = pids[self.rr % len(pids)]
            q = self.queues[pid]

            # Determine this process's current head: either the one we are holding, or the next one off its queue
            if pid in held:
                sys_prompt, prompt, cost, model, sampler, fut = held[pid]
            elif not q.empty():
                sys_prompt, prompt, cost, model, sampler, fut = q.get_nowait()
            else:

                # The current process has nothing: advance the turn. If nobody has work at all, wait; otherwise
                # keep rotating until we reach a process that does
                self.rr = (self.rr + 1) % len(pids)
                if all(self.queues[p].empty() for p in pids) and not held:
                    await self._wait_locked()
                continue

            if self.available >= cost:
                self.available -= cost
                held.pop(pid, None)
                asyncio.create_task(
                    self._run_job(sys_prompt, prompt, cost, model, sampler, fut, call))
                self.rr = (self.rr + 1) % len(pids)
                continue
            else:

                # Strict hold: it is this process's turn and its head does not fit. Hold the head and wait for units
                # to free up. Do NOT advance the cursor and do NOT serve anyone else.
                held[pid] = (sys_prompt, prompt, cost, model, sampler, fut)
                await self._wait_locked()
                continue

The task that runs forever and launches the queued requests in turn with the coroutine call(sys_prompt, prompt, sampler, model). Each launched request takes its cost from available and gives it back when it ends. APIGatewayServer starts one dispatcher per key.

serve_api_gateway

serve_api_gateway() -> None
Source code in unaiverse/modules/utils.py
def serve_api_gateway() -> None:
    """Process entrypoint for the detached gateway server (see the APIGatewayServer class).

    Spawned by the client via
    ``python -c "from unaiverse.modules.utils import serve_api_gateway; serve_api_gateway()"``. We deliberately do
    NOT use ``python -m unaiverse.modules.utils`` here: importing the parent package ``unaiverse.modules`` already
    imports this module, so running it again via ``runpy`` would execute a second copy of it under the name
    ``__main__`` (RuntimeWarning, and two distinct APIGatewayServer classes). Calling this function avoids that.
    """

    async def _main():

        # Construct the server INSIDE the running loop: the scheduler builds an asyncio.Condition, which binds to
        # the current loop at creation. Building it before asyncio.run() would bind it to the wrong loop.
        await APIGatewayServer(call=featherless_call).run()

    try:
        asyncio.run(_main())
    except OSError:
        pass  # Port already bound: another process beat us to it, just exit

The entry point of the gateway process. It runs APIGatewayServer(call=featherless_call).run() in a new event loop and returns when the gateway shuts down. An OSError (the port is taken) ends it silently. FeatherlessAPI starts it with python -c "from unaiverse.modules.utils import serve_api_gateway; serve_api_gateway()".