Misc
Miscellaneous utility functions
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
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)
¶
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
message_from(sender, message)
¶
Prepend the sender object's name and id to a string message.
Let us imagine that we have a class named Example
:
from evotorch.tools import message_from
class Example:
def say_hello(self):
print(message_from(self, "Hello!"))
Let us now instantiate this class and use its say_hello
method:
The output becomes something like this:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sender
|
object
|
The object which produces the message |
required |
message
|
Any
|
The message, as something that can be converted to string |
required |
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
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. |