An agent runs every processor through a ModuleWrapper. The wrapper sits between the streams of the agent and the model: it converts each input sample into what the model reads (a PIL picture into a normalized tensor, a tensor onto the right device), calls the model, checks and converts each output back into a stream sample and runs the backward step when the agent learns. It also runs the model in a worker thread of its own so that the node keeps answering its peers during a long call (see Agents). When the agent is built, AgentProcessorChecker wraps the processor in a ModuleWrapper and fills in what the developer did not describe: the input and output streams and the learning options.
The module also holds HumanModule (the processor of a person), the image transforms used by the ready-made classifiers, a few helpers for training and testing and the local gateway that the FeatherlessAPI processors of one machine share (see networks).
importtorchfromunaiverse.agentimportAgentnet=torch.nn.Sequential(torch.nn.Linear(4,16),torch.nn.ReLU(),torch.nn.Linear(16,3))agent=Agent(proc=net)# The checker wraps net and guesses its streamsprint(agent.proc_inputs[0].get_name(),agent.proc_outputs[0].get_name())# proc_input_0 proc_output_0
The streams of a processor whose StreamType has no name (the name "unk") are named after their position: proc_input_0, proc_input_1, ... for the inputs and proc_output_0, proc_output_1, ... for the outputs. AgentProcessorChecker gives these names. An interaction addresses the streams of a processor by these names (see Interactions). In data_samples={"proc_output_0": picture} the key names the first output stream of the requester.
def__init__(self,module:torch.nn.Module|Callable,proc_inputs:list[StreamType]|None=None,proc_outputs:list[StreamType]|None=None,proc_opts:dict|None=None,seed:int=-1,agent:object=None,device:str|torch.device|None=None)->None:"""Initializes the ModuleWrapper. Args: module: The torch.nn.Module or callable object to wrap (default: None). proc_inputs: List of Stream objects describing the input types (default: None). proc_outputs: List of Stream objects describing the output types (default: None). proc_opts: Dictionary with keys ``"optimizer"`` and ``"losses"`` (default: None). seed: Random seed to fix before instantiation; negative values are ignored (default: -1). agent: The agent who owns this processor. device: The device on which to run the processor (default: None). """super(ModuleWrapper,self).__init__()self.device=Noneself.module:Callable|None=Noneself.proc_inputs=None# The list of Stream objects describing the input types of the moduleself.proc_outputs=None# The list of Stream objects describing the output types of the moduleself.proc_opts=Noneself.proc_optional_inputs=[]self.agent=Noneself._has_first=Falseself._has_last=Falseself._sig_defaults=[]self._last_raw_outputs=Noneself._last_module_s=None# Seconds the last module call blocked its thread (see runs_long)# Workingset_seed(seed)self.guess_device(device)self.set_module(module)self.set_proc_inputs_and_outputs(proc_inputs,proc_outputs)self.set_proc_opts(proc_opts)self.set_agent(agent)
A torch.nn.Module that wraps a model and the description of its streams.
Argument
Type
Default
Meaning
module
torch.nn.Module or callable
required
The model. A torch.nn.Module moves to device. A plain callable stays as it is.
proc_inputs
list[StreamType] or None
None
One descriptor per input of the model, in the order of its positional arguments.
proc_outputs
list[StreamType] or None
None
One descriptor per output of the model, in the order of the returned tuple.
proc_opts
dict or None
None
The learning options: {"optimizer": torch.optim.Optimizer, "losses": [loss, ...]} (see Learning over time).
seed
int
-1
A non-negative value seeds torch, random and numpy (see set_seed). The seeding happens after the model is built and before it moves to device.
agent
object or None
None
The agent that owns the processor. With an agent the wrapper renders interactive messages for the model and checks the answers (see Interactive messages).
device
str, torch.device or None
None
The device of the model and of the input tensors (see guess_device).
The wrapper accepts only StreamType objects in proc_inputs and proc_outputs. AgentProcessorChecker converts the strings such as "text" before the wrapper sees them.
Attribute
Type
Content
module
torch.nn.Module or callable
The wrapped model.
device
torch.device
The device of the model.
proc_inputs, proc_outputs
list[StreamType]
The descriptors of the streams.
proc_opts
dict
The learning options.
proc_optional_inputs
list[dict]
One entry per input, parallel to proc_inputs: {"has_default": bool, "default_value": ...} read from the signature of the model. The agent uses it to call the model when an optional input has no sample.
agent
object
The owner of the processor.
The model may declare the class attributes UAI_ECHOES_INPUT = True (it gives back its input, as HumanModule and MultiIdentity do) and UAI_OFFLOAD = False (it must run on the event loop). A subclass of the wrapper may declare UAI_OFFLOAD = False as well.
8. The maximum number of times that the answer check of an interactive message asks the model again within one call. A policy of the agent that allows more retries is capped at this value.
defforward(self,*args:Any,**kwargs:Any)->tuple:"""Preprocesses inputs, runs the wrapped module, and post-processes the outputs. Args: *args: Positional inputs; each element is preprocessed via the corresponding ``proc_inputs`` Stream. **kwargs: Extra keyword arguments forwarded to the module. The ``first`` and ``last`` keys are silently removed before the call. Returns: A tuple of post-processed outputs, one per entry in ``proc_outputs``. """return_run_to_end(self.__forward(list(args),kwargs,offload=False))
Runs one call of the model synchronously and returns a tuple with one element per entry of proc_outputs. The steps are these:
It drops the keyword arguments first and last when the signature of the model has no parameter with that name. The agent always passes both.
When the wrapper has an agent and the model does not echo its input, every string input that contains an interactive block becomes the plain text of that block for the model.
Each input args[i] goes through proc_inputs[i].check_and_preprocess(..., device=device). That method checks its type and shape and applies the stream-to-processor transform. Positional arguments beyond len(proc_inputs) are dropped. Fewer arguments raise IndexError.
It calls the model. A result that is not a tuple becomes a tuple of one element. The raw result stays available to learn_backward.
Each output outputs[i] goes through proc_outputs[i].check_and_postprocess(...). Outputs beyond len(proc_outputs) are dropped.
When the wrapper has an agent, the answer check of interactive messages runs on the first text output. It may ask the model again (up to UAI_HARD_CAP times), replace the text or raise unaiverse.uai.AnswerWithheld when no answer may leave the agent.
A check that fails in step 3 or 5 raises ValueError or TypeError from the stream. The method raises AssertionError when module, proc_inputs or proc_outputs is None. An async model works only when it returns without waiting. A model that suspends makes the method raise RuntimeError("A coroutine run without an event loop suspended") and needs aforward instead.
asyncdefaforward(self,*args:Any,offload:bool=True,**kwargs:Any)->tuple:"""forward(), with the module and its pre/postprocessing in the worker thread of this wrapper (async). What concerns the agent (the rendering of interactive blocks before the call, the answer gate after it) stays on the event loop; the module calls (the first one and every re-ask of the gate) run in the worker, one at a time. Inline instead, as forward(), in the browser, with Custom.OFFLOAD_ENABLED off, for modules that echo their input or say UAI_OFFLOAD = False, and when a subclass overrides forward(). Args: *args: As for forward(). offload: False to run on the event loop even where the worker would be used (the steps of a multistep interaction, which must take their samples one per tick). An async module is awaited either way. **kwargs: As for forward(). Returns: As forward(). """iftype(self).forwardisnotModuleWrapper.forward:returnself.forward(*args,**kwargs)returnawaitself.__forward(list(args),kwargs,offload=offloadandself.__offloads())
The coroutine that the agent awaits in process and learn. It does what forward does with the same arguments and returns the same tuple. The calls of the model run in the worker thread of the wrapper. The rendering of interactive messages and the answer check stay on the event loop.
Argument
Type
Default
Meaning
*args, **kwargs
As for forward.
offload
bool
True
False runs the model on the event loop. The agent passes False for the steps of a multi-step interaction unless runs_long() is True.
The calls run inline (on the event loop) also in these cases: NODE_OFFLOAD=0, the browser runtime (no threads), a model with UAI_ECHOES_INPUT = True or UAI_OFFLOAD = False and a wrapper with UAI_OFFLOAD = False. A subclass that overrides forward is called synchronously through its own forward. An async model is awaited on the event loop in every case.
Each wrapper owns one worker thread (ThreadPoolExecutor(max_workers=1), thread name unaiverse-proc). Two calls of the same wrapper therefore never overlap. On the other hand the wrappers of different agents run their models in parallel. The worker runs with the grad mode, the inference mode and the context variables of the caller.
defruns_long(self)->bool:"""Tells whether the last call of the module was long, at least Custom.OFFLOAD_SLOW_S seconds of work on its thread (the wait of an async module is not counted: it blocks nothing). Returns: True when it was long; False when it was short, or before the first call. """returnself._last_module_sisnotNoneandself._last_module_s>=Custom.OFFLOAD_SLOW_S
Returns True when the last call took at least Custom.OFFLOAD_SLOW_S seconds (environment variable NODE_OFFLOAD_SLOW, default 0.5) on its thread. The time covers the preprocessing, the model call and the postprocessing. The wait of an async model is not counted. Before the first call the method returns False. The agent reads it to decide whether the steps of a multi-step interaction go to the worker thread.
deflearn_backward(self,targets:list|None=None)->list:"""Runs a supervised or unsupervised backward pass and optimizer step. Args: targets: Optional list of target tensors, one per processor output. Individual entries may be ``None`` (treated as unsupervised for that slot). Returns: A list of per-output loss values if a backward pass was performed. """if(self.proc_optsisNoneorlen(self.proc_opts)==0or('losses'notinself.proc_optsand'optimizer'notinself.proc_opts)orself.proc_outputsisNone):return[]loss_functions:list=self.proc_opts['losses']optimizer:torch.optim.optimizer.Optimizer=self.proc_opts['optimizer']# Evaluating loss function(s), one for each processor output slot (they are set to 0. if no targets are there)iftargetsisnotNoneandlen(targets)>0andany(xisnotNoneforxintargets):# Preprocessing targetstargets=[self.proc_outputs[i].check_and_preprocess(targets[i],device=self.device,allow_class_ids=True,targets=True)foriinrange(0,len(self.proc_outputs))]# Supervised or partly supervised learningloss_values=[loss_fcn(self._last_raw_outputs[i],targets[i])iftargets[i]isnotNoneelsetorch.tensor(0.,device=self.device)fori,loss_fcninenumerate(loss_functions)]loss=torch.stack(loss_values).sum()# Sum of losseselse:# Unsupervised learningloss_values=[loss_fcn(self._last_raw_outputs[i])fori,loss_fcninenumerate(loss_functions)]loss=torch.stack(loss_values).sum()# Sum of losses# Learning stepoptimizer.zero_grad()loss.backward()optimizer.step()# Teaching (for autoregressive models, expected to have attribute "y")iftargetsisnotNoneandhasattr(self.module,'y'):self.module.y=targets[0]returnloss_values
Runs one optimization step on the outputs of the last call and returns the list of the loss tensors in the order of the outputs.
Argument
Type
Default
Meaning
targets
list or None
None
One target per output. None entries give a loss of zero for that output.
With at least one target, each target goes through proc_outputs[i].check_and_preprocess(..., allow_class_ids=True, targets=True) and the loss of output i is losses[i](raw_output[i], target[i]). Without targets the step is unsupervised and the loss is losses[i](raw_output[i]). The method sums the losses and runs optimizer.zero_grad(), loss.backward() and optimizer.step(). When targets are given and the model has an attribute y, the first target replaces module.y for the next step.
The method returns [] without learning when proc_opts is empty, has neither optimizer nor losses or when proc_outputs is None. An optimizer equal to None makes it raise AttributeError. A None loss raises TypeError when its output has a target or the step is unsupervised. Agent.learn checks the optimizer and the losses before it calls the method.
asyncdefalearn_backward(self,targets:list|None=None,offload:bool=True)->list:"""learn_backward(), in the worker thread of this wrapper, after the forward pass it learns from (async). Inline in the same cases as aforward(). Args: targets: As for learn_backward(). offload: False to run on the event loop even where the worker would be used (as for aforward()). Returns: As learn_backward(). """iftype(self).learn_backwardisnotModuleWrapper.learn_backwardornot(offloadandself.__offloads()):returnself.learn_backward(targets)returnawaitself.__in_worker(self.learn_backward,targets)
The coroutine that the agent awaits in learn. It runs learn_backward(targets) in the worker thread under the rules of aforward and returns its result. offload=False runs it inline. A subclass that overrides learn_backward is called inline.
defguess_device(self,device:str|torch.device|None)->None:"""Sets the device of the processor: the given one, else the PROC_DEVICE environment variable, else CPU. Args: device: The device to use, or None to guess it. """device_env=os.getenv("PROC_DEVICE",None)self.device=torch.device("cpu")ifdevice_envisNoneelsetorch.device(device_env)# Override if it was givenifdeviceisnotNone:self.device=torch.device(device)ifisinstance(device,str)elsedevice
Stores the device of the wrapper in device: the argument when it is not None (a string becomes a torch.device), else the environment variable PROC_DEVICE, else cpu. It moves nothing. The constructor calls it before set_module moves the model.
defset_proc_inputs_and_outputs(self,proc_inputs:list[StreamType]|None,proc_outputs:list[StreamType]|None)->None:"""Sets the descriptors of the inputs and of the outputs of the processor (None leaves them unchanged). Args: proc_inputs: The list of the input stream descriptors, or None. proc_outputs: The list of the output stream descriptors, or None. """ifproc_inputsisnotNone:self.proc_inputs=proc_inputsself.__refresh_proc_optional_inputs()# rebuilds, truncating or padding as neededifproc_outputsisnotNone:self.proc_outputs=proc_outputs
Replaces proc_inputs and proc_outputs. A None argument leaves that list unchanged. A new proc_inputs also rebuilds proc_optional_inputs with the same length. The inputs beyond the parameters of the model get no default.
defset_proc_opts(self,proc_opts:dict|None)->None:"""Sets the learning options of the processor (None leaves them unchanged). Args: proc_opts: Dictionary with keys ``"optimizer"`` and ``"losses"``, or None. """ifproc_optsisnotNone:self.proc_opts=proc_opts
defset_module(self,mod:Callable|torch.nn.Module)->None:"""Sets the wrapped module, caching what its signature tells (first/last flags, defaults of the inputs). Args: mod: The torch.nn.Module or callable object to wrap. Raises: GenException: If the signature of the module cannot be guessed. """# Case 1: torch.nn.Module / object with .forwardifhasattr(mod,"forward")andcallable(getattr(mod,"forward")):sig=inspect.signature(mod.forward)elifcallable(mod):sig=inspect.signature(mod)else:raiseGenException("Invalid processor module, cannot guess the signature of the callable method, if any")self.module=mod.to(self.device)ifisinstance(mod,torch.nn.Module)elsemodself._has_first="first"insig.parameters# B8: rename belowself._has_last="last"insig.parameters# Cache the signature-derived defaults ONCE, excluding framework-handled kwargs and *args/**kwargs# catch-alls. This is the canonical per-positional-data-arg default list of the wrapped module's forward.framework_kwargs={"first","last"}self._sig_defaults:list[dict]=[]forname,paraminsig.parameters.items():ifnameinframework_kwargs:continueifparam.kindin(inspect.Parameter.VAR_POSITIONAL,inspect.Parameter.VAR_KEYWORD):continueifparam.defaultisnotinspect.Parameter.empty:self._sig_defaults.append({"has_default":True,"default_value":param.default})else:self._sig_defaults.append({"has_default":False,"default_value":None})# Align proc_optional_inputs to current proc_inputs (if already known)self.__refresh_proc_optional_inputs()
Replaces the model. The method reads the signature of mod.forward (or of mod itself for a plain callable), notes whether it accepts first and last and records the default of each other parameter for proc_optional_inputs. A torch.nn.Module moves to device. An object that is not callable raises unaiverse.custom.GenException.
def__init__(self,agent:object)->None:"""Validates and normalizes processor attributes on the given container. Checks that ``processor_container`` exposes the required processor attributes, performs type validation, auto-wraps plain ``torch.nn.Module`` objects in ``ModuleWrapper``, and infers missing ``proc_inputs``, ``proc_outputs``, and ``proc_opts`` heuristically. The validated and completed values are written back onto ``processor_container``. Args: agent: Any object that exposes ``proc``, ``proc_inputs``, ``proc_outputs``, ``proc_opts``, and ``proc_optional_inputs`` attributes. """# Right now, the processor has its own attributes, but they are also directly referenced from the agent object.# In the future, we might drop the ones on the agent side.asserthasattr(agent,'proc'),"Invalid processor container (agent) object"asserthasattr(agent,'proc_inputs'),"Invalid processor container (agent) object"asserthasattr(agent,'proc_outputs'),"Invalid processor container (agent) object"asserthasattr(agent,'proc_opts'),"Invalid processor container (agent) object"asserthasattr(agent,'proc_optional_inputs'),"Invalid processor container (agent) object"# Getting processor-related info from the main object which collects processor and its propertiesproc:torch.nn.Module|ModuleWrapper|Callable|None=agent.procproc_inputs:list[StreamType]|list[str]|None=agent.proc_inputsproc_outputs:list[StreamType]|list[str]|None=agent.proc_outputsproc_opts:dict|None=agent.proc_opts# The agent itself could be a processorifprocisNoneandcallable(agent):proc=agentifnot(procisNoneorisinstance_fcn(proc,torch.nn.Module)orisinstance_fcn(proc,ModuleWrapper)orcallable(proc)or(isinstance(proc,str)andproc=="human")):raiseGenException("Processor (proc) must be either None or a torch.nn.Module, ""or a ModuleWrapper, or a callable object")ifnot((proc_inputsisNoneor(isinstance_fcn(proc_inputs,list)and(len(proc_inputs)==0or(len(proc_inputs)>0andisinstance_fcn(proc_inputs[0],(StreamType,str))))))):raiseGenException("Invalid proc_inputs: it must be None or a list of StreamType/str")ifnot((proc_outputsisNoneor(isinstance_fcn(proc_outputs,list)and(len(proc_outputs)==0or(len(proc_outputs)>0andisinstance_fcn(proc_outputs[0],(StreamType,str))))))):raiseGenException("Invalid proc_outputs: it must be None or a list of StreamType/str")ifnot(proc_optsisNoneorisinstance_fcn(proc_opts,dict)):raiseGenException("Invalid proc_opts: it must be None or a dictionary")# From strings to StreamType (proc_inputs)ifproc_inputsisnotNone:proc_inputs_copy=proc_inputs.copy()fori,pinenumerate(proc_inputs_copy):ifisinstance(p,str):try:proc_inputs_copy[i]=StreamType(data_type=p,pubsub=False,private_only=False)exceptExceptionase:raiseGenException(f"Invalid stream type {p}: {e}")proc_inputs=proc_inputs_copy# From strings to StreamType (proc_outputs)ifproc_outputsisnotNone:proc_outputs_copy=proc_outputs.copy()fori,pinenumerate(proc_outputs_copy):ifisinstance(p,str):try:proc_outputs_copy[i]=StreamType(data_type=p,pubsub=False,private_only=False)exceptExceptionase:raiseGenException(f"Invalid stream type {p}: {e}")proc_outputs=proc_outputs_copy# From None to empty dictionary (proc_opts)ifproc_optsisNone:proc_opts={}# Type checkingifproc_inputsisnotNone:proc_inputs:list[StreamType]ifproc_outputsisnotNone:proc_outputs:list[StreamType]# Dummy processor (if no processor was provided)ifprocisNone:ifproc_inputsisNone:proc_inputs:list[StreamType]=[StreamType(data_type="all",pubsub=False,private_only=False)]ifproc_outputsisNone:proc_outputs:list[StreamType]=[StreamType(data_type="all",pubsub=False,private_only=False)]assertproc_outputsisnotNoneproc_opts={'optimizer':None,'losses':[None]*len(proc_outputs)}proc=ModuleWrapper(module=MultiIdentity(),proc_inputs=proc_inputs,proc_outputs=proc_outputs,proc_opts=proc_opts,agent=agent,device=torch.device("cpu"))else:ifisinstance(proc,str)andproc.lower().strip()=="human":proc_inputs:list[StreamType]=[StreamType(data_type="text",pubsub=False,private_only=False),StreamType(data_type="img",pubsub=False,private_only=False)]proc_outputs:list[StreamType]=[StreamType(data_type="text",pubsub=False,private_only=False),StreamType(data_type="img",pubsub=False,private_only=False)]proc=ModuleWrapper(module=HumanModule(),proc_inputs=proc_inputs,proc_outputs=proc_outputs,agent=agent,device=torch.device("cpu"))# Creating a ModuleWrapper with the given processorelifnotisinstance(proc,ModuleWrapper):proc:torch.Module|Callableproc=ModuleWrapper(module=proc,proc_opts=proc_opts,proc_inputs=proc_inputs,proc_outputs=proc_outputs,agent=agent,device=torch.device("cpu"))else:# If it is already a ModuleWrapper, we force the reference to the agent and the references to the# types of inputs and outputs: actually, the inputs/outpus/opts might have been already defined by the# wrapper creator, but we give priority to the user optionsproc.set_proc_inputs_and_outputs(proc_inputs,proc_outputs)proc.set_proc_opts(proc_opts)proc.set_agent(agent)# From here after, the proc is not None, and it is a ModuleWrapper.# However, proc_inputs, proc_outputs, and proc_opts might still not be specifiedassertprocisnotNoneassertisinstance(proc,ModuleWrapper)# Guessing inputs, fixing attributesAgentProcessorChecker.__guess_proc_inputs(proc)ifproc.proc_inputsisNone:raiseGenException("The inputs of the processor were not described and cannot be automatically guessed")# Fixing naming conventionsAgentProcessorChecker.__fix_proc_inputs(proc)# Guessing outputs, fixing attributesAgentProcessorChecker.__guess_proc_outputs(proc)ifproc.proc_outputsisNone:raiseGenException("The outputs of the processor were not described and cannot be automatically guessed")# Fixing naming conventions (should not be needed)AgentProcessorChecker.__fix_proc_outputs(proc)# Guessing optimization-related options and stuff, fixing attributesAgentProcessorChecker.__guess_proc_opts(proc)# Fixing attribute-presence conventionsAgentProcessorChecker.__fix_proc_opts(proc)# Ensuring all is OKassertproc.proc_inputsisnotNoneassertproc.proc_outputsisnotNoneassertproc.proc_optsisnotNoneassertproc.proc_optional_inputsisnotNone# Updating processor container object (agent)agent.proc=procagent.proc_inputs=proc.proc_inputsagent.proc_outputs=proc.proc_outputsagent.proc_opts=proc.proc_optsagent.proc_optional_inputs=proc.proc_optional_inputs
Checks and completes the processor of an agent. The constructor does all the work and writes the result back to the agent. AgentBasics.__init__ calls it once per agent. The argument is any object with the attributes proc, proc_inputs, proc_outputs, proc_opts and proc_optional_inputs. An object without them raises AssertionError. The steps are these:
A proc that is None on a callable agent becomes the agent itself.
proc must be None, a torch.nn.Module, a callable or the string "human". proc_inputs and proc_outputs must be None or lists of StreamType or str. proc_opts must be None or a dict. A violation raises GenException.
Each string in proc_inputs and proc_outputs becomes StreamType(data_type=s). An unknown type raises GenException.
The processor becomes a ModuleWrapper on the CPU:
proc
Result
None
MultiIdentity with one input and one output of type "all" unless the lists are given.
"human"
HumanModule with the inputs and outputs text and img. The given lists are ignored.
a ModuleWrapper
Kept. The given lists and options replace its own and the agent becomes its owner.
anything else
A new ModuleWrapper around it with device=torch.device("cpu"). PROC_DEVICE does not apply.
Without proc_inputs the checker guesses one input from the first Conv2d, Linear, Conv1d or Embedding layer of the module (table below). A module without such a layer is guessed from the annotation of the first data parameter of its forward: str gives text and PIL.Image.Image gives img. A module that cannot be guessed raises ValueError and a callable that cannot be guessed raises GenException.
The unnamed inputs take the names proc_input_<j>.
Without proc_outputs the checker calls the module once on dummy inputs (a random tensor with batch size 1 and 8 for every unknown size, a random 224 × 224 RGB picture or the text "test text as input") and describes each output it receives (table below). An output of another type raises ValueError("Unsupported output type ...").
The unnamed outputs take the names proc_output_<j>.
proc_opts gains optimizer: None and losses: [None] * len(proc_outputs) when they are missing. Each torch.nn.functional.cross_entropy or torch.nn.CrossEntropyLoss among the losses becomes target_shape_fixed_cross_entropy.
The agent receives proc, proc_inputs, proc_outputs, proc_opts and proc_optional_inputs from the wrapper.
First layer
Guessed input
Conv2d with 1 or 3 channels
img. The checker tries the module on an RGB and a grayscale picture. When it accepts both there is no transform. When it accepts only RGB the transform converts to 3 channels. When it accepts only grayscale the transform converts to 1 channel. When it accepts neither the transform is transforms_factory("rgb") or transforms_factory("gray").
Conv2d with another number of channels
tensor of torch.float32 with shape (None, C, None, None).
Conv1d
tensor of torch.float32 with shape (None, C, None).
Linear
tensor of torch.float32 with shape (None, in_features).
Embedding
text when the module accepts a string. Otherwise a torch.long tensor of token ids with labels token0, token1, ... of shape (None, None) or (None, 1).
Output of the dummy call
Guessed output
PIL.Image.Image
img.
tensor of shape [b, 3, H, W] or [b, 1, H, W]
img with the inverse of transforms_factory("rgb") or transforms_factory("gray").
other tensor
tensor with its dtype and the shape (None, *shape[1:]). A 0-dimensional tensor gives the shape ().
str
text.
The probes of steps 5 and 7 restore the state_dict of the module afterwards. The dummy call of step 7 is a real call of the model. An explicit proc_outputs skips it. A slow model or a model behind a paid API should therefore always get one.
proc_opts must use the keys optimizer and losses. Because step 9 always adds both keys, an optimizer or a known loss function stored under any other key makes the checker raise AssertionError (About proc_opts: cannot find required keys ...). A key lr creates no optimizer.
defhas_human_processor(agent:object)->bool:"""Checks whether the given agent has a human processor module. Args: agent: The agent object to inspect; expected to have a ``proc`` attribute. Returns: True if the agent's processor module is a HumanModule, False otherwise. """asserthasattr(agent,"proc")returngetattr(agent,"proc")isnotNoneandisinstance(getattr(agent,"proc").module,HumanModule)
Returns True when agent.proc is a wrapper around a HumanModule. The agent must have the attribute proc (otherwise AssertionError). AgentBasics calls it to know whether a person drives the agent.
defforward(self,text:str|None=None,img:Image.Image|None=None,file:object|None=None,whatever:object|None=None)->tuple[str|None,Image.Image|None,object|None]:"""Returns the text, image and file inputs as-is (placeholder for human interaction). The person's inputs are text, img, file and all; the outputs that a node declares take these in order (a node with outputs text and img gives back the text and the image only). Args: text: Optional text input. img: Optional PIL image input. file: Optional file input (a FileContainer). whatever: Optional additional input (ignored). Returns: A tuple ``(text, img, file)`` with the unchanged inputs. """returntext,img,file
Returns (text, img, file) unchanged. The four parameters text, img, file and whatever default to None. whatever is accepted and ignored. A node with proc_outputs=["text"] keeps the text only because the wrapper drops the outputs beyond proc_outputs. Pass proc_inputs and proc_outputs explicitly because the guess of the outputs fails on the None elements of the tuple. proc="human" builds the same module with the streams text and img.
defforward(self,*args:object,**kwargs:object)->object:"""Returns the single input unchanged, or all positional inputs as a tuple. Args: *args: One or more input tensors / objects. **kwargs: Unused. Returns: The single input if exactly one positional argument is given, otherwise the full ``args`` tuple. """iflen(args)==1:returnargs[0]returnargs
Returns its single positional argument. With zero or more than one positional argument it returns their tuple. Keyword arguments are ignored.
def__init__(self,log_file:str|None=None)->None:"""Initializes the LoggerModule. Args: log_file: Path to the log file that records inputs and outputs (default: ``"app_log.txt"``). """super().__init__()self.log_file=log_fileself._initialized=Falseself._logger=logging.getLogger("CallableLogger")self._logger.setLevel(logging.INFO)self.__handler=Noneself._idx=0self._objects=["telescope","hammer","compass","anchor","lantern","keyboard","cat","dog","tiger","zebra","batman","superman","candy","table","chair","balloon","kitchen","sofa","lamp","arrow","green","red","blue","yellow","magenta","brown","pink","orange","white","paris","rome","boston","york","berlin","singapore","taiwan","japan","china","turkey","italy","france","germany","spain","madrid","barcelona","portugal","norway","sweden","belgium","romania","sunny","snowy","rainy"]random.shuffle(self._objects)
A test processor that logs what it receives and answers with a word from a list. The constructor takes log_file (str or None, default None) and shuffles a list of 53 words (objects, animals, colors, cities, weather).
defforward(self,text:str,img:Image.Image|None=None)->tuple[str|None,Image.Image|None]:"""Logs the received inputs and returns a cycling dummy text response with no image output. Args: text: The text input to log. img: An optional PIL image input to log (not forwarded to the output). Returns: A tuple ``(response_text, None)`` where ``response_text`` is the next item from the internal word cycle. """ifself.log_fileisnotNone:ifnotself._initialized:self.__setup_logger()self._logger.info("-------------------------------------------------------------------------------")self._logger.info(f"[INPUT] text={textiftextisnotNoneelseNone}, "f"img={img.sizeifimgisnotNoneelseNone}")else:log.user(f"[INPUT] text={textiftextisnotNoneelseNone}, "f"img={img.sizeifimgisnotNoneelseNone}")text=f"{self._idx}_{self._objects[self._idx]}"self._idx=(self._idx+1)%len(self._objects)img=Noneifself.log_fileisnotNone:self._logger.info(f"[OUTPUT] text={text}, img={None}")self._logger.info("-------------------------------------------------------------------------------")self.__handler.flush()else:log.user(f"[OUTPUT] text={text}, img={None}")returntext,img
Takes text and an optional picture img and returns (f"{i}_{word}", None) with i the position in the list. The position cycles over the list. With log_file=None the input and the answer go to the USER channel of the logger. With a path the first call creates its folders and truncates the file. Every call then writes the input (the text and the size of the picture) and the answer to it. Because all the instances share the Python logger "CallableLogger", two instances with two files write each line to both files.
deftransforms_factory(trans_type:str,add_batch_dim:bool=True,return_inverse:bool=False)->transforms.Compose|None:"""Builds and returns a torchvision transform pipeline for the given type. Args: trans_type: A string identifying the desired transform. Supported values are ``"rgb<N>"`` / ``"gray<N>"`` (resize + center-crop to ``<N>`` pixels, with normalization). ``"rgb-no_norm<N>"`` / ``"gray-no_norm<N>"`` (resize + center-crop, no normalization). ``"rgb"`` / ``"gray"`` (full-image with normalization). ``"rgb-no_norm"`` / ``"gray-no_norm"`` (full-image, no normalization). ``"gray_mnist"`` (MNIST-specific 28×28 grayscale pipeline). add_batch_dim: If True, appends an ``unsqueeze(0)`` step to the forward transform and inserts a ``squeeze(0)`` step at the start of the inverse transform (default: True). return_inverse: If True, returns the inverse (de-normalization) transform instead of the forward transform (default: False). Returns: The requested ``transforms.Compose`` pipeline (or None, if the type is unknown). """supported_types={"rgb*","gray*","rgb-no_norm*","gray-no_norm*","rgb","gray","rgb-no_norm","gray-no_norm","gray_mnist"}found=Falsenum=-1for_typeinsupported_types:if_type.endswith("*"):has_star=True__type=_type[0:-1]else:has_star=False__type=_typeifhas_starandtrans_type.startswith(__type)andlen(trans_type)>len(__type):try:num=int(trans_type[len(__type):])trans_type=_typefound=TruebreakexceptValueError:passeliftrans_type==_type:found=Truebreakifnotfound:raiseValueError(f"Invalid transformation type '{trans_type}': must be one of {supported_types}, "f"where * is an integer number")trans=Noneinverse_trans=Noneiftrans_type=="rgb*":trans=transforms.Compose([transforms.Lambda(lambdaimg:img.convert("RGB")ifimg.mode!="RGB"elseimg),# Ensure 3 chanstransforms.Resize(num),transforms.CenterCrop(num),transforms.ToTensor(),# Convert PIL to tensor (3, H, W), float [0,1]transforms.Normalize(mean=[0.485,0.456,0.406],std=[0.229,0.224,0.225]),])inverse_trans=transforms.Compose([transforms.Normalize(mean=[0.,0.,0.],std=[1./0.229,1./0.224,1./0.225]),transforms.Lambda(lambdax:torch.clamp(x+torch.tensor([0.485,0.456,0.406]).view(3,1,1),min=0.0,max=1.0)),transforms.ToPILImage()])eliftrans_type=="gray*":trans=transforms.Compose([transforms.Lambda(lambdaimg:img.convert("L")ifimg.mode!="L"elseimg),# Ensure 1 channeltransforms.Resize(num),transforms.CenterCrop(num),transforms.ToTensor(),# Convert PIL to tensor (1, H, W), float [0,1]transforms.Normalize(mean=[0.45],std=[0.225])])inverse_trans=transforms.Compose([transforms.Normalize(mean=[0.],std=[1./0.225]),transforms.Lambda(lambdax:torch.clamp(x+0.45,min=0.0,max=1.0)),transforms.ToPILImage()])eliftrans_type=="rgb-no_norm*":trans=transforms.Compose([transforms.Lambda(lambdaimg:img.convert("RGB")ifimg.mode!="RGB"elseimg),# Ensure 3 channelstransforms.Resize(num),transforms.CenterCrop(num),transforms.PILToTensor(),# Convert PIL to tensor (3, H, W), uint [0,255]])inverse_trans=transforms.Compose([transforms.ToPILImage()])eliftrans_type=="gray-no_norm*":trans=transforms.Compose([transforms.Lambda(lambdaimg:img.convert("L")ifimg.mode!="L"elseimg),# Ensure 1 channeltransforms.Resize(num),transforms.CenterCrop(num),transforms.PILToTensor(),# Convert PIL to tensor (1, H, W), uint [0,255]])inverse_trans=transforms.Compose([transforms.ToPILImage()])eliftrans_type=="rgb":trans=transforms.Compose([transforms.Lambda(lambdaimg:img.convert("RGB")ifimg.mode!="RGB"elseimg),# Ensure 3 channelstransforms.ToTensor(),# Convert PIL to tensor (3, H, W), float [0,1]transforms.Normalize(mean=[0.485,0.456,0.406],std=[0.229,0.224,0.225])])inverse_trans=transforms.Compose([transforms.Normalize(mean=[0.,0.,0.],std=[1./0.229,1./0.224,1./0.225]),transforms.Lambda(lambdax:torch.clamp(x+torch.tensor([0.485,0.456,0.406]).view(3,1,1),min=0.0,max=1.0)),transforms.ToPILImage()])eliftrans_type=="gray":trans=transforms.Compose([transforms.Lambda(lambdaimg:img.convert("L")ifimg.mode!="L"elseimg),# Ensure 1 channeltransforms.ToTensor(),# Convert PIL to tensor (1, H, W), float [0,1]transforms.Normalize(mean=[0.45],std=[0.225])])inverse_trans=transforms.Compose([transforms.Normalize(mean=[0.],std=[1./0.225]),transforms.Lambda(lambdax:torch.clamp(x+0.45,min=0.0,max=1.0)),transforms.ToPILImage()])eliftrans_type=="rgb-no_norm":trans=transforms.Compose([transforms.Lambda(lambdaimg:img.convert("RGB")ifimg.mode!="RGB"elseimg),# Ensure 3 channelstransforms.PILToTensor(),# Convert PIL to tensor (3, H, W), uint [0,255]])inverse_trans=transforms.Compose([transforms.ToPILImage()])eliftrans_type=="gray-no_norm":trans=transforms.Compose([transforms.Lambda(lambdaimg:img.convert("L")ifimg.mode!="L"elseimg),# Ensure 1 channeltransforms.PILToTensor(),# Convert PIL to tensor (1, H, W), uint [0,255]])inverse_trans=transforms.Compose([transforms.ToPILImage()])eliftrans_type=="gray_mnist":trans=transforms.Compose([transforms.Lambda(lambdaimg:img.convert("L")ifimg.mode!="L"elseimg),# Ensure 1 channeltransforms.Resize(28),transforms.CenterCrop(28),transforms.ToTensor(),# Convert PIL to tensor (1, H, W), float [0,1]transforms.Normalize(mean=[0.1307],# MNISTstd=[0.3081])# MNIST])inverse_trans=transforms.Compose([transforms.Normalize(mean=[0.],std=[1./0.3081]),transforms.Lambda(lambdax:torch.clamp(x+0.1307,min=0.0,max=1.0)),transforms.ToPILImage()])ifadd_batch_dimand(transisnotNoneandinverse_transisnotNone):trans.transforms.append(transforms.Lambda(lambdax:x.unsqueeze(0)))inverse_trans.transforms.insert(0,transforms.Lambda(lambdax:x.squeeze(0)))returntransifnotreturn_inverseelseinverse_trans
Returns a torchvision.transforms.Compose that turns a PIL picture into a tensor or the inverse transform.
Argument
Type
Default
Meaning
trans_type
str
required
One of the types below. <N> is an integer.
add_batch_dim
bool
True
True appends unsqueeze(0) to the forward transform and puts squeeze(0) first in the inverse.
return_inverse
bool
False
True returns the inverse transform (tensor to PIL picture).
trans_type
Forward transform
Output (with the batch dimension)
"rgb<N>"
RGB, resize of the shorter side to N, center crop N × N, ToTensor, ImageNet normalization (mean 0.485, 0.456, 0.406, std 0.229, 0.224, 0.225)
[1, 3, N, N], float32
"gray<N>"
Grayscale, resize, center crop, ToTensor, normalization (mean 0.45, std 0.225)
[1, 1, N, N], float32
"rgb-no_norm<N>", "gray-no_norm<N>"
As above without ToTensor and normalization, with PILToTensor
[1, C, N, N], uint8 in [0, 255]
"rgb", "gray"
As "rgb<N>" and "gray<N>" without resize and crop
[1, C, H, W], float32
"rgb-no_norm", "gray-no_norm"
Conversion and PILToTensor only
[1, C, H, W], uint8
"gray_mnist"
Grayscale, resize and crop to 28, ToTensor, MNIST normalization (mean 0.1307, std 0.3081)
[1, 1, 28, 28], float32
The inverse of a normalized type undoes the normalization, clamps to [0, 1] and converts to a PIL picture. The inverse of a no_norm type only converts. Another trans_type raises ValueError.
fromPILimportImagefromunaiverse.modules.utilsimporttransforms_factoryt=transforms_factory("rgb224")x=t(Image.open("cat.jpg"))# [1, 3, 224, 224]back=transforms_factory("rgb224",return_inverse=True)(x)# A PIL picture again
defget_proc_inputs_and_proc_outputs_for_rnn(u_shape:torch.Size|tuple,du_dim:int,y_dim:int)->tuple[list,list]:"""Creates Stream descriptors for the inputs and output of an RNN-style processor. Args: u_shape: Shape of the main input tensor (excluding the batch dimension). du_dim: Dimensionality of the secondary (delta-u) input. y_dim: Dimensionality of the output. Returns: A tuple ``(proc_inputs, proc_outputs)`` where each element is a list of ``Stream`` objects describing the processor's I/O signature. """ifisinstance(u_shape,torch.Size):u_shape=tuple(u_shape)proc_inputs=[StreamType(data_type="tensor",tensor_shape=(None,)+u_shape,tensor_dtype=torch.float32,pubsub=False,private_only=False),StreamType(data_type="tensor",tensor_shape=(None,du_dim,),tensor_dtype=torch.float32,pubsub=False,private_only=False)]proc_outputs=[StreamType(data_type="tensor",tensor_shape=(None,y_dim),tensor_dtype=torch.float32,pubsub=False,private_only=False)]returnproc_inputs,proc_outputs
Returns (proc_inputs, proc_outputs) for a network that reads a signal and a descriptor: two torch.float32 tensor inputs of shape (None, *u_shape) and (None, du_dim) and one torch.float32 tensor output of shape (None, y_dim). u_shape is a tuple or a torch.Size. The recurrent and state-space networks of networks use it.
defget_proc_inputs_and_proc_outputs_for_image_classification(y_dim:int=-1,trans_forms:Callable|None=None) \
->tuple[list[StreamType],list[StreamType]]:"""Creates Stream descriptors for the inputs and output of an image-classification processor. Args: y_dim: Number of output classes. Pass ``-1`` to default to 1000 (ImageNet). trans_forms: Stream to processor transforms, if any (Default: None). Returns: A tuple ``(proc_inputs, proc_outputs)`` where each element is a list of ``Stream`` objects describing the processor's I/O signature. """ify_dim==-1:y_dim=1000# Assuming ImageNet-trained modelsproc_inputs=[StreamType(data_type="img",pubsub=False,private_only=False,stream_to_proc_transforms=trans_forms)]proc_outputs=[StreamType(data_type="tensor",tensor_shape=(None,y_dim),tensor_dtype=torch.float32,pubsub=False,private_only=False)]returnproc_inputs,proc_outputs
Returns (proc_inputs, proc_outputs) for an image classifier: one img input with the stream-to-processor transform trans_forms (default None) and one torch.float32 tensor output of shape (None, y_dim). y_dim=-1 (the default) stands for 1000 classes. The classifiers of networks use it.
defset_seed(seed:int)->None:"""Seeds all relevant random-number generators for reproducibility. Args: seed: The integer seed value. If negative, no seeding is performed. """ifseed>=0:torch.manual_seed(seed)random.seed(seed)np.random.seed(seed)
Seeds torch.manual_seed, random.seed and numpy.random.seed with seed. A negative seed does nothing. ModuleWrapper.__init__ calls it with its seed argument.
defhard_tanh(x:torch.Tensor)->torch.Tensor:"""Clamps tensor values to the range [-1, 1] (hard tanh activation). Args: x: Input tensor. Returns: Tensor with all values clamped to ``[-1, 1]``. """returntorch.clamp(x,min=-1.,max=1.)
deftarget_shape_fixed_cross_entropy(output:torch.Tensor,target:torch.Tensor,*args:Any,**kwargs:Any)->torch.Tensor:"""Computes cross-entropy loss, squeezing a leading batch dimension from the target if present. Args: output: The model output logits tensor. target: The target class-index tensor; if it has more than one dimension the first dimension is squeezed before calling ``cross_entropy``. *args: Additional positional arguments forwarded to ``torch.nn.functional.cross_entropy``. **kwargs: Additional keyword arguments forwarded to ``torch.nn.functional.cross_entropy``. Returns: The scalar cross-entropy loss tensor. """iflen(target.shape)>1:target=target.squeeze(0)returntorch.nn.functional.cross_entropy(output,target,*args,**kwargs)
Calls torch.nn.functional.cross_entropy(output, target, *args, **kwargs) after removing the first dimension of target when target has more than one dimension. A target stream sample of shape [1, b] thus reaches the loss as [b]. AgentProcessorChecker puts it in place of every cross-entropy loss of proc_opts.
defisinstance_fcn(obj:object,class_to_check:type|tuple)->bool:"""Thin wrapper around the built-in ``isinstance`` function. Args: obj: The object to test. class_to_check: A type or tuple of types to check against. Returns: True if ``obj`` is an instance of ``class_to_check``, False otherwise. """returnisinstance(obj,class_to_check)
deferror_rate_mnist_test_set(network:torch.nn.Module,mnist_data_save_path:str)->float:"""Evaluates a network's classification error rate on the MNIST test set, in one blocking call (drains the stepwise generator above). Args: network: The PyTorch module to evaluate. mnist_data_save_path: Path where the MNIST dataset will be downloaded and cached. Returns: The fraction of misclassified test samples (in [0, 1]). """gen=error_rate_mnist_test_set_steps(network,mnist_data_save_path)whileTrue:try:next(gen)exceptStopIterationasstop:returnstop.value
Returns the error rate (a float in [0, 1]) of network on the 10000 pictures of the MNIST test set. The function downloads the dataset into mnist_data_save_path when it is not there, normalizes the pictures (mean 0.1307, std 0.3081) and feeds batches of 200 tensors of shape [200, 1, 28, 28] to the module on the device of its first parameter. The prediction is the argmax over dimension 1. The module runs in evaluation mode and gets its previous mode back at the end. The function needs the PyTorch module itself in place of the wrapper.
deferror_rate_mnist_test_set_steps(network:torch.nn.Module,mnist_data_save_path:str) \
->Generator[None,None,float]:"""Generator variant of error_rate_mnist_test_set, one chunk of work per yield: the dataset setup is a chunk of its own (it may touch the disk), then one test batch per chunk. Built for AgentBasics.stepwise, so the node loop keeps pumping during the evaluation. torch.no_grad() is entered and exited within each chunk (grad mode is thread-global: it must never stay flipped across a yield), and the train-mode restore lives in a finally block, which also runs if an abandoned generator is garbage-collected. Returns the error rate like the plain function. Args: network: The PyTorch module to evaluate. mnist_data_save_path: Path where the MNIST dataset will be downloaded and cached. Returns: The fraction of misclassified test samples (in [0, 1]). """# Getting MNIST test setmnist_test=datasets.MNIST(root=mnist_data_save_path,train=False,download=True,transform=transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.1307,),(0.3081,))]))mnist_test=DataLoader(mnist_test,batch_size=200,shuffle=False)yield# Checking error rateerror_rate=0.n=0training_flag_backup=network.trainingnetwork.eval()try:device=next(network.parameters()).deviceforx,yinmnist_test:withtorch.no_grad():x=x.to(device)y=y.to(device)o=network(x)c=torch.argmax(o,dim=1)error_rate+=float(torch.sum(c!=y).item())n+=x.shape[0]yieldfinally:network.train(training_flag_backup)returnerror_rate/n
The same evaluation as a generator. It yields None once after loading the dataset and once after every batch. Its return value (the value of StopIteration) is the error rate. torch.no_grad() covers each batch only and the evaluation mode is restored in a finally block. A role that evaluates during the life of a node uses it through AgentBasics.stepwise. That method advances the generator one chunk per tick and keeps the node running.
The FeatherlessAPI processors of one machine share one gateway process. The gateway owns the connection to Featherless, keeps one budget of units per API key and serves the requests in strict round robin between processes. The environment variables of this section are read when the module is imported (see Configuration).
The frozenset of the sampling options that the chat-completions API of OpenAI takes as fields: max_tokens, temperature, top_p, frequency_penalty, presence_penalty, stop, seed, n, logit_bias, logprobs, top_logprobs and response_format. featherless_call and OpenRouterAPI send these as fields and every other option in the extra body of the request.
asyncdeffeatherless_call(sys_prompt:str,prompt:str,sampler:dict|None=None,model:str|None=None,api_key:str|None=None)->str|None:"""Perform the actual call to the Featherless API and return the generated text (async). Args: sys_prompt: The system prompt, if any (can be empty). prompt: The prompt string to send to the model. sampler: Sampling parameters to send (e.g. ``temperature``, ``max_tokens``, ``top_p``, ``top_k``, ``frequency_penalty``, ``presence_penalty``, ``repetition_penalty``, ``min_p``). OpenAI-native keys are passed as top-level fields; any other key is forwarded via ``extra_body``. None/empty uses API defaults. model: The model identifier to use; if None, falls back to the MODEL_ID environment variable. api_key: The Featherless API key to authenticate with (None falls back to FEATHERLESS_API_KEY). Returns: The text generated by the model. """client=_get_featherless_client(api_key)model=modeloros.environ.get("MODEL_ID","MOD")ifmodel=="MOD":log.critical("Calling Featherless API: the model argument was not set; ""the MODEL_ID environment variable was not set!")# Split the requested sampler params: OpenAI-native ones go top-level, the rest ride along in extra_bodysampler=sampleror{}extra_body={k:vfork,vinsampler.items()ifknotinOPENAI_NATIVE_SAMPLER_PARAMS}native={k:vfork,vinsampler.items()ifkinOPENAI_NATIVE_SAMPLER_PARAMS}def_account_log(row_to_add:str)->None:"""Append a row to the per-account usage log, if the flag file enables it (crash-durable append)."""flag_file=os.path.expanduser("~/DO_LOG_FEATHERLESS_AI")ifos.path.exists(flag_file):file_path=os.path.join(os.path.expanduser("~"),f"featherless_ai_account_{(api_keyor'env')[-6:]}.log")withopen(file_path,"a")asf:f.write(row_to_add+" \n")f.flush()# Flushes Python's internal buffer to OS bufferos.fsync(f.fileno())# Forces OS buffer to write to physical storage# Retry with exponential backoff, keeping the last error so a final failure reports its causelast_err=Noneforattemptinrange(3):current_time=datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")t0=time.perf_counter()try:# Always use chat completions; include the system message only when a system prompt is givenmsgs=[{"role":"system","content":sys_prompt}]ifsys_promptelse[]msgs.append({"role":"user","content":prompt})# The dict is typed dict[str, object] so PyCharm accepts the mixed value types (str / list / int / float)kwargs:dict[str,object]={"model":model,"messages":msgs,**native}ifextra_body:kwargs["extra_body"]=extra_bodyresp=awaitclient.chat.completions.create(**kwargs)# type: ignoreelapsed=time.perf_counter()-t0# Diagnostics: wall time, throughput, completion length + stop reason. A large completion_tokens count# suggests thinking is still on; a low tokens/sec on a warm model points at a slow/cold API replica.usage=getattr(resp,"usage",None)c_toks=getattr(usage,"completion_tokens",0)finish_reason=resp.choices[0].finish_reasonifresp.choiceselse"n/a"tps=f"{c_toks/elapsed:.1f}"if(c_toksandelapsed>0)else"n/a"_account_log(f"{current_time} model={model} finish_reason={finish_reason} "f"completion_tokens={c_toksifc_toksisnotNoneelse'n/a'} "f"elapsed={elapsed:.2f}s tokens/sec={tps}")# Return the first choice that carries non-empty text (content may be None)forchoiceinresp.choices:content=choice.message.contentifcontentisnotNoneandcontent.strip():returncontent# Empty/blank content: treat it as a transient failure so the loop retries instead of returning ""finish=resp.choices[0].finish_reasonifresp.choiceselse"n/a"last_err=RuntimeError(f"Empty content from model (finish_reason={finish})")exceptExceptionase:last_err=eelapsed=time.perf_counter()-t0_account_log(f"{current_time} model={model} FAILED attempt={attempt+1} "f"elapsed={elapsed:.2f}s error={e!r}")# Retry on either an exception or empty contentlog.error(f"Empty response or exception! (prompt={prompt}, attempt={attempt+1}, last_err={last_err!r}), "f"waiting {2**attempt} seconds before trying again...")awaitasyncio.sleep(2**attempt)log.critical(f"Featherless AI call failed after retries: {last_err!r}")# This will raise an exceptionreturn""# Never reached
The coroutine that the gateway uses for one generation. It returns the text of the answer.
Argument
Type
Default
Meaning
sys_prompt
str
required
The system message. "" sends none.
prompt
str
required
The user message.
sampler
dict or None
None
The sampling options.
model
str or None
None
The model. None reads the environment variable MODEL_ID.
api_key
str or None
None
The key. None reads FEATHERLESS_API_KEY.
The function creates one openai.AsyncOpenAI client per key on https://api.featherless.ai/v1 on first use and keeps it. It raises GenException without a model or a key. An exception or an answer without text counts as a failed attempt. The function logs each failed attempt on the ERROR channel with the whole prompt and then sleeps 2 ** attempt seconds (1 after the first, 2 after the second and 4 after the third). After the third failure and its sleep it raises GenException. When the file ~/DO_LOG_FEATHERLESS_AI exists, every attempt appends a line (time, model, stop reason, tokens, duration) to ~/featherless_ai_account_<last 6 characters of the key>.log.
def__init__(self,call:Callable=featherless_call)->None:"""Create a Server. Args: call: The asynchronous function performing the actual model call (Default: featherless_call). """self.scheds:dict[str,APIGatewayScheduler]={}# API key -> scheduler (own queues/budget/dispatcher)self.call:Callable=callself.live:set=set()# Set of registration writers (one per live client)self.shutdown:asyncio.Event=asyncio.Event()
The gateway. It listens on TCP and speaks newline-delimited JSON:
Message
Direction
Meaning
{"op": "hello"}
client to server
Registers the connection that carries it. The registration lasts as long as the connection.
{"ok": true, "result": "..."} or {"ok": false, "error": "..."}
server to client
The answer to a request on the same connection.
The constructor takes the coroutine call that performs a generation (default featherless_call). It creates the attributes scheds (one APIGatewayScheduler per API key), live (the registered connections) and shutdown (an asyncio.Event).
asyncdefhandle(self,reader:asyncio.StreamReader,writer:asyncio.StreamWriter)->None:"""Serve a single client connection until it closes (async). A connection that sends ``{"op": "hello"}`` is treated as that client's liveness registration; a connection that sends ``{"op": "generate", ...}`` has its query scheduled and the result written back. Args: reader: The stream reader for the client connection. writer: The stream writer for the client connection. """registered=Falsetry:whileTrue:line=awaitreader.readline()ifnotline:break# Connection closed by the client (or it died)try:msg=json.loads(line)exceptjson.JSONDecodeError:continueop=msg.get("op")ifop=="hello":# This connection is the client's liveness registrationregistered=Trueself.live.add(writer)elifop=="generate":pid=msg["process_id"]sys_prompt=msg.get("sys_prompt","")prompt=msg["prompt"]cost=int(msg.get("cost",1))model=msg.get("model")sampler=msg.get("sampler")or{}api_key=msg.get("api_key")oros.environ.get("FEATHERLESS_API_KEY","")key_units=int(msg.get("key_units",APIGatewayServer.TOTAL_UNITS))ifcostnotinAPIGatewayServer.VALID_COSTS:out={"ok":False,"error":f"bad cost {cost}"}elifnotapi_key:out={"ok":False,"error":"no API key: not in the request, and no FEATHERLESS_API_KEY"}else:try:sched=self._sched_for(api_key,key_units)result=awaitsched.submit(pid,sys_prompt,prompt,cost,model,sampler)out={"ok":True,"result":result}exceptExceptionase:out={"ok":False,"error":str(e)}writer.write((json.dumps(out)+"\n").encode())awaitwriter.drain()except(ConnectionResetError,asyncio.IncompleteReadError):passfinally:ifregistered:self.live.discard(writer)# When the last interested client disconnects, shut downifnotself.live:self.shutdown.set()try:writer.close()exceptException:pass
Serves one connection until it closes. A line that is not JSON is ignored. A generate request with a cost outside VALID_COSTS or without a key (in the request or in FEATHERLESS_API_KEY) gets an error answer. Every other request goes to the scheduler of its key and the coroutine writes the answer when the generation ends. An exception of the generation becomes an error answer with its message. When a registered connection closes and no registration is left, the gateway shuts down.
asyncdefrun(self)->None:"""Bind the listening socket, start the dispatcher, and run until shutdown is requested (async). Binding also arbitrates the startup race: if the port is already taken, ``start_server`` raises and this process is not the server. A grace period guards against an orphan server whose starter died before registering. """# Bind first (this is also the startup-race arbiter): if the port is taken, bind() raises and we are NOT# the server. Dispatchers are started lazily, one per API key, on the first request mentioning each keyserver=awaitasyncio.start_server(self.handle,APIGatewayServer.HOST,APIGatewayServer.PORT)# Grace period: if no client registers shortly after boot, exit, so a server spawned by a starter that# immediately died does not lingergrace_secs=float(os.environ.get("GW_GRACE","10"))asyncdefgrace():awaitasyncio.sleep(grace_secs)ifnotself.live:self.shutdown.set()asyncio.create_task(grace())asyncwithserver:awaitself.shutdown.wait()
Binds HOST:PORT and serves until shutdown. Binding fails with OSError when another gateway holds the port. When no client has registered GW_GRACE seconds (default 10) after the start, the gateway shuts down. This handles a starter process that died before registering. The scheduler of a key and its dispatcher task start with the first request that mentions the key. That request also fixes the budget of the key. A later request that declares another budget is served under the first one and the mismatch is logged.
def__init__(self,total_units:int=-1)->None:"""Create a Scheduler. Args: total_units: The total unit budget this scheduler admits (negative falls back to GW_UNITS) (Default: -1). """self.total_units:int=total_unitsiftotal_units>0elseAPIGatewayServer.TOTAL_UNITSself.available:int=self.total_unitsself.cond:asyncio.Condition=asyncio.Condition()self.queues:dict[str,asyncio.Queue]={}# Process ID -> queue of (prompt, cost, model, fut) - ORDEREDself.rr:int=0# Round-robin cursor into the (insertion-ordered) list of process IDs
The queue of the requests of one API key. The constructor takes total_units. Its default -1 stands for APIGatewayServer.TOTAL_UNITS. The attributes are total_units, available (the units not in use), queues (one FIFO queue per process id) and rr (the round-robin cursor).
The scheduler serves one request per process per turn whatever its cost. When the turn comes to a process whose next request does not fit in the available units, the dispatcher holds it and waits for units without serving anybody else. A request whose cost exceeds total_units can never be served and stalls the scheduler of its key forever.
asyncdefsubmit(self,pid:str,sys_prompt:str,prompt:str,cost:int,model:str|None,sampler:dict|None=None)->str:"""Enqueue a query for a process and wait until the dispatcher runs it (async). Args: pid: The process ID the query belongs to (round-robin fairness is per process). sys_prompt: The system prompt string (can be ""). prompt: The prompt string to send to the model. cost: The query's unit cost (one of VALID_COSTS). model: The model identifier to use (None lets the call fall back to its own default). sampler: Sampling parameters to forward to the model call (None means use API defaults). Returns: The model's textual result. """fut:asyncio.Future=asyncio.get_running_loop().create_future()awaitself._queue(pid).put((sys_prompt,prompt,cost,model,sampler,fut))asyncwithself.cond:self.cond.notify_all()# Wake the dispatcher: there is new workreturnawaitfut
Queues a request of process pid and waits for the string of its result. The arguments are pid, sys_prompt, prompt, cost, model and sampler (default None). An exception of the generation is raised here.
asyncdefdispatcher(self,call:Callable)->None:"""Forever serve queued queries in strict round-robin order under the unit budget (async). Args: call: The asynchronous function performing the actual model call (passed on to each job). """# held[pid] holds a (prompt, cost, model, fut) we popped for a process but could not launch yet (its turn came# but the budget did not fit). Strict hold keeps it here until it can run; never put it back nor skip past it.held:dict={}whileTrue:asyncwithself.cond:pids=list(self.queues.keys())ifnotpids:awaitself._wait_locked()continuepid=pids[self.rr%len(pids)]q=self.queues[pid]# Determine this process's current head: either the one we are holding, or the next one off its queueifpidinheld:sys_prompt,prompt,cost,model,sampler,fut=held[pid]elifnotq.empty():sys_prompt,prompt,cost,model,sampler,fut=q.get_nowait()else:# The current process has nothing: advance the turn. If nobody has work at all, wait; otherwise# keep rotating until we reach a process that doesself.rr=(self.rr+1)%len(pids)ifall(self.queues[p].empty()forpinpids)andnotheld:awaitself._wait_locked()continueifself.available>=cost:self.available-=costheld.pop(pid,None)asyncio.create_task(self._run_job(sys_prompt,prompt,cost,model,sampler,fut,call))self.rr=(self.rr+1)%len(pids)continueelse:# Strict hold: it is this process's turn and its head does not fit. Hold the head and wait for units# to free up. Do NOT advance the cursor and do NOT serve anyone else.held[pid]=(sys_prompt,prompt,cost,model,sampler,fut)awaitself._wait_locked()continue
The task that runs forever and launches the queued requests in turn with the coroutine call(sys_prompt, prompt, sampler, model). Each launched request takes its cost from available and gives it back when it ends. APIGatewayServer starts one dispatcher per key.
defserve_api_gateway()->None:"""Process entrypoint for the detached gateway server (see the APIGatewayServer class). Spawned by the client via ``python -c "from unaiverse.modules.utils import serve_api_gateway; serve_api_gateway()"``. We deliberately do NOT use ``python -m unaiverse.modules.utils`` here: importing the parent package ``unaiverse.modules`` already imports this module, so running it again via ``runpy`` would execute a second copy of it under the name ``__main__`` (RuntimeWarning, and two distinct APIGatewayServer classes). Calling this function avoids that. """asyncdef_main():# Construct the server INSIDE the running loop: the scheduler builds an asyncio.Condition, which binds to# the current loop at creation. Building it before asyncio.run() would bind it to the wrong loop.awaitAPIGatewayServer(call=featherless_call).run()try:asyncio.run(_main())exceptOSError:pass# Port already bound: another process beat us to it, just exit
The entry point of the gateway process. It runs APIGatewayServer(call=featherless_call).run() in a new event loop and returns when the gateway shuts down. An OSError (the port is taken) ends it silently. FeatherlessAPI starts it with python -c "from unaiverse.modules.utils import serve_api_gateway; serve_api_gateway()".