instinto 0.2.0__tar.gz
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.
- instinto-0.2.0/LICENSE +21 -0
- instinto-0.2.0/PKG-INFO +88 -0
- instinto-0.2.0/README.md +71 -0
- instinto-0.2.0/instinto.egg-info/PKG-INFO +88 -0
- instinto-0.2.0/instinto.egg-info/SOURCES.txt +8 -0
- instinto-0.2.0/instinto.egg-info/dependency_links.txt +1 -0
- instinto-0.2.0/instinto.egg-info/top_level.txt +1 -0
- instinto-0.2.0/instinto.py +445 -0
- instinto-0.2.0/pyproject.toml +25 -0
- instinto-0.2.0/setup.cfg +4 -0
instinto-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ElEscribanoSilente
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
instinto-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: instinto
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Red neuronal zero-deps para videojuegos: neuroevolucion, imitacion, JIT por codegen y save de una linea.
|
|
5
|
+
Author: esraderey
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/ElEscribanoSilente/instinto
|
|
8
|
+
Keywords: neural-network,neuroevolution,gamedev,zero-dependencies,genetic-algorithm
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Topic :: Games/Entertainment
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
13
|
+
Requires-Python: >=3.8
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# instinto
|
|
19
|
+
|
|
20
|
+
[](https://github.com/ElEscribanoSilente/instinto/actions/workflows/ci.yml)
|
|
21
|
+
[](https://pypi.org/project/instinto/)
|
|
22
|
+
[](https://pypi.org/project/instinto/)
|
|
23
|
+
[](LICENSE)
|
|
24
|
+
|
|
25
|
+
Red neuronal **zero-deps** para videojuegos. Un archivo, solo stdlib.
|
|
26
|
+
|
|
27
|
+
- **`Brain`** — MLP denso con pesos planos. `think()` / `act()`.
|
|
28
|
+
- **Neuroevolución** — `Population` con elitismo, torneo y **sigma autoadaptativo**
|
|
29
|
+
(regla 1/5 de Rechenberg): explora fuerte al inicio, refina solo al final.
|
|
30
|
+
- **Imitación** — `learn()` con backprop (SGD + momentum). Graba al jugador, entrena al NPC.
|
|
31
|
+
- **JIT por codegen** — `compile()` genera el forward desenrollado vía `exec`:
|
|
32
|
+
**3–6× más rápido**, ~120k inferencias/seg en CPython puro.
|
|
33
|
+
- **Save de una línea** — `save()` → float16 + zlib + base85. Un cerebro 2-6-2
|
|
34
|
+
son ~116 chars: pégalo en el JSON de tu partida guardada.
|
|
35
|
+
- **Determinista** — misma seed, misma evolución. Replays reproducibles.
|
|
36
|
+
|
|
37
|
+
## Instalar
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
pip install instinto # o copia instinto.py a tu proyecto
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## 60 segundos
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from instinto import Brain, Population
|
|
47
|
+
|
|
48
|
+
# inferencia
|
|
49
|
+
npc = Brain(n_in=4, hidden=[8], n_out=3, out="softmax", seed=42)
|
|
50
|
+
accion = npc.act([dx, dy, vida, peligro], explore=0.05) # 0|1|2
|
|
51
|
+
|
|
52
|
+
# neuroevolución: el fitness ES tu juego
|
|
53
|
+
pop = Population(60, n_in=4, hidden=[8], n_out=3, out="softmax", seed=7)
|
|
54
|
+
for gen in range(100):
|
|
55
|
+
for brain in pop:
|
|
56
|
+
brain.fitness = jugar_partida(brain) # tu función
|
|
57
|
+
stats = pop.evolve() # {'gen','best','mean','sigma'}
|
|
58
|
+
mejor = pop.best
|
|
59
|
+
|
|
60
|
+
# imitación: aprende del jugador
|
|
61
|
+
datos = [(estado, accion_del_jugador), ...] # índice de clase si softmax
|
|
62
|
+
npc.learn(datos, epochs=300, lr=0.5)
|
|
63
|
+
|
|
64
|
+
# producción
|
|
65
|
+
mejor.compile() # JIT (se invalida solo al mutar)
|
|
66
|
+
blob = mejor.save() # str de una línea
|
|
67
|
+
npc2 = Brain.load(blob)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Demo
|
|
71
|
+
|
|
72
|
+
```
|
|
73
|
+
python demo_caza.py # agentes evolucionan a cazar comida, render ASCII
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## API
|
|
77
|
+
|
|
78
|
+
| | |
|
|
79
|
+
|---|---|
|
|
80
|
+
| `Brain(n_in, hidden, n_out, act, out, seed)` | acts: `tanh sigmoid relu linear` (+`softmax` en salida) |
|
|
81
|
+
| `.think(x) -> list` / `.act(x, explore) -> int` | inferencia / argmax con ε-greedy |
|
|
82
|
+
| `.learn(samples, epochs, lr, momentum, batch, reset)` | backprop; devuelve loss (½·MSE o CE) |
|
|
83
|
+
| `.mutate(rate, power)` / `.cross(other)` / `.clone()` | operadores evolutivos |
|
|
84
|
+
| `.compile()` / `.save(compact)` / `Brain.load(s)` | JIT / persistencia |
|
|
85
|
+
| `Population(size, ..., elite, tournament, mut_rate, sigma, noisy_fitness)` | iterable de Brains |
|
|
86
|
+
| `.evolve() -> stats` / `.best` | siguiente generación / hall of fame |
|
|
87
|
+
|
|
88
|
+
Sin numpy. Sin configs. Sin clases que heredar. Python ≥ 3.8.
|
instinto-0.2.0/README.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# instinto
|
|
2
|
+
|
|
3
|
+
[](https://github.com/ElEscribanoSilente/instinto/actions/workflows/ci.yml)
|
|
4
|
+
[](https://pypi.org/project/instinto/)
|
|
5
|
+
[](https://pypi.org/project/instinto/)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
|
|
8
|
+
Red neuronal **zero-deps** para videojuegos. Un archivo, solo stdlib.
|
|
9
|
+
|
|
10
|
+
- **`Brain`** — MLP denso con pesos planos. `think()` / `act()`.
|
|
11
|
+
- **Neuroevolución** — `Population` con elitismo, torneo y **sigma autoadaptativo**
|
|
12
|
+
(regla 1/5 de Rechenberg): explora fuerte al inicio, refina solo al final.
|
|
13
|
+
- **Imitación** — `learn()` con backprop (SGD + momentum). Graba al jugador, entrena al NPC.
|
|
14
|
+
- **JIT por codegen** — `compile()` genera el forward desenrollado vía `exec`:
|
|
15
|
+
**3–6× más rápido**, ~120k inferencias/seg en CPython puro.
|
|
16
|
+
- **Save de una línea** — `save()` → float16 + zlib + base85. Un cerebro 2-6-2
|
|
17
|
+
son ~116 chars: pégalo en el JSON de tu partida guardada.
|
|
18
|
+
- **Determinista** — misma seed, misma evolución. Replays reproducibles.
|
|
19
|
+
|
|
20
|
+
## Instalar
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
pip install instinto # o copia instinto.py a tu proyecto
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## 60 segundos
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from instinto import Brain, Population
|
|
30
|
+
|
|
31
|
+
# inferencia
|
|
32
|
+
npc = Brain(n_in=4, hidden=[8], n_out=3, out="softmax", seed=42)
|
|
33
|
+
accion = npc.act([dx, dy, vida, peligro], explore=0.05) # 0|1|2
|
|
34
|
+
|
|
35
|
+
# neuroevolución: el fitness ES tu juego
|
|
36
|
+
pop = Population(60, n_in=4, hidden=[8], n_out=3, out="softmax", seed=7)
|
|
37
|
+
for gen in range(100):
|
|
38
|
+
for brain in pop:
|
|
39
|
+
brain.fitness = jugar_partida(brain) # tu función
|
|
40
|
+
stats = pop.evolve() # {'gen','best','mean','sigma'}
|
|
41
|
+
mejor = pop.best
|
|
42
|
+
|
|
43
|
+
# imitación: aprende del jugador
|
|
44
|
+
datos = [(estado, accion_del_jugador), ...] # índice de clase si softmax
|
|
45
|
+
npc.learn(datos, epochs=300, lr=0.5)
|
|
46
|
+
|
|
47
|
+
# producción
|
|
48
|
+
mejor.compile() # JIT (se invalida solo al mutar)
|
|
49
|
+
blob = mejor.save() # str de una línea
|
|
50
|
+
npc2 = Brain.load(blob)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Demo
|
|
54
|
+
|
|
55
|
+
```
|
|
56
|
+
python demo_caza.py # agentes evolucionan a cazar comida, render ASCII
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## API
|
|
60
|
+
|
|
61
|
+
| | |
|
|
62
|
+
|---|---|
|
|
63
|
+
| `Brain(n_in, hidden, n_out, act, out, seed)` | acts: `tanh sigmoid relu linear` (+`softmax` en salida) |
|
|
64
|
+
| `.think(x) -> list` / `.act(x, explore) -> int` | inferencia / argmax con ε-greedy |
|
|
65
|
+
| `.learn(samples, epochs, lr, momentum, batch, reset)` | backprop; devuelve loss (½·MSE o CE) |
|
|
66
|
+
| `.mutate(rate, power)` / `.cross(other)` / `.clone()` | operadores evolutivos |
|
|
67
|
+
| `.compile()` / `.save(compact)` / `Brain.load(s)` | JIT / persistencia |
|
|
68
|
+
| `Population(size, ..., elite, tournament, mut_rate, sigma, noisy_fitness)` | iterable de Brains |
|
|
69
|
+
| `.evolve() -> stats` / `.best` | siguiente generación / hall of fame |
|
|
70
|
+
|
|
71
|
+
Sin numpy. Sin configs. Sin clases que heredar. Python ≥ 3.8.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: instinto
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Red neuronal zero-deps para videojuegos: neuroevolucion, imitacion, JIT por codegen y save de una linea.
|
|
5
|
+
Author: esraderey
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/ElEscribanoSilente/instinto
|
|
8
|
+
Keywords: neural-network,neuroevolution,gamedev,zero-dependencies,genetic-algorithm
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Topic :: Games/Entertainment
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
13
|
+
Requires-Python: >=3.8
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# instinto
|
|
19
|
+
|
|
20
|
+
[](https://github.com/ElEscribanoSilente/instinto/actions/workflows/ci.yml)
|
|
21
|
+
[](https://pypi.org/project/instinto/)
|
|
22
|
+
[](https://pypi.org/project/instinto/)
|
|
23
|
+
[](LICENSE)
|
|
24
|
+
|
|
25
|
+
Red neuronal **zero-deps** para videojuegos. Un archivo, solo stdlib.
|
|
26
|
+
|
|
27
|
+
- **`Brain`** — MLP denso con pesos planos. `think()` / `act()`.
|
|
28
|
+
- **Neuroevolución** — `Population` con elitismo, torneo y **sigma autoadaptativo**
|
|
29
|
+
(regla 1/5 de Rechenberg): explora fuerte al inicio, refina solo al final.
|
|
30
|
+
- **Imitación** — `learn()` con backprop (SGD + momentum). Graba al jugador, entrena al NPC.
|
|
31
|
+
- **JIT por codegen** — `compile()` genera el forward desenrollado vía `exec`:
|
|
32
|
+
**3–6× más rápido**, ~120k inferencias/seg en CPython puro.
|
|
33
|
+
- **Save de una línea** — `save()` → float16 + zlib + base85. Un cerebro 2-6-2
|
|
34
|
+
son ~116 chars: pégalo en el JSON de tu partida guardada.
|
|
35
|
+
- **Determinista** — misma seed, misma evolución. Replays reproducibles.
|
|
36
|
+
|
|
37
|
+
## Instalar
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
pip install instinto # o copia instinto.py a tu proyecto
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## 60 segundos
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from instinto import Brain, Population
|
|
47
|
+
|
|
48
|
+
# inferencia
|
|
49
|
+
npc = Brain(n_in=4, hidden=[8], n_out=3, out="softmax", seed=42)
|
|
50
|
+
accion = npc.act([dx, dy, vida, peligro], explore=0.05) # 0|1|2
|
|
51
|
+
|
|
52
|
+
# neuroevolución: el fitness ES tu juego
|
|
53
|
+
pop = Population(60, n_in=4, hidden=[8], n_out=3, out="softmax", seed=7)
|
|
54
|
+
for gen in range(100):
|
|
55
|
+
for brain in pop:
|
|
56
|
+
brain.fitness = jugar_partida(brain) # tu función
|
|
57
|
+
stats = pop.evolve() # {'gen','best','mean','sigma'}
|
|
58
|
+
mejor = pop.best
|
|
59
|
+
|
|
60
|
+
# imitación: aprende del jugador
|
|
61
|
+
datos = [(estado, accion_del_jugador), ...] # índice de clase si softmax
|
|
62
|
+
npc.learn(datos, epochs=300, lr=0.5)
|
|
63
|
+
|
|
64
|
+
# producción
|
|
65
|
+
mejor.compile() # JIT (se invalida solo al mutar)
|
|
66
|
+
blob = mejor.save() # str de una línea
|
|
67
|
+
npc2 = Brain.load(blob)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Demo
|
|
71
|
+
|
|
72
|
+
```
|
|
73
|
+
python demo_caza.py # agentes evolucionan a cazar comida, render ASCII
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## API
|
|
77
|
+
|
|
78
|
+
| | |
|
|
79
|
+
|---|---|
|
|
80
|
+
| `Brain(n_in, hidden, n_out, act, out, seed)` | acts: `tanh sigmoid relu linear` (+`softmax` en salida) |
|
|
81
|
+
| `.think(x) -> list` / `.act(x, explore) -> int` | inferencia / argmax con ε-greedy |
|
|
82
|
+
| `.learn(samples, epochs, lr, momentum, batch, reset)` | backprop; devuelve loss (½·MSE o CE) |
|
|
83
|
+
| `.mutate(rate, power)` / `.cross(other)` / `.clone()` | operadores evolutivos |
|
|
84
|
+
| `.compile()` / `.save(compact)` / `Brain.load(s)` | JIT / persistencia |
|
|
85
|
+
| `Population(size, ..., elite, tournament, mut_rate, sigma, noisy_fitness)` | iterable de Brains |
|
|
86
|
+
| `.evolve() -> stats` / `.best` | siguiente generación / hall of fame |
|
|
87
|
+
|
|
88
|
+
Sin numpy. Sin configs. Sin clases que heredar. Python ≥ 3.8.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
instinto
|
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
"""instinto — red neuronal zero-deps para videojuegos.
|
|
2
|
+
|
|
3
|
+
MLP denso con pesos planos. Tres vías de entrenamiento: backprop (imitar),
|
|
4
|
+
neuroevolución (Population, sigma adaptativo regla 1/5) y mutación manual.
|
|
5
|
+
JIT por codegen (compile), serialización de una línea (save/load).
|
|
6
|
+
Solo stdlib. Determinista por seed.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import math
|
|
12
|
+
import random
|
|
13
|
+
import struct
|
|
14
|
+
import zlib
|
|
15
|
+
from array import array
|
|
16
|
+
|
|
17
|
+
__version__ = "0.2.0"
|
|
18
|
+
__all__ = ["Brain", "Population"]
|
|
19
|
+
|
|
20
|
+
_F16_MAX = 65504.0
|
|
21
|
+
_HIDDEN_ACTS = ("tanh", "sigmoid", "relu", "linear")
|
|
22
|
+
_OUT_ACTS = _HIDDEN_ACTS + ("softmax",)
|
|
23
|
+
_MAGIC = "in1"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _sig(x: float) -> float:
|
|
27
|
+
if x >= 0.0:
|
|
28
|
+
z = math.exp(-x)
|
|
29
|
+
return 1.0 / (1.0 + z)
|
|
30
|
+
z = math.exp(x)
|
|
31
|
+
return z / (1.0 + z)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _apply(name: str, v: list) -> list:
|
|
35
|
+
if name == "tanh":
|
|
36
|
+
return [math.tanh(x) for x in v]
|
|
37
|
+
if name == "relu":
|
|
38
|
+
return [x if x > 0.0 else 0.0 for x in v]
|
|
39
|
+
if name == "sigmoid":
|
|
40
|
+
return [_sig(x) for x in v]
|
|
41
|
+
if name == "linear":
|
|
42
|
+
return v
|
|
43
|
+
# softmax estable
|
|
44
|
+
m = max(v)
|
|
45
|
+
e = [math.exp(x - m) for x in v]
|
|
46
|
+
s = sum(e)
|
|
47
|
+
return [x / s for x in e]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _dact(name: str, y: float) -> float:
|
|
51
|
+
"""Derivada en función de la salida y."""
|
|
52
|
+
if name == "tanh":
|
|
53
|
+
return 1.0 - y * y
|
|
54
|
+
if name == "sigmoid":
|
|
55
|
+
return y * (1.0 - y)
|
|
56
|
+
if name == "relu":
|
|
57
|
+
return 1.0 if y > 0.0 else 0.0
|
|
58
|
+
return 1.0 # linear
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Brain:
|
|
62
|
+
"""MLP denso. arch=[n_in, *hidden, n_out], pesos planos por capa.
|
|
63
|
+
|
|
64
|
+
W[k][j*n_in + i]: peso entrada i → neurona j de la capa k.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
__slots__ = ("arch", "acts", "W", "B", "fitness", "_rng", "_fwd",
|
|
68
|
+
"_vW", "_vB", "_pfit")
|
|
69
|
+
|
|
70
|
+
def __init__(self, n_in: int, hidden=(), n_out: int = 1,
|
|
71
|
+
act: str = "tanh", out: str = "tanh", seed=None):
|
|
72
|
+
if n_in < 1 or n_out < 1 or any(h < 1 for h in hidden):
|
|
73
|
+
raise ValueError("dimensiones >= 1")
|
|
74
|
+
if act not in _HIDDEN_ACTS:
|
|
75
|
+
raise ValueError(f"act oculta debe ser una de {_HIDDEN_ACTS}")
|
|
76
|
+
if out not in _OUT_ACTS:
|
|
77
|
+
raise ValueError(f"act de salida debe ser una de {_OUT_ACTS}")
|
|
78
|
+
self.arch = [n_in, *hidden, n_out]
|
|
79
|
+
self.acts = [act] * (len(self.arch) - 2) + [out]
|
|
80
|
+
self._rng = random.Random(seed)
|
|
81
|
+
self.W, self.B = [], []
|
|
82
|
+
for k in range(len(self.arch) - 1):
|
|
83
|
+
fi, fo = self.arch[k], self.arch[k + 1]
|
|
84
|
+
lim = math.sqrt(6.0 / (fi + fo)) # Xavier
|
|
85
|
+
self.W.append(array("d", (self._rng.uniform(-lim, lim)
|
|
86
|
+
for _ in range(fi * fo))))
|
|
87
|
+
self.B.append(array("d", (0.0 for _ in range(fo))))
|
|
88
|
+
self.fitness = None
|
|
89
|
+
self._pfit = None # fitness del mejor padre (regla 1/5)
|
|
90
|
+
self._fwd = None # forward JIT
|
|
91
|
+
self._vW = self._vB = None # velocidades momentum
|
|
92
|
+
|
|
93
|
+
# ------------------------------------------------------------- inferencia
|
|
94
|
+
def think(self, x) -> list:
|
|
95
|
+
"""Forward. x: secuencia de floats de tamaño arch[0]."""
|
|
96
|
+
f = self._fwd
|
|
97
|
+
if f is not None:
|
|
98
|
+
return f(x)
|
|
99
|
+
a = x
|
|
100
|
+
arch, W, B, acts = self.arch, self.W, self.B, self.acts
|
|
101
|
+
for k in range(len(W)):
|
|
102
|
+
Wk, Bk, n_in = W[k], B[k], arch[k]
|
|
103
|
+
pre = []
|
|
104
|
+
for j in range(arch[k + 1]):
|
|
105
|
+
s = Bk[j]
|
|
106
|
+
base = j * n_in
|
|
107
|
+
for i in range(n_in):
|
|
108
|
+
s += Wk[base + i] * a[i]
|
|
109
|
+
pre.append(s)
|
|
110
|
+
a = _apply(acts[k], pre)
|
|
111
|
+
return a
|
|
112
|
+
|
|
113
|
+
def act(self, x, explore: float = 0.0) -> int:
|
|
114
|
+
"""Índice de acción (argmax). explore: prob. de acción aleatoria."""
|
|
115
|
+
if explore > 0.0 and self._rng.random() < explore:
|
|
116
|
+
return self._rng.randrange(self.arch[-1])
|
|
117
|
+
y = self.think(x)
|
|
118
|
+
return max(range(len(y)), key=y.__getitem__)
|
|
119
|
+
|
|
120
|
+
# ------------------------------------------------------------ aprendizaje
|
|
121
|
+
def learn(self, samples, epochs: int = 500, lr: float = 0.1,
|
|
122
|
+
momentum: float = 0.0, batch: int | None = None,
|
|
123
|
+
shuffle: bool = True, reset: bool = True) -> float:
|
|
124
|
+
"""Backprop SGD+momentum. samples: [(x, target)]. Devuelve loss final.
|
|
125
|
+
|
|
126
|
+
target: lista de floats; escalar si n_out==1; índice de clase si softmax.
|
|
127
|
+
Loss MSE: 1/2 * sum((y-t)^2) por muestra (el 1/2 hace que el gradiente
|
|
128
|
+
sea (y-t)*act'); cross-entropy si la salida es softmax.
|
|
129
|
+
reset: si True (def.) cada llamada arranca con momentum a cero; ponlo en
|
|
130
|
+
False para continuar entrenando conservando el estado del optimizador.
|
|
131
|
+
"""
|
|
132
|
+
self._fwd = None
|
|
133
|
+
soft = self.acts[-1] == "softmax"
|
|
134
|
+
n_out = self.arch[-1]
|
|
135
|
+
data = []
|
|
136
|
+
for x, t in samples:
|
|
137
|
+
if soft and isinstance(t, int):
|
|
138
|
+
oh = [0.0] * n_out
|
|
139
|
+
oh[t] = 1.0
|
|
140
|
+
t = oh
|
|
141
|
+
elif not isinstance(t, (list, tuple)):
|
|
142
|
+
t = [float(t)]
|
|
143
|
+
data.append((list(map(float, x)), list(map(float, t))))
|
|
144
|
+
if reset or self._vW is None:
|
|
145
|
+
self._vW = [array("d", bytes(8 * len(w))) for w in self.W]
|
|
146
|
+
self._vB = [array("d", bytes(8 * len(b))) for b in self.B]
|
|
147
|
+
bsz = len(data) if not batch else batch
|
|
148
|
+
L = len(self.W)
|
|
149
|
+
loss = 0.0
|
|
150
|
+
for _ in range(epochs):
|
|
151
|
+
if shuffle:
|
|
152
|
+
self._rng.shuffle(data)
|
|
153
|
+
loss = 0.0
|
|
154
|
+
for off in range(0, len(data), bsz):
|
|
155
|
+
chunk = data[off:off + bsz]
|
|
156
|
+
gW = [array("d", bytes(8 * len(w))) for w in self.W]
|
|
157
|
+
gB = [array("d", bytes(8 * len(b))) for b in self.B]
|
|
158
|
+
for x, t in chunk:
|
|
159
|
+
A = self._trace(x)
|
|
160
|
+
y = A[-1]
|
|
161
|
+
if soft:
|
|
162
|
+
loss += -sum(tj * math.log(yj + 1e-12)
|
|
163
|
+
for tj, yj in zip(t, y))
|
|
164
|
+
delta = [yj - tj for yj, tj in zip(y, t)]
|
|
165
|
+
else:
|
|
166
|
+
loss += 0.5 * sum((yj - tj) ** 2 for yj, tj in zip(y, t))
|
|
167
|
+
an = self.acts[-1]
|
|
168
|
+
delta = [(yj - tj) * _dact(an, yj)
|
|
169
|
+
for yj, tj in zip(y, t)]
|
|
170
|
+
for k in range(L - 1, -1, -1):
|
|
171
|
+
prev, n_in = A[k], self.arch[k]
|
|
172
|
+
Gk, Bk = gW[k], gB[k]
|
|
173
|
+
for j, dj in enumerate(delta):
|
|
174
|
+
base = j * n_in
|
|
175
|
+
for i in range(n_in):
|
|
176
|
+
Gk[base + i] += dj * prev[i]
|
|
177
|
+
Bk[j] += dj
|
|
178
|
+
if k:
|
|
179
|
+
Wk, an = self.W[k], self.acts[k - 1]
|
|
180
|
+
delta = [
|
|
181
|
+
_dact(an, prev[i])
|
|
182
|
+
* sum(Wk[j * n_in + i] * delta[j]
|
|
183
|
+
for j in range(len(delta)))
|
|
184
|
+
for i in range(n_in)
|
|
185
|
+
]
|
|
186
|
+
# fin muestra
|
|
187
|
+
inv = lr / len(chunk)
|
|
188
|
+
for k in range(L):
|
|
189
|
+
vW, vB, Wk, Bk = self._vW[k], self._vB[k], self.W[k], self.B[k]
|
|
190
|
+
Gk, Gb = gW[k], gB[k]
|
|
191
|
+
for i in range(len(Wk)):
|
|
192
|
+
vW[i] = momentum * vW[i] - inv * Gk[i]
|
|
193
|
+
Wk[i] += vW[i]
|
|
194
|
+
for j in range(len(Bk)):
|
|
195
|
+
vB[j] = momentum * vB[j] - inv * Gb[j]
|
|
196
|
+
Bk[j] += vB[j]
|
|
197
|
+
loss /= len(data)
|
|
198
|
+
return loss
|
|
199
|
+
|
|
200
|
+
def _trace(self, x) -> list:
|
|
201
|
+
"""Forward guardando activaciones de cada capa (para backprop)."""
|
|
202
|
+
A = [x]
|
|
203
|
+
a = x
|
|
204
|
+
for k in range(len(self.W)):
|
|
205
|
+
Wk, Bk, n_in = self.W[k], self.B[k], self.arch[k]
|
|
206
|
+
pre = []
|
|
207
|
+
for j in range(self.arch[k + 1]):
|
|
208
|
+
s = Bk[j]
|
|
209
|
+
base = j * n_in
|
|
210
|
+
for i in range(n_in):
|
|
211
|
+
s += Wk[base + i] * a[i]
|
|
212
|
+
pre.append(s)
|
|
213
|
+
a = _apply(self.acts[k], pre)
|
|
214
|
+
A.append(a)
|
|
215
|
+
return A
|
|
216
|
+
|
|
217
|
+
# -------------------------------------------------------------- evolución
|
|
218
|
+
def mutate(self, rate: float = 0.1, power: float = 0.5, rng=None) -> "Brain":
|
|
219
|
+
"""Perturbación gaussiana: cada peso con prob. rate suma N(0, power)."""
|
|
220
|
+
r = rng or self._rng
|
|
221
|
+
self._fwd = None
|
|
222
|
+
for arr in (*self.W, *self.B):
|
|
223
|
+
for i in range(len(arr)):
|
|
224
|
+
if r.random() < rate:
|
|
225
|
+
arr[i] += r.gauss(0.0, power)
|
|
226
|
+
return self
|
|
227
|
+
|
|
228
|
+
def cross(self, other: "Brain", rng=None) -> "Brain":
|
|
229
|
+
"""Cruce uniforme gen a gen. Requiere arquitecturas idénticas."""
|
|
230
|
+
if self.arch != other.arch or self.acts != other.acts:
|
|
231
|
+
raise ValueError("arquitecturas incompatibles para cross")
|
|
232
|
+
r = rng or self._rng
|
|
233
|
+
child = self.clone()
|
|
234
|
+
child.fitness = child._pfit = None
|
|
235
|
+
for ca, oa in zip((*child.W, *child.B), (*other.W, *other.B)):
|
|
236
|
+
for i in range(len(ca)):
|
|
237
|
+
if r.random() < 0.5:
|
|
238
|
+
ca[i] = oa[i]
|
|
239
|
+
return child
|
|
240
|
+
|
|
241
|
+
def clone(self) -> "Brain":
|
|
242
|
+
"""Copia profunda (réplica exacta de pesos y estado RNG)."""
|
|
243
|
+
c = object.__new__(Brain)
|
|
244
|
+
c.arch, c.acts = list(self.arch), list(self.acts)
|
|
245
|
+
c.W = [array("d", w) for w in self.W]
|
|
246
|
+
c.B = [array("d", b) for b in self.B]
|
|
247
|
+
c.fitness, c._pfit = self.fitness, self._pfit
|
|
248
|
+
c._fwd = None
|
|
249
|
+
c._vW = c._vB = None
|
|
250
|
+
c._rng = random.Random()
|
|
251
|
+
c._rng.setstate(self._rng.getstate())
|
|
252
|
+
return c
|
|
253
|
+
|
|
254
|
+
def reseed(self, seed) -> "Brain":
|
|
255
|
+
self._rng.seed(seed)
|
|
256
|
+
return self
|
|
257
|
+
|
|
258
|
+
# ------------------------------------------------------------------- JIT
|
|
259
|
+
def compile(self, max_params: int = 8000) -> "Brain":
|
|
260
|
+
"""Genera forward desenrollado vía exec (3-6x más rápido). Se
|
|
261
|
+
invalida solo tras mutate/learn/load; recompilar si hace falta."""
|
|
262
|
+
if self.n_params > max_params:
|
|
263
|
+
raise ValueError(f"demasiados parámetros para JIT (> {max_params})")
|
|
264
|
+
if not all(math.isfinite(v) for arr in (*self.W, *self.B) for v in arr):
|
|
265
|
+
raise ValueError("pesos no finitos (inf/nan): el entrenamiento "
|
|
266
|
+
"divergió, no se puede compilar")
|
|
267
|
+
src = ["def _f(x):"]
|
|
268
|
+
prev = [f"x[{i}]" for i in range(self.arch[0])]
|
|
269
|
+
tmp = 0
|
|
270
|
+
for k in range(len(self.W)):
|
|
271
|
+
Wk, Bk, n_in, act = self.W[k], self.B[k], self.arch[k], self.acts[k]
|
|
272
|
+
exprs = []
|
|
273
|
+
for j in range(self.arch[k + 1]):
|
|
274
|
+
base = j * n_in
|
|
275
|
+
e = repr(Bk[j]) + "".join(
|
|
276
|
+
f" + {Wk[base + i]!r}*{prev[i]}" for i in range(n_in))
|
|
277
|
+
exprs.append(e)
|
|
278
|
+
cur = []
|
|
279
|
+
if act == "softmax":
|
|
280
|
+
ts = []
|
|
281
|
+
for e in exprs:
|
|
282
|
+
t = f"t{tmp}"; tmp += 1
|
|
283
|
+
src.append(f" {t} = {e}")
|
|
284
|
+
ts.append(t)
|
|
285
|
+
src.append(f" m = max({', '.join(ts)})")
|
|
286
|
+
es = []
|
|
287
|
+
for t in ts:
|
|
288
|
+
src.append(f" e{t} = _exp({t} - m)")
|
|
289
|
+
es.append(f"e{t}")
|
|
290
|
+
src.append(f" s = {' + '.join(es)}")
|
|
291
|
+
cur = [f"{e}/s" for e in es]
|
|
292
|
+
else:
|
|
293
|
+
wrap = {"tanh": "_tanh({})", "sigmoid": "_sig({})",
|
|
294
|
+
"linear": "{}"}.get(act)
|
|
295
|
+
for e in exprs:
|
|
296
|
+
t = f"t{tmp}"; tmp += 1
|
|
297
|
+
if act == "relu":
|
|
298
|
+
src.append(f" {t} = {e}")
|
|
299
|
+
src.append(f" {t} = {t} if {t} > 0.0 else 0.0")
|
|
300
|
+
else:
|
|
301
|
+
src.append(f" {t} = {wrap.format(e)}")
|
|
302
|
+
cur.append(t)
|
|
303
|
+
prev = cur
|
|
304
|
+
src.append(f" return [{', '.join(prev)}]")
|
|
305
|
+
ns = {"_tanh": math.tanh, "_exp": math.exp, "_sig": _sig}
|
|
306
|
+
exec("\n".join(src), ns) # noqa: S102 — fuente generada localmente
|
|
307
|
+
self._fwd = ns["_f"]
|
|
308
|
+
return self
|
|
309
|
+
|
|
310
|
+
# ----------------------------------------------------------- persistencia
|
|
311
|
+
def save(self, compact: bool = True) -> str:
|
|
312
|
+
"""Serializa a una línea: 'in1|fmt|arch|acts|blob'. compact=float16."""
|
|
313
|
+
fmt = "e" if compact else "f"
|
|
314
|
+
flat = []
|
|
315
|
+
for k in range(len(self.W)):
|
|
316
|
+
flat.extend(self.W[k])
|
|
317
|
+
flat.extend(self.B[k])
|
|
318
|
+
if compact:
|
|
319
|
+
flat = [max(-_F16_MAX, min(_F16_MAX, v)) for v in flat]
|
|
320
|
+
raw = struct.pack(f"<{len(flat)}{fmt}", *flat)
|
|
321
|
+
blob = base64.b85encode(zlib.compress(raw, 9)).decode("ascii")
|
|
322
|
+
return "|".join((_MAGIC, fmt, ",".join(map(str, self.arch)),
|
|
323
|
+
",".join(self.acts), blob))
|
|
324
|
+
|
|
325
|
+
@classmethod
|
|
326
|
+
def load(cls, data: str) -> "Brain":
|
|
327
|
+
try:
|
|
328
|
+
magic, fmt, arch_s, acts_s, blob = data.strip().split("|", 4)
|
|
329
|
+
if magic != _MAGIC or fmt not in "ef":
|
|
330
|
+
raise ValueError
|
|
331
|
+
arch = [int(v) for v in arch_s.split(",")]
|
|
332
|
+
acts = acts_s.split(",")
|
|
333
|
+
raw = zlib.decompress(base64.b85decode(blob))
|
|
334
|
+
size = struct.calcsize(fmt)
|
|
335
|
+
flat = struct.unpack(f"<{len(raw) // size}{fmt}", raw)
|
|
336
|
+
except (ValueError, zlib.error, struct.error) as e:
|
|
337
|
+
raise ValueError("blob de Brain inválido") from e
|
|
338
|
+
need = sum(arch[k] * arch[k + 1] + arch[k + 1]
|
|
339
|
+
for k in range(len(arch) - 1))
|
|
340
|
+
if len(arch) < 2 or len(flat) != need:
|
|
341
|
+
raise ValueError("blob de Brain inválido: tamaño no coincide")
|
|
342
|
+
b = cls(arch[0], arch[1:-1], arch[-1],
|
|
343
|
+
act=acts[0] if len(acts) > 1 else "tanh", out=acts[-1])
|
|
344
|
+
pos = 0
|
|
345
|
+
for k in range(len(b.W)):
|
|
346
|
+
nw, nb = len(b.W[k]), len(b.B[k])
|
|
347
|
+
b.W[k] = array("d", flat[pos:pos + nw]); pos += nw
|
|
348
|
+
b.B[k] = array("d", flat[pos:pos + nb]); pos += nb
|
|
349
|
+
return b
|
|
350
|
+
|
|
351
|
+
# ------------------------------------------------------------------ varios
|
|
352
|
+
@property
|
|
353
|
+
def n_params(self) -> int:
|
|
354
|
+
return sum(len(w) for w in self.W) + sum(len(b) for b in self.B)
|
|
355
|
+
|
|
356
|
+
def __repr__(self):
|
|
357
|
+
a = "-".join(map(str, self.arch))
|
|
358
|
+
f = f", fit={self.fitness:.4g}" if self.fitness is not None else ""
|
|
359
|
+
return f"Brain({a} {self.acts[0]}/{self.acts[-1]}, {self.n_params}p{f})"
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
class Population:
|
|
363
|
+
"""Neuroevolución: elitismo + torneo + cruce uniforme + mutación gaussiana
|
|
364
|
+
con sigma autoadaptativo (regla 1/5 de Rechenberg).
|
|
365
|
+
|
|
366
|
+
noisy_fitness: si el fitness es ruidoso o no estacionario (p. ej. el entorno
|
|
367
|
+
cambia cada generación), ponlo en True para que `best` siga al campeón de la
|
|
368
|
+
generación actual —re-medido y comparable— en vez de congelar un fitness con
|
|
369
|
+
suerte de una generación pasada (el genoma campeón se conserva igual vía
|
|
370
|
+
elitismo). Con fitness determinista déjalo en False: mejor de todos los tiempos."""
|
|
371
|
+
|
|
372
|
+
def __init__(self, size: int, n_in: int, hidden=(), n_out: int = 1,
|
|
373
|
+
act: str = "tanh", out: str = "tanh", seed=None,
|
|
374
|
+
elite: float = 0.1, tournament: int = 3,
|
|
375
|
+
mut_rate: float = 0.15, sigma: float = 0.5,
|
|
376
|
+
noisy_fitness: bool = False):
|
|
377
|
+
if size < 4:
|
|
378
|
+
raise ValueError("size >= 4")
|
|
379
|
+
self._rng = random.Random(seed)
|
|
380
|
+
self.brains = [Brain(n_in, hidden, n_out, act, out,
|
|
381
|
+
seed=self._rng.getrandbits(64))
|
|
382
|
+
for _ in range(size)]
|
|
383
|
+
self.size, self.elite, self.tournament = size, elite, tournament
|
|
384
|
+
self.mut_rate, self.sigma = mut_rate, sigma
|
|
385
|
+
self.noisy_fitness = noisy_fitness
|
|
386
|
+
self.generation = 0
|
|
387
|
+
self.best: Brain | None = None # hall of fame (clon congelado)
|
|
388
|
+
|
|
389
|
+
def __iter__(self):
|
|
390
|
+
return iter(self.brains)
|
|
391
|
+
|
|
392
|
+
def __len__(self):
|
|
393
|
+
return self.size
|
|
394
|
+
|
|
395
|
+
def __getitem__(self, i):
|
|
396
|
+
return self.brains[i]
|
|
397
|
+
|
|
398
|
+
def evolve(self) -> dict:
|
|
399
|
+
"""Consume los .fitness asignados y produce la siguiente generación.
|
|
400
|
+
|
|
401
|
+
Devuelve {'gen', 'best', 'mean', 'sigma'}.
|
|
402
|
+
"""
|
|
403
|
+
if any(b.fitness is None for b in self.brains):
|
|
404
|
+
raise RuntimeError("asigna .fitness a todos los Brain antes de evolve()")
|
|
405
|
+
# regla 1/5: ajustar sigma según éxito de los hijos de la gen anterior
|
|
406
|
+
scored = [(b.fitness, b._pfit) for b in self.brains if b._pfit is not None]
|
|
407
|
+
if scored:
|
|
408
|
+
ok = sum(f > p for f, p in scored) / len(scored)
|
|
409
|
+
self.sigma *= 1.22 if ok > 0.2 else 1 / 1.22
|
|
410
|
+
self.sigma = min(2.0, max(1e-3, self.sigma))
|
|
411
|
+
ranked = sorted(self.brains, key=lambda b: b.fitness, reverse=True)
|
|
412
|
+
# hall of fame: con fitness estacionario, el mejor de todos los tiempos;
|
|
413
|
+
# con noisy_fitness, el top de la gen actual (re-medido, comparable).
|
|
414
|
+
if self.noisy_fitness or self.best is None \
|
|
415
|
+
or ranked[0].fitness > self.best.fitness:
|
|
416
|
+
self.best = ranked[0].clone()
|
|
417
|
+
rng = self._rng
|
|
418
|
+
n_elite = max(1, int(self.elite * self.size))
|
|
419
|
+
nxt = []
|
|
420
|
+
for b in ranked[:n_elite]:
|
|
421
|
+
e = b.clone()
|
|
422
|
+
e.fitness = e._pfit = None
|
|
423
|
+
e.reseed(rng.getrandbits(64))
|
|
424
|
+
nxt.append(e)
|
|
425
|
+
while len(nxt) < self.size:
|
|
426
|
+
p1 = max(rng.sample(ranked, self.tournament),
|
|
427
|
+
key=lambda b: b.fitness)
|
|
428
|
+
p2 = max(rng.sample(ranked, self.tournament),
|
|
429
|
+
key=lambda b: b.fitness)
|
|
430
|
+
child = p1.cross(p2, rng=rng).mutate(self.mut_rate, self.sigma,
|
|
431
|
+
rng=rng)
|
|
432
|
+
child._pfit = max(p1.fitness, p2.fitness)
|
|
433
|
+
child.reseed(rng.getrandbits(64))
|
|
434
|
+
nxt.append(child)
|
|
435
|
+
stats = {"gen": self.generation,
|
|
436
|
+
"best": ranked[0].fitness,
|
|
437
|
+
"mean": sum(b.fitness for b in self.brains) / self.size,
|
|
438
|
+
"sigma": self.sigma}
|
|
439
|
+
self.brains = nxt
|
|
440
|
+
self.generation += 1
|
|
441
|
+
return stats
|
|
442
|
+
|
|
443
|
+
def __repr__(self):
|
|
444
|
+
hof = f", best={self.best.fitness:.4g}" if self.best else ""
|
|
445
|
+
return f"Population({self.size} brains, gen {self.generation}{hof})"
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "instinto"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Red neuronal zero-deps para videojuegos: neuroevolucion, imitacion, JIT por codegen y save de una linea."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "esraderey" }]
|
|
13
|
+
keywords = ["neural-network", "neuroevolution", "gamedev", "zero-dependencies", "genetic-algorithm"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Topic :: Games/Entertainment",
|
|
18
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://github.com/ElEscribanoSilente/instinto"
|
|
23
|
+
|
|
24
|
+
[tool.setuptools]
|
|
25
|
+
py-modules = ["instinto"]
|
instinto-0.2.0/setup.cfg
ADDED