mlx.nn.Module
- class mlx.nn.Module
Base class for building neural networks with MLX.
All the layers provided in
mlx.nn.layers
subclass this class and your models should do the same.A
Module
can contain otherModule
instances ormlx.core.array
instances in arbitrary nesting of python lists or dicts. TheModule
then allows recursively extracting all themlx.core.array
instances usingmlx.nn.Module.parameters()
.In addition, the
Module
has the concept of trainable and non trainable parameters (called “frozen”). When usingmlx.nn.value_and_grad()
the gradients are returned only with respect to the trainable parameters. All arrays in a module are trainable unless they are added in the “frozen” set by callingfreeze()
.import mlx.core as mx import mlx.nn as nn class MyMLP(nn.Module): def __init__(self, in_dims: int, out_dims: int, hidden_dims: int = 16): super().__init__() self.in_proj = nn.Linear(in_dims, hidden_dims) self.out_proj = nn.Linear(hidden_dims, out_dims) def __call__(self, x): x = self.in_proj(x) x = mx.maximum(x, 0) return self.out_proj(x) model = MyMLP(2, 1) # All the model parameters are created but since MLX is lazy by # default, they are not evaluated yet. Calling `mx.eval` actually # allocates memory and initializes the parameters. mx.eval(model.parameters()) # Setting a parameter to a new value is as simply as accessing that # parameter and assigning a new array to it. model.in_proj.weight = model.in_proj.weight * 2 mx.eval(model.parameters())
- apply(map_fn: Callable[[array], array], filter_fn: Optional[Callable[[Module, str, Any], bool]] = None)
Map all the parameters using the provided
map_fn
and immediately update the module with the mapped parameters.For instance running
model.apply(lambda x: x.astype(mx.float16))
casts all parameters to 16 bit floats.- Parameters:
map_fn (Callable) – Maps an array to another array
filter_fn (Callable, optional) – Filter to select which arrays to map (default:
Module.valid_parameter_filter()
).
- apply_to_modules(apply_fn: Callable[[str, Module], Any])
Apply a function to all the modules in this instance (including this instance).
- Parameters:
apply_fn (Callable) – The function to apply to the modules.
- children()
Return the direct descendants of this Module instance.
- filter_and_map(filter_fn: Callable[[Module, str, Any], bool], map_fn: Optional[Callable] = None, is_leaf_fn: Optional[Callable[[Module, str, Any], bool]] = None)
Recursively filter the contents of the module using
filter_fn
, namely only select keys and values wherefilter_fn
returns true.This is used to implement
parameters()
andtrainable_parameters()
but it can also be used to extract any subset of the module’s parameters.- Parameters:
filter_fn (Callable) – Given a value, the key in which it is found and the containing module, decide whether to keep the value or drop it.
map_fn (Callable, optional) – Optionally transform the value before returning it.
is_leaf_fn (Callable, optional) – Given a value, the key in which it is found and the containing module decide if it is a leaf.
- Returns:
A dictionary containing the contents of the module recursively filtered
- freeze(*, recurse: bool = True, keys: Optional[Union[str, List[str]]] = None, strict: bool = False)
Freeze the Module’s parameters or some of them. Freezing a parameter means not computing gradients for it.
This function is idempotent ie freezing a frozen model is a noop.
For instance to only train the attention parameters from a transformer:
model = … model.freeze() model.apply_to_modules(lambda k, v: v.unfreeze() if k.endswith(“attention”) else None)
- Parameters:
recurse (bool, optional) – If True then freeze the parameters of the submodules as well (default: True).
keys (str or list[str], optional) – If provided then only these parameters will be frozen otherwise all the parameters of a module. For instance freeze all biases by calling
module.freeze(keys="bias")
.strict (bool, optional) – If set to True validate that the passed keys exist (default: False).
- leaf_modules()
Return the submodules that do not contain other modules.
- modules()
Return a list with all the modules in this instance.
- Returns:
A list of
mlx.nn.Module
instances.
- named_modules()
Return a list with all the modules in this instance and their name with dot notation.
- Returns:
A list of tuples (str,
mlx.nn.Module
).
- parameters()
Recursively return all the
mlx.core.array
members of this Module as a dict of dicts and lists.
- trainable_parameters()
Recursively return all the non frozen
mlx.core.array
members of this Module as a dict of dicts and lists.
- unfreeze(*, recurse: bool = True, keys: Optional[Union[str, List[str]]] = None, strict: bool = False)
Unfreeze the Module’s parameters or some of them.
This function is idempotent ie unfreezing a model that is not frozen is a noop.
For instance to only train the biases one can do:
model = … model.freeze() model.unfreeze(keys=”bias”)
- Parameters:
recurse (bool, optional) – If True then unfreeze the parameters of the submodules as well (default: True).
keys (str or list[str], optional) – If provided then only these parameters will be unfrozen otherwise all the parameters of a module. For instance unfreeze all biases by calling
module.unfreeze(keys="bias")
.strict (bool, optional) – If set to True validate that the passed keys exist (default: False).
- update(parameters: dict)
Replace the parameters of this Module with the provided ones in the dict of dicts and lists.
Commonly used by the optimizer to change the model to the updated (optimized) parameters. Also used by the
mlx.nn.value_and_grad()
to set the tracers in the model in order to compute gradients.The passed in parameters dictionary need not be a full dictionary similar to
parameters()
. Only the provided locations will be updated.- Parameters:
parameters (dict) – A complete or partial dictionary of the modules parameters.