torchneat 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. torchneat/__init__.py +85 -0
  2. torchneat/_version.py +1 -0
  3. torchneat/backends/__init__.py +26 -0
  4. torchneat/backends/cpu/__init__.py +47 -0
  5. torchneat/backends/cpu/backend.py +60 -0
  6. torchneat/backends/cpu/functional.py +74 -0
  7. torchneat/backends/cpu/initialization.py +57 -0
  8. torchneat/backends/cpu/mutation.py +110 -0
  9. torchneat/backends/cpu/reproduction.py +91 -0
  10. torchneat/backends/cpu/speciation.py +116 -0
  11. torchneat/backends/execution.py +229 -0
  12. torchneat/backends/functional.py +58 -0
  13. torchneat/backends/gpu/__init__.py +47 -0
  14. torchneat/backends/gpu/backend.py +66 -0
  15. torchneat/backends/gpu/functional.py +106 -0
  16. torchneat/backends/gpu/initialization.py +51 -0
  17. torchneat/backends/gpu/mutation.py +100 -0
  18. torchneat/backends/gpu/reproduction.py +77 -0
  19. torchneat/backends/gpu/speciation.py +115 -0
  20. torchneat/backends/initialization.py +62 -0
  21. torchneat/backends/interface.py +69 -0
  22. torchneat/backends/reproduction.py +652 -0
  23. torchneat/backends/seeding.py +92 -0
  24. torchneat/backends/speciation.py +256 -0
  25. torchneat/backends/util.py +127 -0
  26. torchneat/config/__init__.py +6 -0
  27. torchneat/config/base.py +123 -0
  28. torchneat/config/types.py +153 -0
  29. torchneat/core/__init__.py +38 -0
  30. torchneat/core/constants.py +23 -0
  31. torchneat/core/genome.py +47 -0
  32. torchneat/core/population.py +999 -0
  33. torchneat/core/reproduction.py +63 -0
  34. torchneat/core/species.py +151 -0
  35. torchneat/core/stagnation.py +106 -0
  36. torchneat/nn/__init__.py +152 -0
  37. torchneat/nn/activations.py +64 -0
  38. torchneat/nn/blocks/__init__.py +48 -0
  39. torchneat/nn/blocks/_common.py +20 -0
  40. torchneat/nn/blocks/attention.py +721 -0
  41. torchneat/nn/blocks/conv_attention.py +519 -0
  42. torchneat/nn/blocks/conver.py +367 -0
  43. torchneat/nn/blocks/encoding.py +474 -0
  44. torchneat/nn/blocks/feedforward.py +144 -0
  45. torchneat/nn/blocks/reformer.py +221 -0
  46. torchneat/nn/blocks/residual.py +94 -0
  47. torchneat/nn/blocks/transformer.py +225 -0
  48. torchneat/nn/distributions.py +170 -0
  49. torchneat/nn/layers/__init__.py +22 -0
  50. torchneat/nn/layers/containers.py +64 -0
  51. torchneat/nn/layers/convolution.py +254 -0
  52. torchneat/nn/layers/embedding.py +59 -0
  53. torchneat/nn/layers/linear.py +87 -0
  54. torchneat/nn/layers/normalization.py +204 -0
  55. torchneat/nn/layers/pooling.py +173 -0
  56. torchneat/nn/layers/recurrent.py +83 -0
  57. torchneat/nn/layers/shape.py +61 -0
  58. torchneat/nn/legacy.py +98 -0
  59. torchneat/nn/model.py +130 -0
  60. torchneat/nn/module.py +1000 -0
  61. torchneat/nn/parameter.py +212 -0
  62. torchneat/nn/utils.py +80 -0
  63. torchneat/nn/wrapped.py +81 -0
  64. torchneat/optim/__init__.py +6 -0
  65. torchneat/optim/scheduler.py +216 -0
  66. torchneat/py.typed +0 -0
  67. torchneat/reporting/__init__.py +10 -0
  68. torchneat/reporting/attention.py +253 -0
  69. torchneat/reporting/base.py +77 -0
  70. torchneat/reporting/reporters.py +95 -0
  71. torchneat/rl/__init__.py +21 -0
  72. torchneat/rl/base.py +897 -0
  73. torchneat/rl/functional.py +731 -0
  74. torchneat/rl/logger.py +191 -0
  75. torchneat/rl/neat.py +542 -0
  76. torchneat/rl/ppo.py +550 -0
  77. torchneat/rl/replay.py +784 -0
  78. torchneat/utils/__init__.py +11 -0
  79. torchneat/utils/console.py +10 -0
  80. torchneat/utils/helpers.py +34 -0
  81. torchneat/utils/replay.py +276 -0
  82. torchneat/utils/storage.py +295 -0
  83. torchneat/utils/timing.py +41 -0
  84. torchneat-0.1.0.dist-info/METADATA +135 -0
  85. torchneat-0.1.0.dist-info/RECORD +88 -0
  86. torchneat-0.1.0.dist-info/WHEEL +5 -0
  87. torchneat-0.1.0.dist-info/licenses/LICENSE +21 -0
  88. torchneat-0.1.0.dist-info/top_level.txt +1 -0
