Neuralink-Ssammy 0.1.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.
- neuralink_ssammy-0.1.0/Neuralink/__init__.py +725 -0
- neuralink_ssammy-0.1.0/Neuralink/d_relu_aarch64.s +23 -0
- neuralink_ssammy-0.1.0/Neuralink/d_relu_armv7.s +44 -0
- neuralink_ssammy-0.1.0/Neuralink/d_relu_i386.s +36 -0
- neuralink_ssammy-0.1.0/Neuralink/d_relu_x86_64.s +35 -0
- neuralink_ssammy-0.1.0/Neuralink/libmotor.so +0 -0
- neuralink_ssammy-0.1.0/Neuralink/motor.c +97 -0
- neuralink_ssammy-0.1.0/Neuralink/motor_o0.s +413 -0
- neuralink_ssammy-0.1.0/Neuralink/motor_o3.s +328 -0
- neuralink_ssammy-0.1.0/Neuralink/patch_red.py +77 -0
- neuralink_ssammy-0.1.0/Neuralink/servidor.py +640 -0
- neuralink_ssammy-0.1.0/Neuralink_Ssammy.egg-info/PKG-INFO +7 -0
- neuralink_ssammy-0.1.0/Neuralink_Ssammy.egg-info/SOURCES.txt +18 -0
- neuralink_ssammy-0.1.0/Neuralink_Ssammy.egg-info/dependency_links.txt +1 -0
- neuralink_ssammy-0.1.0/Neuralink_Ssammy.egg-info/requires.txt +1 -0
- neuralink_ssammy-0.1.0/Neuralink_Ssammy.egg-info/top_level.txt +1 -0
- neuralink_ssammy-0.1.0/PKG-INFO +7 -0
- neuralink_ssammy-0.1.0/README.md +0 -0
- neuralink_ssammy-0.1.0/pyproject.toml +18 -0
- neuralink_ssammy-0.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,725 @@
|
|
|
1
|
+
import ctypes
|
|
2
|
+
import platform
|
|
3
|
+
import subprocess
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
# ==========================================
|
|
8
|
+
# 0. PUENTE HACIA MOTOR EN C (AUTO-ARQUITECTURA)
|
|
9
|
+
# ==========================================
|
|
10
|
+
|
|
11
|
+
_BASE_DIR = Path(__file__).resolve().parent
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def detectar_arquitectura() -> str:
|
|
15
|
+
maquina = platform.machine().lower()
|
|
16
|
+
if maquina in ("aarch64", "arm64"):
|
|
17
|
+
return "aarch64"
|
|
18
|
+
if maquina.startswith("armv7") or maquina in ("arm", "armhf"):
|
|
19
|
+
return "armv7"
|
|
20
|
+
if maquina in ("x86_64", "amd64"):
|
|
21
|
+
return "x86_64"
|
|
22
|
+
if maquina in ("i386", "i686", "x86"):
|
|
23
|
+
return "i386"
|
|
24
|
+
return maquina
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _compilar_motor(arch: str, salida_so: Path) -> bool:
|
|
28
|
+
c_file = _BASE_DIR / "motor.c"
|
|
29
|
+
asm_file = _BASE_DIR / f"d_relu_{arch}.s"
|
|
30
|
+
if not c_file.exists():
|
|
31
|
+
return False
|
|
32
|
+
|
|
33
|
+
fuentes = [str(c_file)]
|
|
34
|
+
if asm_file.exists():
|
|
35
|
+
fuentes.append(str(asm_file))
|
|
36
|
+
|
|
37
|
+
for compilador in ("cc", "gcc", "clang"):
|
|
38
|
+
try:
|
|
39
|
+
subprocess.run(
|
|
40
|
+
[compilador, "-O3", "-fPIC", "-shared", *fuentes, "-o", str(salida_so)],
|
|
41
|
+
check=True,
|
|
42
|
+
stdout=subprocess.DEVNULL,
|
|
43
|
+
stderr=subprocess.DEVNULL,
|
|
44
|
+
)
|
|
45
|
+
if salida_so.exists():
|
|
46
|
+
return True
|
|
47
|
+
except (OSError, subprocess.CalledProcessError):
|
|
48
|
+
continue
|
|
49
|
+
return False
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _cargar_libmotor():
|
|
53
|
+
arch = detectar_arquitectura()
|
|
54
|
+
so_arch = _BASE_DIR / f"libmotor_{arch}.so"
|
|
55
|
+
so_default = _BASE_DIR / "libmotor.so"
|
|
56
|
+
|
|
57
|
+
for candidato in (so_arch, so_default):
|
|
58
|
+
if candidato.exists():
|
|
59
|
+
try:
|
|
60
|
+
return ctypes.CDLL(str(candidato)), arch, candidato
|
|
61
|
+
except OSError:
|
|
62
|
+
pass
|
|
63
|
+
|
|
64
|
+
if _compilar_motor(arch, so_arch):
|
|
65
|
+
return ctypes.CDLL(str(so_arch)), arch, so_arch
|
|
66
|
+
|
|
67
|
+
raise RuntimeError(
|
|
68
|
+
f"No se pudo cargar ni compilar libmotor para la arquitectura '{arch}'. "
|
|
69
|
+
f"Verifica motor.c / d_relu_{arch}.s o un compilador (cc/gcc/clang)."
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
lib, ARQUITECTURA_ACTUAL, _LIB_PATH = _cargar_libmotor()
|
|
74
|
+
|
|
75
|
+
VOID_PTR = ctypes.c_void_p
|
|
76
|
+
|
|
77
|
+
_FUNCIONES_1D = [
|
|
78
|
+
"c_sig",
|
|
79
|
+
"c_d_sig",
|
|
80
|
+
"c_tanh",
|
|
81
|
+
"c_d_tanh",
|
|
82
|
+
"c_relu",
|
|
83
|
+
"c_d_relu",
|
|
84
|
+
"asm_d_relu",
|
|
85
|
+
]
|
|
86
|
+
|
|
87
|
+
_FN_MAP = {}
|
|
88
|
+
for _nombre in _FUNCIONES_1D:
|
|
89
|
+
_fn = getattr(lib, _nombre)
|
|
90
|
+
_fn.argtypes = [VOID_PTR, VOID_PTR, ctypes.c_size_t]
|
|
91
|
+
_fn.restype = None
|
|
92
|
+
_FN_MAP[_nombre] = _fn
|
|
93
|
+
|
|
94
|
+
_np_ascontiguousarray = np.ascontiguousarray
|
|
95
|
+
_np_empty = np.empty
|
|
96
|
+
_np_empty_like = np.empty_like
|
|
97
|
+
_np_zeros_like = np.zeros_like
|
|
98
|
+
_np_matmul = np.matmul
|
|
99
|
+
_np_add = np.add
|
|
100
|
+
_np_subtract = np.subtract
|
|
101
|
+
_np_multiply = np.multiply
|
|
102
|
+
_np_sum = np.sum
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _llamar_c(nombre_c, x, out=None):
|
|
106
|
+
if isinstance(x, np.ndarray) and x.dtype == np.float64 and x.flags["C_CONTIGUOUS"]:
|
|
107
|
+
arr = x
|
|
108
|
+
else:
|
|
109
|
+
arr = _np_ascontiguousarray(x, dtype=np.float64)
|
|
110
|
+
|
|
111
|
+
if out is None or out.shape != arr.shape or not out.flags["C_CONTIGUOUS"]:
|
|
112
|
+
out = _np_empty_like(arr, dtype=np.float64)
|
|
113
|
+
|
|
114
|
+
_FN_MAP[nombre_c](
|
|
115
|
+
VOID_PTR(arr.ctypes.data),
|
|
116
|
+
VOID_PTR(out.ctypes.data),
|
|
117
|
+
arr.size,
|
|
118
|
+
)
|
|
119
|
+
return out
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def sig_c(x, out=None):
|
|
123
|
+
return _llamar_c("c_sig", x, out)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def d_sig_c(x, out=None):
|
|
127
|
+
return _llamar_c("c_d_sig", x, out)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def tanh_c(x, out=None):
|
|
131
|
+
return _llamar_c("c_tanh", x, out)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def d_tanh_c(x, out=None):
|
|
135
|
+
return _llamar_c("c_d_tanh", x, out)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def relu_c(x, out=None):
|
|
139
|
+
return _llamar_c("c_relu", x, out)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def d_relu_c(x, out=None):
|
|
143
|
+
return _llamar_c("c_d_relu", x, out)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def d_relu_asm(x, out=None):
|
|
147
|
+
return _llamar_c("asm_d_relu", x, out)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
# ==========================================
|
|
151
|
+
# 1. FUNCIONES DE ACTIVACIÓN Y SUS DERIVADAS (FALLBACK / LINEAL)
|
|
152
|
+
# ==========================================
|
|
153
|
+
|
|
154
|
+
def sig(x, out=None):
|
|
155
|
+
x_clip = np.clip(x, -500.0, 500.0)
|
|
156
|
+
with np.errstate(over="ignore", invalid="ignore"):
|
|
157
|
+
res = 1.0 / (1.0 + np.exp(-x_clip))
|
|
158
|
+
if out is not None and out.shape == res.shape:
|
|
159
|
+
out[...] = res
|
|
160
|
+
return out
|
|
161
|
+
return res
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def d_sig(x, out=None):
|
|
165
|
+
s = sig(x)
|
|
166
|
+
res = s * (1.0 - s)
|
|
167
|
+
if out is not None and out.shape == res.shape:
|
|
168
|
+
out[...] = res
|
|
169
|
+
return out
|
|
170
|
+
return res
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def tanh(x, out=None):
|
|
174
|
+
x_clip = np.clip(x, -20.0, 20.0)
|
|
175
|
+
with np.errstate(over="ignore", invalid="ignore"):
|
|
176
|
+
res = np.tanh(x_clip)
|
|
177
|
+
if out is not None and out.shape == res.shape:
|
|
178
|
+
out[...] = res
|
|
179
|
+
return out
|
|
180
|
+
return res
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def d_tanh(x, out=None):
|
|
184
|
+
t = tanh(x)
|
|
185
|
+
res = 1.0 - (t * t)
|
|
186
|
+
if out is not None and out.shape == res.shape:
|
|
187
|
+
out[...] = res
|
|
188
|
+
return out
|
|
189
|
+
return res
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def relu(x, out=None):
|
|
193
|
+
res = np.maximum(0.0, x)
|
|
194
|
+
if out is not None and out.shape == res.shape:
|
|
195
|
+
out[...] = res
|
|
196
|
+
return out
|
|
197
|
+
return res
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def d_relu(x, out=None):
|
|
201
|
+
res = (np.asarray(x) > 0.0).astype(np.float64)
|
|
202
|
+
if out is not None and out.shape == res.shape:
|
|
203
|
+
out[...] = res
|
|
204
|
+
return out
|
|
205
|
+
return res
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def lineal(x, out=None):
|
|
209
|
+
arr = np.asarray(x, dtype=np.float64)
|
|
210
|
+
if out is not None and out.shape == arr.shape:
|
|
211
|
+
out[...] = arr
|
|
212
|
+
return out
|
|
213
|
+
return arr
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def d_lineal(x, out=None):
|
|
217
|
+
arr = np.asarray(x, dtype=np.float64)
|
|
218
|
+
if out is not None and out.shape == arr.shape:
|
|
219
|
+
out.fill(1.0)
|
|
220
|
+
return out
|
|
221
|
+
return np.ones_like(arr, dtype=np.float64)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
ACTIVACIONES = {
|
|
225
|
+
"sig": (sig_c, d_sig_c),
|
|
226
|
+
"tanh": (tanh_c, d_tanh_c),
|
|
227
|
+
"relu": (relu_c, d_relu_asm),
|
|
228
|
+
"lineal": (lineal, d_lineal),
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
# ==========================================
|
|
233
|
+
# 2. CLASE CAPA (C/ASM + ADAM/ADAMW + MEMORIA)
|
|
234
|
+
# ==========================================
|
|
235
|
+
|
|
236
|
+
class Capa:
|
|
237
|
+
def __init__(self, entradas, salidas, activacion="sig", peso_l2=0.0, clip_grad=None):
|
|
238
|
+
if activacion not in ACTIVACIONES:
|
|
239
|
+
raise ValueError(f"Activación '{activacion}' no válida. Usa: {list(ACTIVACIONES.keys())}")
|
|
240
|
+
|
|
241
|
+
if activacion == "relu":
|
|
242
|
+
escala = np.sqrt(2.0 / max(entradas, 1))
|
|
243
|
+
elif activacion == "tanh":
|
|
244
|
+
escala = np.sqrt(1.0 / max(entradas, 1))
|
|
245
|
+
else:
|
|
246
|
+
escala = 1.0
|
|
247
|
+
|
|
248
|
+
self.entradas = entradas
|
|
249
|
+
self.salidas = salidas
|
|
250
|
+
self.activacion = activacion
|
|
251
|
+
self.peso_l2 = float(peso_l2)
|
|
252
|
+
self.clip_grad = clip_grad
|
|
253
|
+
|
|
254
|
+
self.w = _np_ascontiguousarray(np.random.randn(entradas, salidas) * escala, dtype=np.float64)
|
|
255
|
+
self.b = np.zeros((1, salidas), dtype=np.float64)
|
|
256
|
+
self.fn, self.d_fn = ACTIVACIONES[activacion]
|
|
257
|
+
|
|
258
|
+
# Estado SGD / Momentum
|
|
259
|
+
self.v_w = _np_zeros_like(self.w)
|
|
260
|
+
self.v_b = _np_zeros_like(self.b)
|
|
261
|
+
|
|
262
|
+
# Estado Adam / AdamW
|
|
263
|
+
self.m_w = _np_zeros_like(self.w)
|
|
264
|
+
self.v_adam_w = _np_zeros_like(self.w)
|
|
265
|
+
self.m_b = _np_zeros_like(self.b)
|
|
266
|
+
self.v_adam_b = _np_zeros_like(self.b)
|
|
267
|
+
self.paso_adam = 0
|
|
268
|
+
|
|
269
|
+
# Memoria de consolidación (ancla + importancia omega)
|
|
270
|
+
self.w_ancla = None
|
|
271
|
+
self.b_ancla = None
|
|
272
|
+
self.omega_w = _np_zeros_like(self.w)
|
|
273
|
+
self.omega_b = _np_zeros_like(self.b)
|
|
274
|
+
|
|
275
|
+
# Buffers reutilizables
|
|
276
|
+
self.entrada = None
|
|
277
|
+
self.z = None
|
|
278
|
+
self.salida = None
|
|
279
|
+
self._buf_fn = None
|
|
280
|
+
self._buf_dfn = None
|
|
281
|
+
self._buf_delta = None
|
|
282
|
+
self._buf_err_ant = None
|
|
283
|
+
self._buf_grad_w = None
|
|
284
|
+
self._buf_grad_b = None
|
|
285
|
+
self._buf_m_hat = None
|
|
286
|
+
self._buf_v_hat = None
|
|
287
|
+
self._buf_paso = None
|
|
288
|
+
|
|
289
|
+
def fijar_ancla(self, omega_w=None, omega_b=None):
|
|
290
|
+
self.w_ancla = self.w.copy()
|
|
291
|
+
self.b_ancla = self.b.copy()
|
|
292
|
+
if omega_w is not None:
|
|
293
|
+
self.omega_w[...] = np.asarray(omega_w, dtype=np.float64)
|
|
294
|
+
if omega_b is not None:
|
|
295
|
+
self.omega_b[...] = np.asarray(omega_b, dtype=np.float64)
|
|
296
|
+
|
|
297
|
+
def limpiar_ancla(self):
|
|
298
|
+
self.w_ancla = None
|
|
299
|
+
self.b_ancla = None
|
|
300
|
+
self.omega_w.fill(0.0)
|
|
301
|
+
self.omega_b.fill(0.0)
|
|
302
|
+
|
|
303
|
+
def reset_momentos(self):
|
|
304
|
+
self.v_w.fill(0.0)
|
|
305
|
+
self.v_b.fill(0.0)
|
|
306
|
+
self.m_w.fill(0.0)
|
|
307
|
+
self.v_adam_w.fill(0.0)
|
|
308
|
+
self.m_b.fill(0.0)
|
|
309
|
+
self.v_adam_b.fill(0.0)
|
|
310
|
+
self.paso_adam = 0
|
|
311
|
+
|
|
312
|
+
def adelante(self, x):
|
|
313
|
+
self.entrada = x
|
|
314
|
+
shape_z = (x.shape[0], self.w.shape[1])
|
|
315
|
+
if self.z is None or self.z.shape != shape_z:
|
|
316
|
+
self.z = _np_empty(shape_z, dtype=np.float64)
|
|
317
|
+
_np_matmul(x, self.w, out=self.z)
|
|
318
|
+
_np_add(self.z, self.b, out=self.z)
|
|
319
|
+
|
|
320
|
+
if self._buf_fn is None or self._buf_fn.shape != shape_z:
|
|
321
|
+
self._buf_fn = _np_empty(shape_z, dtype=np.float64)
|
|
322
|
+
self.salida = self.fn(self.z, out=self._buf_fn)
|
|
323
|
+
return self.salida
|
|
324
|
+
|
|
325
|
+
def _paso_adam_in_place(self, param, grad, m, v, lr, beta1, beta2, eps):
|
|
326
|
+
m *= beta1
|
|
327
|
+
m += (1.0 - beta1) * grad
|
|
328
|
+
|
|
329
|
+
v *= beta2
|
|
330
|
+
v += (1.0 - beta2) * (grad * grad)
|
|
331
|
+
|
|
332
|
+
denom_m = max(1.0 - (beta1 ** self.paso_adam), 1e-12)
|
|
333
|
+
denom_v = max(1.0 - (beta2 ** self.paso_adam), 1e-12)
|
|
334
|
+
|
|
335
|
+
m_hat = m / denom_m
|
|
336
|
+
v_hat = v / denom_v
|
|
337
|
+
param -= lr * (m_hat / (np.sqrt(v_hat) + eps))
|
|
338
|
+
|
|
339
|
+
def atras(
|
|
340
|
+
self,
|
|
341
|
+
error_siguiente,
|
|
342
|
+
taza,
|
|
343
|
+
momentum=0.85,
|
|
344
|
+
optimizador="adamw",
|
|
345
|
+
beta1=0.9,
|
|
346
|
+
beta2=0.999,
|
|
347
|
+
eps=1e-8,
|
|
348
|
+
ancla_fuerza=0.0,
|
|
349
|
+
):
|
|
350
|
+
shape_z = self.z.shape
|
|
351
|
+
shape_err = (shape_z[0], self.w.shape[0])
|
|
352
|
+
|
|
353
|
+
if self._buf_dfn is None or self._buf_dfn.shape != shape_z:
|
|
354
|
+
self._buf_dfn = _np_empty(shape_z, dtype=np.float64)
|
|
355
|
+
if self._buf_delta is None or self._buf_delta.shape != shape_z:
|
|
356
|
+
self._buf_delta = _np_empty(shape_z, dtype=np.float64)
|
|
357
|
+
if self._buf_err_ant is None or self._buf_err_ant.shape != shape_err:
|
|
358
|
+
self._buf_err_ant = _np_empty(shape_err, dtype=np.float64)
|
|
359
|
+
if self._buf_grad_w is None or self._buf_grad_w.shape != self.w.shape:
|
|
360
|
+
self._buf_grad_w = _np_empty(self.w.shape, dtype=np.float64)
|
|
361
|
+
if self._buf_grad_b is None or self._buf_grad_b.shape != self.b.shape:
|
|
362
|
+
self._buf_grad_b = _np_empty(self.b.shape, dtype=np.float64)
|
|
363
|
+
|
|
364
|
+
dfn_val = self.d_fn(self.z, out=self._buf_dfn)
|
|
365
|
+
_np_multiply(error_siguiente, dfn_val, out=self._buf_delta)
|
|
366
|
+
delta = self._buf_delta
|
|
367
|
+
|
|
368
|
+
_np_matmul(delta, self.w.T, out=self._buf_err_ant)
|
|
369
|
+
_np_matmul(self.entrada.T, delta, out=self._buf_grad_w)
|
|
370
|
+
_np_sum(delta, axis=0, keepdims=True, out=self._buf_grad_b)
|
|
371
|
+
|
|
372
|
+
grad_w = self._buf_grad_w
|
|
373
|
+
grad_b = self._buf_grad_b
|
|
374
|
+
|
|
375
|
+
if ancla_fuerza > 0.0 and self.w_ancla is not None:
|
|
376
|
+
grad_w += ancla_fuerza * self.omega_w * (self.w - self.w_ancla)
|
|
377
|
+
if self.b_ancla is not None:
|
|
378
|
+
grad_b += ancla_fuerza * self.omega_b * (self.b - self.b_ancla)
|
|
379
|
+
|
|
380
|
+
opt = optimizador.lower()
|
|
381
|
+
|
|
382
|
+
if opt != "adamw" and self.peso_l2 > 0.0:
|
|
383
|
+
grad_w += self.peso_l2 * self.w
|
|
384
|
+
|
|
385
|
+
if self.clip_grad is not None and self.clip_grad > 0.0:
|
|
386
|
+
norma_w = float(np.linalg.norm(grad_w))
|
|
387
|
+
if np.isfinite(norma_w) and norma_w > self.clip_grad:
|
|
388
|
+
grad_w *= (self.clip_grad / norma_w)
|
|
389
|
+
|
|
390
|
+
if opt in ("adam", "adamw"):
|
|
391
|
+
self.paso_adam += 1
|
|
392
|
+
if opt == "adamw" and self.peso_l2 > 0.0:
|
|
393
|
+
self.w -= taza * self.peso_l2 * self.w
|
|
394
|
+
self.b -= taza * self.peso_l2 * self.b
|
|
395
|
+
|
|
396
|
+
self._paso_adam_in_place(
|
|
397
|
+
self.w, grad_w, self.m_w, self.v_adam_w, taza, beta1, beta2, eps
|
|
398
|
+
)
|
|
399
|
+
self._paso_adam_in_place(
|
|
400
|
+
self.b, grad_b, self.m_b, self.v_adam_b, taza, beta1, beta2, eps
|
|
401
|
+
)
|
|
402
|
+
elif opt == "momentum":
|
|
403
|
+
self.v_w *= momentum
|
|
404
|
+
self.v_w += taza * grad_w
|
|
405
|
+
self.w -= self.v_w
|
|
406
|
+
|
|
407
|
+
self.v_b *= momentum
|
|
408
|
+
self.v_b += taza * grad_b
|
|
409
|
+
self.b -= self.v_b
|
|
410
|
+
elif opt == "sgd":
|
|
411
|
+
grad_w *= taza
|
|
412
|
+
self.w -= grad_w
|
|
413
|
+
|
|
414
|
+
grad_b *= taza
|
|
415
|
+
self.b -= grad_b
|
|
416
|
+
else:
|
|
417
|
+
raise ValueError(f"Optimizador '{optimizador}' no válido. Usa: adam, adamw, momentum, sgd.")
|
|
418
|
+
|
|
419
|
+
return self._buf_err_ant
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
# ==========================================
|
|
423
|
+
# 3. CLASE RED NEURONAL
|
|
424
|
+
# ==========================================
|
|
425
|
+
|
|
426
|
+
class RedNeuronal:
|
|
427
|
+
def __init__(self, arquitectura, activaciones="sig", peso_l2=0.0, clip_grad=None):
|
|
428
|
+
num_capas = len(arquitectura) - 1
|
|
429
|
+
|
|
430
|
+
if isinstance(activaciones, str):
|
|
431
|
+
lista_act = [activaciones] * num_capas
|
|
432
|
+
else:
|
|
433
|
+
lista_act = activaciones
|
|
434
|
+
|
|
435
|
+
self.capas = [
|
|
436
|
+
Capa(
|
|
437
|
+
arquitectura[i],
|
|
438
|
+
arquitectura[i + 1],
|
|
439
|
+
activacion=lista_act[i],
|
|
440
|
+
peso_l2=peso_l2,
|
|
441
|
+
clip_grad=clip_grad,
|
|
442
|
+
)
|
|
443
|
+
for i in range(num_capas)
|
|
444
|
+
]
|
|
445
|
+
self._capas_inv = list(reversed(self.capas))
|
|
446
|
+
self._buf_error = None
|
|
447
|
+
self.snapshots_memoria = {}
|
|
448
|
+
|
|
449
|
+
def predecir(self, x):
|
|
450
|
+
actual = _np_ascontiguousarray(x, dtype=np.float64)
|
|
451
|
+
for capa in self.capas:
|
|
452
|
+
actual = capa.adelante(actual)
|
|
453
|
+
return actual
|
|
454
|
+
|
|
455
|
+
def _clonar_pesos(self):
|
|
456
|
+
return [
|
|
457
|
+
(
|
|
458
|
+
c.w.copy(),
|
|
459
|
+
c.b.copy(),
|
|
460
|
+
c.v_w.copy(),
|
|
461
|
+
c.v_b.copy(),
|
|
462
|
+
c.m_w.copy(),
|
|
463
|
+
c.v_adam_w.copy(),
|
|
464
|
+
c.m_b.copy(),
|
|
465
|
+
c.v_adam_b.copy(),
|
|
466
|
+
c.paso_adam,
|
|
467
|
+
)
|
|
468
|
+
for c in self.capas
|
|
469
|
+
]
|
|
470
|
+
|
|
471
|
+
def _restaurar_pesos(self, snap):
|
|
472
|
+
for capa, datos in zip(self.capas, snap):
|
|
473
|
+
w, b, vw, vb, mw, vaw, mb, vab, paso = datos
|
|
474
|
+
capa.w[...] = w
|
|
475
|
+
capa.b[...] = b
|
|
476
|
+
capa.v_w[...] = vw
|
|
477
|
+
capa.v_b[...] = vb
|
|
478
|
+
capa.m_w[...] = mw
|
|
479
|
+
capa.v_adam_w[...] = vaw
|
|
480
|
+
capa.m_b[...] = mb
|
|
481
|
+
capa.v_adam_b[...] = vab
|
|
482
|
+
capa.paso_adam = paso
|
|
483
|
+
|
|
484
|
+
def _sacudir_pesos(self, escala_ruido=0.15):
|
|
485
|
+
for capa in self.capas:
|
|
486
|
+
freno = (1.0 / (1.0 + capa.omega_w)) if capa.w_ancla is not None else 1.0
|
|
487
|
+
capa.w += np.random.randn(*capa.w.shape) * escala_ruido * freno
|
|
488
|
+
capa.b += np.random.randn(*capa.b.shape) * (escala_ruido * 0.5)
|
|
489
|
+
capa.reset_momentos()
|
|
490
|
+
|
|
491
|
+
def guardar_checkpoint(self, etiqueta):
|
|
492
|
+
self.snapshots_memoria[etiqueta] = self._clonar_pesos()
|
|
493
|
+
|
|
494
|
+
def cargar_checkpoint(self, etiqueta):
|
|
495
|
+
if etiqueta not in self.snapshots_memoria:
|
|
496
|
+
raise KeyError(f"No existe el checkpoint '{etiqueta}'.")
|
|
497
|
+
self._restaurar_pesos(self.snapshots_memoria[etiqueta])
|
|
498
|
+
|
|
499
|
+
def consolidar_memoria(self, x, y, etiqueta="tarea_base", escalar_omega=1.0):
|
|
500
|
+
x_arr = _np_ascontiguousarray(x, dtype=np.float64)
|
|
501
|
+
y_arr = _np_ascontiguousarray(y, dtype=np.float64)
|
|
502
|
+
n = max(x_arr.shape[0], 1)
|
|
503
|
+
|
|
504
|
+
actual = x_arr
|
|
505
|
+
for capa in self.capas:
|
|
506
|
+
actual = capa.adelante(actual)
|
|
507
|
+
|
|
508
|
+
error_actual = (actual - y_arr) / n
|
|
509
|
+
grads_w = [None] * len(self.capas)
|
|
510
|
+
grads_b = [None] * len(self.capas)
|
|
511
|
+
|
|
512
|
+
for idx in range(len(self.capas) - 1, -1, -1):
|
|
513
|
+
capa = self.capas[idx]
|
|
514
|
+
dfn_val = capa.d_fn(capa.z)
|
|
515
|
+
delta = error_actual * dfn_val
|
|
516
|
+
error_actual = delta @ capa.w.T
|
|
517
|
+
grads_w[idx] = capa.entrada.T @ delta
|
|
518
|
+
grads_b[idx] = np.sum(delta, axis=0, keepdims=True)
|
|
519
|
+
|
|
520
|
+
for capa, gw, gb in zip(self.capas, grads_w, grads_b):
|
|
521
|
+
ow = (gw ** 2) * escalar_omega
|
|
522
|
+
ob = (gb ** 2) * escalar_omega
|
|
523
|
+
max_w = float(np.max(ow)) if ow.size > 0 else 0.0
|
|
524
|
+
if max_w > 0.0:
|
|
525
|
+
ow = ow / max_w
|
|
526
|
+
max_b = float(np.max(ob)) if ob.size > 0 else 0.0
|
|
527
|
+
if max_b > 0.0:
|
|
528
|
+
ob = ob / max_b
|
|
529
|
+
capa.fijar_ancla(omega_w=ow, omega_b=ob)
|
|
530
|
+
|
|
531
|
+
self.guardar_checkpoint(etiqueta)
|
|
532
|
+
|
|
533
|
+
def entrenar(
|
|
534
|
+
self,
|
|
535
|
+
x,
|
|
536
|
+
y,
|
|
537
|
+
vueltas,
|
|
538
|
+
taza,
|
|
539
|
+
optimizador="sgd",
|
|
540
|
+
momentum=0.85,
|
|
541
|
+
beta1=0.9,
|
|
542
|
+
beta2=0.999,
|
|
543
|
+
ancla_fuerza=0.0,
|
|
544
|
+
):
|
|
545
|
+
x_arr = _np_ascontiguousarray(x, dtype=np.float64)
|
|
546
|
+
y_arr = _np_ascontiguousarray(y, dtype=np.float64)
|
|
547
|
+
n = max(x_arr.shape[0], 1)
|
|
548
|
+
inv_n = 1.0 / n
|
|
549
|
+
capas = self.capas
|
|
550
|
+
capas_inv = self._capas_inv
|
|
551
|
+
|
|
552
|
+
for _ in range(vueltas):
|
|
553
|
+
actual = x_arr
|
|
554
|
+
for capa in capas:
|
|
555
|
+
actual = capa.adelante(actual)
|
|
556
|
+
|
|
557
|
+
if self._buf_error is None or self._buf_error.shape != actual.shape:
|
|
558
|
+
self._buf_error = _np_empty(actual.shape, dtype=np.float64)
|
|
559
|
+
_np_subtract(actual, y_arr, out=self._buf_error)
|
|
560
|
+
self._buf_error *= inv_n
|
|
561
|
+
error = self._buf_error
|
|
562
|
+
|
|
563
|
+
for capa in capas_inv:
|
|
564
|
+
error = capa.atras(
|
|
565
|
+
error,
|
|
566
|
+
taza=taza,
|
|
567
|
+
momentum=momentum,
|
|
568
|
+
optimizador=optimizador,
|
|
569
|
+
beta1=beta1,
|
|
570
|
+
beta2=beta2,
|
|
571
|
+
ancla_fuerza=ancla_fuerza,
|
|
572
|
+
)
|
|
573
|
+
|
|
574
|
+
def entrenar_legendario(
|
|
575
|
+
self,
|
|
576
|
+
x,
|
|
577
|
+
y,
|
|
578
|
+
vueltas=2500,
|
|
579
|
+
taza_inicial=0.015,
|
|
580
|
+
optimizador="adamw",
|
|
581
|
+
momentum=0.85,
|
|
582
|
+
beta1=0.9,
|
|
583
|
+
beta2=0.999,
|
|
584
|
+
ancla_fuerza=0.0,
|
|
585
|
+
tol=1e-4,
|
|
586
|
+
paciencia=120,
|
|
587
|
+
max_sacudidas=3,
|
|
588
|
+
reglas=None,
|
|
589
|
+
log_cada=500,
|
|
590
|
+
):
|
|
591
|
+
x_arr = _np_ascontiguousarray(x, dtype=np.float64)
|
|
592
|
+
y_arr = _np_ascontiguousarray(y, dtype=np.float64)
|
|
593
|
+
reglas = reglas or []
|
|
594
|
+
n = max(x_arr.shape[0], 1)
|
|
595
|
+
inv_n = 1.0 / n
|
|
596
|
+
|
|
597
|
+
mejor_mse = float("inf")
|
|
598
|
+
mejor_snap = self._clonar_pesos()
|
|
599
|
+
sin_mejora = 0
|
|
600
|
+
sacudidas = 0
|
|
601
|
+
ultimo_disparo = {i: -10**9 for i in range(len(reglas))}
|
|
602
|
+
|
|
603
|
+
ctx = {
|
|
604
|
+
"epoca": 0,
|
|
605
|
+
"mse": float("inf"),
|
|
606
|
+
"err_max": float("inf"),
|
|
607
|
+
"mejor_mse": mejor_mse,
|
|
608
|
+
"sin_mejora": 0,
|
|
609
|
+
"sacudidas": 0,
|
|
610
|
+
"taza": float(taza_inicial),
|
|
611
|
+
"optimizador": optimizador,
|
|
612
|
+
"momentum": float(momentum),
|
|
613
|
+
"ancla_fuerza": float(ancla_fuerza),
|
|
614
|
+
"detener": False,
|
|
615
|
+
"error": None,
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
historial = []
|
|
619
|
+
eventos = []
|
|
620
|
+
capas = self.capas
|
|
621
|
+
capas_inv = self._capas_inv
|
|
622
|
+
|
|
623
|
+
for vuelta in range(1, vueltas + 1):
|
|
624
|
+
actual = x_arr
|
|
625
|
+
for capa in capas:
|
|
626
|
+
actual = capa.adelante(actual)
|
|
627
|
+
|
|
628
|
+
if self._buf_error is None or self._buf_error.shape != actual.shape:
|
|
629
|
+
self._buf_error = _np_empty(actual.shape, dtype=np.float64)
|
|
630
|
+
_np_subtract(actual, y_arr, out=self._buf_error)
|
|
631
|
+
error_raw = self._buf_error
|
|
632
|
+
|
|
633
|
+
mse = float(np.mean(error_raw ** 2))
|
|
634
|
+
err_max = float(np.max(np.abs(error_raw)))
|
|
635
|
+
|
|
636
|
+
if not np.isfinite(mse):
|
|
637
|
+
self._restaurar_pesos(mejor_snap)
|
|
638
|
+
self._sacudir_pesos(escala_ruido=0.1)
|
|
639
|
+
ctx["taza"] = max(ctx["taza"] * 0.5, 1e-5)
|
|
640
|
+
sin_mejora = 0
|
|
641
|
+
eventos.append(f"Época {vuelta}: explosión numérica -> restauró mejor estado y bajó lr a {ctx['taza']:.6f}")
|
|
642
|
+
continue
|
|
643
|
+
|
|
644
|
+
if mse < mejor_mse - 1e-7:
|
|
645
|
+
mejor_mse = mse
|
|
646
|
+
mejor_snap = self._clonar_pesos()
|
|
647
|
+
sin_mejora = 0
|
|
648
|
+
else:
|
|
649
|
+
sin_mejora += 1
|
|
650
|
+
|
|
651
|
+
ctx["epoca"] = vuelta
|
|
652
|
+
ctx["mse"] = mse
|
|
653
|
+
ctx["err_max"] = err_max
|
|
654
|
+
ctx["mejor_mse"] = mejor_mse
|
|
655
|
+
ctx["sin_mejora"] = sin_mejora
|
|
656
|
+
ctx["sacudidas"] = sacudidas
|
|
657
|
+
ctx["error"] = error_raw
|
|
658
|
+
|
|
659
|
+
if vuelta == 1 or vuelta % log_cada == 0 or vuelta == vueltas:
|
|
660
|
+
historial.append((vuelta, mse, ctx["taza"], ctx["optimizador"]))
|
|
661
|
+
|
|
662
|
+
if (err_max <= tol) and (mse <= tol):
|
|
663
|
+
eventos.append(f"Época {vuelta}: objetivo alcanzado (MSE={mse:.6f}).")
|
|
664
|
+
break
|
|
665
|
+
|
|
666
|
+
for idx, regla in enumerate(reglas):
|
|
667
|
+
cada = regla.get("cada", 1)
|
|
668
|
+
cooldown = regla.get("cooldown", 1)
|
|
669
|
+
if vuelta % cada != 0:
|
|
670
|
+
continue
|
|
671
|
+
if vuelta - ultimo_disparo[idx] < cooldown:
|
|
672
|
+
continue
|
|
673
|
+
if regla["condicion"](ctx):
|
|
674
|
+
nota = regla["accion"](self, ctx)
|
|
675
|
+
ultimo_disparo[idx] = vuelta
|
|
676
|
+
detalle = f" -> {nota}" if nota else ""
|
|
677
|
+
eventos.append(f"Época {vuelta} [Regla '{regla['nombre']}']{detalle}")
|
|
678
|
+
|
|
679
|
+
if ctx["detener"]:
|
|
680
|
+
eventos.append(f"Época {vuelta}: detención solicitada por regla.")
|
|
681
|
+
break
|
|
682
|
+
|
|
683
|
+
if sin_mejora >= paciencia:
|
|
684
|
+
if sacudidas < max_sacudidas:
|
|
685
|
+
sacudidas += 1
|
|
686
|
+
ctx["sacudidas"] = sacudidas
|
|
687
|
+
self._restaurar_pesos(mejor_snap)
|
|
688
|
+
self._sacudir_pesos(escala_ruido=0.12 * sacudidas)
|
|
689
|
+
ctx["taza"] = min(ctx["taza"] * 1.15, 0.1)
|
|
690
|
+
sin_mejora = 0
|
|
691
|
+
ctx["sin_mejora"] = 0
|
|
692
|
+
eventos.append(
|
|
693
|
+
f"Época {vuelta}: estancado -> sacudida #{sacudidas}, lr={ctx['taza']:.5f}"
|
|
694
|
+
)
|
|
695
|
+
else:
|
|
696
|
+
self._restaurar_pesos(mejor_snap)
|
|
697
|
+
ctx["taza"] = max(ctx["taza"] * 0.7, 1e-5)
|
|
698
|
+
sin_mejora = 0
|
|
699
|
+
ctx["sin_mejora"] = 0
|
|
700
|
+
eventos.append(
|
|
701
|
+
f"Época {vuelta}: rescate fino -> lr={ctx['taza']:.6f}"
|
|
702
|
+
)
|
|
703
|
+
|
|
704
|
+
error_raw *= inv_n
|
|
705
|
+
err_actual = error_raw
|
|
706
|
+
for capa in capas_inv:
|
|
707
|
+
err_actual = capa.atras(
|
|
708
|
+
err_actual,
|
|
709
|
+
taza=ctx["taza"],
|
|
710
|
+
momentum=ctx["momentum"],
|
|
711
|
+
optimizador=ctx["optimizador"],
|
|
712
|
+
beta1=beta1,
|
|
713
|
+
beta2=beta2,
|
|
714
|
+
ancla_fuerza=ctx["ancla_fuerza"],
|
|
715
|
+
)
|
|
716
|
+
|
|
717
|
+
self._restaurar_pesos(mejor_snap)
|
|
718
|
+
return historial, eventos
|
|
719
|
+
|
|
720
|
+
print(f"""
|
|
721
|
+
HECHO POR SAMMY...
|
|
722
|
+
|
|
723
|
+
arquitectura:
|
|
724
|
+
{ARQUITECTURA_ACTUAL}
|
|
725
|
+
""")
|