lucid-dl 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.
lucid_dl-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Chan Lee
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.
@@ -0,0 +1,170 @@
1
+ Metadata-Version: 2.1
2
+ Name: lucid-dl
3
+ Version: 0.1.0
4
+ Summary: Lumerico's Comprehensive Interface for Deep Learning
5
+ Home-page: https://github.com/ChanLumerico/lucid
6
+ Author: ChanLumerico
7
+ Author-email: greensox284@gmail.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.12
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: numpy
15
+
16
+ # Lucid 💎
17
+
18
+ **Lucid** is an educational deep learning framework developed to help users understand
19
+ the underlying mechanics of deep learning models and tensor operations.
20
+
21
+ It is designed to provide a simple yet powerful environment to experiment with neural networks,
22
+ optimization, and backpropagation using only **`NumPy`**.
23
+
24
+ Lucid is ideal for those who want to learn about the inner workings of deep learning
25
+ algorithms and operations without the complexity of high-level frameworks.
26
+
27
+ *Latest version: **0.1.0***
28
+
29
+ [📑 Lucid Documentation](https://chanlumerico.github.io/lucid/build/html/index.html)
30
+
31
+ ## Overview
32
+
33
+ Lucid provides core functionality for building and training deep learning models.
34
+ By utilizing `NumPy` arrays as the fundamental data structure (referred to as **Tensors**),
35
+ Lucid allows for the construction of layers, models, and operations commonly found in neural networks.
36
+
37
+ It offers automatic differentiation (autodiff) for computing gradients and performing backpropagation,
38
+ enabling efficient optimization of model parameters.
39
+
40
+ ## Key Features
41
+
42
+ - **Tensors**: Tensors are the main data structure in Lucid,
43
+ similar to arrays in `NumPy` but with additional features such as automatic gradient tracking.
44
+
45
+ - **Autodiff**: Lucid computes gradients automatically using reverse-mode differentiation,
46
+ making it possible to train models through backpropagation.
47
+
48
+ - **Modularity**: Lucid is designed with modularity in mind, allowing users to build and
49
+ customize layers, models, and operations with ease.
50
+
51
+ - **Gradient Tracking**: Support for tracking gradients through Tensors,
52
+ enabling automatic backpropagation during training.
53
+
54
+ - **Educational Focus**: Lucid is a minimalistic library designed to be intuitive and provide
55
+ a deeper understanding of the mechanics of deep learning.
56
+
57
+ ## Core Components
58
+
59
+ ### Tensors
60
+
61
+ Tensors are the primary data structure in Lucid, similar to `NumPy` arrays but with additional capabilities,
62
+ such as the ability to track gradients.
63
+
64
+ Operations performed on tensors are automatically tracked, allowing for efficient backpropagation.
65
+
66
+ - **Tensor Operations**: Basic operations like addition, subtraction, multiplication,
67
+ and division are supported, with automatic gradient computation for supported operations.
68
+
69
+ - **Gradient Tracking**: When constructing Tensors,
70
+ users can specify if they require gradients for backpropagation.
71
+
72
+ - **Shape Management**: Lucid supports reshaping, transposing, and other tensor manipulation
73
+ operations to allow for flexible model design.
74
+
75
+ ### Neural Networks (`lucid.nn`)
76
+
77
+ Lucid provides a framework for defining and training neural networks.
78
+ Models are built by subclassing the **nn.Module** class, which allows users to define layers,
79
+ forward passes, and backward passes (gradient computations) for the model.
80
+
81
+ - **Layer Definitions**: Layers can be constructed using basic operations, like matrix multiplication,
82
+ activation functions, and loss functions.
83
+
84
+ - **Forward and Backward Passes**: Users define the computation graph in the `forward` method,
85
+ and Lucid handles backpropagation automatically by tracking operations performed on tensors.
86
+
87
+ ### Linear Algebra Operations (`lucid.linalg`)
88
+
89
+ Lucid includes basic linear algebra operations, such as matrix multiplication,
90
+ inverse, determinant calculation, and more.
91
+
92
+ - **Matrix Operations**: These operations are essential for building and manipulating neural networks,
93
+ particularly for tasks like transforming data in the forward pass.
94
+
95
+ ### Optimization
96
+
97
+ Lucid supports optimization routines like Stochastic Gradient Descent (SGD),
98
+ which allow for the training of models by minimizing a loss function.
99
+
100
+ - **Autodiff and Backpropagation**: Lucid's autodiff capabilities make it easy to compute
101
+ gradients and optimize model parameters using backpropagation.
102
+
103
+ ## Example Usage
104
+
105
+ The following example demonstrates how to define and train a simple neural network using Lucid.
106
+
107
+ ```python
108
+ # Example of a Simple Model
109
+
110
+ import lucid
111
+ import lucid.nn as nn
112
+ import lucid.nn.functional as F
113
+
114
+ # Define a simple model class
115
+ class SimpleModel(nn.Module):
116
+ def __init__(self):
117
+ super().__init__()
118
+ self.dense1 = nn.Linear(3, 5)
119
+ self.dense2 = nn.Linear(5, 1)
120
+
121
+ def forward(self, x):
122
+ x = self.dense1(x)
123
+ x = F.relu(x)
124
+ x = self.dense2(x)
125
+ return x
126
+
127
+ # Create an instance of the model
128
+ model = SimpleModel()
129
+
130
+ # Create a sample input tensor
131
+ input_tensor = lucid.Tensor([[1.0, 2.0, 3.0]])
132
+
133
+ # Forward pass
134
+ output = model(input_tensor)
135
+
136
+ print(output)
137
+ ```
138
+
139
+ In the above example, we define a simple model with two dense layers,
140
+ apply a ReLU activation, and perform a forward pass using an input tensor.
141
+
142
+ This showcases how easy it is to define models and run computations with Lucid.
143
+
144
+ ## Notes
145
+
146
+ Lucid is built for learning and experimenting with deep learning concepts,
147
+ allowing users to see how operations like backpropagation, optimization,
148
+ and activation functions are implemented at a low level.
149
+
150
+ Lucid is lightweight, with no external dependencies beyond `NumPy`,
151
+ making it easy to install and use without complex setups or specialized hardware.
152
+
153
+ ## Limitations
154
+
155
+ Lucid does not aim to provide the high-level functionalities of production-ready frameworks.
156
+ Instead, it focuses on educational value and understanding how deep
157
+ learning models are built from scratch.
158
+
159
+ Performance optimizations that are available in specialized libraries may not be as
160
+ efficient in Lucid, as it is not optimized for production workloads.
161
+
162
+ ## Conclusion
163
+
164
+ Lucid provides a minimalistic, educational environment to learn about deep learning using only `NumPy`.
165
+ It gives users the tools to experiment with neural networks, automatic differentiation,
166
+ optimization, and other essential components of deep learning, all while providing insight into how
167
+ these operations are implemented at the core level.
168
+
169
+ For further information and usage details, refer to the documentation of specific modules like
170
+ lucid.nn and lucid.linalg.
@@ -0,0 +1,155 @@
1
+ # Lucid 💎
2
+
3
+ **Lucid** is an educational deep learning framework developed to help users understand
4
+ the underlying mechanics of deep learning models and tensor operations.
5
+
6
+ It is designed to provide a simple yet powerful environment to experiment with neural networks,
7
+ optimization, and backpropagation using only **`NumPy`**.
8
+
9
+ Lucid is ideal for those who want to learn about the inner workings of deep learning
10
+ algorithms and operations without the complexity of high-level frameworks.
11
+
12
+ *Latest version: **0.1.0***
13
+
14
+ [📑 Lucid Documentation](https://chanlumerico.github.io/lucid/build/html/index.html)
15
+
16
+ ## Overview
17
+
18
+ Lucid provides core functionality for building and training deep learning models.
19
+ By utilizing `NumPy` arrays as the fundamental data structure (referred to as **Tensors**),
20
+ Lucid allows for the construction of layers, models, and operations commonly found in neural networks.
21
+
22
+ It offers automatic differentiation (autodiff) for computing gradients and performing backpropagation,
23
+ enabling efficient optimization of model parameters.
24
+
25
+ ## Key Features
26
+
27
+ - **Tensors**: Tensors are the main data structure in Lucid,
28
+ similar to arrays in `NumPy` but with additional features such as automatic gradient tracking.
29
+
30
+ - **Autodiff**: Lucid computes gradients automatically using reverse-mode differentiation,
31
+ making it possible to train models through backpropagation.
32
+
33
+ - **Modularity**: Lucid is designed with modularity in mind, allowing users to build and
34
+ customize layers, models, and operations with ease.
35
+
36
+ - **Gradient Tracking**: Support for tracking gradients through Tensors,
37
+ enabling automatic backpropagation during training.
38
+
39
+ - **Educational Focus**: Lucid is a minimalistic library designed to be intuitive and provide
40
+ a deeper understanding of the mechanics of deep learning.
41
+
42
+ ## Core Components
43
+
44
+ ### Tensors
45
+
46
+ Tensors are the primary data structure in Lucid, similar to `NumPy` arrays but with additional capabilities,
47
+ such as the ability to track gradients.
48
+
49
+ Operations performed on tensors are automatically tracked, allowing for efficient backpropagation.
50
+
51
+ - **Tensor Operations**: Basic operations like addition, subtraction, multiplication,
52
+ and division are supported, with automatic gradient computation for supported operations.
53
+
54
+ - **Gradient Tracking**: When constructing Tensors,
55
+ users can specify if they require gradients for backpropagation.
56
+
57
+ - **Shape Management**: Lucid supports reshaping, transposing, and other tensor manipulation
58
+ operations to allow for flexible model design.
59
+
60
+ ### Neural Networks (`lucid.nn`)
61
+
62
+ Lucid provides a framework for defining and training neural networks.
63
+ Models are built by subclassing the **nn.Module** class, which allows users to define layers,
64
+ forward passes, and backward passes (gradient computations) for the model.
65
+
66
+ - **Layer Definitions**: Layers can be constructed using basic operations, like matrix multiplication,
67
+ activation functions, and loss functions.
68
+
69
+ - **Forward and Backward Passes**: Users define the computation graph in the `forward` method,
70
+ and Lucid handles backpropagation automatically by tracking operations performed on tensors.
71
+
72
+ ### Linear Algebra Operations (`lucid.linalg`)
73
+
74
+ Lucid includes basic linear algebra operations, such as matrix multiplication,
75
+ inverse, determinant calculation, and more.
76
+
77
+ - **Matrix Operations**: These operations are essential for building and manipulating neural networks,
78
+ particularly for tasks like transforming data in the forward pass.
79
+
80
+ ### Optimization
81
+
82
+ Lucid supports optimization routines like Stochastic Gradient Descent (SGD),
83
+ which allow for the training of models by minimizing a loss function.
84
+
85
+ - **Autodiff and Backpropagation**: Lucid's autodiff capabilities make it easy to compute
86
+ gradients and optimize model parameters using backpropagation.
87
+
88
+ ## Example Usage
89
+
90
+ The following example demonstrates how to define and train a simple neural network using Lucid.
91
+
92
+ ```python
93
+ # Example of a Simple Model
94
+
95
+ import lucid
96
+ import lucid.nn as nn
97
+ import lucid.nn.functional as F
98
+
99
+ # Define a simple model class
100
+ class SimpleModel(nn.Module):
101
+ def __init__(self):
102
+ super().__init__()
103
+ self.dense1 = nn.Linear(3, 5)
104
+ self.dense2 = nn.Linear(5, 1)
105
+
106
+ def forward(self, x):
107
+ x = self.dense1(x)
108
+ x = F.relu(x)
109
+ x = self.dense2(x)
110
+ return x
111
+
112
+ # Create an instance of the model
113
+ model = SimpleModel()
114
+
115
+ # Create a sample input tensor
116
+ input_tensor = lucid.Tensor([[1.0, 2.0, 3.0]])
117
+
118
+ # Forward pass
119
+ output = model(input_tensor)
120
+
121
+ print(output)
122
+ ```
123
+
124
+ In the above example, we define a simple model with two dense layers,
125
+ apply a ReLU activation, and perform a forward pass using an input tensor.
126
+
127
+ This showcases how easy it is to define models and run computations with Lucid.
128
+
129
+ ## Notes
130
+
131
+ Lucid is built for learning and experimenting with deep learning concepts,
132
+ allowing users to see how operations like backpropagation, optimization,
133
+ and activation functions are implemented at a low level.
134
+
135
+ Lucid is lightweight, with no external dependencies beyond `NumPy`,
136
+ making it easy to install and use without complex setups or specialized hardware.
137
+
138
+ ## Limitations
139
+
140
+ Lucid does not aim to provide the high-level functionalities of production-ready frameworks.
141
+ Instead, it focuses on educational value and understanding how deep
142
+ learning models are built from scratch.
143
+
144
+ Performance optimizations that are available in specialized libraries may not be as
145
+ efficient in Lucid, as it is not optimized for production workloads.
146
+
147
+ ## Conclusion
148
+
149
+ Lucid provides a minimalistic, educational environment to learn about deep learning using only `NumPy`.
150
+ It gives users the tools to experiment with neural networks, automatic differentiation,
151
+ optimization, and other essential components of deep learning, all while providing insight into how
152
+ these operations are implemented at the core level.
153
+
154
+ For further information and usage details, refer to the documentation of specific modules like
155
+ lucid.nn and lucid.linalg.
@@ -0,0 +1,55 @@
1
+ """
2
+ # `Lucid `
3
+
4
+ **Lucid** is an educational deep learning framework developed to help users understand
5
+ the underlying mechanics of deep learning models and tensor operations.
6
+
7
+ It is designed to provide a simple yet powerful environment to experiment with neural networks,
8
+ optimization, and backpropagation using only `NumPy`.
9
+
10
+ Lucid is ideal for those who want to learn about the inner workings of deep learning
11
+ algorithms and operations without the complexity of high-level frameworks.
12
+
13
+ [📑 Lucid Documentation](https://chanlumerico.github.io/lucid/build/html/index.html)
14
+ """
15
+
16
+ from contextlib import contextmanager
17
+ from typing import Any, Generator
18
+ import numpy as np
19
+
20
+ from lucid._tensor import Tensor
21
+ from lucid._func import *
22
+ from lucid._util import *
23
+
24
+ from lucid.types import _ArrayOrScalar
25
+
26
+ import lucid.linalg as linalg
27
+ import lucid.random as random
28
+ import lucid.nn as nn
29
+
30
+ _grad_enabled: bool = True
31
+
32
+ newaxis = np.newaxis
33
+
34
+
35
+ def tensor(
36
+ data: Tensor | _ArrayOrScalar, requires_grad: bool = False, dtype: Any = np.float32
37
+ ) -> Tensor:
38
+ if isinstance(data, Tensor):
39
+ data = data.data
40
+ return Tensor(data, requires_grad, dtype)
41
+
42
+
43
+ @contextmanager
44
+ def no_grad() -> Generator:
45
+ global _grad_enabled
46
+ prev_state = _grad_enabled
47
+ _grad_enabled = False
48
+ try:
49
+ yield
50
+ finally:
51
+ _grad_enabled = prev_state
52
+
53
+
54
+ def grad_enabled() -> bool:
55
+ return _grad_enabled
@@ -0,0 +1,6 @@
1
+ from lucid._backend.func_op import (
2
+ _FuncOpReturnType,
3
+ create_func_op,
4
+ create_bfunc_op,
5
+ create_ufunc_op,
6
+ )
@@ -0,0 +1,104 @@
1
+ import functools
2
+ from typing import Callable, Tuple
3
+
4
+ import numpy as np
5
+
6
+ import lucid
7
+ from lucid._tensor import Tensor
8
+ from lucid.types import _NumPyArray, _ArrayOrScalar
9
+
10
+ _GradFuncType = Callable[[None], _NumPyArray | Tuple[_NumPyArray, ...]]
11
+
12
+ _ReturnGradFuncPair = Tuple[Tensor, _GradFuncType]
13
+
14
+ _FuncOpReturnType = _ReturnGradFuncPair | Tuple[_ReturnGradFuncPair, ...]
15
+
16
+
17
+ def _set_tensor_grad(tensor: Tensor, grad: _NumPyArray) -> None:
18
+ if tensor.requires_grad:
19
+ if tensor.grad is None:
20
+ tensor.grad = grad
21
+ else:
22
+ tensor.grad = tensor.grad + grad
23
+
24
+
25
+ def _check_is_tensor(any: Tensor | _ArrayOrScalar) -> Tensor:
26
+ if not isinstance(any, Tensor):
27
+ return Tensor(any)
28
+ return any
29
+
30
+
31
+ def _match_grad_shape(data: _NumPyArray, grad: _NumPyArray) -> _NumPyArray:
32
+ if data.shape == grad.shape:
33
+ return grad
34
+
35
+ if data.size == grad.size:
36
+ reshaped_grad = grad
37
+ elif data.size < grad.size:
38
+ axis = []
39
+ if data.ndim == 0:
40
+ axis.extend(range(grad.ndim))
41
+ else:
42
+ for ax in range(data.ndim):
43
+ if data.shape[ax] != grad.shape[ax] and data.shape[ax] == 1:
44
+ axis.append(ax)
45
+
46
+ reshaped_grad = np.sum(grad, axis=tuple(axis)).reshape(data.shape)
47
+ else:
48
+ reshaped_grad = np.broadcast_to(grad, data.shape)
49
+
50
+ return reshaped_grad
51
+
52
+
53
+ def create_func_op(n_in: int, n_ret: int, has_gradient: bool = True) -> callable:
54
+
55
+ def decorator(func: Callable[..., _FuncOpReturnType]) -> callable:
56
+ @functools.wraps(func)
57
+ def wrapper(*args, **kwargs) -> tuple[Tensor, ...]:
58
+ tensors: tuple[Tensor] = tuple()
59
+ requires_grad = False
60
+
61
+ for arg in args[:n_in]:
62
+ tensor = _check_is_tensor(arg)
63
+ tensors += (tensor,)
64
+ requires_grad = requires_grad or tensor.requires_grad
65
+
66
+ new_args = (*tensors, *args[n_in:])
67
+ func_return_pairs = func(*new_args, **kwargs)
68
+
69
+ if n_ret == 1:
70
+ func_return_pairs = (func_return_pairs,)
71
+
72
+ results: tuple[Tensor] = tuple()
73
+ for result, compute_grad in func_return_pairs:
74
+ result.requires_grad = requires_grad and has_gradient
75
+ results += (result,)
76
+
77
+ def _backward_op(*, _func: callable = compute_grad) -> None:
78
+ grads = _func()
79
+ if n_in == 1:
80
+ grads = (grads,)
81
+
82
+ for tensor, grad in zip(tensors, grads, strict=True):
83
+ new_grad = _match_grad_shape(tensor.data, grad)
84
+ _set_tensor_grad(tensor, new_grad)
85
+
86
+ if not lucid.grad_enabled():
87
+ continue
88
+
89
+ result._backward_op = _backward_op
90
+ result._prev = tensors
91
+
92
+ return results if n_ret > 1 else results[0]
93
+
94
+ return wrapper
95
+
96
+ return decorator
97
+
98
+
99
+ def create_bfunc_op(has_gradient: bool = True) -> callable:
100
+ return create_func_op(n_in=2, n_ret=1, has_gradient=has_gradient)
101
+
102
+
103
+ def create_ufunc_op(has_gradient: bool = True) -> callable:
104
+ return create_func_op(n_in=1, n_ret=1, has_gradient=has_gradient)