-
Notifications
You must be signed in to change notification settings - Fork 10
Feature/optuna #67
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
PonteIneptique
wants to merge
16
commits into
emanjavacas:master
Choose a base branch
from
PonteIneptique:feature/optuna
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Feature/optuna #67
Changes from 5 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
3bfb8b7
(Optimize with RayTune) Not working ATM
PonteIneptique 79b2898
(feature/optuna) Optuna seems to run.
PonteIneptique ba436e5
(Feature/Optuna) Reworked how training can be setup while avoiding hu…
PonteIneptique f652ba4
(Feature/Optuna) Deal with path
PonteIneptique 87ad36d
(Feature/Optuna) Allows for optimization
PonteIneptique c6b5b48
(Feature/Optuna) Applying first parts of @emanjavacas review
PonteIneptique 1a3a2fe
(Feature/Optuna) Harmonzied train.py with tune.py to reduce line dupl…
PonteIneptique 111b9aa
(Feature/Optuna) Reworked the OptunaTrainer to reuse the original dic…
PonteIneptique e49c914
(Feature/Optuna) Sampler implemented
PonteIneptique e01bf28
(Feature/Optuna) Optuna as an extra
PonteIneptique bcc112c
(Feature/Optuna) Fixed a missing file for Optuna requirements + Added…
PonteIneptique 480df23
(Feature/Optuna) Fixed an error in the way scores were reported
PonteIneptique fb2fabe
(Feature/Optuna) Fixed and added test for a bug where Trial would not…
PonteIneptique 1936429
Merge branch 'master' into feature/optuna
PonteIneptique 330be31
(Bugfix) Epoch Callback is not checked before it's called. Broken tra…
PonteIneptique dfc8635
Merge branch 'master' into feature/optuna
PonteIneptique File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| { | ||
| "params": [ | ||
| // Example for changing a category | ||
| // { | ||
| // "path": "cemb_type", | ||
| // "type": "suggest_categorical", | ||
| // "args": [["cnn", "rnn"]] | ||
| // } | ||
|
|
||
| // Example for changing an INT dimension | ||
| // { | ||
| // "path": "cemb_dim", | ||
| // "type": "suggest_int", | ||
| // "args": [200, 600] | ||
| //} | ||
|
|
||
| // Example for path | ||
| // { | ||
| // "path": "task_defaults/decoder", | ||
PonteIneptique marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| // "type": "suggest_categorical", | ||
| // "args": [["linear", "crf"]] | ||
| // } | ||
|
|
||
| // See more options using the same | ||
| // Architecture there : https://optuna.readthedocs.io/en/stable/tutorial/configurations.html#defining-parameter-spaces | ||
| ], | ||
| // Pruner are available there : https://optuna.readthedocs.io/en/stable/reference/pruners.html | ||
| // Follow this scheme for more detail | ||
| "pruner": { | ||
| "name": "MedianPruner", | ||
| "args": [], | ||
| "kwargs": {} | ||
| }, | ||
| "study": { | ||
| // ToDo ! | ||
| "name": "default-optimization-name", | ||
| "gpus": [] | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,195 @@ | ||
| # Can be run with python -m pie.scripts.tune | ||
| import os | ||
| from datetime import datetime | ||
| import logging | ||
| import random | ||
|
|
||
| # set seeds | ||
| import numpy | ||
| import torch | ||
| import optuna | ||
|
|
||
|
|
||
| from pie.settings import settings_from_file, OPT_DEFAULT_PATH | ||
| from pie.trainer import Trainer | ||
| from typing import Dict, Any, Optional, List | ||
|
|
||
|
|
||
| def get_targets(settings): | ||
| return [task['name'] for task in settings.tasks if task.get('target')] | ||
|
|
||
|
|
||
| def get_fname_infix(settings): | ||
| # fname | ||
| fname = os.path.join(settings.modelpath, settings.modelname) | ||
| timestamp = datetime.now().strftime("%Y_%m_%d-%H_%M_%S") | ||
| infix = '+'.join(get_targets(settings)) + '-' + timestamp | ||
| return fname, infix | ||
|
|
||
|
|
||
| def save(checkpoint_dir, settings, model): | ||
| # save model | ||
| fpath, infix = get_fname_infix(settings) | ||
| fpath = os.path.join(fpath, "checkpoint-"+str(checkpoint_dir)) | ||
| os.makedirs(fpath, exist_ok=True) | ||
| fpath = model.save(fpath, infix=infix, settings=settings) | ||
| return fpath | ||
|
|
||
|
|
||
| def env_setup(settings): | ||
| now = datetime.now() | ||
| # set seed | ||
| seed = now.hour * 10000 + now.minute * 100 + now.second | ||
| print("Using seed:", seed) | ||
| random.seed(seed) | ||
| numpy.random.seed(seed) | ||
| torch.manual_seed(seed) | ||
| if torch.cuda.is_available(): | ||
| torch.cuda.manual_seed(seed) | ||
|
|
||
| if settings.verbose: | ||
| logging.basicConfig(level=logging.INFO) | ||
|
|
||
|
|
||
| def affect_settings(target: Dict[str, Any], key: str, value): | ||
| if "/" in key: | ||
| i = key.index("/") | ||
| subkey, key = key[:i], key[i+1:] | ||
| # Would be cool to be able to filter with `[KEY=Value]` in a list, specifically for target=True | ||
| if subkey not in target: | ||
| target[subkey] = {} | ||
| target[subkey] = affect_settings(target[subkey], key, value) | ||
| else: | ||
| target[key] = value | ||
| return target | ||
|
|
||
|
|
||
| def get_pruner(pruner_settings: Dict[str, Any]): | ||
| return getattr(optuna.pruners, pruner_settings["name"])( | ||
| *pruner_settings.get("args", []), | ||
| **pruner_settings.get("kwargs", {}) | ||
| ) | ||
|
|
||
|
|
||
| # https://github.com/ray-project/ray/blob/master/python/ray/tune/examples/async_hyperband_example.py | ||
|
|
||
| def create_tuna_optimization(trial: optuna.Trial, fn: str, name: str, value: List[Any]): | ||
| """ Generate tuna value generator | ||
|
|
||
| Might use self one day, so... | ||
|
|
||
| :param trial: | ||
| :param fn: | ||
| :param name: | ||
| :param value: | ||
| :return: | ||
| """ | ||
| return getattr(trial, fn)(name, *value) | ||
|
|
||
|
|
||
| class Optimizer(object): | ||
| def __init__(self, settings, optimization_settings: List[Dict[str, Any]], gpus: List[int] = []): | ||
PonteIneptique marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| self.focus: str = [task["name"] for task in settings.tasks if task.get("target") is True][0] | ||
| self.settings = settings | ||
| self.optimization_settings = optimization_settings | ||
| self.gpus = gpus | ||
|
|
||
| def optimize(self, trial: optuna.Trial): | ||
| env_setup(self.settings) | ||
|
|
||
| settings = self.settings | ||
|
|
||
| for opt_set in self.optimization_settings: | ||
| settings = affect_settings( | ||
| target=settings, | ||
| key=opt_set["path"], | ||
| value=create_tuna_optimization( | ||
| trial=trial, | ||
| fn=opt_set["type"], | ||
| name=opt_set["path"].replace("/", "__"), | ||
| value=opt_set["args"] | ||
| ) | ||
| ) | ||
|
|
||
| trainer, model, trainset, devset, label_encoder, reader = Trainer.setup(settings) | ||
|
|
||
| def report(epoch_id, _scores): | ||
| target = _scores[self.focus]["all"]["accuracy"] | ||
PonteIneptique marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| trial.report(target, epoch_id) | ||
| # Handle pruning based on the intermediate value. | ||
| if trial.should_prune(): | ||
| raise optuna.TrialPruned() | ||
|
|
||
| scores = trainer.train_epochs(self.settings.epochs, devset=devset, epoch_callback=report) | ||
| save(str(trial.number), self.settings, model) | ||
PonteIneptique marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| return scores[self.focus]["all"]["accuracy"] | ||
|
|
||
|
|
||
| def run_optimize( | ||
| settings, opt_settings, | ||
| generate_csv: bool = True, generate_html: bool = True, | ||
| use_sqlite: Optional[str] = None, resume: bool = False): | ||
| """ | ||
|
|
||
| :param settings: | ||
| :param opt_settings: | ||
| :param study_name: | ||
| :param generate_csv: | ||
| :param generate_html: | ||
| :param use_sqlite: | ||
| :param resume: | ||
| :return: | ||
| """ | ||
|
|
||
| import pprint | ||
| pprint.pprint(opt_settings) | ||
| storage = None | ||
|
|
||
| if use_sqlite: | ||
| storage = 'sqlite:///{}'.format(use_sqlite) | ||
|
|
||
| trial_creator = Optimizer( | ||
| settings, | ||
| opt_settings["params"] | ||
| ) | ||
|
|
||
| study = optuna.create_study( | ||
| study_name=opt_settings["study"]["name"], | ||
| direction='maximize', | ||
| pruner=get_pruner(opt_settings["pruner"]), | ||
| storage=storage, | ||
| load_if_exists=resume | ||
| ) | ||
| study.optimize(trial_creator.optimize, n_trials=20) | ||
|
|
||
| if generate_csv: | ||
| df = study.trials_dataframe() | ||
| df.to_csv(opt_settings["study"]["name"]+".csv") | ||
|
|
||
| if generate_html: | ||
| optuna.visualization.plot_intermediate_values(study).write_html(opt_settings["study"]["name"]) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| import argparse | ||
| parser = argparse.ArgumentParser() | ||
| parser.add_argument('config_path', help='Path to optimization file (see default_settings.json)') | ||
| parser.add_argument('optuna_path', help='Path to optimization file (see default_optuna.json)') | ||
| parser.add_argument('--html', action='store_true', default=False, help="Generate a HTML report using" | ||
| "study name") | ||
| parser.add_argument('--csv', action='store_true', default=False, help="Generate a CSV report using" | ||
| "study name") | ||
| parser.add_argument('--sqlite', default=None, help="Path to a SQLite DB File (Creates if not exists)") | ||
| parser.add_argument('--resume', action='store_true', default=False, help="Resume a previous study using SQLite" | ||
| "if it exists") | ||
| args = parser.parse_args() | ||
|
|
||
| run_optimize( | ||
| settings_from_file(args.config_path), | ||
| settings_from_file(args.optuna_path, default_path=OPT_DEFAULT_PATH), | ||
| generate_csv=args.csv, | ||
| generate_html=args.html, | ||
| use_sqlite=args.sqlite, | ||
| resume=args.resume | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Doesn't optuna allow to define sampling distributions for the parameters?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The way I designed it, you can basically use any optuna distribution function. It just makes it simpler as you don't have to "code" it.
I have not yet implemented the GridSampler and stuff like this. Should probably be the next target... https://optuna.readthedocs.io/en/stable/reference/samplers.html?highlight=suggest#optuna.samplers.GridSampler
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done ;)