afnio
afnio.MultiTurnMessages = List[Dict[str, List[Variable]]]
module-attribute
Type alias for a list of dictionaries representing multi-turn chat messages.
Each message is a mapping with:
role: Sender role (e.g."user","assistant","system").content: List ofVariableparts representing the message content.
Examples:
>>> msgs: MultiTurnMessages = [
... {"role": "system", "content": [afnio.Variable("You are a helpful assistant.")]},
... {"role": "user", "content": [afnio.Variable("Hello")]}
... ]
afnio.Variable
A class to represent generic data, such as textual inputs, outputs, or numeric data.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
str | int | float | list[str | int | float] | None
|
The raw data, which can be a scalar string or number, or a sequence of such scalars. |
role |
str
|
A specific description of the role of the variable in the agent that provides context to the optimizer. |
requires_grad |
bool
|
Whether to track operations for automatic differentiation and compute gradients. |
grad |
list[Variable]
|
Stores the gradient of the variable, if |
Source code in afnio/_variable.py
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 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 | |
role = role
instance-attribute
A specific description of the role of the variable in the agent. For example, it could be "system prompt for sentiment classification", "input email or message", "output categories", etc.
It is used to give more context about the purpose of the Variable to the Optimizer.
requires_grad = requires_grad
instance-attribute
is_leaf = not requires_grad or self.grad_fn is None
instance-attribute
All Variables that have requires_grad which is False
will be leaf Variables by convention.
For Variables that have requires_grad which is True, they
will be leaf Variables if they were created by the user. This means that they are
not the result of an operation and so grad_fn is None.
Only leaf Variables will have their grad populated during a call to
backward. To get grad populated for non-leaf Variables,
you can use retain_grad.
Examples:
>>> a = afnio.Variable("abc", requires_grad=True)
>>> a.is_leaf
True
>>> b = afnio.Variable("abc", requires_grad=True).upper()
>>> b.is_leaf
False
# b was created by the operation that converts all string characters to uppercase
>>> c = afnio.Variable("abc", requires_grad=True) + "def"
>>> c.is_leaf
False
# c was created by the addition operation
>>> d = afnio.Variable("abc").upper()
>>> d.is_leaf
True
# d does not require gradients and so has no operation creating it (that is tracked by the autodiff engine)
>>> e = afnio.Variable("abc").upper().requires_grad_()
>>> e.is_leaf
True
# e requires gradients and has no operations creating it
data
property
writable
The raw data of the Variable.
Can be either:
- a scalar:
str,intorfloat, or - a sequence: a
listortupleof scalars.
Sequence values must be homogeneous: either all strings or all numbers (ints/floats). Tuples are converted to lists; if a numeric sequence mixes ints and floats the values are promoted to float. Heterogeneous sequences mixing strings and numbers are rejected.
Returns:
| Type | Description |
|---|---|
str | int | float | list[str | int | float] | None
|
The underlying data value (a scalar or a list of scalars). |
grad
property
writable
This attribute is an empty list by default and becomes a list of
Variables the first time a call to backward computes
gradients for self. The attribute will then contain the gradients computed and
future calls to backward will accumulate (append) gradients
into it.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the variable is a non-leaf without |
__init__(data='', role='', requires_grad=False)
Initializes a Variable instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
str | int | float | list[str | int | float] | None
|
The raw data for the variable, which can be a scalar string or number, or a sequence of such scalars. |
''
|
role
|
str
|
A specific description of the role of the variable in the agent that
provides context to the |
''
|
requires_grad
|
bool
|
Whether to track operations for automatic differentiation and compute gradients. |
False
|
Source code in afnio/_variable.py
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 | |
backward(gradient=None, retain_graph=None, create_graph=False, inputs=None)
Computes the gradient of current variable with respect to graph leaves.
The graph is differentiated using the chain rule. If the variable is non-scalar
(i.e. its data has more than one element) and requires gradient, the function
additionally requires specifying a gradient. It should be a variable with
data of matching type and shape, that represents the gradient of the
differentiated function with respect to self.
This function accumulates gradients in the leaf variables; each call to
backward appends new gradient values to the grad list. Clear
existing gradients before calling it again if accumulation is not desired.
Note
When inputs are provided, each input must be a leaf variable. If any
input is not a leaf, a RuntimeError is raised.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gradient
|
Variable | None
|
The gradient of the function being differentiated with respect to
|
None
|
retain_graph
|
bool | None
|
If |
None
|
create_graph
|
bool | None
|
If |
False
|
inputs
|
Variable | Sequence[Variable] | None
|
Inputs with respect to which the gradient will be accumulated into
|
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the variable is a leaf (i.e., does not require grad or
does not have a |
Source code in afnio/_variable.py
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 | |
requires_grad_(mode=True)
Change if autodiff should record operations on this variable: sets this
variable's requires_grad attribute in-place.
Returns this variable.
requires_grad_'s main use case is to tell autodiff to begin recording
operations on a Variable variable. If variable has requires_grad=False
(because it was obtained through a DataLoader, or required preprocessing or
initialization), variable.requires_grad_() makes it so that autodiff will
begin to record operations on variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
bool
|
If autodiff should record operations on this variable. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
self |
Variable
|
The variable with updated |
Examples:
>>> # Initialize with requires_grad=False for data preprocessing
>>> x = afnio.Variable(data="abc", role="input")
>>> x = preprocess(x) # Preprocess without gradient tracking
>>> x
variable(abc, role=input, requires_grad=False)
...
>>> # Now enable requires_grad for backpropagation
>>> x.requires_grad_()
>>> output = model(x)
>>> output.backward() # Backpropagation through `x`
>>> x.grad
variable(ABC, role=input, requires_grad=True)
Source code in afnio/_variable.py
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 | |
append_grad(gradient)
Appends a gradient value to the list grad for this variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gradient
|
Variable
|
The gradient variable to append. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the variable is a non-leaf without |
Source code in afnio/_variable.py
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 | |
retain_grad()
Enables this Variable to have their grad populated during
backward(). This is a no-op for leaf Variables.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the variable is a leaf. |
Source code in afnio/_variable.py
488 489 490 491 492 493 494 495 496 497 498 499 | |
detach()
Returns a new Variable, detached from the computation graph.
This new Variable will not have a grad_fn and will not track gradients.
Returns:
| Type | Description |
|---|---|
Variable
|
A new Variable with the same data and role, but with |
Source code in afnio/_variable.py
501 502 503 504 505 506 507 508 509 | |
copy_(src)
Copies the data from the source Variable into this Variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
Variable
|
The source Variable to copy from. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
self |
Variable
|
The current Variable with updated |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the source is not a Variable. |
ValueError
|
If the source data type does not match the target data type. |
Source code in afnio/_variable.py
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 | |
is_floating_point()
Checks if the Variable's data contains floating-point values.
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in afnio/_variable.py
591 592 593 594 595 596 597 598 599 600 601 602 603 604 | |
to(dtype=None)
Cast the data of the Variable to the specified dtype.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
type | None
|
The target type to cast the data (e.g., |
None
|
Returns:
| Type | Description |
|---|---|
Variable
|
A new Variable with |
Source code in afnio/_variable.py
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 | |
afnio.GradientEdge
Bases: NamedTuple
Object representing a given gradient edge within the autodiff backward graph.
A GradientEdge identifies where a gradient should be propagated during backpropagation. It points to a specific backward node and a specific output index of that node.
Each Variable that participates in autodiff is associated with
one or more GradientEdge objects, which define how gradients flow through the
computation graph.
To get the gradient edge where a given Variable gradient will be computed,
you can do edge = autodiff.graph.get_gradient_edge(variable).
Attributes:
| Name | Type | Description |
|---|---|---|
node |
Node
|
The backward node responsible for producing gradients. This is an instance of a backward Function (e.g. AccumulateGrad, SumBackward0, ChatCompletionBackward0). |
output_nr |
int
|
The index of the output of |
Source code in afnio/autodiff/graph.py
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 | |
afnio.Node
Base class for nodes in the autograd computation graph.
A Node represents a single operation in the backward graph and is
responsible for producing gradients during backpropagation. Each Node
may have multiple inputs and outputs and is connected to other nodes
via GradientEdge objects.
Attributes:
| Name | Type | Description |
|---|---|---|
next_functions |
tuple[GradientEdge]
|
The gradient edges to this node's parent nodes in the backward graph. |
Source code in afnio/autodiff/graph.py
4 5 6 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 | |
next_functions
property
writable
Returns the gradient edges to this node's parent nodes in the backward graph.
Each entry is a tuple of (Node, output_nr) identifying where gradients
should be propagated next during backpropagation.
Returns:
| Type | Description |
|---|---|
tuple[GradientEdge]
|
A tuple of [ |
name()
Returns the name of the backward node.
Returns:
| Type | Description |
|---|---|
str
|
The name of the backward node, which is typically the name of the forward operation that produced the output associated with this node. |
Examples:
>>> import afnio
>>> import afnio.cognitive.functional as F
>>> a = afnio.Variable("Hello,", requires_grad=True)
>>> b = afnio.Variable("world!", requires_grad=True)
>>> c = F.sum([a, b])
>>> assert isinstance(c.grad_fn, afnio.autodiff.graph.Node)
>>> print(c.grad_fn.name())
SumBackward0
Source code in afnio/autodiff/graph.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | |
afnio.get_backward_model_client()
Retrieve the global model client singleton.
This is useful for tracking token usage across the entire backward pass, as all backward operations will use this global client instance.
Returns:
| Type | Description |
|---|---|
ModelClientSingleton
|
The global model client singleton instance. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no model client is set globally. |
Source code in afnio/_model_client.py
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | |
afnio.set_backward_model_client(model_path='openai/gpt-4o', client_args=None, completion_args=None)
Set the global model client for backward operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str
|
Path in the format |
'openai/gpt-4o'
|
client_args
|
dict[str, Any] | None
|
Arguments to initialize the model client such as:
|
None
|
completion_args
|
dict[str, Any] | None
|
Arguments to pass to
|
None
|
Note
For a complete list of supported client_args and completion_args
for each model, refer to the respective API documentation.
Source code in afnio/_model_client.py
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 | |
afnio.is_grad_enabled()
Check whether grad mode is currently enabled.
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in afnio/autodiff/grad_mode.py
9 10 11 12 13 14 15 16 | |
afnio.no_grad()
Context manager that disables gradient calculation. All operations within this block will not track gradients, making them more memory-efficient.
Disabling gradient calculation is useful for inference, when you are sure
that you will not call Variable.backward(). It will
reduce memory consumption for computations that would otherwise have
requires_grad=True.
In this mode, the result of every computation will have
requires_grad=False, even when the inputs have requires_grad=True.
There is an exception! All factory functions, or functions that create
a new Variable and take a requires_grad kwarg, will NOT be affected by
this mode.
This context manager is thread local; it will not affect computation in other threads.
Also functions as a decorator.
Examples:
>>> x = afnio.Variable("abc", role="variable", requires_grad=True)
>>> with afnio.no_grad():
... y = x + x
>>> y.requires_grad
False
>>> @afnio.no_grad()
... def doubler(x):
... return x + x
>>> z = doubler(x)
>>> z.requires_grad
False
>>> @afnio.no_grad()
... def tripler(x):
... return x + x + x
>>> z = tripler(x)
>>> z.requires_grad
False
>>> # factory function exception
>>> with afnio.no_grad():
... a = afnio.cognitive.Parameter("xyz")
>>> a.requires_grad
True
Source code in afnio/autodiff/grad_mode.py
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 | |
afnio.set_grad_enabled(mode)
Set the global state of gradient calculation on or off.
set_grad_enabled will enable or disable gradients based on its argument mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
bool
|
If |
required |
Examples:
>>> x = afnio.Variable("Hello", requires_grad=True)
>>> _ = afnio.set_grad_enabled(True)
>>> y = x + x
>>> y.requires_grad
True
>>> _ = afnio.set_grad_enabled(False)
>>> y = x + x
>>> y.requires_grad
False
Source code in afnio/autodiff/grad_mode.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | |
afnio.load(f)
Loads an object from a disk file using zip compression and pickle serialization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
str | PathLike | BinaryIO | IO[bytes]
|
A file-like object (must
implement |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The deserialized object. |
Examples:
>>> # Load from file
>>> obj = afnio.load('model.hf')
>>> # Load from io.BytesIO buffer
>>> buffer = io.BytesIO()
>>> obj = afnio.load(buffer)
Source code in afnio/serialization.py
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 | |
afnio.save(obj, f, pickle_protocol=DEFAULT_PROTOCOL)
Saves an object to a disk file using zip compression and pickle serialization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
object
|
The object to be saved. |
required |
f
|
str | PathLike | BinaryIO | IO[bytes]
|
A file-like object (must
implement write/flush) or a string or |
required |
pickle_protocol
|
int
|
Pickle protocol version. |
DEFAULT_PROTOCOL
|
Note
A common Afnio convention is to save variables using .hf file extension.
The .hf extension is a naming convention inspired by the chemical symbol
for Hafnium (Hf). "Afnio" is the
Italian word for Hafnium.
Examples:
>>> # Save to file
>>> x = afnio.Variable(data="You are a doctor.", role="system prompt")
>>> afnio.save(x, 'variable.hf')
>>> # Save to io.BytesIO buffer
>>> buffer = io.BytesIO()
>>> afnio.save(x, buffer)
Source code in afnio/serialization.py
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 | |