-
Notifications
You must be signed in to change notification settings - Fork 243
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
Feature/param reset #328
Draft
joshuaspear
wants to merge
12
commits into
takuseno:master
Choose a base branch
from
joshuaspear:feature/param_reset
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.
Draft
Feature/param reset #328
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
4a6edc9
tracking of cql regularisation for continuous cql
joshuaspear 5b7185c
updated for linting and formatting
joshuaspear 7fd0a37
overwriting dr3 pull and aligning cql logging
joshuaspear a52651e
updated formatting
joshuaspear a46d73f
update gitignore
joshuaspear 0874990
merging refactor_loss branch and resolved conflicts with cql and cql_…
joshuaspear e87cb94
corrected formatting
joshuaspear 3ebd8cb
first draft of parameter reset callback
joshuaspear 2846d20
corrected formatting
joshuaspear 7017e6f
first go at tests for param reset callback
joshuaspear def6ad7
Merge branch 'master' into feature/param_reset
joshuaspear d793c6f
fixed issues in call method
joshuaspear 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 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 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,73 @@ | ||
from abc import ABCMeta, abstractmethod | ||
from typing import Sequence, List | ||
import torch.nn as nn | ||
|
||
from ... import QLearningAlgoBase, QLearningAlgoImplBase | ||
from ....constants import IMPL_NOT_INITIALIZED_ERROR | ||
|
||
__all__ = [ | ||
"ParameterReset" | ||
] | ||
|
||
class QLearningCallback(metaclass=ABCMeta): | ||
@abstractmethod | ||
def __call__(self, algo: QLearningAlgoBase, epoch: int, total_step: int): | ||
pass | ||
|
||
|
||
class ParameterReset(QLearningCallback): | ||
def __init__(self, replay_ratio: int, encoder_reset:Sequence[bool], | ||
output_reset:bool, algo:QLearningAlgoBase=None) -> None: | ||
self._replay_ratio = replay_ratio | ||
self._encoder_reset = encoder_reset | ||
self._output_reset = output_reset | ||
self._check = False | ||
if algo is not None: | ||
self._check_layer_resets(algo=algo) | ||
|
||
|
||
def _get_layers(self, q_func:nn.ModuleList)->List[nn.Module]: | ||
all_modules = {nm:module for (nm, module) in q_func.named_modules()} | ||
q_func_layers = [ | ||
*all_modules["_encoder._layers"], | ||
all_modules["_fc"] | ||
] | ||
return q_func_layers | ||
|
||
def _check_layer_resets(self, algo:QLearningAlgoBase): | ||
assert algo._impl is not None, IMPL_NOT_INITIALIZED_ERROR | ||
assert isinstance(algo._impl, QLearningAlgoImplBase) | ||
|
||
all_valid_layers = [] | ||
for q_func in algo._impl.q_function: | ||
q_func_layers = self._get_layers(q_func) | ||
if len(self._encoder_reset) + 1 != len(q_func_layers): | ||
raise ValueError( | ||
f""" | ||
q_function layers: {q_func_layers}; | ||
specified encoder layers: {self._encoder_reset} | ||
""" | ||
) | ||
valid_layers = [ | ||
hasattr(layer, 'reset_parameters') for lr, layer in zip( | ||
self._encoder_reset, q_func_layers) | ||
if lr | ||
] | ||
all_valid_layers.append(all(valid_layers)) | ||
self._check = all(all_valid_layers) | ||
if not self._check: | ||
raise ValueError( | ||
"Some layer do not contain resettable parameters" | ||
) | ||
|
||
def __call__(self, algo: QLearningAlgoBase, epoch: int, total_step: int): | ||
if not self._check: | ||
self._check_layer_resets(algo=algo) | ||
assert isinstance(algo._impl, QLearningAlgoImplBase) | ||
if epoch % self._replay_ratio == 0: | ||
reset_lst = [*self._encoder_reset, self._output_reset] | ||
for q_func in algo._impl.q_function: | ||
q_func_layers = self._get_layers(q_func) | ||
for lr, layer in zip(reset_lst, q_func_layers): | ||
if lr: | ||
layer.reset_parameters() |
This file contains 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 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 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,113 @@ | ||
import pytest | ||
from typing import Any, Sequence, List, Union | ||
from unittest.mock import MagicMock, Mock | ||
from d3rlpy.dataset import Shape | ||
|
||
from d3rlpy.algos.qlearning.torch.callbacks import ParameterReset | ||
from d3rlpy.algos import QLearningAlgoBase, QLearningAlgoImplBase | ||
from d3rlpy.torch_utility import Modules | ||
import torch | ||
|
||
from ...test_torch_utility import DummyModules | ||
|
||
|
||
class LayerHasResetMock: | ||
|
||
def reset_parameters(self): | ||
return True | ||
|
||
class LayerNoResetMock: | ||
pass | ||
|
||
fc = torch.nn.Linear(100, 100) | ||
optim = torch.optim.Adam(fc.parameters()) | ||
modules = DummyModules(fc=fc, optim=optim) | ||
|
||
class ImplMock(MagicMock): | ||
|
||
def __init__( | ||
self, q_funcs:List[Union[LayerHasResetMock, LayerNoResetMock]] | ||
) -> None: | ||
super().__init__(spec=QLearningAlgoImplBase) | ||
self.q_function = q_funcs | ||
|
||
|
||
class QLearningAlgoBaseMock(MagicMock): | ||
|
||
def __init__(self, spec, layer_setup:Sequence[bool]) -> None: | ||
super().__init__(spec=spec) | ||
q_funcs = [] | ||
for i in layer_setup: | ||
if i: | ||
q_funcs.append(LayerHasResetMock()) | ||
else: | ||
q_funcs.append(LayerNoResetMock()) | ||
self._impl = ImplMock(q_funcs=q_funcs) | ||
|
||
|
||
|
||
def test_check_layer_resets(): | ||
algo = QLearningAlgoBaseMock(spec=QLearningAlgoBase, | ||
layer_setup=[True, True, False]) | ||
replay_ratio = 2 | ||
layer_reset_valid = [True, True, False] | ||
pr = ParameterReset( | ||
replay_ratio=replay_ratio, | ||
layer_reset=layer_reset_valid, | ||
algo=algo | ||
) | ||
assert pr._check is True | ||
|
||
layer_reset_invalid = [True, True, True] | ||
try: | ||
pr = ParameterReset( | ||
replay_ratio=replay_ratio, | ||
layer_reset=layer_reset_invalid, | ||
algo=algo | ||
) | ||
raise Exception | ||
except ValueError as e: | ||
assert True | ||
|
||
layer_reset_long = [True, True, True, False] | ||
try: | ||
pr = ParameterReset( | ||
replay_ratio=replay_ratio, | ||
layer_reset=layer_reset_long, | ||
algo=algo | ||
) | ||
raise Exception | ||
except ValueError as e: | ||
assert True | ||
|
||
layer_reset_shrt = [True, True] | ||
try: | ||
pr = ParameterReset( | ||
replay_ratio=replay_ratio, | ||
layer_reset=layer_reset_shrt, | ||
algo=algo | ||
) | ||
raise Exception | ||
except ValueError as e: | ||
assert True | ||
|
||
|
||
def test_call(): | ||
algo = QLearningAlgoBaseMock(spec=QLearningAlgoBase, | ||
layer_setup=[True, True, False]) | ||
replay_ratio = 2 | ||
layer_reset_valid = [True, True, False] | ||
pr = ParameterReset( | ||
replay_ratio=replay_ratio, | ||
layer_reset=layer_reset_valid, | ||
algo=algo | ||
) | ||
pr(algo=algo, epoch=1, total_step=100) | ||
pr(algo=algo, epoch=2, total_step=100) | ||
|
||
pr = ParameterReset( | ||
replay_ratio=replay_ratio, | ||
layer_reset=layer_reset_valid, | ||
) | ||
pr(algo=algo, epoch=1, total_step=100) | ||
pr(algo=algo, epoch=2, total_step=100) |
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.
@takuseno assuming you're happy with the general approach of using the epoch_callback to inject the parameter reset functionality - I wondered if you could recommend a better approach for obtaining the encoder and fc layers which follows static typing?