afnio.cognitive.modules
afnio.cognitive.modules.Add
Bases: Module
Performs element-wise addition of two input Variables.
This module utilizes the Add operation from
afnio.autodiff.basic_ops. The inputs must be instances of the
Variable class. The forward method applies the addition
operation to the data field of the inputs and returns
the resulting Variable.
Note
This module does not have any trainable parameters.
Examples:
>>> from afnio import cognitive as cog
>>> class Addition(cog.Module):
... def __init__(self):
... super().__init__()
... self.add = cog.Add()
>>> def forward(self, x, y):
... return self.add(x, y)
>>> input1 = afnio.Variable(data="abc", role="input1")
>>> input2 = afnio.Variable(data="def", role="input2")
>>> addition = Addition()
>>> result = addition(input1, input2)
>>> print(result.data)
'abcdef'
>>> print(result.role)
'input1 and input2'
Raises:
| Type | Description |
|---|---|
TypeError
|
If either input is not an instance of |
TypeError
|
If addition between the input types is not allowed. |
ValueError
|
|
ValueError
|
If list |
See Also
afnio.autodiff.basic_ops.Add
for the underlying operation.
Source code in afnio/cognitive/modules/add.py
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | |
forward(x, y)
Forward pass for element-wise addition.
Warning
Users should not call this method directly. Instead, they should call the
module instance itself, which will internally invoke this forward method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Variable
|
The first input |
required |
y
|
Variable
|
The second input |
required |
Returns:
| Type | Description |
|---|---|
Variable
|
A new |
Raises:
| Type | Description |
|---|---|
TypeError
|
If either input is not an instance
of |
TypeError
|
If addition between the input types is not allowed. |
ValueError
|
|
ValueError
|
If list |
Source code in afnio/cognitive/modules/add.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | |
afnio.cognitive.modules.ChatCompletion
Bases: Module
Generates a chat-based completion using a language model.
This module leverages the ChatCompletion
operation from afnio.autodiff.lm_ops to perform model inference. The forward
method accepts a list of messages representing the conversation history, with
optional dynamic inputs for filling placeholders within the messages. The
forward_model_client is responsible for interfacing with the language model
(e.g., gpt-4.1), while completion_args allows customization of generation
parameters such as temperature, maximum tokens, and seed.
Examples:
>>> from afnio import cognitive as cog
>>> from afnio.models.openai import OpenAI
>>> from afnio import set_backward_model_client
>>> fwd_model_client = OpenAI()
>>> fwd_model_args = {"model": "gpt-4o", "temperature": 0.7}
>>> set_backward_model_client("openai/gpt-4o")
>>> class Assistant(cog.Module):
... def __init__(self):
... super().__init__()
... self.chat = cog.ChatCompletion()
... def forward(self, fwd_model, messages, inputs, **completion_args):
... return self.chat(fwd_model, messages, inputs, **completion_args)
>>> system = Variable(
... "You are a helpful assistant.",
... role="system instruction",
... requires_grad=True
... )
>>> user = Variable("Translate 'Hello' to {language}.", role="user query")
>>> language = afnio.Variable("Italian", role="language")
>>> messages = [
... {"role": "system", "content": [system]},
... {"role": "user", "content": [user]},
... ]
>>> agent = Assistant()
>>> response = agent(
... fwd_model_client,
... messages,
... inputs={"language": language},
... **fwd_model_args
... )
>>> print(response.data)
'Ciao'
>>> feedback = Variable("Use only capital letters.", role="feedback")
>>> response.backward(feedback)
>>> system.grad[0].data
'The system instruction should enforce the use of capital letters only.'
Raises:
| Type | Description |
|---|---|
TypeError
|
If the types of |
See Also
afnio.autodiff.lm_ops.ChatCompletion
for the underlying operation.
Source code in afnio/cognitive/modules/chat_completion.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
forward(forward_model_client, messages, inputs=None, **completion_args)
Forward pass for the chat completion function.
Warning
Users should not call this method directly. Instead, they should call the
module instance itself, which will internally invoke this forward method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forward_model_client
|
ChatCompletionModel | None
|
The LM model client used for generating chat completions. |
required |
messages
|
MultiTurnMessages
|
A list of messages that compose the prompt/context for the LM.
Each message is a dictionary with a |
required |
inputs
|
dict[str, str | Variable] | None
|
A dictionary mapping placeholder names to their corresponding
values, which can be strings or |
None
|
**completion_args
|
Additional keyword arguments to pass to the LM model
client's |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
response |
Variable
|
A |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the types of |
Source code in afnio/cognitive/modules/chat_completion.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
afnio.cognitive.modules.DeterministicEvaluator
Bases: Module
Evaluates predictions deterministically using a user-defined evaluation function.
This module utilizes the DeterministicEvaluator
operation from afnio.autodiff.evaluator to compute evaluation scores and
explanations. The forward method takes in a prediction, a target, an
evaluation function (eval_fn), and its purpose description (eval_fn_purpose).
It also accepts a reduction function (reduction_fn) and its purpose description
(reduction_fn_purpose) to aggregate scores if needed. The method outputs
an evaluation score and an explanation, both as Variable instances. The
success_fn checks if all evaluations are successful, allowing the backward pass
to skip unnecessary gradient computations. The method outputs an evaluation
score and an explanation, both as Variable instances.
Examples:
>>> from afnio import cognitive as cog
>>> from afnio import set_backward_model_client
>>> set_backward_model_client("openai/gpt-4o")
>>> class ExactColor(cog.Module):
... def __init__(self):
... super().__init__()
... def exact_match_fn(pred: str, tgt: str) -> int:
... return 1 if pred == tgt_data else 0
... self.exact_match_fn = exact_match_fn
... self.fn_purpose = "exact match"
... self.reduction_fn = sum
... self.reduction_fn_purpose = "summation"
... self.exact_match = cog.DeterministicEvaluator()
... def forward(self, prediction, target):
... return self.exact_match(
... prediction,
... target,
... self.exact_match_fn,
... self.fn_purpose,
... self.reduction_fn,
... self.reduction_fn_purpose,
... )
>>> prediction = afnio.Variable(
... data=["the color is green", "blue"],
... role="color prediction",
... requires_grad=True
... )
>>> target = ["green", "blue"]
>>> eval = ExactColor()
>>> score, explanation = eval(prediction, target)
>>> print(score.data)
1
>>> print(explanation.data)
'The evaluation function, designed for 'exact match', compared the <DATA> fields of the predicted variable and the target variable across all samples in the batch, generating individual scores for each pair. These scores were then aggregated using the reduction function 'summation', resulting in a final aggregated score: 1.'
>>> explanation.backward()
>>> prediction.grad[0].data
'Reassess the criteria that led to the initial prediction of 'green'.'
Raises:
| Type | Description |
|---|---|
TypeError
|
If the types of |
ValueError
|
If the lengths of |
See Also
afnio.autodiff.evaluator.DeterministicEvaluator
for the underlying operation.
Source code in afnio/cognitive/modules/deterministic_evaluator.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | |
forward(prediction, target, eval_fn, eval_fn_purpose, success_fn, reduction_fn, reduction_fn_purpose)
Forward pass for the deterministic evaluator function.
Warning
Users should not call this method directly. Instead, they should call the
module instance itself, which will internally invoke this forward method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prediction
|
Variable
|
The predicted variable to evaluate, which can have scalar or
list |
required |
target
|
str | list[str] | Variable
|
The target (ground truth) to compare against, which can be a string,
a list of strings, or a |
required |
eval_fn
|
Callable[[Variable, Union[str, Variable]], list[Any]]
|
required | |
eval_fn_purpose
|
str | Variable
|
A brief description of the purpose of |
required |
success_fn
|
Callable[[List[Any]], bool] | None
|
A user-defined function that takes the list of scores returned
by |
required |
reduction_fn
|
Callable[[List[Any]], Any] | None
|
An optional function to aggregate scores across a batch of
predictions and targets. If |
required |
reduction_fn_purpose
|
str | Variable | None
|
A brief description of the purpose of |
required |
Returns:
| Name | Type | Description |
|---|---|---|
score |
Variable
|
A variable containing the evaluation score(s),
or their aggregation if |
explanation |
Variable
|
A variable containing the explanation(s) of the evaluation,
or their aggregation if |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the types of |
ValueError
|
If the lengths of |
Source code in afnio/cognitive/modules/deterministic_evaluator.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | |
afnio.cognitive.modules.ExactMatchEvaluator
Bases: Module
Evaluates predictions using an exact match criterion.
This module leverages the ExactMatchEvaluator
operation from afnio.autodiff.evaluator and is a specialized version of the
DeterministicEvaluator
that uses an exact matching function to compare the prediction and target.
It returns an evaluation score (1 for exact match, 0 otherwise)
and an explanation describing the evaluation result.
Examples:
>>> from afnio import cognitive as cog
>>> from afnio import set_backward_model_client
>>> set_backward_model_client("openai/gpt-4o")
>>> class ExactColor(cog.Module):
... def __init__(self):
... super().__init__()
... self.exact_match = cog.ExactMatchEvaluator()
... def forward(self, prediction, target):
... return self.exact_match(prediction, target)
>>> prediction = afnio.Variable(
... data="green",
... role="color prediction",
... requires_grad=True
... )
>>> target = "red"
>>> eval = ExactColor()
>>> score, explanation = eval(prediction, target)
>>> print(score.data)
0
>>> print(explanation.data)
'The evaluation function, designed for 'exact match', compared the <DATA> fields of the predicted variable and the target variable, resulting in a score: 0.'
>>> explanation.backward()
>>> prediction.grad[0].data
'Reassess the criteria that led to the initial prediction of 'green'.'
Raises:
| Type | Description |
|---|---|
TypeError
|
If the types of |
ValueError
|
If the lengths of |
See Also
afnio.autodiff.evaluator.ExactMatchEvaluator
for the underlying operation.
Source code in afnio/cognitive/modules/exact_match_evaluator.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
forward(prediction, target, reduction_fn=sum, reduction_fn_purpose='summation')
Forward pass for the exact match evaluator function.
Warning
Users should not call this method directly. Instead, they should call the
module instance itself, which will internally invoke this forward method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prediction
|
Variable
|
The predicted variable to evaluate, which can have scalar or
list |
required |
target
|
str | list[str] | Variable
|
The target (ground truth) to compare against, which can be a string,
a list of strings, or a |
required |
reduction_fn
|
Callable[[List[Any]], Any] | None
|
An optional function to aggregate scores across a batch of
predictions and targets. If |
sum
|
reduction_fn_purpose
|
str | Variable | None
|
A brief description of the purpose of |
'summation'
|
Returns:
| Name | Type | Description |
|---|---|---|
score |
Variable
|
A variable containing the evaluation score(s),
or their aggregation if |
explanation |
Variable
|
A variable containing the explanation(s) of the evaluation,
or their aggregation if |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the types of |
ValueError
|
If the lengths of |
Source code in afnio/cognitive/modules/exact_match_evaluator.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
afnio.cognitive.modules.LMJudgeEvaluator
Bases: Module
Evaluates predictions using a language model (LM) as the judge.
This module leverages the LMJudgeEvaluator
operation from afnio.autodiff.evaluator to perform model-based evaluations.
The forward method accepts a list of messages that construct the evaluation
prompt, with optional inputs to dynamically fill placeholders within message
templates. A prediction is compared against a target (optional) to generate
a score and an explanation.
When processing a batch of predictions and targets, reduction_fn function
aggregates individual scores (e.g., using sum to compute a total score). The
reduction_fn_purpose parameter is a brief description of the aggregation's purpose
(e.g., "summation"). If aggregation is not desired, set reduction_fn and
reduction_fn_purpose to None. The success_fn checks if all evaluations are
successful, allowing the backward pass to skip unnecessary gradient computations.
This module supports both evaluation (eval_mode=True) and optimization
(eval_mode=False) modes.
The forward_model_client specifies the LM responsible for evaluation, while
completion_args allows customization of generation parameters like temperature,
max tokens, and seed.
Examples:
>>> from afnio import cognitive as cog
>>> from afnio.models.openai import OpenAI
>>> from afnio import set_backward_model_client
>>> fwd_model_client = OpenAI()
>>> fwd_model_args = {"model": "gpt-4o", "temperature": 0.5}
>>> set_backward_model_client("openai/gpt-4o")
>>> class Evaluator(cog.Module):
... def __init__(self):
... super().__init__()
... self.judge = cog.LMJudgeEvaluator()
... def forward(self, fwd_model, messages, prediction, target, inputs, **completion_args):
... return self.judge(fwd_model, messages, prediction, target, inputs, **completion_args)
>>> task = afnio.Variable(
... "Evaluate if the translation is {metric}.",
... role="evaluation task",
... requires_grad=True
... )
>>> format = afnio.Variable(
... "Provide 'score' (true/false) and 'explanation' in JSON.",
... role="output format"
... )
>>> metric = afnio.Variable(["accurate", "accurate"], role="metric")
>>> user = afnio.Variable(
... "<PREDICTION>{prediction}</PREDICTION><TARGET>{target}</TARGET>",
.. role="user query"
... )
>>> prediction = afnio.Variable(
... ["Hola Mundo", "Salve a tutti"],
... role="translated text",
... requires_grad=True
... )
>>> target = ["Ciao Mondo", "Salve a tutti"]
>>> messages = [
... {"role": "system", "content": [task, format]},
... {"role": "user", "content": [user]},
... ]
>>> eval = Evaluator()
>>> score, explanation = eval(
... fwd_model_client,
... messages,
... prediction,
... target,
... inputs={"metric": metric},
... reduction_fn=sum,
... reduction_fn_purpose="summation",
... **fwd_model_args
... )
>>> print(score.data)
1
>>> print(explanation.data)
'The evaluation function, designed using an LM as the judge, compared the <DATA> fields of the predicted variable and the target variable across all samples in the batch. These scores were then aggregated using the reduction function 'summation', resulting in a final aggregated score: 1.'
>>> explanation.backward()
>>> system.grad[0].data
'The translated text should be in Italian.'
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the LM response to generate the evaluation |
TypeError
|
If the types of |
ValueError
|
If the lengths of |
See Also
afnio.autodiff.evaluator.LMJudgeEvaluator
for the underlying operation.
Source code in afnio/cognitive/modules/lm_judge_evaluator.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
forward(forward_model_client, messages, prediction, target=None, inputs=None, success_fn=None, reduction_fn=sum, reduction_fn_purpose='summation', eval_mode=True, **completion_args)
Forward pass for the LM Judge evaluator function.
Warning
Users should not call this method directly. Instead, they should call the
module instance itself, which will internally invoke this forward method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forward_model_client
|
ChatCompletionModel | None
|
The LM model client used for the forward pass evaluation. |
required |
messages
|
MultiTurnMessages
|
A list of messages that compose the prompt/context for the LM.
Each message is a dictionary with a |
required |
prediction
|
Variable
|
The predicted variable to evaluate, which can have scalar or
list |
required |
target
|
str | list[str] | Variable | None
|
The target (ground truth) to compare against, which can be a string,
a list of strings, or a |
None
|
inputs
|
dict[str, str | Variable] | None
|
A dictionary mapping placeholder names to their corresponding
values, which can be strings or |
None
|
success_fn
|
Callable[[List[Any]], bool] | None
|
A user-defined function that takes the list of scores returned
by the LM Judge and returns |
None
|
reduction_fn
|
Callable[[List[Any]], Any] | None
|
An optional function to aggregate scores across a batch of
predictions and targets. If |
sum
|
reduction_fn_purpose
|
str | Variable | None
|
A brief description of the purpose of |
'summation'
|
eval_mode
|
bool | Variable
|
Indicates the evaluation mode. If |
True
|
**completion_args
|
Additional keyword arguments to pass to the LM model
client's |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
score |
Variable
|
A variable containing the evaluation score(s),
or their aggregation if |
explanation |
Variable
|
A variable containing the explanation(s) of the evaluation,
or their aggregation if |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the LM response to generate the evaluation |
TypeError
|
If the types of |
ValueError
|
If the lengths of |
Source code in afnio/cognitive/modules/lm_judge_evaluator.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
afnio.cognitive.modules.Module
Base class for all LM pipeline modules.
Your pipeline should also subclass this class.
Modules can also contain other Modules, allowing to nest them in a tree structure. You can assign the submodules as regular attributes.
Examples:
>>> import afnio as hf
>>> import afnio.cognitive as cog
>>> import torch.cognitive.functional as F
>>> from afnio.models.openai import OpenAI
>>> from afnio import set_backward_model_client
>>>
>>> fwd_model_client = OpenAI()
>>> fwd_model_args = {"model": "gpt-4o", "temperature": 0.7}
>>> set_backward_model_client("openai/gpt-4o")
>>>
>>> class MedQA(cog.Module):
... def __init__(self):
... super().__init__()
... self.system_prompt = cog.Parameter(
... data="You are a doctor. Only answer medical questions on these areas:",
... role="system prompt",
... requires_grad=True,
... )
... self.topics = cog.Parameter(
... data="Dermatology and Cardiology",
... role="medical topics",
... requires_grad=False,
... )
... self.epilogue = afnio.Variable(
... data="\nThank you for your query.",
... role="response preamble",
... )
... self.chat = cog.ChatCompletion()
>>>
>>> def forward(self, fwd_model, user_query, inputs, **completion_args):
... messages = [
... {"role": "system", "content": [self.system_prompt, self.topics]},
... {"role": "user", "content": [user_query]},
... ]
... response = self.chat(fwd_model, messages, inputs, **completion_args)
... return F.Add(response, self.epilogue)
Submodules assigned in this way will be registered with the Module.
For example, in the MedQA example above, self.chat (the ChatCompletion()
instance) is the submodule that gets registered with the Module MedQA.
Note
As per the example above, an __init__() call to the parent class
must be made before assignment on the child.
Attributes:
| Name | Type | Description |
|---|---|---|
training |
bool
|
Boolean represents whether this module is in training or evaluation
mode. Defaults to |
automatic_optimization |
bool
|
Boolean that determines whether optimization steps
handled automatically by the
|
Source code in afnio/cognitive/modules/module.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 | |
training
instance-attribute
Boolean represents whether this module is in training or evaluation mode.
Defaults to True.
automatic_optimization
instance-attribute
Boolean that determines whether optimization steps handled automatically
by the Trainer.fit() or manually by the user.
Defaults to True.
If True, the Trainer.fit() method will
automatically call optimizer.clear_grad(), explanation.backward(), and
optimizer.step(). If False, the user must perform backpropagation and optimizer
steps manually in the [training_step()][afnio.cognitive.modules.Module.automatic_optimization.training_step] method.
__init__(*args, **kwargs)
Initialize internal Module state.
Calls super().__setattr__('a', a) instead of the typical self.a = a
to avoid Module.__setattr__ overhead. Module's __setattr__ has special
handling for parameters, submodules, buffers, multi-turn chats, language model
clients and completion configurations but simply calls into
super().__setattr__ for all other attributes.
Source code in afnio/cognitive/modules/module.py
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | |
forward(*args, **kwargs)
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
One should invoke the Module instance (Module.__call__ method)
instead of directly calling Module.forward(). This way hooks are
registered and run.
Source code in afnio/cognitive/modules/module.py
197 198 199 200 201 202 203 204 205 206 207 208 209 210 | |
extra_repr()
abstractmethod
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
Returns:
| Type | Description |
|---|---|
str
|
A string containing the extra representation of the module, which will be included in the module's |
Source code in afnio/cognitive/modules/module.py
218 219 220 221 222 223 224 225 226 227 228 229 | |
register_buffer(name, variable, persistent=True)
Add a buffer to the module.
This is typically used to register a buffer that should not to be
considered an agent Parameter.
For example, LMJudgeEvaluator's
reduction_fn_purpose is not a parameter, but is part of the module's state.
Buffers, by default, are persistent and will be saved alongside parameters.
This behavior can be changed by setting persistent to False. The only
difference between a persistent buffer and a non-persistent buffer is that the
latter will not be a part of this module's state_dict.
Buffers can be accessed as attributes using given names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the buffer. The buffer can be accessed from this module using the given name. |
required |
variable
|
Variable | None
|
Buffer to be registered. If |
required |
persistent
|
bool
|
Whether the buffer is part of this module's
|
True
|
Example:: >>> self.register_buffer('reduction_fn_purpose', afnio.Variable(data="summation", role="reduction function purpose"))
Source code in afnio/cognitive/modules/module.py
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |
register_parameter(name, param)
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the parameter. The parameter can be accessed from this module using the given name. |
required |
param
|
Parameter | None
|
Parameter to be added to the module. If |
required |
Source code in afnio/cognitive/modules/module.py
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 | |
register_chat(name, messages)
Add multi-turn chat messages to the module.
The chat can be accessed as an attribute using given name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the chat. The chat can be accessed from this module using the given name. |
required |
messages
|
MultiTurnMessages | None
|
Chat to be added to the module. If |
required |
Source code in afnio/cognitive/modules/module.py
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 | |
register_model(name, model)
Add language model the module.
The language model can be accessed as an attribute using given name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the model. The model can be accessed from this module using the given name. |
required |
model
|
BaseModel | None
|
Model to be added to the module. If |
required |
Source code in afnio/cognitive/modules/module.py
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 | |
register_completion_config(name, args)
Register completion-specific arguments for text generation.
This method allows dynamic storage of completion-related parameters
such as temperature, max_tokens, top_p, etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the completion argument set. |
required |
args
|
dict[str, Any] | None
|
Dictionary of completion arguments. If |
required |
Source code in afnio/cognitive/modules/module.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 | |
register_function(name, func)
Add a function to the module.
The function can be accessed as an attribute using given name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the function. The function can be accessed from this module using the given name. |
required |
func
|
FunctionType | None
|
A standard Python function (i.e., a def-defined function, not a lambda
or callable object) that can be pickled and registered for later
execution. If |
required |
Source code in afnio/cognitive/modules/module.py
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 | |
register_module(name, module)
Add a child module to the current module.
This method explicitly adds a child module to the current module's hierarchy.
The child module can then be accessed as an attribute using the given name
and will be registered in the _modules dictionary.
When to use:
- Use register_module() when dynamically adding submodules at runtime,
especially when the submodule name is determined programmatically.
- This can be useful for creating flexible and modular architectures.
When it's unnecessary:
- Directly assigning the module to an attribute (e.g.,
self.module_name = SubModule()) automatically registers it, so using
register_module() is unnecessary in such cases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the child module. The child module can be accessed from this module using the given name. |
required |
module
|
Module | None
|
Child module to be added to the module. |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
KeyError
|
If |
Examples:
>>> class DynamicPipeline(cog.Module):
>>> def __init__(self):
>>> super().__init__()
>>> # Dynamically add submodules
>>> for i in range(3):
>>> self.register_module(f"layer_{i}", cog.Module())
>>>
>>> pipeline = DynamicPipeline()
>>> print(pipeline._modules.keys())
odict_keys(['layer_0', 'layer_1', 'layer_2'])
Note
If assigning submodules using standard attribute assignment
(e.g., self.submodule = SubModule()), calling register_module()
explicitly is not required. Direct assignment automatically registers
the module.
Source code in afnio/cognitive/modules/module.py
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 | |
state_dict(*, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Parameters, persistent buffers (e.g. running averages), multi-turn chats,
models, completion configs and functions are included. Keys are corresponding
parameter, buffer, chat, model, completion config and function names.
Parameters, buffers, chats, models, completion configs and functions
set to None are not included.
Note
The returned object is a shallow copy. It contains references to the module's parameters, buffers, chats, models, completion configs and functions.
Warning
Please avoid the use of argument destination as it is not
designed for end-users.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
destination
|
dict
|
If provided, the state of module will
be updated into the dict and the same object is returned.
Otherwise, an |
None
|
prefix
|
str
|
A prefix added to parameter, buffer, chat, model,
completion config and function names to compose the keys in state_dict.
Default: |
''
|
keep_vars
|
bool
|
By default the |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
A dictionary containing a whole state of the module. |
Examples:
>>> module.state_dict().keys()
['system_prompt', 'classification_labels', 'format_type', 'user_prompt']
Source code in afnio/cognitive/modules/module.py
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 | |
load_state_dict(state_dict, strict=True, assign=False, model_clients=None)
Copy parameters, buffers, chats, models, completion configs and functions
from state_dict into this module and its descendants.
If strict is True, then the keys of state_dict must exactly match the keys
returned by this module's state_dict function.
Warning
If assign is True the optimizer must be created after
the call to load_state_dict.
Note
If a parameter, or buffer, or chat, or model, or completion config, or
function is registered as None and its corresponding key exists in
state_dict, load_state_dict will raise a RuntimeError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dict
|
dict
|
A dict containing parameters, persistent buffers, chats, models, completion configs and functions. |
required |
strict
|
bool
|
Whether to strictly enforce that the keys
in |
True
|
assign
|
bool
|
When |
False
|
model_clients
|
dict
|
A dictionary mapping model client keys
(e.g., 'fw_model_client') to their respective instances of
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
incompatible_keys |
NamedTuple
|
A |
Note
The return value reports key mismatches encountered during loading:
missing_keysis a list of str containing any keys that are expected by this module but missing from the providedstate_dict.unexpected_keysis a list of str containing the keys that are not expected by this module but present in the providedstate_dict.
Source code in afnio/cognitive/modules/module.py
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 | |
get_extra_state()
Return any extra state to include in the module's state_dict.
Implement this and a corresponding set_extra_state for
your module if you need to store extra state. This function is called when
building the module's state_dict().
Note that extra state should be picklable to ensure working serialization of the state_dict.
Returns:
| Name | Type | Description |
|---|---|---|
object |
Any
|
Any extra state to store in the module's state_dict. |
Source code in afnio/cognitive/modules/module.py
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 | |
set_extra_state(state)
Set extra state contained in the loaded state_dict.
This function is called from load_state_dict to handle
any extra state found within the state_dict. Implement this function and a
corresponding get_extra_state for your module if you need
to store extra state within its state_dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict
|
Extra state from the |
required |
Source code in afnio/cognitive/modules/module.py
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 | |
buffers(recurse=True)
Return an iterator over module buffers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recurse
|
bool
|
if |
True
|
Yields:
| Type | Description |
|---|---|
Variable
|
Module buffer |
Examples:
>>> for buf in model.buffers():
>>> print(type(buf), buf.data)
<class 'afnio.Variable'> ("Structure your answer as JSON.")
<class 'afnio.Variable'> ("Use the format\n\n{\n \"response\": \"Your concise answer here.\"\n}")
Source code in afnio/cognitive/modules/module.py
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 | |
named_buffers(prefix='', recurse=True, remove_duplicate=True)
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
prefix to prepend to all buffer names. |
''
|
recurse
|
bool
|
if |
True
|
remove_duplicate
|
bool
|
whether to remove the duplicated buffers
in the result. Defaults to |
True
|
Yields:
| Type | Description |
|---|---|
tuple[str, Variable]
|
Tuple containing the name and buffer |
Examples:
>>> for name, buf in self.named_buffers():
>>> if "format_type" in name:
>>> print(param.data)
Source code in afnio/cognitive/modules/module.py
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 | |
parameters(recurse=True)
Return an iterator over module parameters.
This is typically passed to an optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recurse
|
bool
|
if |
True
|
Yields:
| Type | Description |
|---|---|
Parameter
|
Module parameter |
Examples:
>>> for param in pipeline.parameters():
>>> print(type(param), param.data)
<class 'cog.Parameter'> ("You are a doctor.")
<class 'cog.Parameter'> ("Only answer with YES or NO.")
Source code in afnio/cognitive/modules/module.py
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 | |
named_parameters(prefix='', recurse=True, remove_duplicate=True)
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
prefix to prepend to all parameter names. |
''
|
recurse
|
bool
|
if |
True
|
remove_duplicate
|
bool
|
whether to remove the duplicated
parameters in the result. Defaults to |
True
|
Yields:
| Type | Description |
|---|---|
tuple[str, Parameter]
|
Tuple containing the name and parameter |
Examples:
>>> for name, param in self.named_parameters():
>>> if "prompt" in name:
>>> print(param.data)
Source code in afnio/cognitive/modules/module.py
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 | |
chats(recurse=True)
Return an iterator over module multi-turn chats.
This is typically passed to an optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recurse
|
bool
|
if |
True
|
Yields:
| Type | Description |
|---|---|
MultiTurnMessages
|
Module chats |
Examples:
>>> for chat in pipeline.chats():
>>> print(type(chat), chat)
<class 'cog.MultiTurnMessages'> [{'role': 'system', 'content': [Variable(data=You are a doctor., role=system instruction, requires_grad=False)]}, {'role': 'user', 'content': [Variable(data=Is {item} a disease?, role=user query, requires_grad=False)]}]
<class 'cog.MultiTurnMessages'> [{'role': 'system', 'content': [Variable(data=You are a helpful assistant., role=system instruction, requires_grad=False), Variable(data=Only answer with YES or NO., role=user query, requires_grad=False)]}]
Source code in afnio/cognitive/modules/module.py
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 | |
named_chats(prefix='', recurse=True, remove_duplicate=True)
Return an iterator over module multi-turn chats, yielding both the name of chat as well as the chat itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
prefix to prepend to all chat names. |
''
|
recurse
|
bool
|
if |
True
|
remove_duplicate
|
bool
|
whether to remove the duplicated
chats in the result. Defaults to |
True
|
Yields:
| Type | Description |
|---|---|
tuple[str, MultiTurnMessages]
|
Tuple containing the name and chat |
Examples:
>>> for name, chat in self.named_chats():
>>> if "messages" in name:
>>> print(messages[0]["role"])
Source code in afnio/cognitive/modules/module.py
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 | |
models(recurse=True)
Return an iterator over module language model clients.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recurse
|
bool
|
if |
True
|
Yields:
| Type | Description |
|---|---|
BaseModel
|
Module model |
Examples:
>>> for model in pipeline.models():
>>> print(type(model))
<class 'afnio.models.openai.AsyncOpenAI'>
Source code in afnio/cognitive/modules/module.py
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 | |
named_models(prefix='', recurse=True, remove_duplicate=True)
Return an iterator over module model clients, yielding both the name of the model as well as the model itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
prefix to prepend to all model names. |
''
|
recurse
|
bool
|
if |
True
|
remove_duplicate
|
bool
|
whether to remove the duplicated
models in the result. Defaults to |
True
|
Yields:
| Type | Description |
|---|---|
tuple[str, BaseModel]
|
Tuple containing the name and model |
Examples:
>>> for name, model in self.named_models():
>>> print(name, type(model))
model_client <class 'afnio.models.openai.AsyncOpenAI'>
Source code in afnio/cognitive/modules/module.py
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 | |
completion_configs(recurse=True)
Return an iterator over registered completion configs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recurse
|
bool
|
if |
True
|
Yields:
| Type | Description |
|---|---|
dict[str, Any]
|
Completion arguments |
Examples:
>>> for config in model.completion_configs():
>>> print(config)
{"model": "gpt-4o", "seed": 42, "temperature": 0}
Source code in afnio/cognitive/modules/module.py
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 | |
named_completion_configs(prefix='', recurse=True, remove_duplicate=True)
Return an iterator over module completion configs, yielding both the name of the completion config as well as the completion config itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
prefix to prepend to all completion config names. |
''
|
recurse
|
bool
|
if |
True
|
remove_duplicate
|
bool
|
whether to remove the duplicated
completion configs in the result. Defaults to |
True
|
Yields:
| Type | Description |
|---|---|
tuple[str, dict[str, Any]]
|
Tuple containing the name and completion configs |
Examples:
>>> for name, config in self.named_completion_configs():
>>> print(name, type(config))
chat.completion_args {'model': 'gpt-4o', 'seed': 42, 'temperature': 0}
Source code in afnio/cognitive/modules/module.py
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 | |
functions(recurse=True)
Return an iterator over registered functions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recurse
|
bool
|
if |
True
|
Yields:
| Type | Description |
|---|---|
dict[str, Any]
|
Functions |
Examples:
>>> for func in model.functions():
>>> print(func)
<built-in function sum>
<function my_func at 0x7e7a0665b9c0>
Source code in afnio/cognitive/modules/module.py
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 | |
named_functions(prefix='', recurse=True, remove_duplicate=True)
Return an iterator over module functions, yielding both the name of the function as well as the function itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
prefix to prepend to all function names. |
''
|
recurse
|
bool
|
if |
True
|
remove_duplicate
|
bool
|
whether to remove the duplicated
functions in the result. Defaults to |
True
|
Yields:
| Type | Description |
|---|---|
tuple[str, dict[str, Any]]
|
Tuple containing the name and functions |
Examples:
>>> for name, func in self.named_functions():
>>> print(name, func)
reduction_fn <built-in function sum>
eval_fn <function my_func at 0x7e7a0665b9c0>
Source code in afnio/cognitive/modules/module.py
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 | |
children()
Return an iterator over immediate children modules.
Yields:
| Type | Description |
|---|---|
Module
|
A child module |
Source code in afnio/cognitive/modules/module.py
1929 1930 1931 1932 1933 1934 1935 1936 | |
named_children()
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
Yields:
| Type | Description |
|---|---|
tuple[str, Module]
|
Tuple containing a name and child module |
Source code in afnio/cognitive/modules/module.py
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 | |
modules()
Return an iterator over all modules in the network.
Yields:
| Type | Description |
|---|---|
Module
|
A module in the network |
Note
Duplicate modules are returned only once. In the following
example, add will be returned only once.
Examples:
>>> class MyPipeline(cog.Module):
... def __init__(self):
... super().__init__()
... add = cog.Add()
... self.module1 = add
... self.module2 = add
>>> def forward(self, x, y):
... out1 = self.module1(x, x)
... out2 = self.module2(x, y)
... return out1 + out2
>>> pipeline = MyPipeline()
>>> for idx, m in enumerate(model.modules()):
... print(idx, '->', m)
0 -> MyModel(
(module1): Module()
(module2): Module()
)
1 -> Module()
Source code in afnio/cognitive/modules/module.py
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 | |
named_modules(memo=None, prefix='', remove_duplicate=True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
memo
|
set[Module] | None
|
a memo to store the set of modules already added to the result |
None
|
prefix
|
str
|
a prefix that will be added to the name of the module |
''
|
remove_duplicate
|
bool
|
whether to remove the duplicated module instances in the result or not |
True
|
Yields:
| Type | Description |
|---|---|
tuple[str, Module]
|
Tuple of name and module |
Note
Duplicate modules are returned only once. In the following
example, add will be returned only once.
Examples:
>>> class MyPipeline(cog.Module):
... def __init__(self):
... super().__init__()
... add = cog.Add()
... self.module1 = add
... self.module2 = add
>>> def forward(self, x, y):
... out1 = self.module1(x, x)
... out2 = self.module2(x, y)
... return out1 + out2
>>> pipeline = MyPipeline()
>>> for idx, m in enumerate(model.named_modules()):
... print(idx, '->', m)
0 -> ('', MyModel(
(module1): Module()
(module2): Module()
))
1 -> ('module1', Module())
>>> class MyPipeline(cog.Module):
... def __init__(self):
... super().__init__()
... add = cog.Add()
... self.module1 = add
... self.module2 = add
>>> def forward(self, x, y):
... out1 = self.module1(x, x)
... out2 = self.module2(x, y)
... return out1 + out2
>>> pipeline = MyPipeline()
>>> for idx, m in enumerate(model.named_modules(remove_duplicate=False)):
... print(idx, '->', m)
0 -> ('', MyModel(
(module1): Module()
(module2): Module()
))
1 -> ('module1', Module())
2 -> ('module2', Module())
Source code in afnio/cognitive/modules/module.py
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 | |
train(mode=True)
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
bool
|
whether to set training mode ( |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
Module
|
The module itself. |
Source code in afnio/cognitive/modules/module.py
2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 | |
eval()
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected.
This is equivalent with calling self.train(False).
See train for more details.
Returns:
| Name | Type | Description |
|---|---|---|
self |
Module
|
The module itself. |
Source code in afnio/cognitive/modules/module.py
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 | |
requires_grad_(requires_grad=True)
Change if autodiff should record operations on parameters and chats in this module.
This method sets the requires_grad attributes
of all module parameters in-place. It also sets the
requires_grad attributes of all the
Variables within the content of multi-turn chats.
Effect on Parameters:
- Sets
requires_gradfor each registered parameter in the module.
Effect on Chats:
- Iterates through all multi-turn chats and sets
requires_gradfor eachVariablein the"content"key of the chat's message.
This method is helpful for freezing part of the module for finetuning or training parts of a model individually.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
requires_grad
|
bool
|
Whether autodiff should record operations on parameters and chats in this module. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
Module
|
The module itself. |
Source code in afnio/cognitive/modules/module.py
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 | |
empty_grad()
Reset gradients of all model parameters and content variables in chats' messages.
This method is useful for clearing out gradients before starting a new optimization step. It ensures that both module parameters and Variables within multi-turn chat's message contents have their gradients reset, avoiding unintended gradient accumulation.
Source code in afnio/cognitive/modules/module.py
2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 | |
training_step(batch, batch_idx)
Perform a single training step.
This method should be implemented in subclasses to define the training logic.
It is called by the Trainer
during the training loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Any
|
The output of your data iterable, normally
a [ |
required |
batch_idx
|
int
|
The index of this batch. |
required |
Returns:
| Type | Description |
|---|---|
STEP_OUTPUT
|
The result of the training step (see below below note for details). |
Notes
The return value can be one of the following:
Tuple[Variable, Variable]: The loss as a tuple of twoVariables:- The evaluation
score(aVariablecontaining the loss value). - The
explanation(aVariablecontaining a string explanation of the evaluation result).
- The evaluation
dict: A dictionary. Can include any keys, but must include the key'loss'containing a tuple of twoVariables (scoreandexplanation).None: Skip to the next batch.
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If not implemented in a subclass. |
Source code in afnio/cognitive/modules/module.py
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 | |
validation_step(batch, batch_idx)
Perform a single validation step.
This method should be implemented in subclasses to define the validation logic.
It is called by the Trainer
during the validation loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Any
|
The output of your data iterable,
normally a [ |
required |
batch_idx
|
int
|
The index of this batch. |
required |
Returns:
| Type | Description |
|---|---|
STEP_OUTPUT
|
The result of the validation step (see below below note for details). |
Notes
The return value can be one of the following:
Tuple[Variable, Variable]: The loss as a tuple of twoVariables:- The evaluation
score(aVariablecontaining the loss value). - The
explanation(aVariablecontaining a string explanation of the evaluation result).
- The evaluation
dict: A dictionary. Can include any keys, but must include the key'loss'containing a tuple of twoVariables (scoreandexplanation).None: Skip to the next batch.
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If not implemented in a subclass. |
Source code in afnio/cognitive/modules/module.py
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 | |
test_step(batch, batch_idx)
Perform a single test step.
This method should be implemented in subclasses to define the test logic.
It is called by the Trainer
during the testing loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Any
|
The output of your data iterable,
normally a [ |
required |
batch_idx
|
int
|
The index of this batch. |
required |
Returns:
| Type | Description |
|---|---|
STEP_OUTPUT
|
The result of the test step (see below below note for details). |
Notes
The return value can be one of the following:
Tuple[Variable, Variable]: The loss as a tuple of twoVariables:- The evaluation
score(aVariablecontaining the loss value). - The
explanation(aVariablecontaining a string explanation of the evaluation result).
- The evaluation
dict: A dictionary. Can include any keys, but must include the key'loss'containing a tuple of twoVariables (scoreandexplanation).- None: Skip to the next batch.
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If not implemented in a subclass. |
Source code in afnio/cognitive/modules/module.py
2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 | |
configure_optimizers()
Configure and return the optimizer for this module.
This method should be implemented in subclasses to define the optimizer
configuration. It is called by the Trainer
to set up the optimization routine.
Returns:
| Type | Description |
|---|---|
Optimizer
|
An instance of an optimizer configured for this module. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If not implemented in a subclass. |
Source code in afnio/cognitive/modules/module.py
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 | |
optimizers()
Returns the optimizer(s) that are being used during training. Useful for manual optimization.
This method is useful for accessing the optimizer(s) configured in the
configure_optimizers method by the
Trainer.fit() method.
Returns:
| Type | Description |
|---|---|
Optimizer | list[Optimizer]
|
The optimizer(s) used by this module. |
Examples:
>>> optimizers = model.optimizers()
>>> for optimizer in optimizers:
>>> print(optimizer)
TGD (
Parameter Group 0
completion_args: {'model': 'gpt-4.1'}
constraints: []
inputs: {}
messages: [
{'role': 'system', 'content': [Variable(data="Placeholder Textual Gradient Descent optimizer system prompt", role=Textual Gradient Descent optimizer system prompt, requires_grad=False)]},
{'role': 'user', 'content': [Variable(data="Placeholder for Textual Gradient Descent optimizer user prompt", role=Textual Gradient Descent optimizer user prompt, requires_grad=False)]}
]
model_client: <afnio.models.openai.AsyncOpenAI object at 0x710df9c149a0>
momentum: 3
)
Source code in afnio/cognitive/modules/module.py
2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 | |
afnio.cognitive.modules.Split
Bases: Module
Splits a single input Variable into multiple output Variables.
This module utilizes the Split operation
from afnio.autodiff.basic_ops. It supports string data types, splitting the string
data of the input Variable based on a specified delimiter and an optional maximum
number of splits.
Note
This module does not have any trainable parameters.
Examples:
>>> from afnio import cognitive as cog
>>> class Splitter(cog.Module):
... def __init__(self):
... super().__init__()
... self.split = cog.Split()
>>> def forward(self, x):
... return self.split(x, " ", 1)
>>> input = afnio.Variable(data="Afnio is great!", role="sentence")
>>> splitter = Splitter()
>>> result = splitter(input)
>>> print([r.data for r in result])
['Afnio', 'is great!']
>>> print([r.role for r in result])
['split part 0 of sentence', 'split part 1 of sentence']
Raises:
| Type | Description |
|---|---|
TypeError
|
See Also
afnio.autodiff.basic_ops.Split
for the underlying operation.
Source code in afnio/cognitive/modules/split.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | |
forward(x, sep=None, maxsplit=-1)
Forward pass for splitting a Variable.
Warning
Users should not call this method directly. Instead, they should call the
module instance itself, which will internally invoke this forward method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Variable
|
The input |
required |
sep
|
str | Variable | None
|
The delimiter to use for splitting the string. If |
None
|
maxsplit
|
int | Variable | None
|
The maximum number of splits to perform. If |
-1
|
Returns:
| Type | Description |
|---|---|
list[Variable]
|
A tuple of |
Raises:
| Type | Description |
|---|---|
TypeError
|
Source code in afnio/cognitive/modules/split.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | |
afnio.cognitive.modules.Sum
Bases: Module
Aggregates a list of input Variables into a single output Variable.
This module utilizes the Sum operation from
afnio.autodiff.basic_ops. It supports both numerical (int, float) and string data
types. For numerical data, it computes the sum. For string data, it concatenates
the values and wraps each in <ITEM></ITEM> tags.
Note
This module does not have any trainable parameters.
Examples:
>>> from afnio import cognitive as cog
>>> class Summation(cog.Module):
... def __init__(self):
... super().__init__()
... self.sum = cog.Sum()
>>> def forward(self, x):
... return self.sum(x)
>>> input1 = afnio.Variable(data="abc", role="input1")
>>> input2 = afnio.Variable(data="def", role="input2")
>>> input3 = afnio.Variable(data="ghi", role="input3")
>>> summation = Summation()
>>> result = summation([input1, input2, input3])
>>> print(result.data)
'<ITEM>abc</ITEM><ITEM>def</ITEM><ITEM>ghi</ITEM>'
>>> print(result.role)
'input1 and input2 and input3'
Raises:
| Type | Description |
|---|---|
TypeError
|
See Also
afnio.autodiff.basic_ops.Sum
for the underlying operation.
Source code in afnio/cognitive/modules/sum.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | |
forward(x)
Forward pass for summation.
Warning
Users should not call this method directly. Instead, they should call the
module instance itself, which will internally invoke this forward method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
list[Variable]
|
A list of |
required |
Returns:
| Type | Description |
|---|---|
Variable
|
A new |
Raises:
| Type | Description |
|---|---|
TypeError
|
Source code in afnio/cognitive/modules/sum.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | |