-
Notifications
You must be signed in to change notification settings - Fork 6k
Add visualdl callback function #27565
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
Merged
Merged
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
b80f73b
add visualdl callback
LielinJiang e7818d3
add to all
LielinJiang e6c2843
fix sample code, test=document_fix
LielinJiang 58d63fe
fix step count and writer create
LielinJiang 8b0f098
fix unittest
LielinJiang 7bab3f0
fix import
LielinJiang 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 |
|---|---|---|
|
|
@@ -15,10 +15,11 @@ | |
| import os | ||
|
|
||
| from paddle.fluid.dygraph.parallel import ParallelEnv | ||
| from paddle.utils import try_import | ||
|
|
||
| from .progressbar import ProgressBar | ||
|
|
||
| __all__ = ['Callback', 'ProgBarLogger', 'ModelCheckpoint'] | ||
| __all__ = ['Callback', 'ProgBarLogger', 'ModelCheckpoint', 'VisualDL'] | ||
|
|
||
|
|
||
| def config_callbacks(callbacks=None, | ||
|
|
@@ -469,3 +470,112 @@ def on_train_end(self, logs=None): | |
| path = '{}/final'.format(self.save_dir) | ||
| print('save checkpoint at {}'.format(os.path.abspath(path))) | ||
| self.model.save(path) | ||
|
|
||
|
|
||
| class VisualDL(Callback): | ||
| """VisualDL callback function | ||
| Args: | ||
| log_dir (str): The directory to save visualdl log file. | ||
|
|
||
| Examples: | ||
| .. code-block:: python | ||
|
|
||
| import paddle | ||
| from paddle.static import InputSpec | ||
|
|
||
| inputs = [InputSpec([-1, 1, 28, 28], 'float32', 'image')] | ||
| labels = [InputSpec([None, 1], 'int64', 'label')] | ||
|
|
||
| train_dataset = paddle.vision.datasets.MNIST(mode='train') | ||
| eval_dataset = paddle.vision.datasets.MNIST(mode='test') | ||
|
|
||
| net = paddle.vision.LeNet() | ||
| model = paddle.Model(net, inputs, labels) | ||
|
|
||
| optim = paddle.optimizer.Adam(0.001, parameters=net.parameters()) | ||
| model.prepare(optimizer=optim, | ||
| loss=paddle.nn.CrossEntropyLoss(), | ||
| metrics=paddle.metric.Accuracy()) | ||
|
|
||
| # uncomment following lines to fit model with visualdl callback function | ||
| # callback = paddle.callbacks.VisualDL(log_dir='visualdl_log_dir') | ||
| # model.fit(train_dataset, eval_dataset, batch_size=64, callbacks=callback) | ||
|
|
||
| """ | ||
|
|
||
| def __init__(self, log_dir): | ||
| self.log_dir = log_dir | ||
| self.epochs = None | ||
| self.steps = None | ||
|
|
||
| def _is_write(self): | ||
| return ParallelEnv().local_rank == 0 | ||
|
|
||
| def on_train_begin(self, logs=None): | ||
| self.epochs = self.params['epochs'] | ||
| assert self.epochs | ||
| self.train_metrics = self.params['metrics'] | ||
| assert self.train_metrics | ||
| self._is_fit = True | ||
|
|
||
| def on_epoch_begin(self, epoch=None, logs=None): | ||
| visualdl = try_import('visualdl') | ||
| self.steps = self.params['steps'] | ||
| self.epoch = epoch | ||
| self.train_step = 0 | ||
| self.train_writer = visualdl.LogWriter(self.log_dir) | ||
|
|
||
| def _updates(self, logs, mode): | ||
| metrics = getattr(self, '%s_metrics' % (mode)) | ||
| writer = getattr(self, '%s_writer' % (mode)) | ||
| current_step = getattr(self, '%s_step' % (mode)) | ||
| if mode == 'train': | ||
| total_step = self.epoch * self.steps + current_step | ||
|
||
| else: | ||
| total_step = self.epoch | ||
|
|
||
| for k in metrics: | ||
| if k in logs: | ||
| temp_tag = mode + '/' + k | ||
|
|
||
| if isinstance(logs[k], (list, tuple)): | ||
| temp_value = logs[k][0] | ||
| elif isinstance(logs[k], numbers.Number): | ||
| temp_value = logs[k] | ||
| else: | ||
| continue | ||
| writer.add_scalar( | ||
| tag=temp_tag, step=total_step, value=temp_value) | ||
|
|
||
| def on_train_batch_end(self, step, logs=None): | ||
| logs = logs or {} | ||
| self.train_step += 1 | ||
|
|
||
| if self._is_write(): | ||
| if self.steps is None or self.train_step < self.steps: | ||
| self._updates(logs, 'train') | ||
|
|
||
| def on_epoch_end(self, epoch, logs=None): | ||
| logs = logs or {} | ||
| if self._is_write() and (self.steps is not None): | ||
| self._updates(logs, 'train') | ||
|
|
||
| def on_eval_begin(self, logs=None): | ||
| visualdl = try_import('visualdl') | ||
| self.eval_steps = logs.get('steps', None) | ||
| self.eval_metrics = logs.get('metrics', []) | ||
| self.eval_step = 0 | ||
| self.evaled_samples = 0 | ||
| self.eval_writer = visualdl.LogWriter(self.log_dir) | ||
|
|
||
| def on_train_end(self, logs=None): | ||
| if hasattr(self, 'train_writer'): | ||
| self.train_writer.close() | ||
| if hasattr(self, 'eval_writer'): | ||
| self.eval_writer.close() | ||
|
|
||
| def on_eval_end(self, logs=None): | ||
| self._updates(logs, 'eval') | ||
|
|
||
| if (not hasattr(self, '_is_fit')) and hasattr(self, 'eval_writer'): | ||
| self.eval_writer.close() | ||
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
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.
需要每个epoch开始,重新new一个train_writer吗?
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, only create one writer for one callback instance.