Skip to content

unaiverse.modules.networks

This module holds the ready-made processors of the SDK. Each class is a subclass of ModuleWrapper that builds a model and declares its input and output streams (proc_inputs and proc_outputs) by itself. Agent(proc=TinyLLama()) therefore needs no stream description. The classes fall into four families:

  1. Recurrent and state-space networks that process a signal sample by sample (RNN, RNNTokenLM, CSSM, CDiagR, CDiagC, CTE, CTB, CTBE and their variants).
  2. Image classifiers and a detector built on torchvision (CNN, ResNet, ViT, DenseNet, EfficientNet, FasterRCNN and the CNU variants).
  3. Language and vision models that run locally through Hugging Face transformers (TinyLLama, LLama, Phi, SmolVLM, LangSegmentAnything, SiteRAG).
  4. Clients of hosted language models (FeatherlessAPI, OpenRouterAPI).

The concepts behind them are in Models. Agents explains when the agent calls a processor in a worker thread and when inline.

from unaiverse.agent import Agent
from unaiverse.modules.networks import ResNet

agent = Agent(proc=ResNet(d_dim=5))     # One picture in, five scores in (0, 1) out

Arguments shared by every class

Every constructor ends with *args, **kwargs that go to ModuleWrapper.__init__. The useful ones are proc_opts (the optimizer and the losses, see Learning over time) and seed. seed seeds torch, random and numpy after the network of the class has been built. Because the weights exist by then, seed does not make them reproducible. Reproducible initial weights need a call of torch.manual_seed before the constructor.

The device of the wrapper comes from the device keyword argument, then from the environment variable PROC_DEVICE, then defaults to the CPU (see ModuleWrapper.guess_device). The classes with an explicit device parameter (the language and vision models) use the same rule for their model.

Recurrent and state-space networks

These networks keep a hidden state h of size h_dim across calls. They read two tensor streams and write one:

Stream Kind Shape Content
proc_input_0 tensor, torch.float32 (None, *u_shape) The signal u. The network flattens it to [b, u_dim] with u_dim the product of u_shape.
proc_input_1 tensor, torch.float32 (None, d_dim) The descriptor du, an extra input concatenated before u.
proc_output_0 tensor, torch.float32 (None, y_dim) The output y.

The inner module (the attribute module of the wrapper) has the signature forward(u, du, first=True). The agent passes first=True on the first step of an interaction and False on the following ones. With first=True the state restarts from h_init. This buffer of shape [batch_size, h_dim] is drawn from a normal distribution at construction. With first=False it continues from the state of the previous call. A None input stands for a zero tensor of the right shape.

The state-space networks (CSSM and the following classes) share these arguments and attributes:

Argument Type Default Meaning
u_shape tuple[int] required The shape of one sample of u without the batch dimension.
d_dim int required The size of the descriptor du.
y_dim int required The size of the output.
h_dim int required The size of the state.
sigma callable torch.tanh for CSSM, the identity elsewhere The function applied to the state before the output layer: y = C(sigma(h)).
project_every int 0 The network projects the parameters of its transition onto a stable set once every project_every calls (the projection of each class is below). 0 never projects.
local bool False True exposes the old state as h and reads the output from it. False exposes the new state.
batch_size int 1 The batch size of h_init and of the zero inputs.

After each call the inner module exposes h, dh = (h_new - h) / delta and delta. These are the attributes that HL reads to run Hamiltonian Learning. CSSM, CDiagR and CDiagC use delta = 1.

RNN

RNN(u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, batch_size: int = 1, device=None, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, batch_size: int = 1, device=None,
             *args, **kwargs):
    u_shape = torch.Size(u_shape)
    u_dim = u_shape.numel()
    du_dim = d_dim

    class Net(torch.nn.Module):
        def __init__(self, _device):
            super().__init__()
            self.A = torch.nn.Linear(h_dim, h_dim, bias=False)
            self.B = torch.nn.Linear(u_dim + du_dim, h_dim, bias=False)
            self.C = torch.nn.Linear(h_dim, y_dim, bias=False)
            self.register_buffer('h_init', torch.randn((batch_size, h_dim)))
            self.h = None
            self.u_dim = u_dim
            self.du_dim = du_dim
            self._device = _device

        def forward(self, u: torch.Tensor, du: torch.Tensor, first: bool = True):
            if first:
                h = self.h_init.data
            else:
                h = self.h.detach()
            if u is None:
                u = torch.zeros((h.shape[0], self.u_dim), dtype=torch.float32, device=self._device)
            else:
                u = u.to(self._device)
            if du is None:
                du = torch.zeros((h.shape[0], self.du_dim), dtype=torch.float32, device=self._device)
            else:
                du = du.to(self._device)

            self.h = torch.tanh(self.A(h) + self.B(torch.cat([du, u], dim=1)))
            y = self.C(self.h)
            return y

    # Populate self.device
    self.guess_device(device)

    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_rnn(u_shape, du_dim, y_dim)
    super(RNN, self).__init__(module=Net(self.device), proc_inputs=proc_inputs, proc_outputs=proc_outputs,
                              *args, **kwargs)

A plain recurrent network with linear maps without bias: h = tanh(A h + B [du, u]) and y = C h.

Argument Type Default Meaning
u_shape, d_dim, y_dim, h_dim, batch_size As in the table above.
device str, torch.device or None None The device to which the inner module moves its inputs.

With first=False the previous state enters the step detached from the graph. The class does not forward device to ModuleWrapper. The wrapper therefore places the network on PROC_DEVICE or on the CPU while the inputs go to device. A device different from that placement makes the first call fail with a device mismatch.

RNNTokenLM