torchneat/__init__.py ADDED
@@ -0,0 +1,85 @@
1
+ """TorchNEAT: CPU/GPU accelerated neuroevolution for PyTorch modules.
2
+
3
+ Typical use::
4
+
5
+ import torchneat as tn
6
+
7
+ config = tn.Config("demo", "demo")
8
+ population = tn.Population(100, MyPolicy(), config)
9
+
10
+ ``torchneat.nn`` mirrors ``torch.nn`` (evolvable layers plus the common PyTorch modules re-exported), so model code
11
+ only needs ``import torchneat.nn as nn``.
12
+ """
13
+
14
+ from importlib import import_module
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ._version import __version__
18
+
19
+ # name -> submodule that defines it. Everything is imported lazily (PEP 562) so ``import torchneat`` stays cheap and
20
+ # the optional GPU / logging dependencies are never touched until used.
21
+ _EXPORTS = {
22
+ # configuration
23
+ "Config": "config",
24
+ # modules
25
+ "Genome": "core.genome",
26
+ "Model": "nn.model",
27
+ "NeatModule": "nn.module",
28
+ "NeatParameter": "nn.parameter",
29
+ # evolution
30
+ "Population": "core.population",
31
+ "Reproduction": "core.reproduction",
32
+ "Species": "core.species",
33
+ "SpeciesSet": "core.species",
34
+ "Stagnation": "core.stagnation",
35
+ # reporting
36
+ "BaseReporter": "reporting",
37
+ "ReporterSet": "reporting",
38
+ "StdOutReporter": "reporting",
39
+ # reinforcement learning
40
+ "NEAT": "rl",
41
+ "PPO": "rl",
42
+ # backends
43
+ "cuda_is_available": "backends",
44
+ "get_device": "backends",
45
+ "get_tpb": "backends",
46
+ "set_device": "backends",
47
+ "set_tpb": "backends",
48
+ # utils
49
+ "CM": "utils",
50
+ "Fore": "utils",
51
+ }
52
+ _SUBMODULES = ("backends", "config", "core", "nn", "optim", "reporting", "rl", "utils")
53
+
54
+ __all__ = ["__version__", *_EXPORTS, *_SUBMODULES]
55
+
56
+ if TYPE_CHECKING: # pragma: no cover
57
+ from . import backends, config, core, nn, optim, reporting, rl, utils
58
+ from .backends import cuda_is_available, get_device, get_tpb, set_device, set_tpb
59
+ from .config import Config
60
+ from .core.genome import Genome
61
+ from .core.population import Population
62
+ from .core.reproduction import Reproduction
63
+ from .core.species import Species, SpeciesSet
64
+ from .core.stagnation import Stagnation
65
+ from .nn.model import Model
66
+ from .nn.module import NeatModule
67
+ from .nn.parameter import NeatParameter
68
+ from .reporting import BaseReporter, ReporterSet, StdOutReporter
69
+ from .rl import NEAT, PPO
70
+ from .utils import CM, Fore
71
+
72
+
73
+ def __getattr__(name):
74
+ if name in _EXPORTS:
75
+ value = getattr(import_module(f"{__name__}.{_EXPORTS[name]}"), name)
76
+ elif name in _SUBMODULES:
77
+ value = import_module(f"{__name__}.{name}")
78
+ else:
79
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
80
+ globals()[name] = value
81
+ return value
82
+
83
+
84
+ def __dir__():
85
+ return sorted(__all__)
torchneat/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,26 @@
1
+ """Execution backends: device selection and the CPU (numba) / GPU (numba.cuda + cupy) kernels for
2
+ initialization, reproduction and speciation."""
3
+
4
+ from .execution import (
5
+ DEVICE_ENV_NAME,
6
+ TPB_ENV_NAME,
7
+ cuda_is_available,
8
+ get_device,
9
+ get_device_env,
10
+ get_tpb,
11
+ get_tpb_env,
12
+ initialize,
13
+ reproduce,
14
+ set_device,
15
+ set_device_env,
16
+ set_tpb,
17
+ set_tpb_env,
18
+ speciate,
19
+ )
20
+
21
+ __all__ = [
22
+ 'DEVICE_ENV_NAME', 'TPB_ENV_NAME', 'cuda_is_available',
23
+ 'get_device', 'get_device_env', 'get_tpb', 'get_tpb_env', 'initialize',
24
+ 'reproduce', 'set_device', 'set_device_env', 'set_tpb', 'set_tpb_env',
25
+ 'speciate',
26
+ ]
@@ -0,0 +1,47 @@
1
+ # ---------- CPU (numba, prange) implementation of the genome methods ---------- #
2
+ # Device independent logic lives in torchneat.base.{initialization, reproduction, speciation, util, functional};
3
+ # this package only holds the numba kernels and the CPU backend that plugs them into it.
4
+
5
+ from ...config import Config
6
+ from ...core.species import SpeciesSet
7
+ from ...core.stagnation import Stagnation
8
+ from ...nn import Genome, NeatModule
9
+ from ...reporting import ReporterSet
10
+ from .. import initialization as _initialization
11
+ from .. import reproduction as _reproduction
12
+ from .. import speciation as _speciation
13
+ from . import initialization, mutation, reproduction, speciation
14
+ from .backend import BACKEND, CpuBackend
15
+ from .mutation import mutate
16
+
17
+ __all__ = [
18
+ 'BACKEND', 'CpuBackend', 'initialize', 'initialization', 'mutate', 'mutation',
19
+ 'reproduce', 'reproduction', 'speciate', 'speciation',
20
+ ]
21
+
22
+
23
+ def initialize(config: Config, module: NeatModule, tpb=1, verbose: bool | int = False):
24
+ return _initialization.initialize(BACKEND, config, module, tpb, verbose)
25
+
26
+
27
+ def reproduce(
28
+ config: Config, genera: list[int], modules: dict[int, NeatModule], population: dict[int, Genome],
29
+ ancestors: dict[int, tuple[Genome, Genome]], generation: int, to_delete: list[int], genome_indexer: int,
30
+ stagnation: Stagnation, species_set: SpeciesSet, reporters: ReporterSet,
31
+ tpb=1, verbose: bool | int = False):
32
+ return _reproduction.reproduce(
33
+ BACKEND, config, genera, modules, population, ancestors, generation, to_delete, genome_indexer,
34
+ stagnation, species_set, reporters, tpb, verbose
35
+ )
36
+
37
+
38
+ def speciate(config: Config, genera: list[int], modules: dict[int, NeatModule],
39
+ species_set: SpeciesSet, population: dict[int, Genome],
40
+ generation: int, tpb=10, verbose: bool | int = False):
41
+ return _speciation.speciate(BACKEND, config, genera, modules, species_set, population, generation, tpb, verbose)
42
+
43
+
44
+ # Keep the old module level entry points (e.g. `base.cpu.reproduction.reproduce`) available
45
+ initialization.initialize = initialize
46
+ reproduction.reproduce = reproduce
47
+ speciation.speciate = speciate
@@ -0,0 +1,60 @@
1
+ import gc
2
+
3
+ import numpy as np
4
+
5
+ from .. import seeding
6
+ from ..interface import Backend
7
+ from .functional import get_rng_states
8
+ from .initialization import initialize as _initialize_kernel
9
+ from .mutation import mutate as _mutate_kernel
10
+ from .reproduction import crossover as _crossover_kernel
11
+ from .speciation import compute_distances as _compute_distances
12
+
13
+
14
+ class CpuBackend(Backend):
15
+ """Numba (prange) implementation of the device interface, running on numpy arrays."""
16
+ name = 'cpu'
17
+ xp = np
18
+ has_fallback = False
19
+
20
+ def asarray(self, array):
21
+ return np.asarray(array)
22
+
23
+ def zeros(self, shape: tuple):
24
+ return np.zeros(shape, np.float64)
25
+
26
+ def release(self):
27
+ gc.collect()
28
+
29
+ def uniform(self, shape: tuple):
30
+ return seeding.numpy_rng().random(size=shape)
31
+
32
+ def normal_states(self, kernel_shape: tuple, seed: int = None):
33
+ return get_rng_states(kernel_shape, seed, get_normal=True)
34
+
35
+ @staticmethod
36
+ def _check(ret_code: int, ndim: int):
37
+ if ret_code == 1: raise ValueError(f"Expected a 3D array, got {ndim}")
38
+ if ret_code == 2: raise ValueError("Out of bounds")
39
+
40
+ def initialize(self, array, init_type, mean, std, minimum, maximum, rng_states, kernel_shape, info=()):
41
+ try:
42
+ self._check(_initialize_kernel(array, init_type, mean, std, minimum, maximum, rng_states), array.ndim)
43
+ except Exception as e:
44
+ print(*info)
45
+ raise e
46
+
47
+ def crossover(self, genus, source, updates, parents, genera, filled, probabilities, equal_sources, kernel_shape):
48
+ self._check(
49
+ _crossover_kernel(genus, source, updates, parents, genera, filled, probabilities, equal_sources),
50
+ updates.ndim
51
+ )
52
+
53
+ def mutate(self, updates, children, *args, kernel_shape):
54
+ self._check(_mutate_kernel(updates, children, *args), updates.ndim)
55
+
56
+ def compute_distances(self, config, module, dtype, tpb, verbose: bool | int = False):
57
+ return _compute_distances(config, module, dtype, tpb, verbose)
58
+
59
+
60
+ BACKEND = CpuBackend()
@@ -0,0 +1,74 @@
1
+ """CPU (numba) helpers: RNG state sampling and element accessors. Device independent ones are re-exported from ``..functional``."""
2
+
3
+ import numpy as np
4
+ from numba import njit
5
+ from numpy import ndarray as CPUArray
6
+
7
+ from .. import seeding
8
+ from ..functional import calc, calc_grid, clamp, set_seed, threads_total # noqa: F401 (re-exported)
9
+
10
+ __all__ = [
11
+ "calc",
12
+ "calc_grid",
13
+ "clamp",
14
+ "gauss",
15
+ "get_enumeration",
16
+ "get_rng_states",
17
+ "normal",
18
+ "prob",
19
+ "set_seed",
20
+ "uniform",
21
+ ]
22
+
23
+
24
+ def get_rng_states(kernel_shape: tuple, seed: int = None, get_normal=True, dtype=np.float64) -> tuple[np.ndarray, int]:
25
+ # `seed` is applied through ``seeding.configure(config.general.seed)``; an explicit value re-seeds the backend
26
+ if seed is not None:
27
+ seeding.configure(seed)
28
+ rng = seeding.numpy_rng()
29
+ total = threads_total(kernel_shape)
30
+ if get_normal:
31
+ rng_states = rng.standard_normal(size=total).astype(dtype)
32
+ else:
33
+ rng_states = rng.random(size=total).astype(dtype)
34
+ return rng_states, total
35
+
36
+
37
+ @njit(cache=True)
38
+ def gauss(states: CPUArray, index: int) -> float:
39
+ """
40
+ Get the value at a given index for a Normal Distribution CPU Array
41
+ :param states: 1D CPUArray for all max possible threads
42
+ :param index: int
43
+ :return:
44
+ """
45
+ return states[index]
46
+
47
+
48
+ @njit(cache=True)
49
+ def prob(states: CPUArray, index: int) -> float:
50
+ """
51
+ Get the value at a given index for a Probability (Uniform[0, 1]) CPU Array
52
+ :param states: 1D CPUArray for all max possible threads
53
+ :param index: int
54
+ :return:
55
+ """
56
+ return states[index]
57
+
58
+
59
+ @njit(cache=True)
60
+ def normal(states: CPUArray, index: int, mean: float, std: float) -> float:
61
+ return mean + gauss(states, index) * std
62
+
63
+
64
+ @njit(cache=True)
65
+ def uniform(states: CPUArray, index: int, minimum: float, maximum: float) -> float:
66
+ difference = maximum - minimum
67
+ return minimum + prob(states, index) * difference
68
+
69
+
70
+ @njit(cache=True)
71
+ def get_enumeration(array: CPUArray):
72
+ positions: list[tuple[int, ...]] = [index for index, value in np.ndenumerate(array)]
73
+ count = len(positions)
74
+ return positions, count
@@ -0,0 +1,57 @@
1
+ """CPU initialization kernels (numba, prange). The orchestration lives in ``torchneat.base.initialization``."""
2
+
3
+ import numpy as np
4
+ from numba import njit, prange
5
+ from numpy import ndarray as CPUArray
6
+
7
+ from .functional import clamp, normal, uniform
8
+
9
+
10
+ @njit(cache=True)
11
+ def initialize_genome(parameter: CPUArray, g: int, x: int, y: int, init_type: int, mean: float, std: float,
12
+ norm_min: float, norm_max: float, rng_states: CPUArray, rng_index: int):
13
+ uni_min = max(norm_min, (mean - (2 * std)))
14
+ uni_max = min(norm_max, (mean + (2 * std)))
15
+ # for index, value in np.ndenumerate(parameter):
16
+ if init_type == 0:
17
+ parameter[g, x, y] = clamp(
18
+ normal(rng_states, rng_index, mean, std),
19
+ norm_min, norm_max
20
+ )
21
+ elif init_type == 1:
22
+ parameter[g, x, y] = uniform(rng_states, rng_index, uni_min, uni_max)
23
+
24
+
25
+ @njit(parallel=True, cache=True)
26
+ def initialize(parameter: CPUArray, init_type: int, mean: float, std: float, minimum: float, maximum: float, rng_states):
27
+ ret_code: int = 0
28
+ if parameter.ndim != 3: ret_code = 1
29
+
30
+ if not ret_code:
31
+ s_g, s_x, s_y = parameter.shape
32
+ # Parameter shape (genomes, *spatial_dims)
33
+ g_lim = parameter.shape[0]
34
+ x_lim = 1 if parameter.ndim <= 1 else parameter.shape[1]
35
+ y_lim = 1 if parameter.ndim <= 2 else parameter.shape[2]
36
+
37
+ # Flat index -> (genome, x, y) without materializing a list of index tuples
38
+ total = s_g * s_x * s_y
39
+ yz = s_x * s_y
40
+ for i in prange(total):
41
+ # prange indices are unsigned: cast to int64 so // and % stay integers (uint64 with int64 -> float64)
42
+ flat = np.int64(i)
43
+ genome_idx = flat // yz
44
+ x = (flat % yz) // s_y
45
+ y = flat % s_y
46
+
47
+ # Linearized thread index
48
+ rng_index = (y * s_x * s_g) + (x * s_g) + genome_idx
49
+
50
+ if genome_idx < g_lim and x < x_lim and y < y_lim:
51
+ initialize_genome(
52
+ parameter, genome_idx, x, y, init_type, mean, std, minimum, maximum, rng_states, rng_index
53
+ )
54
+ else:
55
+ ret_code = 2
56
+
57
+ return ret_code
@@ -0,0 +1,110 @@
1
+ """CPU mutation kernels (numba, prange). See ``torchneat.base.mutation`` for the notes on how mutation works."""
2
+
3
+ import numpy as np
4
+ from numba import njit, prange
5
+ from numpy import ndarray as CPUArray
6
+
7
+ from .functional import clamp, normal, prob
8
+ from .initialization import initialize_genome
9
+
10
+
11
+ @njit(cache=True)
12
+ def mutate_genome(parameter: CPUArray, g: int, x: int, y: int, mutate_rate: float, mutate_power: float,
13
+ replace_rate: float, init_type: int, mean: float, std: float, minimum: float, maximum: float,
14
+ ssm: bool, add_param: float, delete_param: float, epsilon: float,
15
+ probabilities: tuple[CPUArray, ...], normals: CPUArray, rng_index: int):
16
+ value = parameter[g, x, y]
17
+
18
+ zero_param = abs(value) <= epsilon
19
+ if ssm:
20
+ div = max(1.0, add_param + delete_param)
21
+ r = prob(probabilities[0], rng_index)
22
+ if r < (add_param / div):
23
+ if zero_param:
24
+ initialize_genome(
25
+ parameter, g, x, y,
26
+ init_type, mean, std, minimum, maximum,
27
+ normals, rng_index
28
+ )
29
+ # else:
30
+ # clamp(
31
+ # value + normal(normals, rng_index, 0., mutate_power/3),
32
+ # minimum, maximum
33
+ # )
34
+ elif r < ((delete_param + add_param) / div):
35
+ parameter[g, x, y] = epsilon
36
+ else:
37
+ if prob(probabilities[0], rng_index) < add_param:
38
+ if zero_param:
39
+ initialize_genome(
40
+ parameter, g, x, y,
41
+ init_type, mean, std, minimum, maximum,
42
+ normals, rng_index
43
+ )
44
+ # else:
45
+ # clamp(
46
+ # value + normal(normals, rng_index, 0., mutate_power/3),
47
+ # minimum, maximum
48
+ # )
49
+ elif prob(probabilities[1], rng_index) < delete_param:
50
+ parameter[g, x, y] = epsilon
51
+
52
+ r = prob(probabilities[-1], rng_index)
53
+ if r < mutate_rate:
54
+ parameter[g, x, y] = clamp(
55
+ value + normal(normals, rng_index, 0., mutate_power),
56
+ minimum, maximum
57
+ )
58
+ elif r < replace_rate + mutate_rate:
59
+ initialize_genome(
60
+ parameter, g, x, y,
61
+ init_type, mean, std, minimum, maximum,
62
+ normals, rng_index
63
+ )
64
+
65
+
66
+ @njit(parallel=True, cache=True)
67
+ def mutate(
68
+ updates: CPUArray, children: CPUArray,
69
+ mutate_rate: float, mutate_power: float,
70
+ replace_rate: float, init_type: int, mean: float, std: float, minimum: float, maximum: float,
71
+ ssm: bool, add_param: float, delete_param: float, epsilon: float,
72
+ probabilities: tuple[CPUArray, ...], normals: CPUArray,
73
+ # debugging: CPUArray
74
+ ):
75
+ ret_code: int = 0
76
+ if updates.ndim != 3: ret_code = 1
77
+
78
+ if not ret_code:
79
+ s_g, s_x, s_y = updates.shape
80
+ # Parameter shape (genomes, *spatial_dims)
81
+ g_lim = updates.shape[0]
82
+ x_lim = 1 if updates.ndim <= 1 else updates.shape[1]
83
+ y_lim = 1 if updates.ndim <= 2 else updates.shape[2]
84
+
85
+ # Flat index -> (genome, x, y) without materializing a list of index tuples
86
+ total = s_g * s_x * s_y
87
+ yz = s_x * s_y
88
+ for i in prange(total):
89
+ # prange indices are unsigned: cast to int64 so // and % stay integers (uint64 with int64 -> float64)
90
+ flat = np.int64(i)
91
+ genome_idx = flat // yz
92
+ x = (flat % yz) // s_y
93
+ y = flat % s_y
94
+
95
+ # Linearized thread index
96
+ rng_index = (y * s_x * s_g) + (x * s_g) + genome_idx
97
+
98
+ if genome_idx < g_lim and x < x_lim and y < y_lim:
99
+ if children[genome_idx]:
100
+ mutate_genome(
101
+ updates, genome_idx, x, y,
102
+ mutate_rate, mutate_power,
103
+ replace_rate, init_type, mean, std, minimum, maximum,
104
+ ssm, add_param, delete_param, epsilon,
105
+ probabilities, normals, rng_index
106
+ )
107
+ else:
108
+ ret_code = 2
109
+
110
+ return ret_code
@@ -0,0 +1,91 @@
1
+ """CPU crossover kernel (numba, prange). The orchestration lives in ``torchneat.base.reproduction``."""
2
+
3
+ import numpy as np
4
+ from numba import njit, prange
5
+ from numpy import ndarray as CPUArray
6
+
7
+ from .functional import prob
8
+
9
+
10
+ @njit(cache=True)
11
+ def _crossover(value1: float, value2: float, states: CPUArray, index: int):
12
+ if prob(states, index) >= 0.5:
13
+ return value1
14
+ else:
15
+ return value2
16
+
17
+
18
+ @njit(parallel=True, cache=True)
19
+ # TODO: Caching seems to work for now since no custom Classes or prints are used
20
+ def crossover(genus: int, source: CPUArray, updates: CPUArray, parents: CPUArray, genera: CPUArray, filled: CPUArray,
21
+ probabilities: CPUArray, equal_sources: bool):
22
+ # TODO: Ensure no breaks, raises or other multiple return points in order for parallel to work.
23
+ # Avoid assertions too even though most uses have not raised NumbaPerformanceWarning.
24
+ ret_code: int = 0
25
+ if updates.ndim != 3: ret_code = 1
26
+
27
+ if not ret_code:
28
+ s_g, s_x, s_y = updates.shape # cuda.gridsize(3)
29
+ # Parameter shape (genomes, *spatial_dims)
30
+ g_lim = updates.shape[0]
31
+ x_lim = 1 if updates.ndim <= 1 else updates.shape[1]
32
+ y_lim = 1 if updates.ndim <= 2 else updates.shape[2]
33
+
34
+ # Flat index -> (genome, x, y) without materializing a list of index tuples
35
+ total = s_g * s_x * s_y
36
+ yz = s_x * s_y
37
+ for i in prange(total):
38
+ # prange indices are unsigned: cast to int64 so // and % stay integers (uint64 with int64 -> float64)
39
+ flat = np.int64(i)
40
+ genome_idx = flat // yz
41
+ x = (flat % yz) // s_y
42
+ y = flat % s_y
43
+
44
+ # Linearized thread index
45
+ rng_index = (y * s_x * s_g) + (x * s_g) + genome_idx
46
+
47
+ if genome_idx < g_lim and x < x_lim and y < y_lim:
48
+ parent0, parent1, parent_ = parents[genome_idx]
49
+ genus0, genus1, genus_ = genera[genome_idx]
50
+ filled0, filled1, filled_ = filled[genome_idx, x, y]
51
+ if equal_sources or (genus0 == genus1 == genus):
52
+ # For elite genomes or clones
53
+ if (parent0 == parent1) and (genus == genus0 == genus1):
54
+ value = source[parent0, x, y]
55
+ filled[genome_idx, x, y, :2] = True
56
+ # For child crossover
57
+ else:
58
+ already_filled = filled0 or filled1
59
+
60
+ # If not filled, fill from current available source
61
+ value = updates[genome_idx, x, y].item() # Get value in case param has been filled from another source
62
+ if not already_filled:
63
+ if genus == genus0:
64
+ value = source[parent0, x, y]
65
+ filled[genome_idx, x, y, 0] = filled0 = True
66
+ elif genus == genus1:
67
+ value = source[parent1, x, y]
68
+ filled[genome_idx, x, y, 1] = filled1 = True
69
+
70
+ # Crossover when both parents' values are available
71
+ if genus == genus0 and not filled0 and filled1:
72
+ value_c = source[parent0, x, y].item()
73
+ value = _crossover(value, value_c, probabilities, rng_index)
74
+ filled[genome_idx, x, y, 0] = True
75
+ if genus == genus1 and not filled1 and filled0:
76
+ value_c = source[parent1, x, y].item()
77
+ value = _crossover(value, value_c, probabilities, rng_index)
78
+ filled[genome_idx, x, y, 1] = True
79
+ else:
80
+ # Emergency fill on unmatched param groups
81
+ if not filled_ and genus == genus_:
82
+ # TODO: Should random emergency parents be used instead of random cloning?
83
+ value = source[parent_, x, y]
84
+ filled[genome_idx, x, y, 2] = True
85
+ else:
86
+ value = updates[genome_idx, x, y]
87
+
88
+ updates[genome_idx, x, y] = value
89
+ else: ret_code = 2
90
+
91
+ return ret_code
@@ -0,0 +1,116 @@
1
+ """CPU distance kernels (numba, prange). The species grouping lives in ``torchneat.base.speciation``."""
2
+
3
+ import numpy as np
4
+ from numba import njit, prange
5
+ from numpy import ndarray as CPUArray
6
+
7
+ from ...config import Config
8
+ from ...nn.module import NeatModule
9
+ from ..util import parameter_dtype, reshape_to_ndim
10
+
11
+
12
+ @njit(cache=True)
13
+ def calc_distance(parameter: CPUArray, total_distance: CPUArray,
14
+ genome0: int, genome1: int, x: int,
15
+ compatibility_weight_coefficient: float, compatibility_disjoint_coefficient: float):
16
+ """
17
+ Returns the genetic distance between this genome and the other. This distance value
18
+ is used to compute genome compatibility for speciation.
19
+ """
20
+
21
+ value0 = parameter[genome0, x]
22
+ value1 = parameter[genome1, x]
23
+
24
+ current_distance = 0 # total_distance[genome0, genome1]
25
+ disjoint_value = 0
26
+ if value0 == 0:
27
+ disjoint_value += 1
28
+ if value1 == 0:
29
+ disjoint_value = disjoint_value + 1
30
+ if value0 != 0 and value1 != 0:
31
+ current_distance = current_distance + (abs(value0 - value1) * compatibility_weight_coefficient)
32
+ current_distance = current_distance + disjoint_value * compatibility_disjoint_coefficient
33
+
34
+ # Parameter shape = (genomes, x, y | 1)
35
+ x_s = parameter.shape[1] # [:]
36
+ size = x_s # * y_s
37
+ # if size != 0:
38
+ current_distance = current_distance / size
39
+
40
+ return current_distance
41
+
42
+
43
+ @njit(parallel=True, cache=True)
44
+ # NOTE: Same fix as crossover(): a single return point and ret_code instead of
45
+ # raising inside a prange body. Only the outer `genome0` loop is a prange -
46
+ # each iteration exclusively owns row `genome0` of total_distance (lower
47
+ # triangle writes total_distance[genome0, genome1>=genome0], upper triangle
48
+ # writes total_distance[genome0, genome1<genome0] after reading the already
49
+ # completed lower triangle) so there is no cross-thread write conflict.
50
+ # The inner loops stay plain `range` - nesting prange inside prange gives
51
+ # numba nothing extra here and only muddies which loop actually gets parallelized.
52
+ def get_distance(parameter: CPUArray, total_distance: CPUArray,
53
+ compatibility_weight_coefficient: float, compatibility_disjoint_coefficient: float):
54
+ ret_code: int = 0
55
+ if parameter.ndim != 2: ret_code = 1
56
+
57
+ if not ret_code:
58
+ g_lim = total_distance.shape[0]
59
+ x_lim = parameter.shape[1]
60
+
61
+ # TODO: The nested pranges may raise performance warning so find a way to combine
62
+ # and iterate over a single integer like other parralel functions
63
+ # Fill the lower triangle
64
+ # Rows i and (g_lim - 1 - i) are handled by the same iteration to balance the triangular workload.
65
+ # Each row is owned by exactly one iteration, the diagonal is skipped (it only ever added 0.0), and
66
+ # the per-element sum is accumulated in a local (same order as before, so results are identical).
67
+ half = (g_lim + 1) // 2
68
+ for r in prange(half):
69
+ row = np.int64(r) # prange index is unsigned; keep everything int64 (uint64 with int64 -> float64)
70
+ for side in range(2):
71
+ genome0 = row if side == 0 else g_lim - 1 - row
72
+ if side == 1 and genome0 == row:
73
+ continue
74
+ for genome1 in range(genome0 + 1, g_lim):
75
+ acc = total_distance[genome0, genome1]
76
+ for x in range(x_lim):
77
+ acc += calc_distance(
78
+ parameter, total_distance, genome0, genome1, x,
79
+ compatibility_weight_coefficient, compatibility_disjoint_coefficient
80
+ )
81
+ total_distance[genome0, genome1] = acc
82
+ # Fill the upper triangle
83
+ for genome0 in prange(g_lim):
84
+ for genome1 in prange(genome0):
85
+ # Assert limits
86
+ if genome0 < g_lim and genome1 < g_lim:
87
+ distance = total_distance[genome1, genome0]
88
+ total_distance[genome0, genome1] = distance
89
+ else: ret_code = 2
90
+
91
+ return ret_code
92
+
93
+
94
+ def compute_distances(config: Config, module: NeatModule, dtype, tpb: int = 10, verbose: bool | int = False) -> np.ndarray:
95
+ """Genetic distance matrix of the module's genomes (symmetric, zero diagonal), summed over all parameters."""
96
+ total_distance = np.zeros((module.genome_num, module.genome_num), dtype)
97
+
98
+ for param in module.neat_parameters():
99
+ array = np.asarray(reshape_to_ndim(param.data.to(parameter_dtype(param.data.dtype)), 2)[0])
100
+
101
+ try:
102
+ ret_code = get_distance(
103
+ array, total_distance,
104
+ config.genome.compatibility_weight_coefficient,
105
+ config.genome.compatibility_disjoint_coefficient
106
+ )
107
+ if ret_code == 1: raise ValueError(f"Expected a 2D array, got {array.ndim}")
108
+ if ret_code == 2: raise ValueError("Out of bounds")
109
+ except Exception as e:
110
+ print(param.dtype, param.device, array.shape, param.data.shape)
111
+ raise e
112
+
113
+ # Release memory
114
+ del array
115
+
116
+ return total_distance