lucid-dl 2.8.0__py3-none-any.whl → 2.8.4__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.
lucid/nn/modules/rnn.py CHANGED
@@ -5,11 +5,12 @@ import lucid.nn as nn
5
5
  import lucid.nn.functional as F
6
6
 
7
7
  from lucid._tensor import Tensor
8
+ from lucid.types import Numeric, _DeviceType
8
9
 
9
10
  from .activation import Tanh, ReLU
10
11
 
11
12
 
12
- __all__ = ["RNNCell"]
13
+ __all__ = ["RNNCell", "LSTMCell", "GRUCell", "RNNBase", "RNN", "LSTM", "GRU"]
13
14
 
14
15
 
15
16
  def _get_activation(nonlinearity: str) -> type[nn.Module]:
@@ -95,3 +96,434 @@ class RNNCell(nn.Module):
95
96
  if not is_batched:
96
97
  ret = ret.squeeze(axis=0)
97
98
  return ret
99
+
100
+
101
+ class LSTMCell(nn.Module):
102
+ def __init__(
103
+ self, input_size: int, hidden_size: int, bias: bool = True, **kwargs
104
+ ) -> None:
105
+ super().__init__()
106
+ self.input_size = input_size
107
+ self.hidden_size = hidden_size
108
+ self.bias = bias
109
+
110
+ sqrt_k = 1.0 / (hidden_size**0.5)
111
+ self.weight_ih = nn.Parameter(
112
+ lucid.random.uniform(
113
+ -sqrt_k, sqrt_k, (4 * self.hidden_size, self.input_size)
114
+ )
115
+ )
116
+ self.weight_hh = nn.Parameter(
117
+ lucid.random.uniform(
118
+ -sqrt_k, sqrt_k, (4 * self.hidden_size, self.hidden_size)
119
+ )
120
+ )
121
+
122
+ if self.bias:
123
+ self.bias_ih = nn.Parameter(
124
+ lucid.random.uniform(-sqrt_k, sqrt_k, 4 * self.hidden_size)
125
+ )
126
+ self.bias_hh = nn.Parameter(
127
+ lucid.random.uniform(-sqrt_k, sqrt_k, 4 * self.hidden_size)
128
+ )
129
+ else:
130
+ self.bias_ih = None
131
+ self.bias_hh = None
132
+
133
+ def forward(
134
+ self, input_: Tensor, hx: tuple[Tensor, Tensor] | None = None
135
+ ) -> tuple[Tensor, Tensor]:
136
+ if input_.ndim not in (1, 2):
137
+ raise ValueError(
138
+ "LSTMCell expected input with 1 or 2 dimensions, "
139
+ f"got {input_.ndim} dimensions"
140
+ )
141
+
142
+ is_batched = input_.ndim == 2
143
+ if not is_batched:
144
+ input_ = input_.unsqueeze(axis=0)
145
+ batch_size = input_.shape[0]
146
+
147
+ if hx is None:
148
+ h_t = lucid.zeros(
149
+ batch_size, self.hidden_size, dtype=input_.dtype, device=input_.device
150
+ )
151
+ c_t = lucid.zeros(
152
+ batch_size, self.hidden_size, dtype=input_.dtype, device=input_.device
153
+ )
154
+ else:
155
+ h_t, c_t = hx
156
+ if h_t.ndim not in (1, 2) or c_t.ndim not in (1, 2):
157
+ raise ValueError(
158
+ "LSTMCell expected hidden state and cell state with 1 or 2 dimensions"
159
+ )
160
+
161
+ if h_t.ndim == 1:
162
+ h_t = h_t.unsqueeze(axis=0)
163
+ if c_t.ndim == 1:
164
+ c_t = c_t.unsqueeze(axis=0)
165
+
166
+ if h_t.shape[0] != batch_size or h_t.shape[1] != self.hidden_size:
167
+ raise ValueError(
168
+ "LSTMCell expected hidden state with shape "
169
+ f"({batch_size}, {self.hidden_size}), got {h_t.shape}"
170
+ )
171
+ if c_t.shape[0] != batch_size or c_t.shape[1] != self.hidden_size:
172
+ raise ValueError(
173
+ "LSTMCell expected cell state with shape "
174
+ f"({batch_size}, {self.hidden_size}), got {c_t.shape}"
175
+ )
176
+
177
+ gates = F.linear(input_, self.weight_ih, self.bias_ih)
178
+ gates += F.linear(h_t, self.weight_hh, self.bias_hh)
179
+
180
+ i_t, f_t, g_t, o_t = lucid.split(gates, 4, axis=1)
181
+ i_t = F.sigmoid(i_t)
182
+ f_t = F.sigmoid(f_t)
183
+ g_t = F.tanh(g_t)
184
+ o_t = F.sigmoid(o_t)
185
+
186
+ c_t = f_t * c_t + i_t * g_t
187
+ h_t = o_t * F.tanh(c_t)
188
+
189
+ if not is_batched:
190
+ h_t = h_t.squeeze(axis=0)
191
+ c_t = c_t.squeeze(axis=0)
192
+ return h_t, c_t
193
+
194
+
195
+ class GRUCell(nn.Module):
196
+ def __init__(self, input_size: int, hidden_size: int, bias: bool = True) -> None:
197
+ super().__init__()
198
+ self.input_size = input_size
199
+ self.hidden_size = hidden_size
200
+ self.bias = bias
201
+
202
+ sqrt_k = 1.0 / (hidden_size**0.5)
203
+ self.weight_ih = nn.Parameter(
204
+ lucid.random.uniform(
205
+ -sqrt_k, sqrt_k, (3 * self.hidden_size, self.input_size)
206
+ )
207
+ )
208
+ self.weight_hh = nn.Parameter(
209
+ lucid.random.uniform(
210
+ -sqrt_k, sqrt_k, (3 * self.hidden_size, self.hidden_size)
211
+ )
212
+ )
213
+
214
+ if self.bias:
215
+ self.bias_ih = nn.Parameter(
216
+ lucid.random.uniform(-sqrt_k, sqrt_k, 3 * self.hidden_size)
217
+ )
218
+ self.bias_hh = nn.Parameter(
219
+ lucid.random.uniform(-sqrt_k, sqrt_k, 3 * self.hidden_size)
220
+ )
221
+ else:
222
+ self.bias_ih = None
223
+ self.bias_hh = None
224
+
225
+ def forward(self, input_: Tensor, hx: Tensor | None = None) -> Tensor:
226
+ if input_.ndim not in (1, 2):
227
+ raise ValueError(
228
+ "GRUCell expected input with 1 or 2 dimensions, "
229
+ f"got {input_.ndim} dimensions"
230
+ )
231
+
232
+ is_batched = input_.ndim == 2
233
+ if not is_batched:
234
+ input_ = input_.unsqueeze(axis=0)
235
+ batch_size = input_.shape[0]
236
+
237
+ if hx is None:
238
+ hx = lucid.zeros(
239
+ batch_size, self.hidden_size, dtype=input_.dtype, device=input_.device
240
+ )
241
+ else:
242
+ if hx.ndim not in (1, 2):
243
+ raise ValueError(
244
+ "GRUCell expected hidden state with 1 or 2 dimensions, "
245
+ f"got {hx.ndim} dimensions"
246
+ )
247
+
248
+ if hx.ndim == 1:
249
+ hx = hx.unsqueeze(axis=0)
250
+ if hx.shape[0] != batch_size or hx.shape[1] != self.hidden_size:
251
+ raise ValueError(
252
+ "GRUCell expected hidden state with shape "
253
+ f"({batch_size}, {self.hidden_size}), got {hx.shape}"
254
+ )
255
+
256
+ input_gates = F.linear(input_, self.weight_ih, self.bias_ih)
257
+ hidden_gates = F.linear(hx, self.weight_hh, self.bias_hh)
258
+
259
+ i_r, i_z, i_n = lucid.split(input_gates, 3, axis=1)
260
+ h_r, h_z, h_n = lucid.split(hidden_gates, 3, axis=1)
261
+
262
+ r_t = F.sigmoid(i_r + h_r)
263
+ z_t = F.sigmoid(i_z + h_z)
264
+ n_t = F.tanh(i_n + r_t * h_n)
265
+
266
+ h_t = (1 - z_t) * n_t + z_t * hx
267
+
268
+ if not is_batched:
269
+ h_t = h_t.squeeze(axis=0)
270
+ return h_t
271
+
272
+
273
+ class RNNBase(nn.Module):
274
+ def __init__(
275
+ self,
276
+ mode: Literal["RNN_TANH", "RNN_RELU", "LSTM", "GRU"],
277
+ input_size: int,
278
+ hidden_size: int,
279
+ num_layers: int = 1,
280
+ bias: bool = True,
281
+ batch_first: bool = False,
282
+ dropout: float = 0.0,
283
+ ) -> None:
284
+ super().__init__()
285
+ self.is_lstm = False
286
+ cell_kwargs = {}
287
+ nonlinearity = "tanh"
288
+
289
+ if mode == "RNN_TANH":
290
+ cell_cls = RNNCell
291
+ cell_kwargs: dict[str, object] = {"nonlinearity": nonlinearity}
292
+ elif mode == "RNN_RELU":
293
+ nonlinearity = "relu"
294
+ cell_cls = RNNCell
295
+ cell_kwargs = {"nonlinearity": nonlinearity}
296
+ elif mode == "LSTM":
297
+ cell_cls = LSTMCell
298
+ self.is_lstm = True
299
+ elif mode == "GRU":
300
+ cell_cls = GRUCell
301
+ else:
302
+ raise ValueError(
303
+ f"Invalid mode '{mode}'. Supported modes are 'RNN_TANH', "
304
+ "'RNN_RELU', 'LSTM', or 'GRU'."
305
+ )
306
+
307
+ self.mode = mode
308
+ self.nonlinearity = nonlinearity
309
+
310
+ self.input_size = input_size
311
+ self.hidden_size = hidden_size
312
+ self.num_layers = num_layers
313
+ self.bias = bias
314
+ self.batch_first = batch_first
315
+ self.dropout = float(dropout)
316
+
317
+ layers: list[nn.Module] = []
318
+ for layer in range(num_layers):
319
+ layer_input_size = input_size if layer == 0 else hidden_size
320
+ layers.append(
321
+ cell_cls(
322
+ input_size=layer_input_size,
323
+ hidden_size=hidden_size,
324
+ bias=bias,
325
+ **cell_kwargs,
326
+ )
327
+ )
328
+ self.layers = nn.ModuleList(layers)
329
+
330
+ def _init_hidden(
331
+ self, batch_size: int, dtype: Numeric, device: _DeviceType
332
+ ) -> Tensor | tuple[Tensor, Tensor]:
333
+ if self.is_lstm:
334
+ h0 = lucid.zeros(
335
+ self.num_layers,
336
+ batch_size,
337
+ self.hidden_size,
338
+ dtype=dtype,
339
+ device=device,
340
+ )
341
+ c0 = lucid.zeros(
342
+ self.num_layers,
343
+ batch_size,
344
+ self.hidden_size,
345
+ dtype=dtype,
346
+ device=device,
347
+ )
348
+ return h0, c0
349
+ return lucid.zeros(
350
+ self.num_layers, batch_size, self.hidden_size, dtype=dtype, device=device
351
+ )
352
+
353
+ def forward(
354
+ self, input_: Tensor, hx: Tensor | tuple[Tensor, Tensor] | None = None
355
+ ) -> tuple[Tensor, Tensor] | tuple[Tensor, tuple[Tensor, Tensor]]:
356
+ if input_.ndim != 3:
357
+ raise ValueError(
358
+ f"RNNBase expected input with 3 dimensions, got {input_.ndim} dimensions"
359
+ )
360
+
361
+ if self.batch_first:
362
+ input_ = input_.swapaxes(0, 1)
363
+
364
+ seq_len, batch_size, feat = input_.shape
365
+ if feat != self.input_size:
366
+ raise ValueError(
367
+ f"RNNBase expected input with feature size {self.input_size}, got {feat}"
368
+ )
369
+
370
+ if self.is_lstm:
371
+ if hx is None:
372
+ hx = self._init_hidden(batch_size, input_.dtype, input_.device)
373
+ if not (
374
+ isinstance(hx, (tuple, list))
375
+ and len(hx) == 2
376
+ and isinstance(hx[0], Tensor)
377
+ and isinstance(hx[1], Tensor)
378
+ ):
379
+ raise ValueError("LSTM expects hx as a tuple of (h_0, c_0)")
380
+
381
+ h0, c0 = hx
382
+ if h0.ndim == 2:
383
+ h0 = h0.unsqueeze(axis=0)
384
+ if c0.ndim == 2:
385
+ c0 = c0.unsqueeze(axis=0)
386
+
387
+ if h0.ndim != 3 or c0.ndim != 3:
388
+ raise ValueError("LSTM expects h_0 and c_0 with 3 dimensions")
389
+ if h0.shape[0] != self.num_layers or c0.shape[0] != self.num_layers:
390
+ raise ValueError("Incorrect number of layers in h_0 or c_0")
391
+ if h0.shape[1] != batch_size or c0.shape[1] != batch_size:
392
+ raise ValueError("Incorrect batch size in h_0 or c_0")
393
+ if h0.shape[2] != self.hidden_size or c0.shape[2] != self.hidden_size:
394
+ raise ValueError("Incorrect hidden size in h_0 or c_0")
395
+
396
+ hx_h, hx_c = h0, c0
397
+
398
+ else:
399
+ if hx is None:
400
+ hx = self._init_hidden(batch_size, input_.dtype, input_.device)
401
+ if hx.ndim == 2:
402
+ hx = hx.unsqueeze(axis=0)
403
+ if hx.ndim != 3:
404
+ raise ValueError(
405
+ f"RNNBase expected hidden state with 3 dimensions, got {hx.ndim} dimensions"
406
+ )
407
+
408
+ if hx.shape[0] != self.num_layers or hx.shape[1] != batch_size:
409
+ raise ValueError("hx has incorrect shape")
410
+ if hx.shape[2] != self.hidden_size:
411
+ raise ValueError("Incorrect hidden size in hx")
412
+
413
+ layer_input = input_
414
+ h_n_list: list[Tensor] = []
415
+ c_n_list: list[Tensor] | None = [] if self.is_lstm else None
416
+
417
+ for layer_idx, cell in enumerate(self.layers):
418
+ if self.is_lstm:
419
+ h_t = hx_h[layer_idx]
420
+ c_t = hx_c[layer_idx]
421
+ else:
422
+ h_t = hx[layer_idx]
423
+ outputs = []
424
+
425
+ for t in range(seq_len):
426
+ if self.is_lstm:
427
+ h_t, c_t = cell(layer_input[t], (h_t, c_t))
428
+ outputs.append(h_t.unsqueeze(axis=0))
429
+ else:
430
+ h_t = cell(layer_input[t], h_t)
431
+ outputs.append(h_t.unsqueeze(axis=0))
432
+
433
+ layer_output = lucid.concatenate(tuple(outputs), axis=0)
434
+
435
+ if self.training and self.dropout > 0.0 and layer_idx < self.num_layers - 1:
436
+ layer_output = F.dropout(layer_output, p=self.dropout)
437
+
438
+ h_n_list.append(h_t.unsqueeze(axis=0))
439
+ if self.is_lstm and c_n_list is not None:
440
+ c_n_list.append(c_t.unsqueeze(axis=0))
441
+ layer_input = layer_output
442
+
443
+ output = layer_input
444
+ h_n = lucid.concatenate(tuple(h_n_list), axis=0)
445
+ if self.is_lstm and c_n_list is not None:
446
+ c_n = lucid.concatenate(tuple(c_n_list), axis=0)
447
+
448
+ if self.batch_first:
449
+ output = output.swapaxes(0, 1)
450
+
451
+ if self.is_lstm and c_n_list is not None:
452
+ return output, (h_n, c_n)
453
+ return output, h_n
454
+
455
+
456
+ class RNN(RNNBase):
457
+ def __init__(
458
+ self,
459
+ input_size: int,
460
+ hidden_size: int,
461
+ num_layers: int = 1,
462
+ nonlinearity: Literal["tanh", "relu"] = "tanh",
463
+ bias: bool = True,
464
+ batch_first: bool = False,
465
+ dropout: float = 0.0,
466
+ ) -> None:
467
+ if nonlinearity == "tanh":
468
+ mode = "RNN_TANH"
469
+ elif nonlinearity == "relu":
470
+ mode = "RNN_RELU"
471
+ else:
472
+ raise ValueError(
473
+ f"Invalid nonlinearity '{nonlinearity}'. "
474
+ "Supported nonlinearities are 'tanh' and 'relu'."
475
+ )
476
+
477
+ super().__init__(
478
+ mode=mode,
479
+ input_size=input_size,
480
+ hidden_size=hidden_size,
481
+ num_layers=num_layers,
482
+ bias=bias,
483
+ batch_first=batch_first,
484
+ dropout=dropout,
485
+ )
486
+
487
+
488
+ class LSTM(RNNBase):
489
+ def __init__(
490
+ self,
491
+ input_size: int,
492
+ hidden_size: int,
493
+ num_layers: int = 1,
494
+ bias: bool = True,
495
+ batch_first: bool = False,
496
+ dropout: float = 0.0,
497
+ ) -> None:
498
+ mode = "LSTM"
499
+ super().__init__(
500
+ mode=mode,
501
+ input_size=input_size,
502
+ hidden_size=hidden_size,
503
+ num_layers=num_layers,
504
+ bias=bias,
505
+ batch_first=batch_first,
506
+ dropout=dropout,
507
+ )
508
+
509
+
510
+ class GRU(RNNBase):
511
+ def __init__(
512
+ self,
513
+ input_size: int,
514
+ hidden_size: int,
515
+ num_layers: int = 1,
516
+ bias: bool = True,
517
+ batch_first: bool = False,
518
+ dropout: float = 0.0,
519
+ ) -> None:
520
+ mode = "GRU"
521
+ super().__init__(
522
+ mode=mode,
523
+ input_size=input_size,
524
+ hidden_size=hidden_size,
525
+ num_layers=num_layers,
526
+ bias=bias,
527
+ batch_first=batch_first,
528
+ dropout=dropout,
529
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lucid-dl
3
- Version: 2.8.0
3
+ Version: 2.8.4
4
4
  Summary: Lumerico's Comprehensive Interface for Deep Learning
5
5
  Home-page: https://github.com/ChanLumerico/lucid
6
6
  Author: ChanLumerico
@@ -30,10 +30,10 @@ Dynamic: summary
30
30
 
31
31
  ![PyPI - Version](https://img.shields.io/pypi/v/lucid-dl?color=red)
32
32
  ![PyPI - Downloads](https://img.shields.io/pypi/dm/lucid-dl.svg)
33
- ![PyPI - Total Downloads](https://img.shields.io/badge/total%20downloads-33.2k-yellow.svg)
33
+ ![PyPI - Total Downloads](https://img.shields.io/badge/total%20downloads-34.0k-yellow.svg)
34
34
  ![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/ChanLumerico/lucid.svg)
35
35
  ![Code Style](https://img.shields.io/badge/code%20style-black-000000.svg)
36
- ![Lines of Code](https://img.shields.io/badge/lines%20of%20code-26.4k-purple.svg)
36
+ ![Lines of Code](https://img.shields.io/badge/lines%20of%20code-26.5k-purple.svg)
37
37
 
38
38
  **Lucid** is a minimalist deep learning framework built entirely from scratch in Python. It offers a pedagogically rich environment to explore the foundations of modern deep learning systems, including autodiff, neural network modules, and GPU acceleration — all while staying lightweight, readable, and free of complex dependencies.
39
39
 
@@ -46,13 +46,9 @@ Whether you're a student, educator, or an advanced researcher seeking to demysti
46
46
 
47
47
  - Now supports [**`Safetensors`**](https://github.com/huggingface/safetensors) for Lucid neural module porting along with the legacy `.lcd` format
48
48
 
49
- - Added multiple `nn` utilities:
49
+ - Added new neural module category `nn.rnn`, including:
50
50
 
51
- - `nn.util.grad_norm` - Returns the global norm of the gradients
52
- - `nn.util.clip_grad_norm` - Rescales the gradients based on the global norm
53
- - `nn.util.clip_grad_value` - Rescales the gradients based on their values.
54
-
55
- - Implemented **EfficientDet**: `lucid.models.EfficientDet` with variants from `D0` to `D7`
51
+ `nn.RNNBase`, `nn.RNN`, `nn.LSTM`, `nn.GRU`, `nn.RNNCell`, `nn.LSTMCell`, `nn.GRUCell`
56
52
 
57
53
  ## 🔧 How to Install
58
54
 
@@ -99,7 +99,7 @@ lucid/nn/modules/linear.py,sha256=87cuFWYct9JlmtVC3jGR-8eouxxzANaVA6cd7p9r2Ho,28
99
99
  lucid/nn/modules/loss.py,sha256=pjEMIruhtpTHhHFsNThS9LFz-aI_DAXLqMV8KRXydEg,3431
100
100
  lucid/nn/modules/norm.py,sha256=qaaVQ2vfOUkPRLTHT4hgsRNxxN1--kdEhlrKXJmE--w,6803
101
101
  lucid/nn/modules/pool.py,sha256=ymVnS2NZjh08Tw0VeOfkB6AVrMeLmCKvgxkmEO3KUuw,5044
102
- lucid/nn/modules/rnn.py,sha256=iMwWLtTC9i3k_h8pI6to-2rJfiqkXX9hzeDDJT3i7XU,2968
102
+ lucid/nn/modules/rnn.py,sha256=lsvQZiEHm1wGbiNWKQngAle7MbqGaXSBM1LUieCaZIk,17233
103
103
  lucid/nn/modules/sparse.py,sha256=EpjiviED2nI55wUjh1twFwa4Lvlrzw0TR6lpCDGeSbo,1147
104
104
  lucid/nn/modules/transformer.py,sha256=z56emF_eX18pxRELjfmmsY-7Bn9h2yjIdxCaxs6YDwA,11246
105
105
  lucid/nn/modules/vision.py,sha256=8xYasT7TNj4NXwMwwJIw1nbV1paeWEFg_ZohXn9kZBg,1579
@@ -121,8 +121,8 @@ lucid/visual/__init__.py,sha256=6TuFDfmXTwpLyHl7_KqBfdzW6zqHjGzIFvymjFPlvjI,21
121
121
  lucid/visual/graph.py,sha256=YjpIDM_lloZARw3sCBiXPl_hT5A2gTk2fEHvwvJWXTk,4599
122
122
  lucid/weights/__init__.py,sha256=z1AikA3rOEeckWGkYWlcZkxNlJo9Xwa39PL6ly3hWnc,8801
123
123
  lucid/weights/__init__.pyi,sha256=lFonYC3cUx2Idolf3AEPnjFcyqcn3UDU84oJlZafqLY,3013
124
- lucid_dl-2.8.0.dist-info/licenses/LICENSE,sha256=vxRFYnVD1IeYtsvw-KmoElfqrjxKHv1h9YTvsG54loQ,1065
125
- lucid_dl-2.8.0.dist-info/METADATA,sha256=zLT-u67ODSZMq4vod9l1GqZCQN-0XDl_lKXSTdVcSzY,11519
126
- lucid_dl-2.8.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
127
- lucid_dl-2.8.0.dist-info/top_level.txt,sha256=uzP_qBx9iNWIHKJRlElYcBLYVqMpdm9Q1Ma63QPYbFc,6
128
- lucid_dl-2.8.0.dist-info/RECORD,,
124
+ lucid_dl-2.8.4.dist-info/licenses/LICENSE,sha256=vxRFYnVD1IeYtsvw-KmoElfqrjxKHv1h9YTvsG54loQ,1065
125
+ lucid_dl-2.8.4.dist-info/METADATA,sha256=PEJ39ILJW83H4hJU6hTTHhZat3TME8R_BMXtBIZjwZs,11314
126
+ lucid_dl-2.8.4.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
127
+ lucid_dl-2.8.4.dist-info/top_level.txt,sha256=uzP_qBx9iNWIHKJRlElYcBLYVqMpdm9Q1Ma63QPYbFc,6
128
+ lucid_dl-2.8.4.dist-info/RECORD,,