parallel-metalearn 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.
- parallel_metalearn-0.1.0/LICENSE +21 -0
- parallel_metalearn-0.1.0/PKG-INFO +163 -0
- parallel_metalearn-0.1.0/README.md +140 -0
- parallel_metalearn-0.1.0/metalearn/__init__.py +0 -0
- parallel_metalearn-0.1.0/metalearn/algorithms/BaseLearner.py +57 -0
- parallel_metalearn-0.1.0/metalearn/algorithms/MAML.py +366 -0
- parallel_metalearn-0.1.0/metalearn/algorithms/MetaUtils.py +30 -0
- parallel_metalearn-0.1.0/metalearn/algorithms/__init__.py +2 -0
- parallel_metalearn-0.1.0/metalearn/dataset/Scalers.py +327 -0
- parallel_metalearn-0.1.0/metalearn/dataset/__init__.py +2 -0
- parallel_metalearn-0.1.0/metalearn/dataset/classification_task.py +485 -0
- parallel_metalearn-0.1.0/metalearn/file_manager/FileHandle.py +257 -0
- parallel_metalearn-0.1.0/metalearn/file_manager/__init__.py +0 -0
- parallel_metalearn-0.1.0/metalearn/inner_optimizers/SGD.py +48 -0
- parallel_metalearn-0.1.0/metalearn/inner_optimizers/__init__.py +2 -0
- parallel_metalearn-0.1.0/metalearn/inner_optimizers/base.py +132 -0
- parallel_metalearn-0.1.0/metalearn/loss/CEloss.py +51 -0
- parallel_metalearn-0.1.0/metalearn/loss/Encoder.py +99 -0
- parallel_metalearn-0.1.0/metalearn/loss/__init__.py +4 -0
- parallel_metalearn-0.1.0/metalearn/loss/base.py +34 -0
- parallel_metalearn-0.1.0/metalearn/loss/categorical_accuracy.py +35 -0
- parallel_metalearn-0.1.0/metalearn/model_wrappers/MAMLWrapper.py +179 -0
- parallel_metalearn-0.1.0/metalearn/model_wrappers/__init__.py +1 -0
- parallel_metalearn-0.1.0/metalearn/nn_models/CNN2D4L.py +78 -0
- parallel_metalearn-0.1.0/metalearn/nn_models/ModelUtils.py +8 -0
- parallel_metalearn-0.1.0/metalearn/nn_models/__init__.py +1 -0
- parallel_metalearn-0.1.0/metalearn/nn_models/basic_layers/BatchNormalization.py +127 -0
- parallel_metalearn-0.1.0/metalearn/nn_models/basic_layers/__init__.py +1 -0
- parallel_metalearn-0.1.0/metalearn/train/MetaTrain.py +360 -0
- parallel_metalearn-0.1.0/metalearn/train/Utils.py +143 -0
- parallel_metalearn-0.1.0/metalearn/train/__init__.py +1 -0
- parallel_metalearn-0.1.0/parallel_metalearn.egg-info/PKG-INFO +163 -0
- parallel_metalearn-0.1.0/parallel_metalearn.egg-info/SOURCES.txt +36 -0
- parallel_metalearn-0.1.0/parallel_metalearn.egg-info/dependency_links.txt +1 -0
- parallel_metalearn-0.1.0/parallel_metalearn.egg-info/requires.txt +3 -0
- parallel_metalearn-0.1.0/parallel_metalearn.egg-info/top_level.txt +1 -0
- parallel_metalearn-0.1.0/pyproject.toml +46 -0
- parallel_metalearn-0.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ali Razani
|
|
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,163 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: parallel-metalearn
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A high-performance, vmap-accelerated functional meta-learning framework built natively on PyTorch.
|
|
5
|
+
Author: Ali Razani
|
|
6
|
+
Project-URL: Homepage, https://github.com/Razani-Ali/parallel-metalearn
|
|
7
|
+
Project-URL: Bug Tracker, https://github.com/Razani-Ali/parallel-metalearn/issues
|
|
8
|
+
Keywords: meta-learning,maml,anil,few-shot-learning,pytorch,vmap,functional-api,fault-diagnosis,deep-learning
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Science/Research
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: torch>=2.5.0
|
|
20
|
+
Requires-Dist: numpy>=2.0.0
|
|
21
|
+
Requires-Dist: tqdm>=4.60.0
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# π Parallel-MetaLearn: Blazing-Fast, VMAP-Powered Functional Meta-Learning for PyTorch
|
|
27
|
+
|
|
28
|
+
**Stop writing slow `for` loops over your meta-batches. Stop rewriting your PyTorch models into awkward functional syntax.**
|
|
29
|
+
|
|
30
|
+
MetaLearn is a next-generation, high-performance meta-learning framework built natively on top of PyTorch 2.0+ `torch.func`. Designed for researchers and production engineers, it delivers **massive speedups** by vectorizing the outer-loop task processing while keeping your code clean, modular, and purely object-oriented.
|
|
31
|
+
|
|
32
|
+
Whether you are doing Few-Shot Classification, Domain Adaptation, Semantic Segmentation, or Regression, MetaLearn adapts to your taskβnot the other way around.
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## π₯ Why Choose Parallel-MetaLearn? (The Game Changers)
|
|
37
|
+
|
|
38
|
+
Existing libraries (like `learn2learn` or `higher`) force you into difficult compromises: they either use sequential `for` loops that bottleneck your GPU, or they require you to completely rewrite your model's forward pass to accept explicit parameters (e.g., `torch.functional.conv1d(x, weight=params['w'])`).
|
|
39
|
+
|
|
40
|
+
**MetaLearn solves all of this:**
|
|
41
|
+
|
|
42
|
+
* β‘ **True Parallelism via `vmap`:** We eliminated the task `for` loop. By leveraging PyTorch's `vmap`, MetaLearn processes the entire meta-batch simultaneously. Expect speedups directly proportional to your task batch size (e.g., up to **Q-times faster** where Q is the number of tasks).
|
|
43
|
+
* π§ **Zero-Friction Model Definitions:** Write your `nn.Module` exactly as you normally would. No need to pass parameter dictionaries into your `forward()` method. We handle the stateless functional calls completely under the hood.
|
|
44
|
+
* π **Dynamic Task Imbalance & Masking:** `vmap` usually crashes if tasks have different batch sizes. We engineered a robust **Masking & Padding engine** under the hood. You can now train on highly imbalanced tasks (`support_shot=(min_shot,max_shot)`) without breaking vectorization!
|
|
45
|
+
* π― **Class-Agnostic & Class-Specific Modes:** Seamlessly switch between Class-Agnostic encoding (perfect for Out-Of-Distribution (OOD) generalization to unseen classes) and standard Class-Specific targets.
|
|
46
|
+
* π§© **Task-Agnostic Architecture:** MetaLearn doesn't care if you are doing Classification, Regression, or Segmentation. Just swap out the Dataset and Loss classes. The core MAML remain 100% untouched.
|
|
47
|
+
* β±οΈ **Step-Aware Inner Loop:** Your inner models and optimizers can be fully aware of the current gradient step, allowing for per-step learning rates and independent buffer management (crucial for MAML++).
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## π οΈ Supported Algorithms
|
|
52
|
+
|
|
53
|
+
Currently, the library natively supports the most powerful gradient-based meta-learning algorithms out of the box:
|
|
54
|
+
|
|
55
|
+
* β
**MAML** (Model-Agnostic Meta-Learning)
|
|
56
|
+
* β
**FOMAML** (First Order MAML)
|
|
57
|
+
* β
**ANIL** (Almost No Inner Loop)
|
|
58
|
+
* β
**Meta-SGD** (Learnable inner learning rates)
|
|
59
|
+
* β
**MAML++** (Multi-Step Loss Optimization & Per-step parameters)
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
## π¦ Core Features at a Glance
|
|
64
|
+
|
|
65
|
+
* **Customizable Data Pipelines:** Use our highly flexible `MetaTaskDataset` to randomly or deterministically sample N-way K-shot tasks, or easily subclass it for your own custom data logic.
|
|
66
|
+
* **Plug-and-Play Optimizers:** Build your own custom Inner-Optimizers effortlessly, and use any standard PyTorch optimizer (Adam, SGD, etc.) for the Outer-Loop.
|
|
67
|
+
* **Automated Pipeline:** Say goodbye to boilerplate code. Our `MetaTrain` engine automatically handles the meta-training loop, validation intervals, metric logging, early stopping, and checkpoint saving.
|
|
68
|
+
|
|
69
|
+
---
|
|
70
|
+
|
|
71
|
+
## π Quick Start
|
|
72
|
+
|
|
73
|
+
The complete pipeline works out of the box. Check out `main.py` for a fully working example on the CWRU Fault Diagnosis dataset. Here is how simple it is to initialize and train:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
import torch
|
|
77
|
+
from metalearn.model_wrappers import MAML_Model
|
|
78
|
+
from metalearn.loss import LabelEncoder, CrossEntropy, CategoricalAccuracy
|
|
79
|
+
from metalearn.inner_optimizers import InnerSGD
|
|
80
|
+
from metalearn.algorithms import MAML
|
|
81
|
+
from metalearn.train import MetaTrain
|
|
82
|
+
|
|
83
|
+
# 1. Define your standard PyTorch models (No functional rewrites needed!)
|
|
84
|
+
backbone = MyCNNBackbone()
|
|
85
|
+
head = MyLinearHead()
|
|
86
|
+
model = MAML_Model(backbone=backbone, head=head, drop_rate=0.5)
|
|
87
|
+
|
|
88
|
+
# 2. Setup Class-Agnostic Encoding & Loss
|
|
89
|
+
label_encoder = LabelEncoder(num_classes=10, max_n_way=3, shuffle=True)
|
|
90
|
+
loss_fn = CrossEntropy(metric_fn=CategoricalAccuracy())
|
|
91
|
+
|
|
92
|
+
# 3. Define Optimizers
|
|
93
|
+
inner_optimizer = InnerSGD(initial_fast_weights=model.get_fast_weights(), inner_lr=0.01)
|
|
94
|
+
outer_optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
|
|
95
|
+
|
|
96
|
+
# 4. Initialize Algorithm (MAML, ANIL, MAML++, etc.)
|
|
97
|
+
algorithm = MAML(
|
|
98
|
+
model=model,
|
|
99
|
+
optimizer=outer_optimizer,
|
|
100
|
+
inner_optimizer=inner_optimizer,
|
|
101
|
+
support_loss_fn=loss_fn,
|
|
102
|
+
encoder=label_encoder,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
# 5. Train with Automated Logging & Checkpointing!
|
|
106
|
+
trainer = MetaTrain(
|
|
107
|
+
TrainLoader=train_loader,
|
|
108
|
+
ValLoader=val_loader,
|
|
109
|
+
algorithm=algorithm
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
history, best_metric, best_loss = trainer.train(
|
|
113
|
+
epochs=1500,
|
|
114
|
+
check_idx=10,
|
|
115
|
+
log_checkpoint_path="logs"
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
---
|
|
121
|
+
|
|
122
|
+
## πΊοΈ Roadmap (Upcoming Features)
|
|
123
|
+
|
|
124
|
+
We are constantly pushing the boundaries of what is possible in functional meta-learning. In our upcoming releases, look forward to:
|
|
125
|
+
|
|
126
|
+
* **Recurrent Network Support:** Native, `vmap`-safe support for `LSTM` and `GRU` layers.
|
|
127
|
+
* **Advanced Noise Management:** Robust meta-learning under input perturbations.
|
|
128
|
+
* **New Meta-Algorithms:** Integration of cutting-edge algorithms (e.g., ProtoMAML, Reptile).
|
|
129
|
+
* **New Inner Optimizers:** Second-order approximation optimizers and adaptive inner-loop schedulers.
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
## π οΈ Unmatched Extensibility for Researchers (Developer Guide)
|
|
134
|
+
|
|
135
|
+
MetaLearn is architected around **strict separation of concerns**. The core MAML execution engine operates purely on standardized output dictionaries (`out_dict`) and target dictionaries (`targets`). This means you can extend MetaLearn to cutting-edge research paradigms **without ever touching the core MAML execution loop or `vmap` logic**:
|
|
136
|
+
|
|
137
|
+
### 1. π Multi-Task Learning (MTL)
|
|
138
|
+
Need joint classification and auxiliary regression/reconstruction?
|
|
139
|
+
* **Data:** Return auxiliary targets alongside labels in `MetaTaskDataset` (e.g., `y_dict = {"labels": y, "reg_targets": reg_y}`).
|
|
140
|
+
* **Loss:** Subclass `BaseLoss` to compute composite loss (`cls_loss + lambda * reg_loss`).
|
|
141
|
+
* *MAML engine automatically propagates gradients across all tasks!*
|
|
142
|
+
|
|
143
|
+
### 2. π Meta-Domain Adaptation (MDA)
|
|
144
|
+
Want to align feature distributions across shifting domains?
|
|
145
|
+
* **Data:** Pass domain indicators inside your dataset targets (e.g., `y_dict = {"labels": y, "domain_id": d}`).
|
|
146
|
+
* **Loss:** Extract features from `out_dict["features"]` and compute domain alignment loss (e.g., MMD, Wasserstein Distance, or Adversarial Loss) inside your custom Loss class.
|
|
147
|
+
|
|
148
|
+
### 3. π Federated Meta-Learning (FedMeta)
|
|
149
|
+
Want to simulate decentralized client adaptation or privacy-preserving meta-learning?
|
|
150
|
+
* **Data & Algorithm:** Keep the same functional `MAML` step, but customize the task assignment logic to simulate client-side local updates before global aggregation.
|
|
151
|
+
|
|
152
|
+
### 4. π Federated Learning (FedAvg, FedGrad, FedProx) & FedMeta
|
|
153
|
+
Because MetaLearn processes inner-loop updates in a stateless, functional manner, you can effortlessly simulate **Pure Federated Learning algorithms** (e.g., FedAvg, FedGrad) alongside **Federated Meta-Learning (FedMeta)**:
|
|
154
|
+
* **Parallel Client Simulation via `vmap`:** Instead of sequentially looping through individual clients, MetaLearn simulates dozens of local client updates *simultaneously* on the GPU using `vmap`.
|
|
155
|
+
* **Zero-Overhead Aggregation:** Extract adapted local parameters $\theta_i'$ from each client task, perform global server aggregation (e.g., weighted averaging via `torch.stack(client_weights).mean(dim=0)`), and seamlessly set the new global start state for the next communication round.
|
|
156
|
+
|
|
157
|
+
---
|
|
158
|
+
|
|
159
|
+
## π€ Contributing & Citation
|
|
160
|
+
|
|
161
|
+
If you use MetaLearn in your research or production pipelines, we'd love to hear about it! Contributions, issues, and feature requests are always welcome.
|
|
162
|
+
|
|
163
|
+
> *Fully functional example available in `main.py`.* Just run `python main.py` and watch the `vmap` magic happen!
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
# π Parallel-MetaLearn: Blazing-Fast, VMAP-Powered Functional Meta-Learning for PyTorch
|
|
4
|
+
|
|
5
|
+
**Stop writing slow `for` loops over your meta-batches. Stop rewriting your PyTorch models into awkward functional syntax.**
|
|
6
|
+
|
|
7
|
+
MetaLearn is a next-generation, high-performance meta-learning framework built natively on top of PyTorch 2.0+ `torch.func`. Designed for researchers and production engineers, it delivers **massive speedups** by vectorizing the outer-loop task processing while keeping your code clean, modular, and purely object-oriented.
|
|
8
|
+
|
|
9
|
+
Whether you are doing Few-Shot Classification, Domain Adaptation, Semantic Segmentation, or Regression, MetaLearn adapts to your taskβnot the other way around.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## π₯ Why Choose Parallel-MetaLearn? (The Game Changers)
|
|
14
|
+
|
|
15
|
+
Existing libraries (like `learn2learn` or `higher`) force you into difficult compromises: they either use sequential `for` loops that bottleneck your GPU, or they require you to completely rewrite your model's forward pass to accept explicit parameters (e.g., `torch.functional.conv1d(x, weight=params['w'])`).
|
|
16
|
+
|
|
17
|
+
**MetaLearn solves all of this:**
|
|
18
|
+
|
|
19
|
+
* β‘ **True Parallelism via `vmap`:** We eliminated the task `for` loop. By leveraging PyTorch's `vmap`, MetaLearn processes the entire meta-batch simultaneously. Expect speedups directly proportional to your task batch size (e.g., up to **Q-times faster** where Q is the number of tasks).
|
|
20
|
+
* π§ **Zero-Friction Model Definitions:** Write your `nn.Module` exactly as you normally would. No need to pass parameter dictionaries into your `forward()` method. We handle the stateless functional calls completely under the hood.
|
|
21
|
+
* π **Dynamic Task Imbalance & Masking:** `vmap` usually crashes if tasks have different batch sizes. We engineered a robust **Masking & Padding engine** under the hood. You can now train on highly imbalanced tasks (`support_shot=(min_shot,max_shot)`) without breaking vectorization!
|
|
22
|
+
* π― **Class-Agnostic & Class-Specific Modes:** Seamlessly switch between Class-Agnostic encoding (perfect for Out-Of-Distribution (OOD) generalization to unseen classes) and standard Class-Specific targets.
|
|
23
|
+
* π§© **Task-Agnostic Architecture:** MetaLearn doesn't care if you are doing Classification, Regression, or Segmentation. Just swap out the Dataset and Loss classes. The core MAML remain 100% untouched.
|
|
24
|
+
* β±οΈ **Step-Aware Inner Loop:** Your inner models and optimizers can be fully aware of the current gradient step, allowing for per-step learning rates and independent buffer management (crucial for MAML++).
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## π οΈ Supported Algorithms
|
|
29
|
+
|
|
30
|
+
Currently, the library natively supports the most powerful gradient-based meta-learning algorithms out of the box:
|
|
31
|
+
|
|
32
|
+
* β
**MAML** (Model-Agnostic Meta-Learning)
|
|
33
|
+
* β
**FOMAML** (First Order MAML)
|
|
34
|
+
* β
**ANIL** (Almost No Inner Loop)
|
|
35
|
+
* β
**Meta-SGD** (Learnable inner learning rates)
|
|
36
|
+
* β
**MAML++** (Multi-Step Loss Optimization & Per-step parameters)
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## π¦ Core Features at a Glance
|
|
41
|
+
|
|
42
|
+
* **Customizable Data Pipelines:** Use our highly flexible `MetaTaskDataset` to randomly or deterministically sample N-way K-shot tasks, or easily subclass it for your own custom data logic.
|
|
43
|
+
* **Plug-and-Play Optimizers:** Build your own custom Inner-Optimizers effortlessly, and use any standard PyTorch optimizer (Adam, SGD, etc.) for the Outer-Loop.
|
|
44
|
+
* **Automated Pipeline:** Say goodbye to boilerplate code. Our `MetaTrain` engine automatically handles the meta-training loop, validation intervals, metric logging, early stopping, and checkpoint saving.
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## π Quick Start
|
|
49
|
+
|
|
50
|
+
The complete pipeline works out of the box. Check out `main.py` for a fully working example on the CWRU Fault Diagnosis dataset. Here is how simple it is to initialize and train:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
import torch
|
|
54
|
+
from metalearn.model_wrappers import MAML_Model
|
|
55
|
+
from metalearn.loss import LabelEncoder, CrossEntropy, CategoricalAccuracy
|
|
56
|
+
from metalearn.inner_optimizers import InnerSGD
|
|
57
|
+
from metalearn.algorithms import MAML
|
|
58
|
+
from metalearn.train import MetaTrain
|
|
59
|
+
|
|
60
|
+
# 1. Define your standard PyTorch models (No functional rewrites needed!)
|
|
61
|
+
backbone = MyCNNBackbone()
|
|
62
|
+
head = MyLinearHead()
|
|
63
|
+
model = MAML_Model(backbone=backbone, head=head, drop_rate=0.5)
|
|
64
|
+
|
|
65
|
+
# 2. Setup Class-Agnostic Encoding & Loss
|
|
66
|
+
label_encoder = LabelEncoder(num_classes=10, max_n_way=3, shuffle=True)
|
|
67
|
+
loss_fn = CrossEntropy(metric_fn=CategoricalAccuracy())
|
|
68
|
+
|
|
69
|
+
# 3. Define Optimizers
|
|
70
|
+
inner_optimizer = InnerSGD(initial_fast_weights=model.get_fast_weights(), inner_lr=0.01)
|
|
71
|
+
outer_optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
|
|
72
|
+
|
|
73
|
+
# 4. Initialize Algorithm (MAML, ANIL, MAML++, etc.)
|
|
74
|
+
algorithm = MAML(
|
|
75
|
+
model=model,
|
|
76
|
+
optimizer=outer_optimizer,
|
|
77
|
+
inner_optimizer=inner_optimizer,
|
|
78
|
+
support_loss_fn=loss_fn,
|
|
79
|
+
encoder=label_encoder,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
# 5. Train with Automated Logging & Checkpointing!
|
|
83
|
+
trainer = MetaTrain(
|
|
84
|
+
TrainLoader=train_loader,
|
|
85
|
+
ValLoader=val_loader,
|
|
86
|
+
algorithm=algorithm
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
history, best_metric, best_loss = trainer.train(
|
|
90
|
+
epochs=1500,
|
|
91
|
+
check_idx=10,
|
|
92
|
+
log_checkpoint_path="logs"
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
---
|
|
98
|
+
|
|
99
|
+
## πΊοΈ Roadmap (Upcoming Features)
|
|
100
|
+
|
|
101
|
+
We are constantly pushing the boundaries of what is possible in functional meta-learning. In our upcoming releases, look forward to:
|
|
102
|
+
|
|
103
|
+
* **Recurrent Network Support:** Native, `vmap`-safe support for `LSTM` and `GRU` layers.
|
|
104
|
+
* **Advanced Noise Management:** Robust meta-learning under input perturbations.
|
|
105
|
+
* **New Meta-Algorithms:** Integration of cutting-edge algorithms (e.g., ProtoMAML, Reptile).
|
|
106
|
+
* **New Inner Optimizers:** Second-order approximation optimizers and adaptive inner-loop schedulers.
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
## π οΈ Unmatched Extensibility for Researchers (Developer Guide)
|
|
111
|
+
|
|
112
|
+
MetaLearn is architected around **strict separation of concerns**. The core MAML execution engine operates purely on standardized output dictionaries (`out_dict`) and target dictionaries (`targets`). This means you can extend MetaLearn to cutting-edge research paradigms **without ever touching the core MAML execution loop or `vmap` logic**:
|
|
113
|
+
|
|
114
|
+
### 1. π Multi-Task Learning (MTL)
|
|
115
|
+
Need joint classification and auxiliary regression/reconstruction?
|
|
116
|
+
* **Data:** Return auxiliary targets alongside labels in `MetaTaskDataset` (e.g., `y_dict = {"labels": y, "reg_targets": reg_y}`).
|
|
117
|
+
* **Loss:** Subclass `BaseLoss` to compute composite loss (`cls_loss + lambda * reg_loss`).
|
|
118
|
+
* *MAML engine automatically propagates gradients across all tasks!*
|
|
119
|
+
|
|
120
|
+
### 2. π Meta-Domain Adaptation (MDA)
|
|
121
|
+
Want to align feature distributions across shifting domains?
|
|
122
|
+
* **Data:** Pass domain indicators inside your dataset targets (e.g., `y_dict = {"labels": y, "domain_id": d}`).
|
|
123
|
+
* **Loss:** Extract features from `out_dict["features"]` and compute domain alignment loss (e.g., MMD, Wasserstein Distance, or Adversarial Loss) inside your custom Loss class.
|
|
124
|
+
|
|
125
|
+
### 3. π Federated Meta-Learning (FedMeta)
|
|
126
|
+
Want to simulate decentralized client adaptation or privacy-preserving meta-learning?
|
|
127
|
+
* **Data & Algorithm:** Keep the same functional `MAML` step, but customize the task assignment logic to simulate client-side local updates before global aggregation.
|
|
128
|
+
|
|
129
|
+
### 4. π Federated Learning (FedAvg, FedGrad, FedProx) & FedMeta
|
|
130
|
+
Because MetaLearn processes inner-loop updates in a stateless, functional manner, you can effortlessly simulate **Pure Federated Learning algorithms** (e.g., FedAvg, FedGrad) alongside **Federated Meta-Learning (FedMeta)**:
|
|
131
|
+
* **Parallel Client Simulation via `vmap`:** Instead of sequentially looping through individual clients, MetaLearn simulates dozens of local client updates *simultaneously* on the GPU using `vmap`.
|
|
132
|
+
* **Zero-Overhead Aggregation:** Extract adapted local parameters $\theta_i'$ from each client task, perform global server aggregation (e.g., weighted averaging via `torch.stack(client_weights).mean(dim=0)`), and seamlessly set the new global start state for the next communication round.
|
|
133
|
+
|
|
134
|
+
---
|
|
135
|
+
|
|
136
|
+
## π€ Contributing & Citation
|
|
137
|
+
|
|
138
|
+
If you use MetaLearn in your research or production pipelines, we'd love to hear about it! Contributions, issues, and feature requests are always welcome.
|
|
139
|
+
|
|
140
|
+
> *Fully functional example available in `main.py`.* Just run `python main.py` and watch the `vmap` magic happen!
|
|
File without changes
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import Tuple, Any, Dict, Optional
|
|
3
|
+
import torch
|
|
4
|
+
import torch.nn as nn
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class MetaOptimizer(nn.Module, ABC):
|
|
8
|
+
"""
|
|
9
|
+
Abstract Base Class for all Meta-Learning Algorithms (e.g., MAML, ProtoNet).
|
|
10
|
+
|
|
11
|
+
Establishes a unified interface for meta-training/evaluation steps
|
|
12
|
+
and test-time adaptation/deployment.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(self):
|
|
16
|
+
super().__init__()
|
|
17
|
+
|
|
18
|
+
@abstractmethod
|
|
19
|
+
def step(
|
|
20
|
+
self,
|
|
21
|
+
task_loader: Any,
|
|
22
|
+
training: bool = True,
|
|
23
|
+
**kwargs: Any
|
|
24
|
+
) -> Tuple[float, float]:
|
|
25
|
+
"""
|
|
26
|
+
Executes a single meta-training or meta-validation step over a batch of tasks.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
task_loader: Dataloader/Iterable yielding batches of tasks
|
|
30
|
+
(typically yielding Xs, Ys, Xq, Yq).
|
|
31
|
+
training (bool): If True, computes meta-gradients and updates outer model parameters.
|
|
32
|
+
**kwargs: Additional contextual arguments (e.g., epoch, inner_steps override).
|
|
33
|
+
|
|
34
|
+
Returns:
|
|
35
|
+
Tuple[float, float]: A tuple containing:
|
|
36
|
+
- mean_meta_loss (float): Average meta-loss value across the batch of tasks.
|
|
37
|
+
- mean_metric (float): Average evaluation metric (e.g., accuracy) across tasks.
|
|
38
|
+
"""
|
|
39
|
+
pass
|
|
40
|
+
|
|
41
|
+
@abstractmethod
|
|
42
|
+
def adapt_and_update(
|
|
43
|
+
self,
|
|
44
|
+
Xsupport: torch.Tensor,
|
|
45
|
+
Ysupport: torch.Tensor,
|
|
46
|
+
**kwargs: Any
|
|
47
|
+
) -> None:
|
|
48
|
+
"""
|
|
49
|
+
Adapts parameters on the provided support set and permanently updates the internal model.
|
|
50
|
+
Intended exclusively for test-time adaptation, fine-tuning, or deployment.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
Xsupport (torch.Tensor): Support set inputs of shape (num_tasks, K_support, ...).
|
|
54
|
+
Ysupport (torch.Tensor): Support set targets of shape (num_tasks, K_support, ...).
|
|
55
|
+
**kwargs: Additional context arguments (e.g., custom inner adaptation steps).
|
|
56
|
+
"""
|
|
57
|
+
pass
|