utorch.nn
utorch.nn
Neural network components, modules, layers, losses, and optimizers.
__all__
module-attribute
__all__ = [
"SGD",
"CrossEntropyLoss",
"Linear",
"MSELoss",
"Module",
"Optimizer",
"Parameter",
"ReLU",
"Sequential",
"Sigmoid",
]
CrossEntropyLoss
Bases: Module
Cross-Entropy loss with logits using numerically stable LogSumExp.
Computes negative log-likelihood without requiring keepdims or ops changes
loss = - mean( sum( target * log_softmax(logits), axis=-1 ) )
forward
Compute negative log-likelihood without requiring keepdims or ops changes.
Source code in utorch/nn/loss.py
Linear
Bases: Module
Fully connected linear transformation layer: Y = X @ W^T + b.
Weights are initialized using Kaiming (He) uniform initialization: W ~ Uniform(-1 / sqrt(in_features), 1 / sqrt(in_features))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_features
|
int
|
Number of input features (D_in). |
required |
out_features
|
int
|
Number of output features (D_out). |
required |
bias
|
bool
|
If True, adds a learnable bias vector of shape (D_out,). |
True
|
Initialize a Linear layer.
Source code in utorch/nn/layers.py
MSELoss
Bases: Module
Mean Squared Error (L2) loss: L = mean((pred - target)^2).
Module
Base class for all neural network modules and layers.
Custom models should subclass Module and implement forward().
Modules automatically register child Module instances and Parameter
attributes, enabling recursive traversal via parameters().
Examples:
import utorch as ut
import utorch.nn as nn
class TwoLayerMLP(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 128)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
return self.fc2(self.relu(self.fc1(x)))
model = TwoLayerMLP()
print(len(model.parameters())) # 4 (fc1.weight, fc1.bias, fc2.weight, fc2.bias)
__call__
forward
Execute forward pass computation. Subclasses must override this.
num_parameters
parameters
Return an ordered list of all trainable Parameters in this module.
Recursively discovers parameters stored as direct attributes, inside
lists/tuples, or within child Module submodules.
Source code in utorch/nn/module.py
Optimizer
Base class for all parameter optimizers.
Initialize a parameter optimizer.
Source code in utorch/nn/optim.py
step
Parameter
Bases: Tensor
A Tensor designated as a trainable model parameter.
Parameters are automatically detected and registered by nn.Module instances
when assigned as attributes, making them discoverable via module.parameters().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
Numerical data (NumPy array, nested list, or scalar). |
required |
name
|
str | None
|
Optional human-readable identifier for diagramming and debugging. |
None
|
Examples:
import numpy as np
import utorch as ut
from utorch.nn import Parameter
# Initialize a trainable weight matrix
w = Parameter(np.random.randn(3, 2), name="weight")
print(isinstance(w, ut.Tensor)) # True
Initialize a model parameter.
Source code in utorch/nn/parameter.py
ReLU
SGD
Bases: Optimizer
Stochastic Gradient Descent optimizer with optional classical momentum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
Iterable[Parameter]
|
Iterable of parameters to optimize. |
required |
lr
|
float
|
Learning rate. |
0.01
|
momentum
|
float
|
Momentum factor (default: 0.0). |
0.0
|
Initialize SGD optimizer.
Source code in utorch/nn/optim.py
step
Perform a single parameter update step.
Source code in utorch/nn/optim.py
Sequential
Sigmoid
layers
Neural network layers, activation modules, and sequential containers.
Linear
Bases: Module
Fully connected linear transformation layer: Y = X @ W^T + b.
Weights are initialized using Kaiming (He) uniform initialization: W ~ Uniform(-1 / sqrt(in_features), 1 / sqrt(in_features))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_features
|
int
|
Number of input features (D_in). |
required |
out_features
|
int
|
Number of output features (D_out). |
required |
bias
|
bool
|
If True, adds a learnable bias vector of shape (D_out,). |
True
|
Initialize a Linear layer.
Source code in utorch/nn/layers.py
ReLU
loss
Loss functions for training neural networks.
CrossEntropyLoss
Bases: Module
Cross-Entropy loss with logits using numerically stable LogSumExp.
Computes negative log-likelihood without requiring keepdims or ops changes
loss = - mean( sum( target * log_softmax(logits), axis=-1 ) )
forward
Compute negative log-likelihood without requiring keepdims or ops changes.
Source code in utorch/nn/loss.py
MSELoss
Bases: Module
Mean Squared Error (L2) loss: L = mean((pred - target)^2).
module
Base Module class for neural network layers and architectures.
Module
Base class for all neural network modules and layers.
Custom models should subclass Module and implement forward().
Modules automatically register child Module instances and Parameter
attributes, enabling recursive traversal via parameters().
Examples:
import utorch as ut
import utorch.nn as nn
class TwoLayerMLP(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 128)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
return self.fc2(self.relu(self.fc1(x)))
model = TwoLayerMLP()
print(len(model.parameters())) # 4 (fc1.weight, fc1.bias, fc2.weight, fc2.bias)
__call__
forward
Execute forward pass computation. Subclasses must override this.
num_parameters
parameters
Return an ordered list of all trainable Parameters in this module.
Recursively discovers parameters stored as direct attributes, inside
lists/tuples, or within child Module submodules.
Source code in utorch/nn/module.py
optim
Optimization algorithms for updating model parameters.
Optimizer
Base class for all parameter optimizers.
Initialize a parameter optimizer.
Source code in utorch/nn/optim.py
step
SGD
Bases: Optimizer
Stochastic Gradient Descent optimizer with optional classical momentum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
Iterable[Parameter]
|
Iterable of parameters to optimize. |
required |
lr
|
float
|
Learning rate. |
0.01
|
momentum
|
float
|
Momentum factor (default: 0.0). |
0.0
|
Initialize SGD optimizer.
Source code in utorch/nn/optim.py
step
Perform a single parameter update step.
Source code in utorch/nn/optim.py
parameter
Trainable network parameter abstraction.
Parameter
Bases: Tensor
A Tensor designated as a trainable model parameter.
Parameters are automatically detected and registered by nn.Module instances
when assigned as attributes, making them discoverable via module.parameters().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
Numerical data (NumPy array, nested list, or scalar). |
required |
name
|
str | None
|
Optional human-readable identifier for diagramming and debugging. |
None
|
Examples:
import numpy as np
import utorch as ut
from utorch.nn import Parameter
# Initialize a trainable weight matrix
w = Parameter(np.random.randn(3, 2), name="weight")
print(isinstance(w, ut.Tensor)) # True
Initialize a model parameter.