Index
This namespace contains various utility functions, classes, and type aliases.
ErroneousResult
¶
Representation of a caught error being returned as a result.
Source code in evotorch/tools/misc.py
call(f, *args, **kwargs)
staticmethod
¶
Call a function with the given arguments. If the function raises an error, wrap the error in an ErroneousResult object, and return that ErroneousResult object instead.
Returns:
Type | Description |
---|---|
Any
|
The result of the function if there was no error, |
Any
|
or an ErroneousResult if there was an error. |
Source code in evotorch/tools/misc.py
Hook
¶
Bases: MutableSequence
A Hook stores a list of callable objects to be called for handling certain events. A Hook itself is callable, which invokes the callables stored in its list. If the callables stored by the Hook return list-like objects or dict-like objects, their returned results are accumulated, and then those accumulated results are finally returned by the Hook.
Source code in evotorch/tools/hook.py
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 |
|
args
property
¶
Positional arguments that will be passed to the stored callables
kwargs
property
¶
Keyword arguments that will be passed to the stored callables
__call__(*args, **kwargs)
¶
Call every callable object stored by the Hook. The results of the stored callable objects (which can be dict-like or list-like objects) are accumulated and finally returned.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
args
|
Any
|
Additional positional arguments to be passed to the stored callables. |
()
|
kwargs
|
Any
|
Additional keyword arguments to be passed to the stored keyword arguments. |
{}
|
Source code in evotorch/tools/hook.py
__init__(callables=None, *, args=None, kwargs=None)
¶
Initialize the Hook.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
callables
|
Optional[Iterable[Callable]]
|
A sequence of callables to be stored by the Hook. |
None
|
args
|
Optional[Iterable]
|
Positional arguments which, when the Hook is called,
are to be passed to every callable stored by the Hook.
Please note that these positional arguments will be passed
as the leftmost arguments, and, the other positional
arguments passed via the |
None
|
kwargs
|
Optional[Mapping]
|
Keyword arguments which, when the Hook is called,
are to be passed to every callable stored by the Hook.
Please note that these keyword arguments could be overriden
by the keyword arguments passed via the |
None
|
Source code in evotorch/tools/hook.py
ObjectArray
¶
Bases: Sequence
, RecursivePrintable
An object container with an interface similar to PyTorch tensors.
It is strictly one-dimensional, and supports advanced indexing and slicing operations supported by PyTorch tensors.
An ObjectArray can store None
values, strings, numbers, booleans,
lists, sets, dictionaries, PyTorch tensors, and numpy arrays.
When a container (such as a list, dictionary, set, is placed into an ObjectArray, an immutable clone of this container is first created, and then this newly created immutable clone gets stored within the ObjectArray. This behavior is to prevent accidental modification of the stored data.
When a numeric array (such as a PyTorch tensor or a numpy array with a
numeric dtype) is placed into an ObjectArray, the target ObjectArray
first checks if the numeric array is read-only. If the numeric array
is indeed read-only, then the array is put into the ObjectArray as it
is. If the array is not read-only, then a read-only clone of the
original numeric array is first created, and then this clone gets
stored by the ObjectArray. This behavior has the following implications:
(i) even when an ObjectArray is shared by multiple components of the
program, the risk of accidental modification of the stored data through
this shared ObjectArray is significantly reduced as the stored numeric
arrays are read-only;
(ii) although not recommended, one could still forcefully modify the
numeric arrays stored by an ObjectArray by explicitly casting them as
mutable arrays
(in the case of a numpy array, one could forcefully set the WRITEABLE
flag, and, in the case of a ReadOnlyTensor, one could forcefully cast it
as a regular PyTorch tensor);
(iii) if an already read-only array x
is placed into an ObjectArray,
but x
shares its memory with a mutable array y
, then the contents
of the ObjectArray can be affected by modifying y
.
The implication (ii) is demonstrated as follows:
objs = ObjectArray(1) # a single-element ObjectArray
# Place a numpy array into objs:
objs[0] = np.array([1, 2, 3], dtype=float)
# At this point, objs[0] is a read-only numpy array.
# objs[0] *= 2 # <- Not allowed
# Possible but NOT recommended:
objs.flags["WRITEABLE"] = True
objs[0] *= 2
The implication (iii) is demonstrated as follows:
objs = ObjectArray(1) # a single-element ObjectArray
# Make a new mutable numpy array
y = np.array([1, 2, 3], dtype=float)
# Make a read-only view to y:
x = y[:]
x.flags["WRITEABLE"] = False
# Place x into objs.
objs[0] = x
# At this point, objs[0] is a read-only numpy array.
# objs[0] *= 2 # <- Not allowed
# During the operation of setting its 0-th item, the ObjectArray
# `objs` did not clone `x` because `x` was already read-only.
# However, the contents of `x` could actually be modified because
# `x` shares its memory with the mutable array `y`.
# Possible but NOT recommended:
y *= 2 # This affects both x and objs!
When a numpy array of dtype object is placed into an ObjectArray, a read-only ObjectArray copy of the original array will first be created, and then, this newly created ObjectArray will be stored by the outer ObjectArray.
An ObjectArray itself has a read-only mode, so that, in addition to its stored data, the ObjectArray itself can be protected against undesired modifications.
An interesting feature of PyTorch: if one slices a tensor A and the result is a new tensor B, and if B is sharing storage memory with A, then A.untyped_storage().data_ptr() and B.untyped_storage().data_ptr() will return the same pointer. This means, one can compare the storage pointers of A and B and see whether or not the two are sharing memory. ObjectArray was designed to have this exact behavior, so that one can understand if two ObjectArray instances are sharing memory. Note that NumPy does NOT have such a behavior. In more details, a NumPy array C and a NumPy array D could report different pointers even when D was created via a basic slicing operation on C.
Source code in evotorch/tools/objectarray.py
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 |
|
device
property
¶
The device which stores the elements of the ObjectArray. In the case of ObjectArray, this property always returns the CPU device.
Returns:
Type | Description |
---|---|
Device
|
The CPU device, as a torch.device object. |
dtype
property
¶
The dtype of the elements stored by the ObjectArray.
In the case of ObjectArray, the dtype is always object
.
is_read_only
property
¶
True if this ObjectArray is read-only; False otherwise.
ndim
property
¶
Number of dimensions handled by the ObjectArray. This is equivalent to getting the length of the size tuple.
shape
property
¶
Shape of the ObjectArray, as a PyTorch Size tuple.
__init__(size=None, *, slice_of=None)
¶
__init__(...)
: Instantiate a new ObjectArray.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
size
|
Optional[Size]
|
Length of the ObjectArray. If this argument is present and
is an integer |
None
|
slice_of
|
Optional[tuple]
|
Optionally a tuple in the form
|
None
|
Source code in evotorch/tools/objectarray.py
clone(*, preserve_read_only=False, memo=None)
¶
Get a deep copy of the ObjectArray.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
preserve_read_only
|
bool
|
Whether or not to preserve the read-only attribute. Note that the default value is False, which means that the newly made clone will NOT be read-only even if the original ObjectArray is. |
False
|
memo
|
Optional[dict]
|
Optionally a dictionary which maps from the ids of the already cloned objects to their clones. In most scenarios, when this method is called from outside, this can be left as None. |
None
|
Source code in evotorch/tools/objectarray.py
dim()
¶
Get the number of dimensions handled by the ObjectArray. This is equivalent to getting the length of the size tuple.
Returns:
Type | Description |
---|---|
int
|
The number of dimensions, as an integer. |
Source code in evotorch/tools/objectarray.py
from_numpy(ndarray)
staticmethod
¶
Convert a numpy array of dtype object
to an ObjectArray
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ndarray
|
ndarray
|
The numpy array that will be converted to |
required |
Source code in evotorch/tools/objectarray.py
get_read_only_view()
¶
numel()
¶
Number of elements stored by the ObjectArray.
Returns:
Type | Description |
---|---|
int
|
The number of elements, as an integer. |
numpy(*, memo=None)
¶
Convert this ObjectArray to a numpy array.
The resulting numpy array will have its dtype set as object
.
This new array itself and its contents will be mutable (those
mutable objects being the copies of their immutable sources).
Returns:
Type | Description |
---|---|
ndarray
|
The numpy counterpart of this ObjectArray. |
Source code in evotorch/tools/objectarray.py
repeat(*sizes)
¶
Repeat the contents of this ObjectArray.
For example, if we have an ObjectArray objs
which stores
["hello", "world"]
, the following line:
objs.repeat(3)
will result in an ObjectArray which stores:
`["hello", "world", "hello", "world", "hello", "world"]`
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sizes
|
Although this argument is named |
()
|
Source code in evotorch/tools/objectarray.py
set_item(i, x, *, memo=None)
¶
Set the i-th item of the ObjectArray as x.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
i
|
Any
|
An index or a slice. |
required |
x
|
Any
|
The object that will be put into the ObjectArray. |
required |
memo
|
Optional[dict]
|
Optionally a dictionary which maps from the ids of the already placed objects to their clones within ObjectArray. In most scenarios, when this method is called from outside, this can be left as None. |
None
|
Source code in evotorch/tools/objectarray.py
size()
¶
Get the size of the ObjectArray, as a PyTorch Size tuple.
Returns:
Type | Description |
---|---|
Size
|
The size (i.e. the shape) of the ObjectArray. |
ReadOnlyTensor
¶
Bases: Tensor
A special type of tensor which is read-only.
This is a subclass of torch.Tensor
which explicitly disallows
operations that would cause in-place modifications.
Since ReadOnlyTensor if a subclass of torch.Tensor
, most
non-destructive PyTorch operations are on this tensor are supported.
Cloning a ReadOnlyTensor using the clone()
method or Python's
deepcopy(...)
function results in a regular PyTorch tensor.
Reshaping or slicing operations might return a ReadOnlyTensor if the
result ends up being a view of the original ReadOnlyTensor; otherwise,
the returned tensor is a regular torch.Tensor
.
Source code in evotorch/tools/readonlytensor.py
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 |
|
TensorFrame
¶
Bases: RecursivePrintable
A structure which allows one to manipulate tensors in a tabular manner.
The interface of this structure is inspired by the DataFrame
class
of the pandas
library.
Motivation.
It is a common scenario to have to work with arrays/tensors that are
associated with each other (e.g. when working on a knapsack problem, we
could have arrays A
and B
, where A[i]
represents the value of the
i-th item and B[i]
represents the weight of the i-th item).
A practical approach for such cases is to organize those arrays and
operate on them in a tabular manner. pandas
is a popular library
for doing such tabular operations.
In the context of evolutionary computation, efficiency via vectorization and/or parallelization becomes an important concern. For example, if we have a fitness function in which a solution vector is evaluated with the help of tabular operations, we would like to be able to obtain a batched version of that function, so that not just a solution, but an entire population can be evaluated efficiently. Another example is when developing custom evolutionary algorithms, where solutions, fitnesses, and algorithm-specific (or problem-specific) metadata can be organized in a tabular manner, and operating on such tabular data has to be vectorized and/or parallelized for increased efficiency.
TensorFrame
is introduced to address these concerns. In more details,
with evolutionary computation in mind, it has these features/behaviors:
(i) The columns of a TensorFrame
are expressed via PyTorch tensors
(or via evotorch.tools.ReadOnlyTensor
instances), allowing one
to place the tabular data on devices such as cuda.
(ii) A TensorFrame
can be placed into a function that is transformed
via torch.vmap
or evotorch.decorators.expects_ndim
or
evotorch.decorators.rowwise
, therefore it can work on batched data.
(iii) Upon being pickled or cloned, a TensorFrame
applies the clone
method on all its columns and ensures that the cloned tensors have
minimally sized storages (even when their originals might have shared
their storages with larger tensors). Therefore, one can send a
TensorFrame
to a remote worker (e.g. using ray
library), without
having to worry about oversized shared tensor storages.
(iv) A TensorFrame
can be placed as an item into an
evotorch.tools.ObjectArray
container. Therefore, it can serve as a
value in a solution of a problem whose dtype
is object
.
Basic usage. A tensorframe can be instantiated like this:
from evotorch.tools import TensorFrame
import torch
my_tensorframe = TensorFrame(
{
"COLUMN1": torch.FloatTensor([1, 2, 3, 4]),
"COLUMN2": torch.FloatTensor([10, 20, 30, 40]),
"COLUMN3": torch.FloatTensor([-10, -20, -30, -40]),
}
)
which represents the following tabular data:
float32 float32 <- dtype of the column
cpu cpu <- device of the column
COLUMN1 COLUMN2 COLUMN3
========= ========= =========
1.0 10.0 -10.0
2.0 20.0 -20.0
3.0 30.0 -30.0
4.0 40.0 -40.0
Rows can be picked and re-organized like this:
which causes my_tensorframe
to now store:
float32 float32 float32
cpu cpu cpu
COLUMN1 COLUMN2 COLUMN3
========= ========= =========
1.0 10.0 -10.0
4.0 40.0 -40.0
3.0 30.0 -30.0
A tensor of a column can be received like this:
print(my_tensorframe["COLUMN1"])
# Note: alternatively: print(my_tensorframe.COLUMN1)
# Prints: torch.tensor([1.0, 4.0, 3.0], dtype=torch.float32)
Multiple columns can be received like this:
print(my_tensorframe[["COLUMN1", "COLUMN2"]])
# Prints:
#
# float32 float32
# cpu cpu
#
# COLUMN1 COLUMN2
# ========= =========
# 1.0 10.0
# 4.0 40.0
# 3.0 30.0
The values of a column can be changed like this:
which causes my_tensorframe
to become:
float32 float32 float32
cpu cpu cpu
COLUMN1 COLUMN2 COLUMN3
========= ========= =========
1.0 10.0 -10.0
7.0 40.0 -40.0
9.0 30.0 -30.0
Multiple columns can be changed like this:
my_tensorframe.pick[1:, ["COLUMN1", "COLUMN2"]] = TensorFrame(
{
"COLUMN1": torch.FloatTensor([11.0, 12.0]),
"COLUMN2": torch.FloatTensor([44.0, 55.0]),
}
)
# Note: alternatively, the right-hand side can be given as a dictionary:
# my_tensorframe.pick[1:, ["COLUMN1", "COLUMN2"]] = {
# "COLUMN1": torch.FloatTensor([11.0, 12.0]),
# "COLUMN2": torch.FloatTensor([44.0, 55.0]),
# }
which causes my_tensorframe
to become:
float32 float32 float32
cpu cpu cpu
COLUMN1 COLUMN2 COLUMN3
========= ========= =========
1.0 10.0 -10.0
11.0 44.0 -40.0
12.0 55.0 -30.0
Further notes.
- A tensor under a TensorFrame column can have more than one dimension. Across different columns, the size of the leftmost dimensions must match.
- Unlike a
pandas.DataFrame
, a TensorFrame does not have a special index column.
Source code in evotorch/tools/tensorframe.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 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 |
|
columns
property
¶
Columns as a list of strings
device
property
¶
Get the device(s) of this TensorFrame.
If different columns exist on different devices, a set of devices will be returned. If all the columns exist on the same device, then that device will be returned.
is_read_only
property
¶
True if this TensorFrame is read-only; False otherwise.
pick
property
¶
__init__(data=None, *, read_only=False, device=None)
¶
__init__(...)
: Initialize the TensorFrame
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
Optional[Union[Mapping, TensorFrame, _PandasDataFrame]]
|
Optionally a TensorFrame, or a dictionary (where the keys
are column names and the values are column values), or a
|
None
|
read_only
|
bool
|
Whether or not the newly made TensorFrame will be read-only. A read-only TensorFrame's columns will be ReadOnlyTensors, and its columns and values will not change. |
False
|
device
|
Optional[Union[device, str]]
|
If left as None, each column can be on a different device.
If given as a string or a |
None
|
Source code in evotorch/tools/tensorframe.py
argsort(by, *, indices=None, ranks=None, descending=False, join=False)
¶
Return row indices (also optionally ranks) for sorting the TensorFrame.
For example, let us assume that we have a TensorFrame named table
.
We can sort this table
like this:
indices_for_sorting = table.argsort(by="A") # sort by the column A
sorted_table = table.pick[indices_for_sorting]
Parameters:
Name | Type | Description | Default |
---|---|---|---|
by
|
Union[str, str_]
|
The name of the column according to which the TensorFrame will be sorted. |
required |
indices
|
Optional[Union[str, str_]]
|
If given as a string |
None
|
ranks
|
Optional[Union[str, str_]]
|
If given as a string |
None
|
descending
|
bool
|
If True, the sorting will be in descending order. |
False
|
join
|
bool
|
Can be used only if column names are given via |
False
|
Source code in evotorch/tools/tensorframe.py
as_tensor(x, *, to_work_with=None, broadcast_if_scalar=False)
¶
Convert the given object x
to a PyTorch tensor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Any
|
The object to be converted to a PyTorch tensor. |
required |
to_work_with
|
Optional[Union[str, str_, Tensor]]
|
Optionally a string, referring to an existing column
within this TensorFrame, or a PyTorch tensor. The object |
None
|
broadcast_if_scalar
|
bool
|
If this argument is given as True and if |
False
|
Source code in evotorch/tools/tensorframe.py
clone(*, preserve_read_only=False, memo=None)
¶
Get a clone of this TensorFrame.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
preserve_read_only
|
bool
|
If True, the newly made clone will be read-only only if this TensorFrame is also read-only. |
False
|
Source code in evotorch/tools/tensorframe.py
cpu()
¶
cuda()
¶
drop(*, columns)
¶
Get a new TensorFrame where the given columns are dropped.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
columns
|
Union[str, str_, Sequence]
|
A single column name or a sequence of column names to be dropped. |
required |
Source code in evotorch/tools/tensorframe.py
each(fn, *, chunk_size=None, randomness='error', join=False, override=False)
¶
For each row of this TensorFrame, perform the operations of fn
.
fn
is executed on the rows in a vectorized manner, with the help
of torch.vmap
.
The function fn
is expected to have this interface:
def fn(row: dict) -> dict:
# `row` is a dictionary where the keys are column names.
# This function is expected to return another dictionary.
...
For example, if we have a TensorFrame with columns A and B, and if we want to create a new column C where, for each row, the value under C is the sum of A's value and B's value, then the function would look like this:
Now, if our current TensorFrame looks like this:
Running tensorframe.each(do_summation_for_each_row)
will result in
the following new TensorFrame:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fn
|
Callable
|
A function which receives a dictionary as its argument, and returns another dictionary. |
required |
chunk_size
|
Optional[int]
|
For performing |
None
|
randomness
|
str
|
If given as "error" (which is the default), any random
number generation operation within |
'error'
|
join
|
bool
|
If given as True, the resulting TensorFrame will also contain this TensorFrame's columns. |
False
|
override
|
bool
|
If given as True (and if |
False
|
Source code in evotorch/tools/tensorframe.py
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 |
|
get_read_only_view()
¶
hstack(other, *, override=False)
¶
Horizontally join this TensorFrame with another.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other
|
TensorFrame
|
The other TensorFrame. |
required |
override
|
bool
|
If this is given as True and if the other TensorFrame has overlapping columns, the other TensorFrame's values will override (i.e. will take priority) in the joined result. |
False
|
Source code in evotorch/tools/tensorframe.py
join(t)
¶
Like the hstack
method, but with a more pandas-like interface.
Joins this TensorFrame with the other TensorFrame.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
t
|
Union[TensorFrame, Sequence]
|
The TensorFrame that will be horizontally stacked to the right. |
required |
Source code in evotorch/tools/tensorframe.py
nlargest(n, columns)
¶
Sort this TensorFrame and take the largest n
rows.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n
|
int
|
Number of rows of the resulting TensorFrame. |
required |
columns
|
Union[str, str_, Sequence]
|
The name of the column according to which the rows will be sorted. Although the name of this argument is plural ("columns") for compatibility with pandas' interface, only one column name is supported. |
required |
Source code in evotorch/tools/tensorframe.py
nsmallest(n, columns)
¶
Sort this TensorFrame and take the smallest n
rows.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n
|
int
|
Number of rows of the resulting TensorFrame. |
required |
columns
|
Union[str, str_, Sequence]
|
The name of the column according to which the rows will be sorted. Although the name of this argument is plural ("columns") for compatibility with pandas' interface, only one column name is supported. |
required |
Source code in evotorch/tools/tensorframe.py
sort(by, *, descending=False)
¶
Return a sorted copy of this TensorFrame.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
by
|
Union[str, str_]
|
Name of the column according to which the sorting will be done. |
required |
descending
|
bool
|
If True, the sorting will be in descending order. |
False
|
Source code in evotorch/tools/tensorframe.py
sort_values(by, *, ascending=True)
¶
Like the sort
method, but with a more pandas-like interface.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
by
|
Union[str, str_, Sequence]
|
Column according to which this TensorFrame will be sorted. |
required |
ascending
|
Union[bool, Sequence]
|
If True, the sorting will be in ascending order. |
True
|
Source code in evotorch/tools/tensorframe.py
to_string(*, max_depth=DEFAULT_MAX_DEPTH_FOR_PRINTING)
¶
Return the string representation of this TensorFrame
Source code in evotorch/tools/tensorframe.py
vstack(other)
¶
Vertically join this TensorFrame with the other TensorFrame.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other
|
TensorFrame
|
The other TensorFrame which will be at the bottom. |
required |
Source code in evotorch/tools/tensorframe.py
with_columns(**kwargs)
¶
Get a modified copy of this TensorFrame with some columns added/updated.
The columns to be updated or added are expected as keyword arguments.
For example, if a keyword argument is given as A=new_a_values
, then,
if A
already exists in the original TensorFrame, those values will be
dropped and the resulting TensorFrame will have the new values
(new_a_values
). On the other hand, if A
does not exist in the
original TensorFrame, the resulting TensorFrame will have a new column
A
with the given new_a_values
.
Source code in evotorch/tools/tensorframe.py
with_enforced_device(device)
¶
Make a shallow copy of this TensorFrame with an enforced device.
In the newly made shallow copy, columns will be forcefully moved onto the specified device.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
device
|
Union[str, device]
|
The device to which the new TensorFrame's columns will move. |
required |
Source code in evotorch/tools/tensorframe.py
without_enforced_device()
¶
Make a shallow copy of this TensorFrame without any enforced device.
In the newly made shallow copy, columns will be able to exist on different devices.
Returns:
Type | Description |
---|---|
TensorFrame
|
A shallow copy of this TensorFrame without any enforced device. |
Source code in evotorch/tools/tensorframe.py
as_read_only_tensor(x, *, dtype=None, device=None)
¶
Convert the given object to a ReadOnlyTensor.
The provided object can be a scalar, or an Iterable of numeric data, or an ObjectArray.
This function can be thought as the read-only counterpart of PyTorch's
torch.as_tensor(...)
function.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Any
|
The object to be converted to a ReadOnlyTensor. |
required |
dtype
|
Optional[dtype]
|
The dtype of the new ReadOnlyTensor (e.g. torch.float32).
If this argument is not specified, dtype will be inferred from |
None
|
device
|
Optional[Union[str, device]]
|
The device in which the ReadOnlyTensor will be stored
(e.g. "cpu").
If this argument is not specified, the device which is storing
the original |
None
|
Source code in evotorch/tools/readonlytensor.py
as_tensor(x, *, dtype=None, device=None)
¶
Get the tensor counterpart of the given object x
.
This function can be used to convert native Python objects to tensors:
my_tensor = as_tensor([1.0, 2.0, 3.0], dtype="float32")
One can also use this function to convert an existing tensor to another dtype:
my_new_tensor = as_tensor(my_tensor, dtype="float16")
This function can also be used for moving a tensor from one device to another:
my_gpu_tensor = as_tensor(my_tensor, device="cuda:0")
This function can also create ObjectArray instances when dtype is
given as object
or Any
or "object" or "O".
my_objects = as_tensor([1, {"a": 3}], dtype=object)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Any
|
Any object to be converted to a tensor. |
required |
dtype
|
Optional[DType]
|
Optionally a string (e.g. "float32") or a PyTorch dtype
(e.g. torch.float32) or, for creating an |
None
|
device
|
Optional[Device]
|
The device in which the resulting tensor will be stored. |
None
|
Source code in evotorch/tools/misc.py
cast_tensors_in_container(container, *, dtype=None, device=None, memo=None)
¶
Cast and/or transfer all the tensors in a Python container.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dtype
|
Optional[DType]
|
If given as a dtype and not as None, then all the PyTorch tensors in the container will be cast to this dtype. |
None
|
device
|
Optional[Device]
|
If given as a device and not as None, then all the PyTorch tensors in the container will be copied to this device. |
None
|
memo
|
Optional[dict]
|
Optionally a memo dictionary to handle shared objects and circular references. In most scenarios, when calling this function from outside, this is expected as None. |
None
|
Source code in evotorch/tools/misc.py
clip_tensor(x, lb=None, ub=None, ensure_copy=True)
¶
Clip the values of a tensor with respect to the given bounds.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
The PyTorch tensor whose values will be clipped. |
required |
lb
|
Optional[Union[float, Iterable]]
|
Lower bounds, as a PyTorch tensor. Can be None if there are no lower bounds. |
None
|
ub
|
Optional[Union[float, Iterable]]
|
Upper bounds, as a PyTorch tensor. Can be None if there are no upper bonuds. |
None
|
ensure_copy
|
bool
|
If |
True
|
Source code in evotorch/tools/misc.py
clone(x, *, memo=None)
¶
Get a deep copy of the given object.
The cloning is done in no_grad mode.
When this function is used on read-only containers (e.g. ReadOnlyTensor,
ImmutableContainer, etc.), the created clones preserve their read-only
behaviors. For creating a mutable clone of an immutable object,
use their clone()
method instead.
Returns:
Type | Description |
---|---|
Any
|
The deep copy of the given object. |
Source code in evotorch/tools/misc.py
device_of(x)
¶
Get the device of the given object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Any
|
The object whose device is being queried.
The object can be a PyTorch tensor, or a PyTorch module
(in which case the device of the first parameter tensor
will be returned), or an ObjectArray (in which case
the returned device will be the cpu device), or any object
with the attribute |
required |
Source code in evotorch/tools/misc.py
device_of_container(container, *, visited=None, visiting=None)
¶
Get the device of the given container.
It is assumed that the given container stores PyTorch tensors from which the device information will be extracted. If the container contains only basic types like int, float, string, bool, or None, or if the container is empty, then the returned device will be None. If the container contains unrecognized objects, an error will be raised.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
container
|
Any
|
A sequence or a dictionary of objects from which the device information will be extracted. |
required |
visited
|
Optional[dict]
|
Optionally a dictionary which stores the (sub)containers which are already visited. In most cases, when this function is called from outside, this is expected as None. |
None
|
visiting
|
Optional[str]
|
Optionally a set which stores the (sub)containers which are being visited. This set is used to prevent recursion errors while handling circular references. In most cases, when this function is called from outside, this argument is expected as None. |
None
|
Source code in evotorch/tools/misc.py
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 |
|
dtype_of(x)
¶
Get the dtype of the given object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Any
|
The object whose dtype is being queried.
The object can be a PyTorch tensor, or a PyTorch module
(in which case the dtype of the first parameter tensor
will be returned), or an ObjectArray (in which case
the returned dtype will be |
required |
Source code in evotorch/tools/misc.py
dtype_of_container(container, *, visited=None, visiting=None)
¶
Get the dtype of the given container.
It is assumed that the given container stores PyTorch tensors from which the dtype information will be extracted. If the container contains only basic types like int, float, string, bool, or None, or if the container is empty, then the returned dtype will be None. If the container contains unrecognized objects, an error will be raised.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
container
|
Any
|
A sequence or a dictionary of objects from which the dtype information will be extracted. |
required |
visited
|
Optional[dict]
|
Optionally a dictionary which stores the (sub)containers which are already visited. In most cases, when this function is called from outside, this is expected as None. |
None
|
visiting
|
Optional[str]
|
Optionally a set which stores the (sub)containers which are being visited. This set is used to prevent recursion errors while handling circular references. In most cases, when this function is called from outside, this argument is expected as None. |
None
|
Source code in evotorch/tools/misc.py
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 |
|
empty_tensor_like(source, *, shape=None, length=None, dtype=None, device=None)
¶
Make an empty tensor with attributes taken from a source tensor.
The source tensor can be a PyTorch tensor, or an ObjectArray.
Unlike torch.empty_like(...)
, this function allows one to redefine the
shape and/or length of the new empty tensor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
source
|
Any
|
The source tensor whose shape, dtype, and device will be used by default for the new empty tensor. |
required |
shape
|
Optional[Union[tuple, int]]
|
If given as None (which is the default), then the shape of the
source tensor will be used for the new empty tensor.
If given as a tuple or a |
None
|
length
|
Optional[int]
|
If given as None (which is the default), then the length of
the new empty tensor will be equal to the length of the source
tensor (where length here means the size of the outermost
dimension, i.e., what is returned by |
None
|
dtype
|
Optional[DType]
|
If given as None, the dtype of the new empty tensor will be
the dtype of the source tensor.
If given as a |
None
|
device
|
Optional[Device]
|
If given as None, the device of the new empty tensor will be
the device of the source tensor.
If given as a |
None
|
Source code in evotorch/tools/misc.py
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 |
|
ensure_ray()
¶
Ensure that the ray parallelization engine is initialized. If ray is already initialized, this function does nothing.
ensure_tensor_length_and_dtype(t, length, dtype, about=None, *, allow_scalar=False, device=None)
¶
Return the given sequence as a tensor while also confirming its length, dtype, and device. If the given object is already a tensor conforming to the desired length, dtype, and device, the object will be returned as it is (there will be no copying).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
t
|
Any
|
The tensor, or a sequence which is convertible to a tensor. |
required |
length
|
int
|
The length to which the tensor is expected to conform. |
required |
dtype
|
DType
|
The dtype to which the tensor is expected to conform. |
required |
about
|
Optional[str]
|
The prefix for the error message. Can be left as None. |
None
|
allow_scalar
|
bool
|
Whether or not to accept scalars in addition
to vector of the desired length.
If |
False
|
device
|
Optional[Device]
|
The device in which the sequence is to be stored.
If the given sequence is on a different device than the
desired device, a copy on the correct device will be made.
If device is None, the default behavior of |
None
|
Source code in evotorch/tools/misc.py
expect_none(msg_prefix, **kwargs)
¶
Expect the values associated with the given keyword arguments to be None. If not, raise error.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
msg_prefix
|
str
|
Prefix of the error message. |
required |
kwargs
|
Keyword arguments whose values are expected to be None. |
{}
|
Source code in evotorch/tools/misc.py
is_bool(x)
¶
Return True if x
represents a bool.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Any
|
An object whose type is being queried. |
required |
Source code in evotorch/tools/misc.py
is_bool_vector(x)
¶
Return True if x
is a vector consisting of bools.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Any
|
An object whose elements' types are to be queried. |
required |
Source code in evotorch/tools/misc.py
is_dtype_bool(t)
¶
Return True if the given dtype is an bool type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
t
|
DType
|
The dtype, which can be a dtype string, a numpy dtype, or a PyTorch dtype. |
required |
Source code in evotorch/tools/misc.py
is_dtype_float(t)
¶
Return True if the given dtype is an float type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
t
|
DType
|
The dtype, which can be a dtype string, a numpy dtype, or a PyTorch dtype. |
required |
Source code in evotorch/tools/misc.py
is_dtype_integer(t)
¶
Return True if the given dtype is an integer type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
t
|
DType
|
The dtype, which can be a dtype string, a numpy dtype, or a PyTorch dtype. |
required |
Source code in evotorch/tools/misc.py
is_dtype_object(dtype)
¶
Return True if the given dtype is object
or Any
.
Returns:
Type | Description |
---|---|
bool
|
True if the given dtype is |
Source code in evotorch/tools/misc.py
is_dtype_real(t)
¶
Return True if the given dtype represents real numbers (i.e. if dtype is an integer type or is a float type).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
t
|
DType
|
The dtype, which can be a dtype string, a numpy dtype, or a PyTorch dtype. |
required |
Source code in evotorch/tools/misc.py
is_integer(x)
¶
Return True if x
is an integer.
Note that this function does NOT consider booleans as integers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Any
|
An object whose type is being queried. |
required |
Source code in evotorch/tools/misc.py
is_integer_vector(x)
¶
Return True if x
is a vector consisting of integers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Any
|
An object whose elements' types are to be queried. |
required |
Source code in evotorch/tools/misc.py
is_real(x)
¶
Return True if x
is a real number.
Note that this function does NOT consider booleans as real numbers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Any
|
An object whose type is being queried. |
required |
Source code in evotorch/tools/misc.py
is_real_vector(x)
¶
Return True if x
is a vector consisting of real numbers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Any
|
An object whose elements' types are to be queried. |
required |
Source code in evotorch/tools/misc.py
is_sequence(x)
¶
Return True if x
is a sequence.
Note that this function considers str
and bytes
as scalars,
not as sequences.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Any
|
The object whose sequential nature is being queried. |
required |
Source code in evotorch/tools/misc.py
is_tensor_on_cpu(tensor)
¶
log_barrier(lhs, comparison, rhs, *, penalty_sign, sharpness=1.0, inf=None)
¶
Return a penalty based on how close the constraint is to being violated.
If the left-hand-side is equal to the right-hand-side, or if the constraint
is violated, the returned penalty will be infinite (+inf
or -inf
,
depending on penalty_sign
). Such inf
values can result in numerical
instabilities. To overcome such instabilities, you might want to set the
keyword argument inf
as a large-enough finite positive quantity M
, so
that very large (or infinite) penalties will be clipped down to M
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
lhs
|
Union[float, Tensor]
|
The left-hand-side of the constraint. In the non-batched case, this is expected as a scalar. If it is given as an n-dimensional tensor where n is at least 1, this is considered as a batch of left-hand-side values. |
required |
comparison
|
str
|
The operator used for comparing the left-hand-side and the right-hand-side. Expected as a string. Acceptable values are: '<=', '>='. |
required |
rhs
|
Union[float, Tensor]
|
The right-hand-side of the constraint. In the non-batched case, this is expected as a scalar. If it is given as an n-dimensional tensor where n is at least 1, this is considered as a batch of right-hand-side values. |
required |
penalty_sign
|
str
|
Expected as string, either as '+' or '-', which
determines the sign of the penalty (i.e. determines if the penalty
will be positive or negative). One should consider the objective
sense of the fitness function at hand for deciding |
required |
sharpness
|
Union[float, Tensor]
|
The logarithmic penalty will be divided by this number. By default, this value is 1. A sharper log-penalization allows the constraint to get closer to its boundary, and then makes a more sudden jump towards infinity. |
1.0
|
inf
|
Optional[Union[float, Tensor]]
|
When concerned about the possible numerical instabilities caused
by infinite penalties, one can specify a finite large-enough
positive quantity |
None
|
Source code in evotorch/tools/constraints.py
make_I(size=None, *, out=None, dtype=None, device=None)
¶
Make a new identity matrix (I), or change an existing tensor into one.
The following example creates a 3x3 identity matrix:
identity_matrix = make_I(3, dtype="float32")
The following example changes an already existing square matrix such that its values will store an identity matrix:
make_I(out=existing_tensor)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
size
|
Optional[int]
|
A single integer or a tuple containing a single integer,
where the integer specifies the length of the target square
matrix. In this context, "length" means both rowwise length
and columnwise length, since the target is a square matrix.
Note that, if the user wishes to fill an existing tensor with
identity values, then |
None
|
out
|
Optional[Tensor]
|
Optionally, the existing tensor whose values will be changed
so that they represent an identity matrix.
If an |
None
|
dtype
|
Optional[DType]
|
Optionally a string (e.g. "float32") or a PyTorch dtype
(e.g. torch.float32).
If |
None
|
device
|
Optional[Device]
|
The device in which the new tensor will be stored.
If not specified, "cpu" will be used.
If an |
None
|
Source code in evotorch/tools/misc.py
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 |
|
make_batched_false_for_vmap(device)
¶
Get False
, properly batched if inside vmap(..., randomness='different')
.
Reasoning. Imagine we have the following function:
import torch
def sample_and_shift(target_shape: tuple, shift: torch.Tensor) -> torch.Tensor:
result = torch.empty(target_shape, device=x.device)
result.normal_()
result += shift
return result
which allocates an empty tensor, then fills it with samples from the
standard normal distribution, then shifts the samples and returns the
result. An important implementation detail regarding this example function
is that all of its operations are in-place (i.e. the method normal_()
and the operator +=
work on the given pre-allocated tensor).
Let us now imagine that we have a batch of shift tensors, and we would like
to generate multiple shifted sample tensors. Ideally, such a batched
operation could be done by transforming the example function with the help
of vmap
:
from torch.func import vmap
batched_sample_and_shift = vmap(sample_and_shift, in_dims=0, randomness="different")
where the argument randomness="different"
tells PyTorch that for each
batch item, we want to generate different samples (instead of just
duplicating the same samples across the batch dimension(s)).
Such a re-sampling approach is usually desired in applications where
preserving stochasticity is crucial, evolutionary computation being one
of such case.
Now let us call our transformed function:
batch_of_shifts = ... # a tensor like `shift`, but with an extra leftmost
# dimension for the batches
# Will fail:
batched_results = batched_sample_and_shift(shape_goes_here, batch_of_shifts)
At this point, we observe that batched_sample_and_shift
fails.
The reason for this failure is that the function first allocates an empty
tensor, then tries to perform random sampling in an in-place manner.
The first allocation via empty
is not properly batched (it is not aware
of the active vmap
), so, when we later call .normal_()
on it,
there is no room for the data that would be re-sampled for each batch item.
To remedy this, we could modify our original function slightly:
import torch
def sample_and_shift2(target_shape: tuple, shift: torch.Tensor) -> torch.Tensor:
result = torch.empty(target_shape, device=x.device)
result = result + result.make_batched_false_for_vmap(x.device)
result.normal_()
result += shift
return result
In this modified function, right after making an initial allocation, we add
onto it a batched false, and re-assign the result to the variable result
.
Thanks to being the result of an interaction with a batched false, the new
result
variable is now properly batched (if we are inside
vmap(..., randomness="different")
. Now, let us transform our function:
from torch.func import vmap
batched_sample_and_shift2 = vmap(sample_and_shift2, in_dims=0, randomness="different")
The following code should now work:
batch_of_shifts = ... # a tensor like `shift`, but with an extra leftmost
# dimension for the batches
# Should work:
batched_results = batched_sample_and_shift2(shape_goes_here, batch_of_shifts)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
device
|
Device
|
The target device on which the batched |
required |
Source code in evotorch/tools/misc.py
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 |
|
make_empty(*size, dtype=None, device=None)
¶
Make an empty tensor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
size
|
Size
|
Shape of the empty tensor to be created.
expected as multiple positional arguments of integers,
or as a single positional argument containing a tuple of
integers.
Note that when the user wishes to create an |
()
|
dtype
|
Optional[DType]
|
Optionally a string (e.g. "float32") or a PyTorch dtype
(e.g. torch.float32) or, for creating an |
None
|
device
|
Optional[Device]
|
The device in which the new empty tensor will be stored. If not specified, "cpu" will be used. |
None
|
Source code in evotorch/tools/misc.py
make_gaussian(*size, center=None, stdev=None, symmetric=False, out=None, dtype=None, device=None, generator=None)
¶
Make a new or existing tensor filled by Gaussian distributed values. This function can work only with float dtypes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
size
|
Size
|
Size of the new tensor to be filled with Gaussian distributed values. This can be given as multiple positional arguments, each such positional argument being an integer, or as a single positional argument of a tuple, the tuple containing multiple integers. Note that, if the user wishes to fill an existing tensor instead, then no positional argument is expected. |
()
|
center
|
Optional[RealOrVector]
|
Center point (i.e. mean) of the Gaussian distribution.
Can be a scalar, or a tensor.
If not specified, the center point will be taken as 0.
Note that, if one specifies |
None
|
stdev
|
Optional[RealOrVector]
|
Standard deviation for the Gaussian distributed values.
Can be a scalar, or a tensor.
If not specified, the standard deviation will be taken as 1.
Note that, if one specifies |
None
|
symmetric
|
bool
|
Whether or not the values should be sampled in a symmetric (i.e. antithetic) manner. The default is False. |
False
|
out
|
Optional[Tensor]
|
Optionally, the tensor to be filled by Gaussian distributed
values. If an |
None
|
dtype
|
Optional[DType]
|
Optionally a string (e.g. "float32") or a PyTorch dtype
(e.g. torch.float32).
If |
None
|
device
|
Optional[Device]
|
The device in which the new tensor will be stored.
If not specified, "cpu" will be used.
If an |
None
|
generator
|
Any
|
Pseudo-random number generator to be used when sampling
the values. Can be a |
None
|
Source code in evotorch/tools/misc.py
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 |
|
make_nan(*size, out=None, dtype=None, device=None)
¶
Make a new tensor filled with NaN, or fill an existing tensor with NaN.
The following example creates a float32 tensor filled with NaN values, of shape (3, 5):
nan_values = make_nan(3, 5, dtype="float32")
The following example fills an existing tensor with NaNs.
make_nan(out=existing_tensor)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
size
|
Size
|
Size of the new tensor to be filled with NaNs. This can be given as multiple positional arguments, each such positional argument being an integer, or as a single positional argument of a tuple, the tuple containing multiple integers. Note that, if the user wishes to fill an existing tensor with NaN values, then no positional argument is expected. |
()
|
out
|
Optional[Tensor]
|
Optionally, the tensor to be filled by NaN values.
If an |
None
|
dtype
|
Optional[DType]
|
Optionally a string (e.g. "float32") or a PyTorch dtype
(e.g. torch.float32).
If |
None
|
device
|
Optional[Device]
|
The device in which the new tensor will be stored.
If not specified, "cpu" will be used.
If an |
None
|
Source code in evotorch/tools/misc.py
make_ones(*size, out=None, dtype=None, device=None)
¶
Make a new tensor filled with 1, or fill an existing tensor with 1.
The following example creates a float32 tensor filled with 1 values, of shape (3, 5):
zero_values = make_ones(3, 5, dtype="float32")
The following example fills an existing tensor with 1s:
make_ones(out=existing_tensor)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
size
|
Size
|
Size of the new tensor to be filled with 1. This can be given as multiple positional arguments, each such positional argument being an integer, or as a single positional argument of a tuple, the tuple containing multiple integers. Note that, if the user wishes to fill an existing tensor with 1 values, then no positional argument is expected. |
()
|
out
|
Optional[Tensor]
|
Optionally, the tensor to be filled by 1 values.
If an |
None
|
dtype
|
Optional[DType]
|
Optionally a string (e.g. "float32") or a PyTorch dtype
(e.g. torch.float32).
If |
None
|
device
|
Optional[Device]
|
The device in which the new tensor will be stored.
If not specified, "cpu" will be used.
If an |
None
|
Source code in evotorch/tools/misc.py
make_randint(*size, n, out=None, dtype=None, device=None, generator=None)
¶
Make a new or existing tensor filled by random integers.
The integers are uniformly distributed within [0 ... n-1]
.
This function can be used with integer or float dtypes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
size
|
Size
|
Size of the new tensor to be filled with uniformly distributed values. This can be given as multiple positional arguments, each such positional argument being an integer, or as a single positional argument of a tuple, the tuple containing multiple integers. Note that, if the user wishes to fill an existing tensor instead, then no positional argument is expected. |
()
|
n
|
Union[int, float, Tensor]
|
Number of choice(s) for integer sampling.
The lowest possible value will be 0, and the highest possible
value will be n - 1.
|
required |
out
|
Optional[Tensor]
|
Optionally, the tensor to be filled by the random integers.
If an |
None
|
dtype
|
Optional[DType]
|
Optionally a string (e.g. "int64") or a PyTorch dtype
(e.g. torch.int64).
If |
None
|
device
|
Optional[Device]
|
The device in which the new tensor will be stored.
If not specified, "cpu" will be used.
If an |
None
|
generator
|
Any
|
Pseudo-random number generator to be used when sampling
the values. Can be a |
None
|
Source code in evotorch/tools/misc.py
make_tensor(data, *, dtype=None, device=None, read_only=False)
¶
Make a new tensor.
This function can be used to create PyTorch tensors, or ObjectArray instances with or without read-only behavior.
The following example creates a 2-dimensional PyTorch tensor:
my_tensor = make_tensor(
[[1, 2], [3, 4]],
dtype="float32", # alternatively, torch.float32
device="cpu",
)
The following example creates an ObjectArray from a list that contains arbitrary data:
my_obj_tensor = make_tensor(["a_string", (1, 2)], dtype=object)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
Any
|
The data to be converted to a tensor.
If one wishes to create a PyTorch tensor, this can be anything
that can be stored by a PyTorch tensor.
If one wishes to create an |
required |
dtype
|
Optional[DType]
|
Optionally a string (e.g. "float32"), or a PyTorch dtype
(e.g. torch.float32), or |
None
|
device
|
Optional[Device]
|
The device in which the tensor will be stored.
If |
None
|
read_only
|
bool
|
Whether or not the created tensor will be read-only. By default, this is False. |
False
|
Source code in evotorch/tools/misc.py
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 |
|
make_uniform(*size, lb=None, ub=None, out=None, dtype=None, device=None, generator=None)
¶
Make a new or existing tensor filled by uniformly distributed values. Both lower and upper bounds are inclusive. This function can work with both float and int dtypes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
size
|
Size
|
Size of the new tensor to be filled with uniformly distributed values. This can be given as multiple positional arguments, each such positional argument being an integer, or as a single positional argument of a tuple, the tuple containing multiple integers. Note that, if the user wishes to fill an existing tensor instead, then no positional argument is expected. |
()
|
lb
|
Optional[RealOrVector]
|
Lower bound for the uniformly distributed values.
Can be a scalar, or a tensor.
If not specified, the lower bound will be taken as 0.
Note that, if one specifies |
None
|
ub
|
Optional[RealOrVector]
|
Upper bound for the uniformly distributed values.
Can be a scalar, or a tensor.
If not specified, the upper bound will be taken as 1.
Note that, if one specifies |
None
|
out
|
Optional[Tensor]
|
Optionally, the tensor to be filled by uniformly distributed
values. If an |
None
|
dtype
|
Optional[DType]
|
Optionally a string (e.g. "float32") or a PyTorch dtype
(e.g. torch.float32).
If |
None
|
device
|
Optional[Device]
|
The device in which the new tensor will be stored.
If not specified, "cpu" will be used.
If an |
None
|
generator
|
Any
|
Pseudo-random number generator to be used when sampling
the values. Can be a |
None
|
Source code in evotorch/tools/misc.py
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 |
|
make_zeros(*size, out=None, dtype=None, device=None)
¶
Make a new tensor filled with 0, or fill an existing tensor with 0.
The following example creates a float32 tensor filled with 0 values, of shape (3, 5):
zero_values = make_zeros(3, 5, dtype="float32")
The following example fills an existing tensor with 0s:
make_zeros(out=existing_tensor)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
size
|
Size
|
Size of the new tensor to be filled with 0. This can be given as multiple positional arguments, each such positional argument being an integer, or as a single positional argument of a tuple, the tuple containing multiple integers. Note that, if the user wishes to fill an existing tensor with 0 values, then no positional argument is expected. |
()
|
out
|
Optional[Tensor]
|
Optionally, the tensor to be filled by 0 values.
If an |
None
|
dtype
|
Optional[DType]
|
Optionally a string (e.g. "float32") or a PyTorch dtype
(e.g. torch.float32).
If |
None
|
device
|
Optional[Device]
|
The device in which the new tensor will be stored.
If not specified, "cpu" will be used.
If an |
None
|
Source code in evotorch/tools/misc.py
modify_tensor(original, target, lb=None, ub=None, max_change=None, in_place=False)
¶
Return the modified version of the original tensor, with bounds checking.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
original
|
Tensor
|
The original tensor. |
required |
target
|
Tensor
|
The target tensor which contains the values to replace the old ones in the original tensor. |
required |
lb
|
Optional[Union[float, Tensor]]
|
The lower bound(s), as a scalar or as an tensor. Values below these bounds are clipped in the resulting tensor. None means -inf. |
None
|
ub
|
Optional[Union[float, Tensor]]
|
The upper bound(s), as a scalar or as an tensor. Value above these bounds are clipped in the resulting tensor. None means +inf. |
None
|
max_change
|
Optional[Union[float, Tensor]]
|
The ratio of allowed change.
In more details, when given as a real number r,
modifications are allowed only within
|
None
|
in_place
|
bool
|
Provide this as True if you wish the modification to be done within the original tensor. The default value of this argument is False, which means, the original tensor is not changed, and its modified version is returned as an independent copy. |
False
|
Source code in evotorch/tools/misc.py
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 |
|
modify_vector(original, target, *, lb=None, ub=None, max_change=None)
¶
Return the modified version(s) of the vector(s), with bounds checking.
This function is similar to modify_tensor
, but it has the following
different behaviors:
- Assumes that all of its arguments are either vectors, or are batches of vectors. If some or more of its arguments have 2 or more dimensions, those arguments will be considered as batches, and the computation will be vectorized to return a batch of results.
- Designed to be
vmap
-friendly. - Designed for functional programming paradigm, and therefore lacks the in-place modification option.
Source code in evotorch/tools/misc.py
numpy_copy(x, dtype=None)
¶
Return a numpy copy of the given iterable.
The newly created numpy array will be mutable, even if the original iterable object is read-only.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Iterable
|
Any Iterable whose numpy copy will be returned. |
required |
dtype
|
Optional[DType]
|
The desired dtype. Can be given as a numpy dtype, as a torch dtype, or a native dtype (e.g. int, float), or as a string (e.g. "float32"). If left as None, dtype will be determined according to the data contained by the original iterable object. |
None
|
Source code in evotorch/tools/misc.py
pass_info_if_needed(f, info)
¶
Pass additional arguments into a callable, the info dictionary is unpacked and passed as additional keyword arguments only if the policy is decorated with the pass_info decorator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
f
|
Callable
|
The callable to be called. |
required |
info
|
Dict[str, Any]
|
The info to be passed to the callable. |
required |
Source code in evotorch/tools/misc.py
penalty(lhs, comparison, rhs, *, penalty_sign, linear=None, step=None, exp=None, exp_inf=None)
¶
Return a penalty based on the amount of violation of the constraint.
Depending on the provided arguments, the penalty can be linear, or exponential, or based on step function, or a combination of these.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
lhs
|
Union[float, Tensor]
|
The left-hand-side of the constraint. In the non-batched case, this is expected as a scalar. If it is given as an n-dimensional tensor where n is at least 1, this is considered as a batch of left-hand-side values. |
required |
comparison
|
str
|
The operator used for comparing the left-hand-side and the right-hand-side. Expected as a string. Acceptable values are: '<=', '==', '>='. |
required |
rhs
|
Union[float, Tensor]
|
The right-hand-side of the constraint. In the non-batched case, this is expected as a scalar. If it is given as an n-dimensional tensor where n is at least 1, this is considered as a batch of right-hand-side values. |
required |
penalty_sign
|
str
|
Expected as string, either as '+' or '-', which
determines the sign of the penalty (i.e. determines if the penalty
will be positive or negative). One should consider the objective
sense of the fitness function at hand for deciding |
required |
linear
|
Optional[Union[float, Tensor]]
|
Multiplier for the linear component of the penalization. If omitted (i.e. left as None), the value of this multiplier will be 0 (meaning that there will not be any linear penalization). In the non-batched case, this argument is expected as a scalar. If this is provided as a tensor 1 or more dimensions, those dimensions will be considered as batch dimensions. |
None
|
step
|
Optional[Union[float, Tensor]]
|
The constant amount that will be added onto the penalty if there is a violation. If omitted (i.e. left as None), this value is 0. In the non-batched case, this argument is expected as a scalar. If this is provided as a tensor 1 or more dimensions, those dimensions will be considered as batch dimensions. |
None
|
exp
|
Optional[Union[float, Tensor]]
|
A constant |
None
|
exp_inf
|
Optional[Union[float, Tensor]]
|
Upper bound for exponential penalty values. If exponential
penalty is enabled but |
None
|
Source code in evotorch/tools/constraints.py
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 |
|
rank(fitnesses, ranking_method, *, higher_is_better)
¶
Get the ranks of the given sequence of numbers.
Better solutions will have numerically higher ranks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fitnesses
|
Iterable[float]
|
A sequence of numbers to be ranked. |
required |
ranking_method
|
str
|
The ranking method to be used.
Can be "centered", which means 0-centered linear ranking
from -0.5 to 0.5.
Can be "linear", which means a linear ranking from 0 to 1.
Can be "nes", which means the ranking method used by
Natural Evolution Strategies.
Can be "normalized", which means that the ranks will be
the normalized counterparts of the fitnesses.
Can be "raw", which means that the fitnesses themselves
(or, if |
required |
higher_is_better
|
bool
|
Whether or not the higher values will be assigned higher ranks. Changing this to False means that lower values are interpreted as better, and therefore lower values will have higher ranks. |
required |
Source code in evotorch/tools/ranking.py
read_only_tensor(x, *, dtype=None, device=None)
¶
Make a ReadOnlyTensor from the given object.
The provided object can be a scalar, or an Iterable of numeric data, or an ObjectArray.
This function can be thought as the read-only counterpart of PyTorch's
torch.tensor(...)
function.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Any
|
The object from which the new ReadOnlyTensor will be made. |
required |
dtype
|
Optional[dtype]
|
The dtype of the new ReadOnlyTensor (e.g. torch.float32). |
None
|
device
|
Optional[Union[str, device]]
|
The device in which the ReadOnlyTensor will be stored (e.g. "cpu"). |
None
|
Source code in evotorch/tools/readonlytensor.py
set_default_logger_config(logger_name='evotorch', logger_level=logging.INFO, show_process=True, show_lineno=False, override=False)
¶
Configure the "EvoTorch" Python logger to print to the console with default format.
The logger will be configured to print to all messages with level INFO or lower to stdout and all messages with level WARNING or higher to stderr.
The default format is:
[2022-11-23 22:28:47] INFO <75935> evotorch: This is a log message
{asctime} {level} {process} {logger_name}: {message}
show_process=False
to hide Process ID or show_lineno=True
to
show the filename and line number of the log message instead of the Logger Name.
This function should be called before any other logging is performed, otherwise the default configuration will
not be applied. If the logger is already configured, this function will do nothing unless override=True
is passed,
in which case the logger will be reconfigured.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
logger_name
|
str
|
Name of the logger to configure. |
'evotorch'
|
logger_level
|
int
|
Level of the logger to configure. |
INFO
|
show_process
|
bool
|
Whether to show the process name in the log message. |
True
|
show_lineno
|
bool
|
Whether to show the filename with the line number in the log message or just the name of the logger. |
False
|
override
|
bool
|
Whether to override the logger configuration if it has already been configured. |
False
|
Source code in evotorch/tools/misc.py
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 |
|
split_workload(workload, num_actors)
¶
Split a workload among actors.
By "workload" what is meant is the total amount of a work, this amount being expressed by an integer. For example, if the "work" is the evaluation of a population, the "workload" would usually be the population size.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
workload
|
int
|
Total amount of work, as an integer. |
required |
num_actors
|
int
|
Number of actors (i.e. remote workers) among which the workload will be distributed. |
required |
Source code in evotorch/tools/misc.py
stdev_from_radius(radius, solution_length)
¶
Get elementwise standard deviation from a given radius.
Sometimes, for a distribution-based search algorithm, the user might
choose to configure the initial coverage area of the search distribution
not via standard deviation, but via a radius value, as was done in the
study of Toklu et al. (2020).
This function takes the desired radius value and the solution length of
the problem at hand, and returns the elementwise standard deviation value.
Let us name this returned standard deviation value as s
.
When a new Gaussian distribution is constructed such that its initial
standard deviation is [s, s, s, ...]
(the length of this vector being
equal to the solution length), this constructed distribution's radius
corresponds with the desired radius.
Here, the "radius" of a Gaussian distribution is defined as the norm
of the standard deviation vector. In the case of a standard normal
distribution, this radius formulation serves as a simplified approximation
to E[||Normal(0, I)||]
(for which a closer approximation is used in
the study of Hansen & Ostermeier (2001)).
Reference:
Toklu, N.E., Liskowski, P., Srivastava, R.K. (2020).
ClipUp: A Simple and Powerful Optimizer
for Distribution-based Policy Evolution.
Parallel Problem Solving from Nature (PPSN 2020).
Nikolaus Hansen, Andreas Ostermeier (2001).
Completely Derandomized Self-Adaptation in Evolution Strategies.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
radius
|
float
|
The radius whose elementwise standard deviation counterpart will be returned. |
required |
solution_length
|
int
|
Length of a solution for the problem at hand. |
required |
Source code in evotorch/tools/misc.py
storage_ptr(x)
¶
Get the pointer to the underlying storage of a tensor of an ObjectArray.
Calling storage_ptr(x)
is equivalent to x.untyped_storage().data_ptr()
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Iterable
|
A regular PyTorch tensor, or a ReadOnlyTensor, or an ObjectArray. |
required |
Source code in evotorch/tools/misc.py
to_numpy_dtype(dtype)
¶
Convert the given string or the given PyTorch dtype to a numpy dtype. If the argument is already a numpy dtype, then the argument is returned as it is.
Returns:
Type | Description |
---|---|
dtype
|
The dtype, converted to a numpy dtype. |
Source code in evotorch/tools/misc.py
to_stdev_init(*, solution_length, stdev_init=None, radius_init=None)
¶
Ask for both standard deviation and radius, return the standard deviation.
It is very common among the distribution-based search algorithms to ask for both standard deviation and for radius for initializing the coverage area of the search distribution. During their initialization phases, these algorithms must check which one the user provided (radius or standard deviation), and return the result as the standard deviation so that a Gaussian distribution can easily be constructed.
This function serves as a helper function for such search algorithms by performing these actions:
- If the user provided a standard deviation and not a radius, then this provided standard deviation is simply returned.
- If the user provided a radius and not a standard deviation, then this provided radius is converted to its standard deviation counterpart, and then returned.
- If both standard deviation and radius are missing, or they are both given at the same time, then an error is raised.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
solution_length
|
int
|
Length of a solution for the problem at hand. |
required |
stdev_init
|
Optional[RealOrVector]
|
Standard deviation. If one wishes to provide a radius
instead, then |
None
|
radius_init
|
Optional[RealOrVector]
|
Radius. If one wishes to provide a standard deviation
instead, then |
None
|
Source code in evotorch/tools/misc.py
to_torch_dtype(dtype)
¶
Convert the given string or the given numpy dtype to a PyTorch dtype. If the argument is already a PyTorch dtype, then the argument is returned as it is.
Returns:
Type | Description |
---|---|
dtype
|
The dtype, converted to a PyTorch dtype. |
Source code in evotorch/tools/misc.py
violation(lhs, comparison, rhs)
¶
Get the amount of constraint violation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
lhs
|
Union[float, Tensor]
|
The left-hand-side of the constraint. In the non-batched case, this is expected as a scalar. If it is given as an n-dimensional tensor where n is at least 1, this is considered as a batch of left-hand-side values. |
required |
comparison
|
str
|
The operator used for comparing the left-hand-side and the right-hand-side. Expected as a string. Acceptable values are: '<=', '==', '>='. |
required |
rhs
|
Union[float, Tensor]
|
The right-hand-side of the constraint. In the non-batched case, this is expected as a scalar. If it is given as an n-dimensional tensor where n is at least 1, this is considered as a batch of right-hand-side values. |
required |