RNNTokenLM(num_emb: int, emb_dim: int, y_dim: int, h_dim: int, batch_size: int = 1, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, num_emb: int, emb_dim: int, y_dim: int, h_dim: int, batch_size: int = 1, *args, **kwargs):

    class Net(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.embeddings = torch.nn.Embedding(num_emb, emb_dim)
            self.A = torch.nn.Linear(h_dim, h_dim, bias=False)
            self.B = torch.nn.Linear(emb_dim, h_dim, bias=False)
            self.C = torch.nn.Linear(h_dim, y_dim, bias=False)
            self.h_init = torch.randn((batch_size, h_dim))
            self.u_init = torch.zeros((batch_size, emb_dim))
            self.h = None
            self.y = None

        def forward(self, u: torch.Tensor | None = None, first: bool = True):
            if first:
                h = self.h_init
                u = self.u_init if (u is None or not isinstance(u, torch.Tensor) or u.shape != self.u_init.shape) \
                    else u
            else:
                h = self.h.detach()
                y_pred = torch.argmax(self.y.detach(), dim=-1).view(-1) if self.y.shape[-1] > 1 else self.y.detach()
                u = self.embeddings(y_pred)

            self.h = torch.tanh(self.A(h) + self.B(u))
            self.y = self.C(self.h)
            return self.y

    super(RNNTokenLM, self).__init__(module=Net(),
                                     proc_inputs=[StreamType(data_type="tensor", tensor_shape=(1,),
                                                             tensor_dtype=torch.long,
                                                             pubsub=False, private_only=False)],
                                     proc_outputs=[StreamType(data_type="tensor", tensor_shape=(y_dim,),
                                                              tensor_dtype=torch.float32,
                                                              pubsub=False, private_only=False)],
                                     *args, **kwargs)

A recurrent language model over tokens: an embedding of num_emb tokens of size emb_dim, a state of size h_dim and a linear output of y_dim logits.

Argument Type Default Meaning
num_emb int required The size of the vocabulary.
emb_dim int required The size of a token embedding.
y_dim int required The number of output logits.
h_dim int required The size of the state.
batch_size int 1 The batch size of the initial state and of the initial input.

On a call with first=False the module ignores its input and feeds the embedding of the argmax of its previous output. This makes it generate a sequence by itself. On a call with first=True it uses its input only when the input is already a float tensor of shape [batch_size, emb_dim]. Any other input makes it start from a zero vector. A token id is never embedded on the first step. During learning ModuleWrapper.learn_backward replaces the stored output y with the target and the next step reads the right token (teacher forcing).

The declared streams do not match what the module returns. The output stream has shape (y_dim,) while the module returns [batch_size, y_dim]. Every call through the wrapper raises ValueError: Expected data with shape (y_dim,), got torch.Size([1, y_dim]). The inner module works when called directly.

CSSM

CSSM(u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, sigma: Callable = tanh, project_every: int = 0, local: bool = False, batch_size: int = 1, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, sigma: Callable = F.tanh,
             project_every: int = 0, local: bool = False, batch_size: int = 1, *args, **kwargs):
    u_shape = torch.Size(u_shape)
    u_dim = u_shape.numel()
    du_dim = d_dim

    class Net(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.A = torch.nn.Linear(h_dim, h_dim, bias=False)
            self.B = torch.nn.Linear(u_dim + du_dim, h_dim, bias=False)
            self.C = torch.nn.Linear(h_dim, y_dim, bias=False)
            self.register_buffer('h_init', torch.randn((batch_size, h_dim)))
            self.register_buffer('h_next', torch.randn((batch_size, h_dim)))
            self.h = None
            self.dh = None
            self.sigma = sigma
            self.u_dim = u_dim
            self.du_dim = du_dim
            self.batch_size = batch_size
            self.delta = 1.
            self.local = local
            self.forward_count = 0
            self.project_every = project_every

        @torch.no_grad()
        def adjust_eigs(self):
            pass

        # noinspection PyUnusedLocal
        def init_h(self, udu: torch.Tensor) -> torch.Tensor:
            return self.h_init.data

        @staticmethod
        def handle_inputs(du, u):
            return du, u

        def forward(self, u: torch.Tensor, du: torch.Tensor, first: bool = True):
            device = self.h_init.device
            u = u.flatten(1).to(device) if u is not None else torch.zeros((self.batch_size, self.u_dim),
                                                                          device=device)
            du = du.to(device) if du is not None else torch.zeros((self.batch_size, self.du_dim), device=device)

            if first:
                h = self.init_h(torch.cat([du, u], dim=1))
                self.forward_count = 0
            else:
                h = self.h_next.data
            h.requires_grad_()

            if self.project_every:
                if self.forward_count % self.project_every == 0:
                    self.adjust_eigs()

            du, u = self.handle_inputs(du, u)
            h_new = self.A(h) + self.B(torch.cat([du, u], dim=1))

            if self.local:
                self.h = h
                self.dh = (h_new - self.h) / self.delta
            else:
                self.h = h_new
                self.dh = (self.h - h) / self.delta

            y = self.C(self.sigma(self.h))
            self.h_next.data = h_new.detach()
            self.forward_count += 1
            return y

    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_rnn(u_shape, du_dim, y_dim)
    super(CSSM, self).__init__(module=Net(), proc_inputs=proc_inputs, proc_outputs=proc_outputs,
                               *args, **kwargs)

A linear state-space network: h_new = A h + B [du, u] with a dense h_dim × h_dim matrix A. The output is C(sigma(h)) with sigma = torch.tanh by default. The projection of project_every does nothing in this class.

CDiagR

CDiagR(u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, sigma: Callable = lambda x: x, project_every: int = 0, local: bool = False, batch_size: int = 1, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, sigma: Callable = lambda x: x,
             project_every: int = 0, local: bool = False, batch_size: int = 1, *args, **kwargs):
    u_shape = torch.Size(u_shape)
    u_dim = u_shape.numel()
    du_dim = d_dim

    class Net(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.diag = torch.nn.Linear(in_features=1, out_features=h_dim, bias=False, dtype=torch.float32)
            self.B = torch.nn.Linear(u_dim + du_dim, h_dim, bias=False)
            self.C = torch.nn.Linear(h_dim, y_dim, bias=False)
            self.register_buffer('h_init', torch.randn((batch_size, h_dim)))
            self.register_buffer('h_next', torch.randn((batch_size, h_dim)))
            self.h = None
            self.dh = None
            self.sigma = sigma
            self.u_dim = u_dim
            self.du_dim = du_dim
            self.batch_size = batch_size
            self.delta = 1.
            self.local = local
            self.forward_count = 0
            self.project_every = project_every

        @torch.no_grad()
        def adjust_eigs(self):
            self.diag.weight.copy_(torch.sign(self.diag.weight))

        # noinspection PyUnusedLocal
        def init_h(self, udu: torch.Tensor) -> torch.Tensor:
            return self.h_init.data

        @staticmethod
        def handle_inputs(du, u):
            return du, u

        def forward(self, u: torch.Tensor, du: torch.Tensor, first: bool = True):
            device = self.h_init.device
            u = u.flatten(1).to(device) if u is not None else torch.zeros((self.batch_size, self.u_dim),
                                                                          device=device)
            du = du.to(device) if du is not None else torch.zeros((self.batch_size, self.du_dim), device=device)

            if first:
                h = self.init_h(torch.cat([du, u], dim=1))
                self.forward_count = 0
            else:
                h = self.h_next.data
            h.requires_grad_()

            if self.project_every:
                if self.forward_count % self.project_every == 0:
                    self.adjust_eigs()

            du, u = self.handle_inputs(du, u)
            h_new = self.diag.weight.view(self.diag.out_features) * h + self.B(torch.cat([du, u], dim=1))

            if self.local:
                self.h = h
                self.dh = (h_new - self.h) / self.delta
            else:
                self.h = h_new
                self.dh = (self.h - h) / self.delta

            y = self.C(self.sigma(self.h))
            self.h_next.data = h_new.detach()
            self.forward_count += 1
            return y

    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_rnn(u_shape, du_dim, y_dim)
    super(CDiagR, self).__init__(module=Net(), proc_inputs=proc_inputs, proc_outputs=proc_outputs,
                                 *args, **kwargs)

A state-space network with a diagonal real transition: h_new = a ⊙ h + B [du, u] where a is a learned vector of size h_dim. The projection replaces a with its sign and thus keeps each eigenvalue at +1 or -1.

CDiagC

CDiagC(u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, sigma: Callable = lambda x: x, project_every: int = 0, local: bool = False, batch_size: int = 1, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, sigma: Callable = lambda x: x,
             project_every: int = 0, local: bool = False, batch_size: int = 1, *args, **kwargs):
    u_shape = torch.Size(u_shape)
    u_dim = u_shape.numel()
    du_dim = d_dim

    class Net(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.diag = torch.nn.Linear(in_features=1, out_features=h_dim, bias=False, dtype=torch.cfloat)
            self.B = torch.nn.Linear(u_dim + du_dim, h_dim, bias=False, dtype=torch.cfloat)
            self.C = torch.nn.Linear(h_dim, y_dim, bias=False, dtype=torch.cfloat)
            self.register_buffer('h_init', torch.randn((batch_size, h_dim)))
            self.register_buffer('h_next', torch.randn((batch_size, h_dim)))
            self.h = None
            self.dh = None
            self.sigma = sigma
            self.u_dim = u_dim
            self.du_dim = du_dim
            self.batch_size = batch_size
            self.delta = 1.
            self.local = local
            self.forward_count = 0
            self.project_every = project_every

        @torch.no_grad()
        def adjust_eigs(self):
            self.diag.weight.div_(self.diag.weight.abs())

        # noinspection PyUnusedLocal
        def init_h(self, udu: torch.Tensor) -> torch.Tensor:
            return self.h_init.data

        @staticmethod
        def handle_inputs(du, u):
            return du, u

        def forward(self, u: torch.Tensor, du: torch.Tensor, first: bool = True):
            device = self.h_init.device
            u = u.flatten(1).to(device) if u is not None else torch.zeros((self.batch_size, self.u_dim),
                                                                          device=device, dtype=torch.cfloat)
            du = du.to(device) if du is not None else torch.zeros((self.batch_size, self.du_dim),
                                                                  device=device, dtype=torch.cfloat)

            if first:
                h = self.init_h(torch.cat([du, u], dim=1))
                self.forward_count = 0
            else:
                h = self.h_next.data
            h.requires_grad_()

            if self.project_every:
                if self.forward_count % self.project_every == 0:
                    self.adjust_eigs()

            du, u = self.handle_inputs(du, u)
            h_new = self.diag.weight.view(self.diag.out_features) * h + self.B(torch.cat([du, u], dim=1))

            if self.local:
                self.h = h
                self.dh = (h_new - self.h) / self.delta
            else:
                self.h = h_new
                self.dh = (self.h - h) / self.delta

            y = self.C(self.sigma(self.h))
            self.h_next.data = h_new.detach()
            self.forward_count += 1
            return y.real

    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_rnn(u_shape, du_dim, y_dim)
    super(CDiagC, self).__init__(module=Net(), proc_inputs=proc_inputs, proc_outputs=proc_outputs,
                                 *args, **kwargs)

The complex counterpart of CDiagR: a, B and C are complex (torch.cfloat) and the output is the real part of C(sigma(h)). The projection divides a by its modulus and thus puts every eigenvalue on the unit circle.

Real inputs fail

The input streams are torch.float32 while B is complex. A call with a real u or du raises RuntimeError: expected m1 and m2 to have the same dtype. Only a call where both inputs are None runs.

CTE

CTE(u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, delta: float, sigma: Callable = lambda x: x, project_every: int = 0, local: bool = False, cnu_memories: int = 0, batch_size: int = 1, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, delta: float,
             sigma: Callable = lambda x: x, project_every: int = 0, local: bool = False,
             cnu_memories: int = 0, batch_size: int = 1, *args, **kwargs):
    u_shape = torch.Size(u_shape)
    u_dim = u_shape.numel()
    du_dim = d_dim
    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_rnn(u_shape, du_dim, y_dim)
    super(CTE, self).__init__(
        module=_CTENet(u_dim, du_dim, y_dim, h_dim, delta, sigma, project_every, local,
                       cnu_memories, batch_size),
        proc_inputs=proc_inputs, proc_outputs=proc_outputs, *args, **kwargs)

A continuous-time network with an antisymmetric transition A = (W - Wᵀ) / 2, integrated exactly over a step of length delta under a constant input:

h_new = exp(A·delta) h + A⁻¹ (exp(A·delta) - I) B [du, u]

Because an antisymmetric matrix has imaginary eigenvalues, the free dynamics neither grow nor decay.

Argument Type Default Meaning
u_shape, d_dim, y_dim, h_dim, sigma, project_every, local, batch_size As in the shared table. The projection does nothing in this class.
delta float required The length of the integration step.
cnu_memories int 0 A positive value replaces the output layer C with a LinearCNU of cnu_memories keys. The CNU layer compares its keys with the input [du, u] and not with the state. It blends one memory per sample (the CNU argument delta=1) and moves its keys with beta_k equal to the integration step delta.

The step inverts A. Because an antisymmetric matrix of odd size is always singular, an odd h_dim makes the first call raise torch.linalg.LinAlgError. With cnu_memories > 0 the output weights are computed for a single sample and the network needs batch_size=1.

CTEInitStateBZeroInput

CTEInitStateBZeroInput(u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, delta: float, sigma: Callable = lambda x: x, project_every: int = 0, local: bool = False, cnu_memories: int = 0, batch_size: int = 1, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, delta: float,
             sigma: Callable = lambda x: x, project_every: int = 0, local: bool = False,
             cnu_memories: int = 0, batch_size: int = 1, *args, **kwargs):
    u_shape = torch.Size(u_shape)
    u_dim = u_shape.numel()
    du_dim = d_dim
    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_rnn(u_shape, du_dim, y_dim)

    class Net(_CTENet):
        @torch.no_grad()
        def init_h(self, udu: torch.Tensor) -> torch.Tensor:
            return self.B(udu).detach() / torch.sum(udu, dim=1)

        @staticmethod
        def handle_inputs(du, u):
            return torch.zeros_like(du), torch.zeros_like(u)

    super(CTEInitStateBZeroInput, self).__init__(
        module=Net(u_dim, du_dim, y_dim, h_dim, delta, sigma, project_every, local,
                   cnu_memories, batch_size),
        proc_inputs=proc_inputs, proc_outputs=proc_outputs, *args, **kwargs)

A CTE whose first sample fixes the initial state and whose dynamics then run without input. On first=True the state starts at B [du, u] divided by the sum of the elements of [du, u]. The input of every step, the first one included, is replaced by zeros before the transition. The arguments are those of CTE. The division is per sample and broadcasts correctly only with batch_size=1. An input whose elements sum to zero gives an infinite or undefined state.

CTEToken

CTEToken(num_emb: int, emb_dim: int, d_dim: int, y_dim: int, h_dim: int, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, num_emb: int, emb_dim: int, d_dim: int, y_dim: int, h_dim: int, *args, **kwargs):
    u_shape = torch.Size((emb_dim,))
    u_dim = u_shape.numel()
    du_dim = d_dim
    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_rnn(u_shape, du_dim, y_dim)

    class Net(_CTENet):
        def __init__(self):
            super().__init__(u_dim, du_dim, y_dim, h_dim, delta=1.0, sigma=lambda x: x,
                             project_every=0, local=False, cnu_memories=0, batch_size=1)
            self.embeddings = torch.nn.Embedding(num_emb, emb_dim)

        def forward(self, u: torch.Tensor | None, du: torch.Tensor | None,
                    first: bool = True, last: bool = False) -> torch.Tensor:
            if u is not None:
                u = self.embeddings(u.to(self.embeddings.weight.device))
            return super().forward(u, du, first=first, last=last)

    super(CTEToken, self).__init__(
        module=Net(), proc_inputs=proc_inputs, proc_outputs=proc_outputs, *args, **kwargs)

A CTE over tokens. An embedding of num_emb tokens of size emb_dim turns each token id into u and the network runs with delta=1, no projection, local=False and batch_size=1.

Argument Type Meaning
num_emb int The size of the vocabulary.
emb_dim int The size of a token embedding.
d_dim, y_dim, h_dim int As in the shared table.

The declared input stream is a torch.float32 tensor of shape (None, emb_dim) while the embedding needs integer ids. The wrapper rejects an integer tensor (Expected data of type torch.float32) and the embedding rejects a float one. A call through the wrapper fails either way. The inner module works when called directly with a torch.long tensor of ids.

CTB

CTB(u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, delta: float = 0.1, alpha: float = 0.0, sigma: Callable = lambda x: x, project_every: int = 0, local: bool = False, batch_size: int = 1, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, delta: float = 0.1,
             alpha: float = 0., sigma: Callable = lambda x: x, project_every: int = 0, local: bool = False,
             batch_size: int = 1, *args, **kwargs):
    u_shape = torch.Size(u_shape)
    u_dim = u_shape.numel()
    du_dim = d_dim
    assert h_dim % 2 == 0, "Hidden dimension must be even for 2x2 blocks"

    class Net(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.order = h_dim // 2
            self.omega = torch.nn.Parameter(torch.empty(self.order))
            self.register_buffer('ones', torch.ones(self.order, requires_grad=False))
            self.B = torch.nn.Linear(u_dim + du_dim, h_dim, bias=False)
            self.C = torch.nn.Linear(h_dim, y_dim, bias=False)

            assert alpha == -1. or alpha >= 0., "Invalid alpha value (must be -1, 0, or > 0)."

            if alpha > 0.:
                self.project_method = 'const'
                self.register_buffer('alpha', torch.full_like(self.omega.data, alpha))
            elif alpha == 0.:
                self.project_method = 'modulus'
                self.register_buffer('alpha', torch.zeros_like(self.omega.data))
            elif alpha == -1.:
                self.project_method = 'alpha'
                self.register_buffer('alpha', torch.zeros_like(self.omega.data))

            self.register_buffer('h_init', torch.randn((batch_size, h_dim)))
            self.register_buffer('h_next', torch.randn((batch_size, h_dim)))
            self.h = None
            self.dh = None
            self.sigma = sigma
            self.u_dim = u_dim
            self.du_dim = du_dim
            self.batch_size = batch_size
            self.delta = delta
            self.local = local
            self.forward_count = 0
            self.project_every = project_every
            self.reset_parameters()

        def reset_parameters(self) -> None:
            torch.nn.init.uniform_(self.omega)

        @torch.no_grad()
        def adjust_eigs(self):
            if self.project_method == 'alpha':
                self.alpha.copy_((1. - torch.sqrt(1. - (self.delta * self.omega) ** 2) / self.delta))
            elif self.project_method == 'modulus':
                module = torch.sqrt(self.ones ** 2 + (self.delta * self.omega) ** 2)
                self.omega.div_(module)
                self.ones.div_(module)

        # noinspection PyUnusedLocal
        def init_h(self, udu: torch.Tensor) -> torch.Tensor:
            return self.h_init.data

        @staticmethod
        def handle_inputs(du, u):
            return du, u

        def forward(self, u: torch.Tensor, du: torch.Tensor, first: bool = True):
            device = self.h_init.device
            u = u.flatten(1).to(device) if u is not None else torch.zeros((self.batch_size, self.u_dim),
                                                                          device=device)
            du = du.to(device) if du is not None else torch.zeros((self.batch_size, self.du_dim), device=device)

            if first:
                h = self.init_h(torch.cat([du, u], dim=1))
                self.forward_count = 0
            else:
                h = self.h_next.data
            h.requires_grad_()
            h_pair = h.view(-1, self.order, 2)

            if self.project_every:
                if self.forward_count % self.project_every == 0:
                    self.adjust_eigs()

            du, u = self.handle_inputs(du, u)
            h1 = (self.ones - self.delta * self.alpha) * h_pair[..., 0] + self.delta * self.omega * h_pair[..., 1]
            h2 = -self.delta * self.omega * h_pair[..., 0] + (self.ones - self.delta * self.alpha) * h_pair[..., 1]
            rec = torch.stack([h1, h2], dim=-1).flatten(start_dim=1)
            inp = self.delta * self.B(torch.cat([du, u], dim=1))

            h_new = rec + inp
            if self.local:
                self.h = h
                self.dh = (h_new - self.h) / self.delta
            else:
                self.h = h_new
                self.dh = (self.h - h) / self.delta

            y = self.C(self.sigma(self.h))
            self.h_next.data = h_new.detach()
            self.forward_count += 1
            return y

    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_rnn(u_shape, du_dim, y_dim)
    super(CTB, self).__init__(module=Net(), proc_inputs=proc_inputs, proc_outputs=proc_outputs,
                              *args, **kwargs)

A network of h_dim / 2 independent 2D rotations integrated with an explicit Euler step. Each pair (h_a, h_b) of the state evolves as

h_a ← (1 - delta·alpha) h_a + delta·omega h_b and h_b ← -delta·omega h_a + (1 - delta·alpha) h_b

and the input enters as delta · B [du, u]. The frequencies omega are learned and start uniform in [0, 1).

Argument Type Default Meaning
u_shape, d_dim, y_dim, h_dim, sigma, project_every, local, batch_size As in the shared table. An odd h_dim makes the constructor raise AssertionError.
delta float 0.1 The Euler step.
alpha float 0.0 The damping on the diagonal. It also chooses the projection.
alpha Damping Projection
> 0 Constant, equal to alpha. None.
0 None. Divides omega and the diagonal by sqrt(1 + (delta·omega)²) to put the eigenvalues of each block on the unit circle.
-1 Starts at zero. Replaces the damping with 1 - sqrt(1 - (delta·omega)²) / delta. With delta < 1 this value is negative and the blocks grow at every step. delta·omega > 1 gives NaN.

Any other negative alpha raises AssertionError.

CTBE

CTBE(u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, delta: float, sigma: Callable = lambda x: x, project_every: int = 0, local: bool = False, cnu_memories: int = 0, batch_size: int = 1, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, delta: float,
             sigma: Callable = lambda x: x, project_every: int = 0, local: bool = False,
             cnu_memories: int = 0, batch_size: int = 1, *args, **kwargs):
    u_shape = torch.Size(u_shape)
    u_dim = u_shape.numel()
    du_dim = d_dim
    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_rnn(u_shape, du_dim, y_dim)
    super(CTBE, self).__init__(
        module=_CTBENet(u_dim, du_dim, y_dim, h_dim, delta, sigma, project_every, local,
                        cnu_memories, batch_size),
        proc_inputs=proc_inputs, proc_outputs=proc_outputs, *args, **kwargs)

The exact counterpart of CTB without damping. Each pair of the state rotates by the angle omega·delta with cos and sin. The input term is the exact integral of the rotation over the step and contains a division by omega. A frequency close to zero therefore makes the input term large. The arguments are those of CTE (with delta required and cnu_memories available) and h_dim must be even. The projection does nothing in this class.

CTBEInitStateBZeroInput

CTBEInitStateBZeroInput(u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, delta: float, sigma: Callable = lambda x: x, project_every: int = 0, local: bool = False, cnu_memories: int = 0, batch_size: int = 1, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, u_shape: tuple[int], d_dim: int, y_dim: int, h_dim: int, delta: float,
             sigma: Callable = lambda x: x, project_every: int = 0, local: bool = False,
             cnu_memories: int = 0, batch_size: int = 1, *args, **kwargs):
    u_shape = torch.Size(u_shape)
    u_dim = u_shape.numel()
    du_dim = d_dim
    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_rnn(u_shape, du_dim, y_dim)

    class Net(_CTBENet):
        @torch.no_grad()
        def init_h(self, udu: torch.Tensor) -> torch.Tensor:
            return self.B(udu).detach() / torch.sum(udu)

        @staticmethod
        def handle_inputs(du, u):
            return torch.zeros_like(du), torch.zeros_like(u)

    super(CTBEInitStateBZeroInput, self).__init__(
        module=Net(u_dim, du_dim, y_dim, h_dim, delta, sigma, project_every, local,
                   cnu_memories, batch_size),
        proc_inputs=proc_inputs, proc_outputs=proc_outputs, *args, **kwargs)

A CTBE whose first sample fixes the initial state and whose dynamics then run without input in the same way as CTEInitStateBZeroInput. Here the initial state is B [du, u] divided by the sum of all the elements of the batch. This version accepts any batch_size.

Image classifiers and detection

The classifiers read one picture (proc_input_0, an img stream) and write one tensor (None, y_dim) of torch.float32 scores (proc_output_0). With d_dim > 0 the scores come from a sigmoid and lie in (0, 1). With d_dim = -1 (where accepted) the pretrained head stays in place and the output holds its 1000 ImageNet logits. The wrapper turns the picture into a batch of one with a transform of transforms_factory. ViT, DenseNet, EfficientNet and FasterRCNN apply their own transform inside the module instead.

CNN

CNN(d_dim: int, in_channels: int = 3, in_res: int = 32, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, d_dim: int, in_channels: int = 3, in_res: int = 32, *args, **kwargs):
    net = torch.nn.Sequential(
        torch.nn.Conv2d(in_channels, 64, kernel_size=5, padding=2),
        torch.nn.ReLU(inplace=True),
        torch.nn.AvgPool2d(kernel_size=3, stride=2),
        torch.nn.Conv2d(64, 128, kernel_size=5, padding=2),
        torch.nn.ReLU(inplace=True),
        torch.nn.AvgPool2d(kernel_size=3, stride=2),
        torch.nn.Conv2d(128, 256, kernel_size=3, padding=1),
        torch.nn.ReLU(inplace=True),
        torch.nn.AvgPool2d(kernel_size=3, stride=2),
        torch.nn.Flatten(),
        torch.nn.LazyLinear(2048),
        torch.nn.ReLU(inplace=True),
        torch.nn.Linear(2048, d_dim),
        torch.nn.Sigmoid())

    transforms = transforms_factory("rgb" + str(in_res) if in_channels == 3 else "gray" + str(in_res))
    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_image_classification(d_dim, transforms)
    super(CNN, self).__init__(net, proc_inputs=proc_inputs, proc_outputs=proc_outputs, *args, **kwargs)

A small convolutional network for tests: three convolutions of 64, 128 and 256 channels with ReLU and average pooling, then LazyLinear(2048), ReLU, Linear(2048, d_dim) and a sigmoid.

Argument Type Default Meaning
d_dim int required The number of outputs.
in_channels int 3 3 resizes the picture with "rgb<in_res>". Any other value uses "gray<in_res>".
in_res int 32 The side of the square picture after resize and center crop.

LazyLinear creates its weights on the first call. An optimizer built before that call does not see them.

CNNCNU

CNNCNU(d_dim: int, cnu_memories: int, in_channels: int = 3, in_res: int = 32, delta: int = 1, scramble: bool = False, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, d_dim: int, cnu_memories: int, in_channels: int = 3, in_res: int = 32,
             delta: int = 1, scramble: bool = False, *args, **kwargs):
    net = torch.nn.Sequential(
        torch.nn.Conv2d(in_channels, 64, kernel_size=5, padding=2),
        torch.nn.ReLU(inplace=True),
        torch.nn.AvgPool2d(kernel_size=3, stride=2),
        torch.nn.Conv2d(64, 128, kernel_size=5, padding=2),
        torch.nn.ReLU(inplace=True),
        torch.nn.AvgPool2d(kernel_size=3, stride=2),
        torch.nn.Conv2d(128, 256, kernel_size=3, padding=1),
        torch.nn.ReLU(inplace=True),
        torch.nn.AvgPool2d(kernel_size=3, stride=2),
        torch.nn.Flatten(),
        torch.nn.LazyLinear(2048),
        torch.nn.ReLU(inplace=True),
        LinearCNU(2048, d_dim, key_mem_units=cnu_memories, delta=delta, scramble=scramble),
        torch.nn.Sigmoid())

    transforms = transforms_factory("rgb" + str(in_res) if in_channels == 3 else "gray" + str(in_res))
    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_image_classification(d_dim, transforms)
    super(CNNCNU, self).__init__(net, proc_inputs=proc_inputs, proc_outputs=proc_outputs, *args, **kwargs)

CNN with a LinearCNU in place of Linear(2048, d_dim).

Argument Type Default Meaning
d_dim, in_channels, in_res As in CNN.
cnu_memories int required The keys and memories of the CNU layer.
delta int 1 How many memories each sample blends.
scramble bool False Scrambling of unused keys (see CNUs).

SingleLayerCNU

SingleLayerCNU(d_dim: int, cnu_memories: int, in_channels: int = 3, in_res: int = 32, delta: int = 1, scramble: bool = False, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, d_dim: int, cnu_memories: int, in_channels: int = 3, in_res: int = 32,
             delta: int = 1, scramble: bool = False, *args, **kwargs):
    net = torch.nn.Sequential(
        torch.nn.Flatten(),
        LinearCNU(in_res * in_res * in_channels, d_dim, key_mem_units=cnu_memories, delta=delta, scramble=scramble),
        torch.nn.Sigmoid())

    transforms = transforms_factory("rgb" + str(in_res) if in_channels == 3 else "gray" + str(in_res))
    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_image_classification(d_dim, transforms)
    super(SingleLayerCNU, self).__init__(net, proc_inputs=proc_inputs, proc_outputs=proc_outputs, *args, **kwargs)

A single LinearCNU from the flattened picture (in_res · in_res · in_channels values) to d_dim outputs and a sigmoid after it. The arguments are those of CNNCNU.

CNNMNIST

CNNMNIST(*args, **kwargs)

Bases: CNN

Source code in unaiverse/modules/networks.py
def __init__(self, *args, **kwargs):
    kwargs['in_channels'] = 1
    kwargs['in_res'] = 28
    super(CNNMNIST, self).__init__(*args, **kwargs)
    for p in self.proc_inputs:
        for prop in p.props:
            prop.set_stream_to_proc_transforms(transforms_factory("gray_mnist"))

CNN for MNIST: it forces in_channels=1 and in_res=28 and replaces the input transform with "gray_mnist". The arguments in_channels and in_res must not be passed by position.

Every call fails

The three MNIST classes replace the transform through set_stream_to_proc_transforms. That method stores a single transform where the stream expects a pair. Every call raises TypeError: 'Compose' object is not subscriptable. CNN(d_dim, in_channels=1, in_res=28) runs with the generic grayscale transform.

CNNCNUMNIST

CNNCNUMNIST(*args, **kwargs)

Bases: CNNCNU

Source code in unaiverse/modules/networks.py
def __init__(self, *args, **kwargs):
    kwargs['in_channels'] = 1
    kwargs['in_res'] = 28
    super(CNNCNUMNIST, self).__init__(*args, **kwargs)
    for p in self.proc_inputs:
        for prop in p.props:
            prop.set_stream_to_proc_transforms(transforms_factory("gray_mnist"))

CNNCNU for MNIST, built as CNNMNIST and affected by the same failure.

SingleLayerCNUMNIST

SingleLayerCNUMNIST(*args, **kwargs)

Bases: SingleLayerCNU

Source code in unaiverse/modules/networks.py
def __init__(self, *args, **kwargs):
    kwargs['in_channels'] = 1
    kwargs['in_res'] = 28
    super(SingleLayerCNUMNIST, self).__init__(*args, **kwargs)
    for p in self.proc_inputs:
        for prop in p.props:
            prop.set_stream_to_proc_transforms(transforms_factory("gray_mnist"))

SingleLayerCNU for MNIST, built as CNNMNIST and affected by the same failure.

ResNet

ResNet(d_dim: int = -1, freeze_backbone: bool = True, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, d_dim: int = -1, freeze_backbone: bool = True, *args, **kwargs):
    net = torchvision.models.resnet50(weights="IMAGENET1K_V1")
    if freeze_backbone:
        for p in net.parameters():
            p.requires_grad = False
        for p in net.fc.parameters():
            p.requires_grad = True

    if d_dim > 0:
        net.fc = torch.nn.Sequential(
            torch.nn.Linear(net.fc.in_features, d_dim),
            torch.nn.Sigmoid())

    transforms = transforms_factory("rgb224")
    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_image_classification(d_dim, transforms)
    super(ResNet, self).__init__(net, proc_inputs=proc_inputs, proc_outputs=proc_outputs, *args, **kwargs)

A torchvision ResNet-50 with the IMAGENET1K_V1 weights that torchvision downloads on first use. The input transform is "rgb224".

Argument Type Default Meaning
d_dim int -1 -1 keeps the ImageNet head (1000 logits). A positive value replaces it with Linear(2048, d_dim) and a sigmoid.
freeze_backbone bool True True freezes every parameter except those of the last layer.

ResNetCNU

ResNetCNU(d_dim: int, cnu_memories: int, delta: int = 1, scramble: bool = False, freeze_backbone: bool = True, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, d_dim: int, cnu_memories: int,
             delta: int = 1, scramble: bool = False, freeze_backbone: bool = True, *args, **kwargs):
    net = torchvision.models.resnet50(weights="IMAGENET1K_V1")
    if freeze_backbone:
        for p in net.parameters():
            p.requires_grad = False
        for p in net.fc.parameters():
            p.requires_grad = True

    if d_dim > 0:
        net.fc = torch.nn.Sequential(
            LinearCNU(net.fc.in_features, d_dim, key_mem_units=cnu_memories, delta=delta, scramble=scramble),
            torch.nn.Sigmoid())

    transforms = transforms_factory("rgb224")
    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_image_classification(d_dim, transforms)
    super(ResNetCNU, self).__init__(net, proc_inputs=proc_inputs, proc_outputs=proc_outputs, *args, **kwargs)

ResNet with a LinearCNU(2048, d_dim) and a sigmoid as last layer. The arguments d_dim and cnu_memories (both required), delta=1, scramble=False and freeze_backbone=True mean what they mean for ResNet and CNNCNU. With d_dim <= 0 the ImageNet head stays in place.

ViT

ViT(d_dim: int = -1, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, d_dim: int = -1, *args, **kwargs):
    weights = torchvision.models.ViT_B_16_Weights.IMAGENET1K_V1
    transforms = torchvision.transforms.Compose([
        weights.transforms(),
        torchvision.transforms.Lambda(lambda x: x.unsqueeze(0))  # Add batch dimension
    ])
    vit = torchvision.models.vit_b_16(weights=weights)

    if d_dim > 0:
        vit.heads = torch.nn.Sequential(
            torch.nn.Linear(vit.heads.head.in_features, 2048),
            torch.nn.ReLU(inplace=True),
            torch.nn.Linear(2048, d_dim),
            torch.nn.Sigmoid()
        )
        self.labels = ["unk"] * d_dim
    else:
        url = "https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt"
        with urllib.request.urlopen(url) as f:
            self.labels = [line.strip().decode('utf-8') for line in f.readlines()]

    class Net(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.backbone = vit
            self.tfm = transforms

        def forward(self, y: Image.Image):
            device = next(self.backbone.parameters()).device
            return self.backbone(self.tfm(y).to(device))

    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_image_classification(d_dim)
    super(ViT, self).__init__(module=Net(), proc_inputs=proc_inputs, proc_outputs=proc_outputs, *args, **kwargs)

A torchvision ViT-B/16 with the IMAGENET1K_V1 weights and their own preprocessing. d_dim > 0 replaces the head with Linear(768, 2048), ReLU, Linear(2048, d_dim) and a sigmoid. Nothing is frozen. The attribute labels holds the class names. With d_dim > 0 they are "unk". With d_dim = -1 the constructor downloads the 1000 ImageNet names from https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt and fails without network access.

DenseNet

DenseNet(d_dim: int = -1, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, d_dim: int = -1, *args, **kwargs):
    transforms = transforms_factory("rgb224")
    densenet = torchvision.models.densenet121(weights=None)

    if d_dim > 0:
        densenet.classifier = torch.nn.Sequential(
            torch.nn.Linear(densenet.classifier.in_features, 2048),
            torch.nn.ReLU(inplace=True),
            torch.nn.Linear(2048, d_dim),
            torch.nn.Sigmoid()
        )

    class Net(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.backbone = densenet
            self.tfm = transforms

        def forward(self, y: Image.Image):
            device = next(self.backbone.parameters()).device
            return self.backbone(self.tfm(y).to(device))

    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_image_classification(d_dim)
    super(DenseNet, self).__init__(module=Net(), proc_inputs=proc_inputs, proc_outputs=proc_outputs,
                                   *args, **kwargs)

A torchvision DenseNet-121 built with weights=None. Its weights are random and the 1000 outputs of d_dim = -1 carry no meaning until the network is trained. d_dim > 0 replaces the classifier as in ViT.

EfficientNet

EfficientNet(d_dim: int = -1, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, d_dim: int = -1, *args, **kwargs):
    weights = torchvision.models.EfficientNet_B0_Weights.IMAGENET1K_V1
    transforms = torchvision.transforms.Compose([
        weights.transforms(),
        torchvision.transforms.Lambda(lambda x: x.unsqueeze(0))  # Add batch dimension
    ])
    effnet = torchvision.models.efficientnet_b0(weights=weights)

    if d_dim > 0:
        effnet.classifier = torch.nn.Sequential(
            torch.nn.Linear(effnet.classifier[1].in_features, 2048),
            torch.nn.ReLU(inplace=True),
            torch.nn.Linear(2048, d_dim),
            torch.nn.Sigmoid()
        )

    class Net(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.backbone = effnet
            self.tfm = transforms

        def forward(self, y: Image.Image):
            device = next(self.backbone.parameters()).device
            o = self.backbone(self.tfm(y).to(device))
            if o.dim() == 1:
                o = o.unsqueeze(0)
            return o

    proc_inputs, proc_outputs = get_proc_inputs_and_proc_outputs_for_image_classification(d_dim)
    super(EfficientNet, self).__init__(module=Net(), proc_inputs=proc_inputs, proc_outputs=proc_outputs,
                                       *args, **kwargs)

A torchvision EfficientNet-B0 with the IMAGENET1K_V1 weights and their own preprocessing. d_dim > 0 replaces the classifier as in ViT.

FasterRCNN

FasterRCNN(*args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, *args, **kwargs):
    self.labels: list[str] = ['__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
                              'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
                              'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
                              'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A',
                              'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
                              'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
                              'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
                              'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
                              'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table',
                              'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard',
                              'cell phone',
                              'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',
                              'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'
                              ]
    labels = self.labels

    weights = torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights.DEFAULT
    faster_rcnn = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights=weights)
    faster_rcnn.eval()
    transforms = torchvision.transforms.Compose([transforms_factory("rgb-no_norm"),
                                                 torchvision.transforms.Lambda(lambda x: x.squeeze(0)),
                                                 weights.transforms()])

    class Net(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self.backbone = faster_rcnn
            self.tfm = transforms
            self.labels = labels

        def forward(self, y: Image.Image):
            device = next(self.backbone.parameters()).device
            o = self.backbone([self.tfm(y).to(device)])  # List with 1 image per element (no batch dim)

            found_class_indices = o[0]['labels']
            found_class_scores = o[0]['scores']
            found_class_boxes = o[0]['boxes']
            valid = found_class_scores > 0.8

            found_class_indices: torch.Tensor = found_class_indices[valid]
            found_class_scores = found_class_scores[valid]
            found_class_boxes = found_class_boxes[valid]
            found_class_names: list[str] = [self.labels[int(i.item())] for i in found_class_indices]

            return found_class_indices, found_class_scores, found_class_boxes, ", ".join(found_class_names)

    super(FasterRCNN, self).__init__(
        module=Net(),
        proc_inputs=[StreamType(data_type="img", pubsub=False, private_only=False)],
        proc_outputs=[StreamType(data_type="tensor", tensor_dtype=torch.long, tensor_shape=(None,),
                                 pubsub=False, private_only=False),
                      StreamType(data_type="tensor", tensor_dtype=torch.float32, tensor_shape=(None,),
                                 pubsub=False, private_only=False),
                      StreamType(data_type="tensor", tensor_dtype=torch.float32, tensor_shape=(None, 4),
                                 pubsub=False, private_only=False),
                      StreamType(data_type="text",
                                 pubsub=False, private_only=False)],
        *args, **kwargs)

Object detection with the torchvision Faster R-CNN ResNet-50 FPN in evaluation mode (DEFAULT weights, COCO classes). It reads one picture and writes four streams:

Stream Kind Content
proc_output_0 tensor torch.long, shape (None,) The class index of each detected object.
proc_output_1 tensor torch.float32, shape (None,) The score of each object.
proc_output_2 tensor torch.float32, shape (None, 4) The box of each object as (x1, y1, x2, y2) in pixels.
proc_output_3 text The names of the objects separated by ", ".

Only the objects with a score above 0.8 are kept. The threshold is fixed. The attribute labels is the list of 91 COCO names indexed by class ("N/A" for the unused indices).

Language and vision models that run locally

These classes download their model from Hugging Face the first time and run it on device (the argument, then PROC_DEVICE, then the CPU). A gated model needs a Hugging Face login on an account that has accepted its license.

TinyLLama

TinyLLama(device=None, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, device=None, *args, **kwargs):

    class Net(torch.nn.Module):
        def __init__(self, _device):
            super().__init__()
            self.__pipe = pipeline("text-generation", model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
                                   torch_dtype=torch.bfloat16, device=_device)

        def forward(self, msg: str) -> str:
            msg_struct = [{"role": "system", "content": "You are a helpful assistant"},
                          {"role": "user", "content": msg}]
            assert self.__pipe.tokenizer is not None
            prompt = self.__pipe.tokenizer.apply_chat_template(msg_struct, tokenize=False,
                                                               add_generation_prompt=True)
            assert isinstance(prompt, str)
            out: list = self.__pipe(prompt, max_new_tokens=256, do_sample=True, temperature=0.7,
                                    top_k=50, top_p=0.95)
            out: str = out[0]["generated_text"] if (out is not None and len(out) > 0 and
                                                    "generated_text" in out[0]) else "Error!"
            if "<|assistant|>\n" in out:
                out = out.split("<|assistant|>\n")[1]
            return out.strip()

    # Populate self.device
    self.guess_device(device)

    super(TinyLLama, self).__init__(
        module=Net(self.device),
        device=device,
        proc_inputs=[StreamType(data_type="text", pubsub=False, private_only=False)],
        proc_outputs=[StreamType(data_type="text", pubsub=False, private_only=False)],
        *args, **kwargs
    )

TinyLlama/TinyLlama-1.1B-Chat-v1.0 in bfloat16. It reads one text stream and writes one text stream. Each call wraps the message in a chat with the system prompt "You are a helpful assistant" and samples up to 256 new tokens with temperature=0.7, top_k=50 and top_p=0.95. The answer is the stripped text after the last assistant tag. An empty generation returns "Error!".

LLama

LLama(device=None, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, device=None, *args, **kwargs):

    class Net(torch.nn.Module):
        def __init__(self, _device):
            super().__init__()
            self.__pipe = pipeline("text-generation", model="meta-llama/Llama-3.2-3B-Instruct",
                                   torch_dtype=torch.bfloat16, device=_device)

        def forward(self, msg: str) -> str:
            msg_struct = [{"role": "system", "content": "You are a helpful assistant"},
                          {"role": "user", "content": msg}]
            assert self.__pipe.tokenizer is not None
            prompt = self.__pipe.tokenizer.apply_chat_template(msg_struct, tokenize=False,
                                                               add_generation_prompt=True)
            assert isinstance(prompt, str)
            out = self.__pipe(prompt, max_new_tokens=256, do_sample=True, return_full_text=False,
                              temperature=0.7, top_k=50, top_p=0.95)
            out = out[0]["generated_text"] if (out is not None and len(out) > 0 and
                                               "generated_text" in out[0]) else "Error!"
            if "<|assistant|>\n" in out:
                out = out.split("<|assistant|>\n")[1]
            return out.strip()

    # Populate self.device
    self.guess_device(device)

    super(LLama, self).__init__(
        module=Net(self.device),
        device=device,
        proc_inputs=[StreamType(data_type="text", pubsub=False, private_only=False)],
        proc_outputs=[StreamType(data_type="text", pubsub=False, private_only=False)],
        *args, **kwargs
    )

meta-llama/Llama-3.2-3B-Instruct in bfloat16 (a gated model). Streams, prompt and sampling are those of TinyLLama. The pipeline returns only the generated text.

Phi

Phi(device=None, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, device=None, *args, **kwargs):
    class Net(torch.nn.Module):
        def __init__(self, _device):
            super().__init__()
            self.__pipe = pipeline("text-generation", model="microsoft/Phi-3.5-mini-instruct",
                                   torch_dtype="auto", device=_device)

        def forward(self, msg: str) -> str:
            msg_struct = [{"role": "system", "content": "You are a helpful assistant"},
                          {"role": "user", "content": msg}]
            assert self.__pipe.tokenizer is not None
            prompt = self.__pipe.tokenizer.apply_chat_template(msg_struct, tokenize=False,
                                                               add_generation_prompt=True)
            assert isinstance(prompt, str)
            out_: list = self.__pipe(prompt, max_new_tokens=256, do_sample=True, return_full_text=False)
            out: str = out_[0]["generated_text"] if (out_ is not None and len(out_) > 0 and
                                                     "generated_text" in out_[0]) else "Error!"
            if "<|assistant|>\n" in out:
                out = out.split("<|assistant|>\n")[1]
            return out.strip()

    # Populate self.device
    self.guess_device(device)

    super(Phi, self).__init__(
        module=Net(self.device),
        device=device,
        proc_inputs=[StreamType(data_type="text", pubsub=False, private_only=False)],
        proc_outputs=[StreamType(data_type="text", pubsub=False, private_only=False)],
        *args, **kwargs
    )

microsoft/Phi-3.5-mini-instruct with the dtype chosen by transformers. Streams and prompt are those of TinyLLama. It samples up to 256 new tokens with the default sampling options of the model.

SmolVLM

SmolVLM(device=None, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, device=None, *args, **kwargs):
    from transformers import AutoModelForImageTextToText

    class Net(torch.nn.Module):
        def __init__(self, _device):
            super().__init__()
            model_id = "HuggingFaceTB/SmolVLM2-500M-Video-Instruct"
            self.__backbone = (
                AutoModelForImageTextToText.from_pretrained(model_id,
                                                            torch_dtype=torch.bfloat16,
                                                            device_map=_device).to(_device))
            self.__pp = AutoProcessor.from_pretrained(model_id, device_map=_device)

        def forward(self, image_pil: Image.Image, msg: str = "what is this?"):
            image_pil = image_pil.convert("RGB") if image_pil.mode != "RGB" else image_pil  # Forcing RGB
            _device = next(self.__backbone.parameters()).device

            msg_struct = [{"role": "user", "content": [{"type": "text", "text": f"{msg}"},
                                                       {"type": "image", "image": image_pil}]}]

            prompt = self.__pp.apply_chat_template(msg_struct,
                                                   tokenize=True,
                                                   add_generation_prompt=True,
                                                   return_dict=True,
                                                   return_tensors="pt").to(_device, dtype=torch.bfloat16)

            out = self.__backbone.generate(**prompt, do_sample=False, max_new_tokens=128)
            out = self.__pp.batch_decode(out, skip_special_tokens=True)[0] if out is not None else "Error!"
            if "Assistant:" in out:
                out = out.split("Assistant:")[1]
            return out.strip()

    # Populate self.device
    self.guess_device(device)

    super(SmolVLM, self).__init__(
        module=Net(self.device),
        device=device,
        proc_inputs=[StreamType(data_type="img", pubsub=False, private_only=False),
                     StreamType(data_type="text", pubsub=False, private_only=False)],
        proc_outputs=[StreamType(data_type="text", pubsub=False, private_only=False)],
        *args, **kwargs
    )

HuggingFaceTB/SmolVLM2-500M-Video-Instruct in bfloat16. It reads a picture (proc_input_0) and a text (proc_input_1) and writes a text. The module converts the picture to RGB, asks the question with greedy decoding and up to 128 new tokens and returns the text after "Assistant:". A call without text asks "what is this?".

LangSegmentAnything

LangSegmentAnything(device=None, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, device=None, *args, **kwargs):
    from lang_sam import LangSAM
    from PIL import ImageDraw, ImageFont

    class Net(torch.nn.Module):
        def __init__(self, _device):
            super().__init__()

            # Generate a 64x64 error image (with text "Error" on it)
            error_img = Image.new("RGB", (64, 64), color="white")
            draw = ImageDraw.Draw(error_img)
            font = ImageFont.load_default()
            text = "Error"
            bbox = draw.textbbox((0, 0), text, font=font)
            text_width = bbox[2] - bbox[0]
            text_height = bbox[3] - bbox[1]
            position = ((64 - text_width) // 2, (64 - text_height) // 2)
            draw.text(position, text, fill="black", font=font)

            self.__sam = LangSAM(device=_device)
            self.__error_img = error_img

        def forward(self, image_pil: Image.Image, msg: str):
            try:
                image_pil = image_pil.convert("RGB") if image_pil.mode != "RGB" else image_pil  # Forcing RGB
                out = self.__sam.predict([image_pil], [msg])
                if (out is None or not isinstance(out, list) or len(out) < 1 or not isinstance(out[0], dict) or
                        'masks' not in out[0]) or out[0]['masks'].ndim != 3:
                    return image_pil
                else:
                    return LangSegmentAnything.highlight_masks_on_image(image_pil, out[0]['masks'])
            except Exception:
                return self.__error_img

    # Populate self.device
    self.guess_device(device)

    super(LangSegmentAnything, self).__init__(
        module=Net(self.device),
        device=device,
        proc_inputs=[StreamType(data_type="img", pubsub=False, private_only=False),
                     StreamType(data_type="text", pubsub=False, private_only=False)],
        proc_outputs=[StreamType(data_type="img", pubsub=False, private_only=False)],
        *args, **kwargs
    )

Segmentation guided by text with LangSAM of the lang_sam package. The package is not a dependency of the SDK and the constructor raises ImportError without it. It reads a picture and a text and writes a picture: the input with the masks of the objects named by the text painted over it. A picture without masks comes back unchanged. Any exception during the call returns a 64 × 64 white picture with the word Error.

highlight_masks_on_image staticmethod

highlight_masks_on_image(image_pil: Image, masks: ndarray, alpha: float = 0.75)
Source code in unaiverse/modules/networks.py
@staticmethod
def highlight_masks_on_image(image_pil: Image.Image, masks: np.ndarray, alpha: float = 0.75):
    img_np = np.array(image_pil, dtype=np.float32) / 255.0
    height, width, _ = img_np.shape
    num_masks = masks.shape[0]

    overlay_np = np.zeros((height, width, 3), dtype=np.float32)
    alpha_mask_combined = np.zeros((height, width, 1), dtype=np.float32)

    color_palette = [
        (255, 102, 102),  # Light Red
        (102, 255, 102),  # Light Green
        (102, 102, 255),  # Light Blue
        (255, 255, 102),  # Light Yellow
        (255, 102, 255),  # Light Magenta
        (102, 255, 255),  # Light Cyan
        (255, 178, 102),  # Orange
        (178, 102, 255),  # Purple
        (102, 178, 255),  # Sky Blue
    ]

    for i in range(num_masks):
        mask = masks[i, :, :].astype(np.bool)

        color_rgb_int = color_palette[i % len(color_palette)]
        color = np.array(color_rgb_int, dtype=np.float32) / 255.0
        overlay_np[mask] = (1 - alpha) * overlay_np[mask] + alpha * color
        alpha_mask_combined[mask] = np.maximum(alpha_mask_combined[mask], alpha)

    # Final blending and conversion ...
    final_np = (1 - alpha_mask_combined) * img_np + alpha_mask_combined * overlay_np
    final_np = (final_np * 255).astype(np.uint8)
    final_image = Image.fromarray(final_np)
    return final_image

A static method that paints masks on a picture and returns a new RGB PIL.Image.

Argument Type Default Meaning
image_pil PIL.Image.Image required An RGB picture of size W × H.
masks numpy.ndarray required The masks of shape [n, H, W]. Each one is nonzero inside its region.
alpha float 0.75 The opacity of the colors.

The colors cycle over a palette of nine light colors. The method uses numpy.bool. NumPy provides it before 1.24 and from 2.0 on.

SiteRAG

SiteRAG(site_url: str, site_folder: str = join('rag', 'downloaded_site'), db_folder: str = join('rag', 'chroma_db'), *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self,
             site_url: str,
             site_folder: str = os.path.join("rag", "downloaded_site"),
             db_folder: str = os.path.join("rag", "chroma_db"),
             *args, **kwargs):
    # Saving options
    self.site_url = site_url
    self.site_folder = site_folder
    self.db_folder = db_folder

    # Loading neural model
    device_env = os.getenv("PROC_DEVICE", None)
    target_device = torch.device("cpu") if device_env is None else torch.device(device_env)
    model_id = "TheBloke/vicuna-7b-1.1-HF"
    tokenizer = AutoTokenizer.from_pretrained(model_id)  # noqa
    model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16,
                                                 device_map=target_device, offload_folder="offload")
    pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=200)

    # Embedder
    from langchain.embeddings import SentenceTransformerEmbeddings
    self.embedder = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2",
                                                  model_kwargs={"device": target_device.type})

    # Crawling site (uses self.embedder + self.site_folder + self.db_folder + self.site_url)
    self.crawl_website()
    self.crawled_site_to_rag_knowledge_base()

    # Setting up RAG stuff
    from langchain.vectorstores import Chroma
    db = Chroma(persist_directory=db_folder, embedding_function=self.embedder)
    retriever = db.as_retriever(search_kwargs={"k": 3})

    class Net(torch.nn.Module):
        def __init__(self):
            super().__init__()
            self._pipe = pipe
            self._retriever = retriever

        def forward(self, msg: str):
            # Build context
            docs = self._retriever.get_relevant_documents(msg)
            context = "\n\n".join(doc.page_content for doc in docs)
            prompt = f"Answer the question based on the following context:\n\n{context}\n\nQuestion: {msg}\nAnswer:"

            # Generate answer
            out = self._pipe(prompt, max_new_tokens=256, do_sample=True, temperature=0.7)
            out = out[0]['generated_text'][len(prompt):].strip() if (out is not None and len(out) > 0 and
                                                                     "generated_text" in out[0]) else "Error!"

            # Append source URLs
            best_doc_with_score = self._retriever.vectorstore.similarity_search_with_score(msg, k=1)
            best_doc, _ = best_doc_with_score[0]
            docs = [best_doc]
            sources = set("<a href='" +
                          doc.metadata['source'] +
                          "' onclick='window.open(this.href); return false;' style='color: blue;'>" +
                          doc.metadata['source'] + "</a>" for doc in docs)
            sources_text = "<br/><br/>\nURLs:\n" + "\n".join(sources)

            return out.strip() + sources_text

    super(SiteRAG, self).__init__(
        module=Net(),
        proc_inputs=[StreamType(data_type="text", pubsub=False, private_only=False)],
        proc_outputs=[StreamType(data_type="text", pubsub=False, private_only=False)],
        *args, **kwargs
    )

Question answering over the pages of one web site with retrieval-augmented generation. The constructor does all the preparation:

  1. It loads TheBloke/vicuna-7b-1.1-HF in float16 on PROC_DEVICE (or the CPU) with offload_folder="offload" in the working directory.
  2. It loads the embedder all-MiniLM-L6-v2.
  3. It calls crawl_website() and crawled_site_to_rag_knowledge_base().
  4. It opens the vector store in db_folder with a retriever of the 3 closest chunks.
Argument Type Default Meaning
site_url str required The first page. The crawler follows only the links that start with this string.
site_folder str "rag/downloaded_site" The folder of the downloaded pages. The constructor deletes it with all its content and creates it again.
db_folder str "rag/chroma_db" The folder of the vector store.

The class needs packages that the SDK does not declare: requests, beautifulsoup4, chromadb, sentence-transformers and a release of langchain that still provides the import paths langchain.embeddings, langchain.vectorstores, langchain.docstore and langchain.text_splitter. It reads one text stream and writes one text stream. The answer is the generated text (sampling with temperature=0.7, up to 256 tokens) followed by <br/><br/> and an HTML link to the page closest to the question.

crawl_website

crawl_website(max_pages=300)
Source code in unaiverse/modules/networks.py
def crawl_website(self, max_pages=300):
    import requests
    from bs4 import BeautifulSoup
    from urllib.parse import urljoin, urlparse

    if os.path.exists(self.site_folder):
        shutil.rmtree(self.site_folder)
    os.makedirs(self.site_folder)
    visited = set()
    to_visit = [self.site_url]

    while to_visit and len(visited) < max_pages:
        url = to_visit.pop(0)
        if url in visited:
            continue
        visited.add(url)

        try:
            r = requests.get(url, timeout=10)
            if "text/html" not in r.headers.get("Content-Type", ""):
                continue

            parsed = urlparse(url)
            filename = parsed.path.strip("/") or "index.html"
            filename += ".crawled"
            file_path = os.path.join(self.site_folder, filename.replace("/", "__"))
            with open(file_path, "w", encoding="utf-8") as f:
                f.write(r.text)

            soup = BeautifulSoup(r.text, "html.parser")
            for link in soup.find_all("a", href=True):
                link: dict
                full_url = urljoin(url, link["href"])
                if full_url.startswith(self.site_url) and full_url not in visited:
                    to_visit.append(full_url)
        except Exception as e:
            print(f"Error fetching {url}: {e}")

    print(f"Crawled {len(visited)} pages.")

Downloads up to max_pages pages (default 300) breadth-first from site_url into site_folder. The method deletes site_folder first. It keeps only the responses of type text/html and saves each one as <path>.crawled with / replaced by __ (index.html.crawled for the root). A request times out after 10 seconds. Errors are printed and skipped. The constructor calls it.

crawled_site_to_rag_knowledge_base

crawled_site_to_rag_knowledge_base()
Source code in unaiverse/modules/networks.py
def crawled_site_to_rag_knowledge_base(self):
    from bs4 import BeautifulSoup
    from urllib.parse import urljoin
    from langchain.vectorstores import Chroma
    from langchain.docstore.document import Document
    from langchain.text_splitter import RecursiveCharacterTextSplitter

    docs = []
    for filename in os.listdir(self.site_folder):
        if filename.endswith(".crawled"):
            file_path = os.path.join(self.site_folder, filename)
            with open(file_path, encoding="utf-8") as f:
                html = f.read()

            soup: BeautifulSoup = BeautifulSoup(html, "html.parser")
            text = soup.get_text(separator=" ", strip=True)  # Type: ignore

            page_path = filename.replace("__", "/").replace(".crawled", "")
            url = urljoin(self.site_url, page_path)

            docs.append(Document(page_content=text, metadata={"source": url}))

    splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
    split_docs = splitter.split_documents(docs)

    chroma_db = Chroma.from_documents(split_docs, self.embedder, persist_directory=self.db_folder)
    chroma_db.persist()

Extracts the text of every .crawled file in site_folder, splits it into chunks of 1000 characters with an overlap of 100, embeds the chunks and writes them to a persistent vector store in db_folder. Each chunk keeps the URL of its page as source. The constructor calls it after crawl_website().

Hosted language models

Both clients read one text stream and write one text stream. They accept the same sampling options. An option left at its default (a negative number or None) is not sent and the provider applies its own default. The options that the OpenAI chat-completions API accepts as named fields (OPENAI_NATIVE_SAMPLER_PARAMS in utils) go into those fields. Every other option (top_k, repetition_penalty, min_p and the keys of sampler) travels in the extra body of the request.

Argument Type Default Meaning
system_prompt str "" The system message of every call. "" sends no system message.
max_tokens int -1 The maximum number of generated tokens. Sent only when positive.
temperature float -1.0 Sent only when >= 0.
top_p float -1.0 Sent only when >= 0.
top_k int -1 Sent only when >= 0.
frequency_penalty float or None None Sent only when not None.
presence_penalty float or None None Sent only when not None.
repetition_penalty float or None None Sent only when not None. Providers without it ignore it.
min_p float or None None Sent only when not None. Providers without it ignore it.
sampler dict or None None Any other option. Its keys are merged last and win over the arguments above.

These clients report a failure through log.critical and the call raises unaiverse.custom.GenException.

FeatherlessAPI

FeatherlessAPI(model: str | None = None, cost: int = 1, system_prompt: str = '', process_id: str | None = None, max_tokens: int = -1, temperature: float = -1.0, top_p: float = -1.0, top_k: int = -1, frequency_penalty: float | None = None, presence_penalty: float | None = None, repetition_penalty: float | None = None, min_p: float | None = None, sampler: dict | None = None, connect_timeout: float = 15.0, api_key: str | None = None, key_units: int | None = None, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, model: str | None = None, cost: int = 1, system_prompt: str = "",
             process_id: str | None = None, max_tokens: int = -1, temperature: float = -1.,
             top_p: float = -1., top_k: int = -1, frequency_penalty: float | None = None,
             presence_penalty: float | None = None, repetition_penalty: float | None = None,
             min_p: float | None = None, sampler: dict | None = None, connect_timeout: float = 15.0,
             api_key: str | None = None, key_units: int | None = None,
             *args, **kwargs):
    """Create a FeatherlessAPI handle and connect it to the shared gateway.

    Args:
        model: The model identifier used for every call (None lets the server fall back to its MODEL_ID default).
        cost: The unit cost charged for every call (one of VALID_COSTS) (Default: 1).
        system_prompt: The system prompt prepended to every call ("" means no system prompt) (Default: "").
        process_id: Identifier used for round-robin fairness; defaults to this process's PID.
        max_tokens: Maximum number of tokens to generate per call (-1 means no limit) (Default: -1).
        temperature: Sampling temperature for every call (negative lets the API use its default) (Default: -1.).
        top_p: Nucleus-sampling probability (negative lets the API use its default) (Default: -1.).
        top_k: Top-k sampling cutoff (negative lets the API use its default) (Default: -1).
        frequency_penalty: Frequency penalty (None lets the API use its default) (Default: None).
        presence_penalty: Presence penalty (None lets the API use its default) (Default: None).
        repetition_penalty: Repetition penalty, a vLLM/Featherless extension (None uses the default) (Default None).
        min_p: Minimum-probability cutoff, a vLLM/Featherless extension (None uses the default) (Default: None).
        sampler: Extra sampler params merged last (its keys win); use it for any knob not covered above.
        connect_timeout: Maximum seconds to wait for the gateway server to come up (Default: 15.0).
        api_key: The Featherless API key (account) charged for every call; None falls back to the
            FEATHERLESS_API_KEY environment variable (Default: None).
        key_units: The total unit budget supported by the account of ``api_key``; None falls back to the
            FEATHERLESS_KEY_UNITS environment variable (the gateway sizes each account's budget on first sight of
            its key, later mismatching declarations are ignored) (Default: None).
    """
    if cost not in APIGatewayServer.VALID_COSTS:
        log.critical(f"Invalid cost {cost}: it must be one of {APIGatewayServer.VALID_COSTS}")

    # Bring up the shared gateway server before opening any sockets (idempotent across processes)
    FeatherlessAPI._ensure_server(connect_timeout)

    class Net(torch.nn.Module):
        """Holds the sampler config and the two gateway sockets, and routes each `forward(prompt)`
        through the gateway. Plain Python attributes (socket, dict, str): none get registered as
        torch submodules since none are `nn.Module`/`Parameter`/`Tensor`."""

        def __init__(self):
            super().__init__()
            self.model_name: str | None = model
            self.cost: int = cost
            self.system_prompt: str = system_prompt

            # Account: the API key charged for every call and the total unit budget of that account. Both travel
            # with each request, so the gateway can keep per-key queues/budgets whatever process spawned it
            self.api_key: str = api_key or os.environ.get("FEATHERLESS_API_KEY", "")
            self.key_units: int = key_units if key_units is not None else (
                int(os.environ.get("FEATHERLESS_KEY_UNITS", "8")))
            if not self.api_key:
                log.critical("No API key: the api_key argument was not given "
                             "and FEATHERLESS_API_KEY was not set!")

            # Per-call sampler: include each knob only when explicitly set, so unset ones fall back
            # to the API default. The free-form `sampler` arg is merged last and overrides.
            self.sampler: dict = {}
            if max_tokens > 0:
                self.sampler["max_tokens"] = max_tokens
            if temperature >= 0.:
                self.sampler["temperature"] = temperature
            if top_p >= 0.:
                self.sampler["top_p"] = top_p
            if top_k >= 0:
                self.sampler["top_k"] = top_k
            if frequency_penalty is not None:
                self.sampler["frequency_penalty"] = frequency_penalty
            if presence_penalty is not None:
                self.sampler["presence_penalty"] = presence_penalty
            if repetition_penalty is not None:
                self.sampler["repetition_penalty"] = repetition_penalty
            if min_p is not None:
                self.sampler["min_p"] = min_p
            if sampler:
                self.sampler.update(sampler)

            # Round-robin fairness is per process; default ID is the PID
            self.process_id: str = str(process_id if process_id is not None else os.getpid())

            # Persistent registration socket: lifetime == this caller's interest in the gateway
            self._reg: socket.socket = socket.create_connection(
                (APIGatewayServer.HOST, APIGatewayServer.PORT))
            self._reg.sendall(b'{"op":"hello"}\n')

            # Separate request socket (one in-flight request per instance; this client is synchronous)
            self._req: socket.socket = socket.create_connection(
                (APIGatewayServer.HOST, APIGatewayServer.PORT))
            self._rf = self._req.makefile("r")

        def forward(self, prompt: str) -> str:
            if not isinstance(prompt, str):
                log.critical(f"Invalid prompt: it must be a str, got {type(prompt).__name__}")
            msg = json.dumps({"op": "generate", "process_id": self.process_id,
                              "sys_prompt": self.system_prompt, "prompt": prompt,
                              "cost": self.cost, "model": self.model_name,
                              "sampler": self.sampler, "api_key": self.api_key,
                              "key_units": self.key_units}) + "\n"
            self._req.sendall(msg.encode())
            line = self._rf.readline()
            if not line:
                log.critical("Gateway closed the connection")
            resp = json.loads(line)
            if not resp.get("ok"):
                log.critical(f"Gateway returned an error: {resp.get('error', 'unknown error')}")
            return resp["result"]

        def close(self) -> None:
            """Close both gateway sockets, releasing this caller's interest."""
            for s in (self._req, self._reg):
                try:
                    s.close()
                except OSError:
                    pass

    super(FeatherlessAPI, self).__init__(
        module=Net(),
        proc_inputs=[StreamType(data_type="text", pubsub=False, private_only=False)],
        proc_outputs=[StreamType(data_type="text", pubsub=False, private_only=False)],
        *args, **kwargs
    )

A client of Featherless. All the FeatherlessAPI instances of one machine send their requests through one local gateway process (APIGatewayServer in utils). The gateway keeps one budget of units per API key and serves the processes in turn. Many agents can therefore share one account without exceeding its concurrency limit.

Argument Type Default Meaning
model str or None None The Featherless model of every call. None lets the gateway use the environment variable MODEL_ID.
cost int 1 The units that each call takes from the budget. It must be one of APIGatewayServer.VALID_COSTS (1, 2, 4 by default).
process_id str or None None The identity under which the gateway queues the requests of the caller. None uses the PID. Instances with the same process_id share one queue.
connect_timeout float 15.0 The seconds to wait for the gateway to come up.
api_key str or None None The Featherless key. None reads FEATHERLESS_API_KEY.
key_units int or None None The total units of the account. None reads FEATHERLESS_KEY_UNITS (default 8). The first request that mentions a key fixes its budget in the gateway. Later values are ignored.

The sampling arguments are those of the shared table. The constructor runs four steps:

  1. It raises GenException when cost is not valid.
  2. It starts the gateway when nobody listens on GW_HOST:GW_PORT (default 127.0.0.1:11321). The gateway is a detached process python -c "from unaiverse.modules.utils import serve_api_gateway; serve_api_gateway()" started under a file lock that lets only one process start it. The constructor raises GenException when the gateway is not reachable within connect_timeout.
  3. It raises GenException when there is no API key.
  4. It opens two TCP connections to the gateway: one that registers the instance for as long as it lives and one for the requests.

A call sends the prompt, blocks until the gateway answers and returns the text. It has no timeout of its own. A call whose prompt is not a str, an error reported by the gateway and a closed connection all raise GenException. The gateway stops when the last registered instance closes. The gateway writes on the terminal of the process that started it because its output is not redirected.

The gateway calls Featherless through the openai package. The SDK does not declare this package and without it every call fails with an error from the gateway. A request whose cost exceeds the budget of its key can never be served. The gateway holds it forever, the caller blocks and every later request on the same key waits behind it.

from unaiverse.modules.networks import FeatherlessAPI

with FeatherlessAPI(model="meta-llama/Meta-Llama-3.1-8B-Instruct", cost=1, max_tokens=200) as api:
    text = api("Name three rivers of Italy.")[0]

close

close() -> None
Source code in unaiverse/modules/networks.py
def close(self) -> None:
    """Close both the request and the persistent registration socket, releasing this caller's interest."""
    assert self.module is not None
    if hasattr(self.module, 'close'):
        self.module.close()

Closes the two connections of this instance. The gateway shuts down when no registered instance is left. Leaving a with block calls it. A process that exits closes the connections as well.

OpenRouterAPI

OpenRouterAPI(model: str | None = None, system_prompt: str = '', max_tokens: int = -1, temperature: float = -1.0, top_p: float = -1.0, top_k: int = -1, frequency_penalty: float | None = None, presence_penalty: float | None = None, repetition_penalty: float | None = None, min_p: float | None = None, sampler: dict | None = None, api_key: str | None = None, timeout: float = 120.0, max_retries: int = 3, *args, **kwargs)

Bases: ModuleWrapper

Source code in unaiverse/modules/networks.py
def __init__(self, model: str | None = None, system_prompt: str = "", max_tokens: int = -1,
             temperature: float = -1., top_p: float = -1., top_k: int = -1,
             frequency_penalty: float | None = None, presence_penalty: float | None = None,
             repetition_penalty: float | None = None, min_p: float | None = None, sampler: dict | None = None,
             api_key: str | None = None, timeout: float = 120., max_retries: int = 3,
             *args, **kwargs):
    """Create an OpenRouterAPI handle with its own OpenAI-compatible client.

    Args:
        model: The OpenRouter model slug used for every call, e.g. "openai/gpt-4o" (None falls back to the
            OPENROUTER_MODEL_ID environment variable) (Default: None).
        system_prompt: The system prompt prepended to every call ("" means no system prompt) (Default: "").
        max_tokens: Maximum number of tokens to generate per call (-1 means no limit) (Default: -1).
        temperature: Sampling temperature for every call (negative lets the API use its default) (Default: -1.).
        top_p: Nucleus-sampling probability (negative lets the API use its default) (Default: -1.).
        top_k: Top-k sampling cutoff (negative lets the API use its default) (Default: -1).
        frequency_penalty: Frequency penalty (None lets the API use its default) (Default: None).
        presence_penalty: Presence penalty (None lets the API use its default) (Default: None).
        repetition_penalty: Repetition penalty, ignored by providers not supporting it (Default: None).
        min_p: Minimum-probability cutoff, ignored by providers not supporting it (Default: None).
        sampler: Extra params merged last (its keys win); use it for any knob not covered above, including
            OpenRouter-specific fields such as "provider", "models" (fallback chain) or "reasoning".
        api_key: The OpenRouter API key charged for every call; None falls back to the OPENROUTER_API_KEY
            environment variable (Default: None).
        timeout: Maximum seconds to wait for a single HTTP request (Default: 120.).
        max_retries: Maximum number of attempts per call, with exponential backoff in between (Default: 3).
    """
    if max_retries < 1:
        log.critical(f"Invalid max_retries {max_retries}: it must be at least 1")

    class Net(torch.nn.Module):
        """Holds the sampler config and the OpenRouter client, and sends each `forward(prompt)` straight to the
        API. Plain Python attributes (client, dict, str): none get registered as torch submodules since none are
        `nn.Module`/`Parameter`/`Tensor`."""

        def __init__(self):
            super().__init__()
            from openai import OpenAI
            from openai.types.chat import ChatCompletion
            self._completion_type = ChatCompletion

            self.model_name: str = model or os.environ.get("OPENROUTER_MODEL_ID", "")
            self.system_prompt: str = system_prompt
            self.max_retries: int = max_retries
            if not self.model_name:
                log.critical("No model: the model argument was not given "
                             "and OPENROUTER_MODEL_ID was not set!")

            # Account: the API key charged for every call
            key = api_key or os.environ.get("OPENROUTER_API_KEY", "")
            if not key:
                log.critical("No API key: the api_key argument was not given "
                             "and OPENROUTER_API_KEY was not set!")

            # Process-local client, reused for every call so HTTP keep-alive avoids a fresh TLS handshake per
            # query. SDK-level retries are off: forward() retries on its own, also covering empty content
            self._client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=key, timeout=timeout,
                                  max_retries=0, default_headers={"HTTP-Referer": "https://unaiverse.io",
                                                                  "X-Title": "UNaIVERSE"})

            # Per-call sampler: include each knob only when explicitly set, so unset ones fall back
            # to the API default. The free-form `sampler` arg is merged last and overrides.
            self.sampler: dict = {}
            if max_tokens > 0:
                self.sampler["max_tokens"] = max_tokens
            if temperature >= 0.:
                self.sampler["temperature"] = temperature
            if top_p >= 0.:
                self.sampler["top_p"] = top_p
            if top_k >= 0:
                self.sampler["top_k"] = top_k
            if frequency_penalty is not None:
                self.sampler["frequency_penalty"] = frequency_penalty
            if presence_penalty is not None:
                self.sampler["presence_penalty"] = presence_penalty
            if repetition_penalty is not None:
                self.sampler["repetition_penalty"] = repetition_penalty
            if min_p is not None:
                self.sampler["min_p"] = min_p
            if sampler:
                self.sampler.update(sampler)

            # Split the sampler once: OpenAI-native keys go top-level, the rest (top_k, min_p, provider, models,
            # ...) ride along in extra_body, otherwise the OpenAI SDK rejects them as unexpected arguments
            self._native: dict = {k: v for k, v in self.sampler.items() if k in OPENAI_NATIVE_SAMPLER_PARAMS}
            self._extra_body: dict = {k: v for k, v in self.sampler.items()
                                      if k not in OPENAI_NATIVE_SAMPLER_PARAMS}

        def forward(self, prompt: str) -> str:
            if not isinstance(prompt, str):
                log.critical(f"Invalid prompt: it must be a str, got {type(prompt).__name__}")

            # Always use chat completions; include the system message only when a system prompt is given
            msgs = [{"role": "system", "content": self.system_prompt}] if self.system_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": self.model_name, "messages": msgs, **self._native}
            if self._extra_body:
                _kwargs["extra_body"] = self._extra_body

            # Retry with exponential backoff, keeping the last error so a final failure reports its cause
            last_err = None
            for attempt in range(self.max_retries):
                try:
                    resp = self._client.chat.completions.create(**_kwargs)  # type: ignore
                    if not isinstance(resp, self._completion_type):
                        log.critical(f"Unexpected response type {type(resp).__name__}: streaming is not supported")

                    # 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 ""
                    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

                # No point sleeping after the last attempt
                if attempt + 1 < self.max_retries:
                    log.error(f"Empty response or exception! (model={self.model_name}, attempt={attempt + 1}, "
                              f"last_err={last_err!r}), waiting {2 ** attempt} seconds before trying again...")
                    time.sleep(2 ** attempt)

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

        def close(self) -> None:
            """Close the HTTP client, releasing its pooled connections."""
            try:
                self._client.close()
            except Exception:
                pass

    super(OpenRouterAPI, self).__init__(
        module=Net(),
        proc_inputs=[StreamType(data_type="text", pubsub=False, private_only=False)],
        proc_outputs=[StreamType(data_type="text", pubsub=False, private_only=False)],
        *args, **kwargs
    )

A client of OpenRouter. Each instance talks to https://openrouter.ai/api/v1 directly with its own HTTP client. There is no gateway and no budget.

Argument Type Default Meaning
model str or None None The OpenRouter model slug, such as "openai/gpt-4o". None reads OPENROUTER_MODEL_ID.
api_key str or None None The OpenRouter key. None reads OPENROUTER_API_KEY.
timeout float 120.0 The seconds allowed to one HTTP request.
max_retries int 3 The attempts per call. A value below 1 raises GenException.

The sampling arguments are those of the shared table. sampler also carries OpenRouter fields such as provider, models (a fallback chain) or reasoning. The class needs the openai package. The SDK does not declare it and without it the constructor raises ImportError. A missing model or key raises GenException.

A call sends the prompt as a user message and returns the first non-blank text of the answer. An exception, a rate limit or a blank answer counts as a failed attempt. The client logs it on the ERROR channel and waits 2 ** attempt seconds (1, 2, 4, ...) before the next attempt. After max_retries failed attempts the call raises GenException with the last error. Every request carries the headers HTTP-Referer: https://unaiverse.io and X-Title: UNaIVERSE.

from unaiverse.agent import Agent
from unaiverse.modules.networks import OpenRouterAPI

agent = Agent(proc=OpenRouterAPI(model="meta-llama/llama-3.3-70b-instruct",
                                 system_prompt="You are the concierge of a small hotel.",
                                 temperature=0.3, max_tokens=300))

close

close() -> None
Source code in unaiverse/modules/networks.py
def close(self) -> None:
    """Close the underlying HTTP client, releasing its pooled connections."""
    assert self.module is not None
    if hasattr(self.module, 'close'):
        self.module.close()

Closes the HTTP client and its pooled connections. Leaving a with block calls it.