Metadata-Version: 2.4
Name: malet
Version: 0.2.2
Summary: Malet: a tool for machine learning experiment
Author-email: Dongyeop Lee <dylee23@postech.ac.kr>
License: Copyright (c) 2023 Dongyeop Lee
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
Project-URL: Repository, https://github.com/dongyeoplee2/Malet.git
Project-URL: Documentation, https://dongyeoplee2.github.io/Malet/
Keywords: machine learning,experiment,plot
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: absl-py>=1.0.0
Requires-Dist: gitpython
Requires-Dist: pandas
Requires-Dist: matplotlib
Requires-Dist: ml-collections>=0.1.0
Requires-Dist: numpy
Requires-Dist: rich
Requires-Dist: seaborn
Dynamic: license-file

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="docs/_static/logo/malet_white.svg">
    <source media="(prefers-color-scheme: light)" srcset="docs/_static/logo/malet.svg">
    <img src="docs/_static/logo/malet.svg" alt="Malet" width="420">
  </picture>
</p>

# Malet: a tool for machine learning experiment

**[Full Documentation](https://dongyeoplee2.github.io/Malet/)** | **[Changelog](CHANGELOG.md)**

**Malet** (**Ma**chine **L**earning **E**xperiment **T**ool) is a tool for hyperparameter grid searches, metric logging, advanced analyses and visualizations.

## Gallery

<p align="center">
  <img src="docs/_static/figures/mlf(lmda)--min.png" alt="Minimum metric plot" height="96">
  <img src="docs/_static/figures/resnet20_animation_curve.gif" alt="Animated curve plot" height="96">
  <img src="docs/_static/figures/lmda-lmda_schedule--min.png" alt="Lambda schedule plot" height="96">
  <img src="docs/_static/figures/mlf(lmda-lr)-flt(step_50:100)-ani(step)--min.gif" alt="Animated lambda learning-rate plot" height="96">
  <img src="docs/_static/figures/interval_val_acc.png" alt="Interval validation accuracy plot" height="96">
  <img src="docs/_static/figures/cifar10-mlf(lmda)-crf(sp-lmda_schedule)-flt(lmda!_0.0001-step_50:200)-ani(step)--min.gif" alt="Lambda distribution plot" height="96">
  <img src="docs/_static/figures/lambda_dense_val_acc.png" alt="Dense lambda validation accuracy plot" height="96">
  <img src="docs/_static/figures/random_sparsity_0.0_loss_param.gif" alt="Lambda distribution plot" height="96">
  <img src="docs/_static/figures/resnet20_heatmap_rho_sp.png" alt="Small lambda distribution plot" height="96">
  <img src="docs/_static/figures/lambda_dist.png" alt="Lambda distribution plot" height="96">
  <img src="docs/_static/figures/random_p_71560.0_[90].gif" alt="Lambda distribution plot" height="96">
  <img src="docs/_static/figures/cifar-mlf(lmda)-crf(sp-lmda_schedule)-flt(lmda!_0.0001-step_150:200)-ani(step)--min.gif" alt="Lambda distribution plot" height="96">
</p>

## Features

- 🔎 Easy & powerful hyperparameter grid search syntax
- 📝 Experiment metric logging and resuming system
- 📊 Flexible data process and visualization tools
- 🚀 Search parallelization for multi-gpus

## Installation

```bash
pip install malet
```

From source:

```bash
pip install git+https://github.com/dongyeoplee2/Malet.git
```

For development (uses [uv](https://docs.astral.sh/uv/)):

```bash
uv sync
```

## Quick Start

### 1. Prerequisite

#### Experiment Folder

Using Malet starts with making a folder with a single yaml config file.
Various files resulting from some experiment is saved in this single folder.
We advise to create a folder for each experiment under `experiments` folder.

```text
experiments/
└── {experiment folder}/
    ├── exp_config.yaml : experiment config yaml file            (User created)
    ├── log.tsv         : log file for saving experiment results (generated by malet.experiment)
    ├── (log_splits)    : folder for splitted logs               (generated by malet.experiment)
    └── figure          : folder for figures                     (generated by malet.plot)
```

#### Pre-existing training pipeline

Say you have some training pipeline that takes in a configuration (any object w/ dictionary-like interface).
We require you to return the result of the training so it gets logged.

```python
def train(config, ...):
    ...
    # training happens here
    ...
    metric_dict = {
        'train_accuracies': train_accuracies,
        'val_accuracies': val_accuracies,
        'train_losses': train_losses,
        'val_losses': val_losses,
    }
    return metric_dict
```

### 2. Running experiments

#### Experiment config yaml

You can configure as you would do in the yaml file.
But we provide useful special keyword `grid`, used as follows:

```yaml
# static configs
model: LeNet5
dataset: mnist

num_epochs: 100
batch_size: 128
optimizer: adam

# grided fields
grid:
  seed: [1, 2, 3]
  lr: [0.0001, 0.001, 0.01, 0.1]
  weight_decay: [0.0, 0.00005, 0.0001]
```

Specifying list of config values under `grid` lets you run all possible combination (_i.e._ grid) of your configurations, with field least frequently changing in the order of declaration in `grid`.

#### Running experiments

The following will run the `train_fn` on grid of configs based on `{exp_folder_path}` and `train_fn`.

```python
from functools import partial
from malet.experiment import Experiment

train_fn = partial(train, ...{other arguments besides config}..)
metric_fields =  ['train_accuracies', 'val_accuracies', 'train_losses', 'val_losses']
experiment = Experiment({exp_folder_path}, train_fn, metric_fields)
experiment.run()
```

Note that you need to partially apply your original function so that you pass in a function with only `config` as its argument.

#### Experiment logs

The experiment log will be automatically saved in the `{exp_folder_path}` as `log.tsv`, where the static configs and the experiment log are each saved in yaml and tsv like structure respectively.
You can retrieve these data in python using `ExperimentLog` in `malet.experiment` as follows:

```python
from malet.experiment import ExperimentLog

log = ExperimentLog.from_tsv({tsv_file})

static_configs = log.static_configs
df = log.df
```

Experiment logs also enable resuming to the most recently run config when a job is suddenly killed.

### 3. Plot making

Running `malet.plot` lets you make plots based on `log.tsv` in the experiment folder.

```bash
malet-plot \
-exp_folder ../experiments/{exp_folder} \
-mode curve-epoch-train_accuracy
```

The key intuition for using this is to _leave only two fields in the dataframe for the x-axis and the y-axis_ by

1. **specifying a specific value** (\_e.g.\_ther hyperparameters),

which will leave only one value for each field.

Available plot modes: `curve`, `curve_best`, `bar`, `heatmap`, `scatter`, `scatter_heat`.

For the full list of CLI arguments, plot configuration options, advanced gridding, parallel GPU training, checkpointing, and more, see the **[full documentation](https://dongyeoplee2.github.io/Malet/)**.

## Citation

If you find Malet useful, please cite it as:

```bibtex
@software{lee2024malet,
  author       = {Dongyeop Lee},
  title        = {Malet: Machine Learning Experiment Tool},
  year         = {2024},
  url          = {https://github.com/dongyeoplee2/Malet},
}
```
