diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..579c5ab --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,10 @@ +MIT License + +Copyright (c) [2023] [Joshua Spear] + +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. \ No newline at end of file diff --git a/README.md b/README.md index 4ca5d6d..7ffb53a 100644 --- a/README.md +++ b/README.md @@ -8,16 +8,18 @@ - [x] components/ - [x] ImportanceSampler.py - [x] Policy.py -- [ ] OPEEstimation +- [x] OPEEstimation - [x] IS.py - [x] utils.py - - [ ] DirectMethod.py - - [ ] DoublyRobust.py + - [x] DirectMethod.py* + - [x] DoublyRobust.py - [ ] LowerBounds - [ ] api/d3rlpy +* Insufficient functionality to test i.e., currently only wrapper classes are implemented for the OPEEstimation/DirectMethod.py + #### Overview -The core importance sampling functionality has been tested however, there still exists some funtionality for which unit tests have not been written. This functionality was deemed lower priority. The d3rlpy/api for importance sampling adds minimal additional functionality therefore, it is likely to function as expected however, no sepcific unit testing has been implemented! +Basic unit testing has been implemented for all the core functionality of the package. The d3rlpy/api for importance sampling adds minimal additional functionality therefore, it is likely to function as expected however, no sepcific unit testing has been implemented! **IMPORTANT**: * More documentation needs to be added however, please refer to examples/ for an illustration of the functionality @@ -61,6 +63,10 @@ The core importance sampling functionality has been tested however, there still ### Future work * Async/multithread support * Additional estimators: - * (Weighted) Doubly robust + * DualDICE * MAGIC + * Extended DR estimator as per equation 12 in https://arxiv.org/pdf/1511.03722.pdf +* APIs + * Extend d3rlpy + * Add additional apis e.g. for stable baselines * Continuous action spaces diff --git a/_version.py b/_version.py deleted file mode 100644 index 5a6bc65..0000000 --- a/_version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "2.0.0" \ No newline at end of file diff --git a/setup.py b/setup.py index 27120b9..c28d11c 100644 --- a/setup.py +++ b/setup.py @@ -9,7 +9,7 @@ README = (HERE / "README.md").read_text() # get __version__ variable -exec(open(os.path.join(HERE, '_version.py')).read()) +exec(open(os.path.join(HERE, "src", "offline_rl_ope", '_version.py')).read()) setuptools.setup( name='offline_rl_ope', diff --git a/src/offline_rl_ope/LowerBounds/__init__.py b/src/offline_rl_ope/LowerBounds/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/offline_rl_ope/OPEEstimators/DoublyRobust.py b/src/offline_rl_ope/OPEEstimators/DoublyRobust.py index 1799c7c..9a3c6d3 100644 --- a/src/offline_rl_ope/OPEEstimators/DoublyRobust.py +++ b/src/offline_rl_ope/OPEEstimators/DoublyRobust.py @@ -1,6 +1,6 @@ import numpy as np import torch -from typing import Callable, List, Dict, Tuple +from typing import Callable, List, Dict, Tuple, Union, Literal import math from .IS import ISEstimatorBase @@ -9,6 +9,9 @@ class DREstimator(ISEstimatorBase): + """ Doubly robust estimator implemented as per: + https://arxiv.org/pdf/1511.03722.pdf + """ def __init__(self, dm_model:DirectMethodBase, norm_weights: bool, clip: float = None, ignore_nan:bool=False @@ -30,7 +33,30 @@ def __ignore_nan(self, p_t): def __raise_nan(self, p_t): return p_t - def __update_step(self, v_t, p_t, r_t, v_dr_t, gamma, q_t): + def __update_step(self, v_t:torch.Tensor, p_t:torch.Tensor, + r_t:torch.Tensor, v_dr_t:torch.Tensor, gamma:torch.Tensor, + q_t:torch.Tensor)->torch.Tensor: + """ Predicts the time t+1 doubly robust value prediction based on time + t values + + Args: + v_t (torch.Tensor): tensor of size 0, representing the time t state + value from a Direct Method + p_t (torch.Tensor): tensor of size 0, representing the time t + importance weight + r_t (torch.Tensor): tensor of size 0, representing the time t + observed reward + v_dr_t (torch.Tensor): tensor of size 0, representing the time t + doubly robust value prediction + gamma (torch.Tensor): tensor of size 0, representing the time t + one step discount factor. Note, this is usually kept constant + q_t (torch.Tensor): tensor of size 0, representing the time t + state-action value from a Direct Method. + + Returns: + torch.Tensor: tensor of size 0, representing the doubly robust value + prediction at time t+1 + """ p_t = self.ignore_nan(p_t) return v_t + p_t*(r_t + gamma*v_dr_t - q_t) @@ -48,21 +74,40 @@ def get_traj_discnt_reward(self, reward_array:torch.Tensor, Returns: torch.Tensor: Tensor of discounted reward values of dimension - (traj_length) + (traj_length) """ v_dr = torch.tensor(0) discount = torch.tensor(discount) v:torch.Tensor = self.dm_model.get_v(state=state_array) q:torch.Tensor = self.dm_model.get_q( state=state_array, action=action_array) + reward_array = torch.flip(reward_array, dims=[0]) + v = torch.flip(v, dims=[0]) + q = torch.flip(q, dims=[0]) + weight_array = torch.flip(weight_array, dims=[0]) for r_t, v_t, q_t, p_t in zip(reward_array,v,q,weight_array): - v_dr = self.__update_step(v_t, p_t, r_t, v_dr, discount, q_t) + v_dr = self.__update_step(v_t=v_t, p_t=p_t, r_t=r_t, v_dr_t=v_dr, + gamma=discount, q_t=q_t) return v_dr def predict(self, rewards:List[torch.Tensor], states:List[torch.Tensor], actions:List[torch.Tensor], weights:torch.Tensor, discount:float, is_msk:torch.Tensor )->torch.Tensor: + """_summary_ + + Args: + rewards (List[torch.Tensor]): _description_ + states (List[torch.Tensor]): _description_ + actions (List[torch.Tensor]): _description_ + weights (torch.Tensor): _description_ + discount (float): _description_ + is_msk (torch.Tensor): _description_ + + Returns: + torch.Tensor: tensor of size 0 defining the mean doubly robust + value across the dataset + """ test = ( len(rewards)==len(states)==len(actions)==weights.shape[0]==\ is_msk.shape[0] @@ -80,4 +125,4 @@ def predict(self, rewards:List[torch.Tensor], states:List[torch.Tensor], weight_array=w, discount=discount) reward_res[i] = reward reward_res = reward_res.sum()/len(reward_res) - return reward_res \ No newline at end of file + return reward_res \ No newline at end of file diff --git a/src/offline_rl_ope/OPEEstimators/__init__.py b/src/offline_rl_ope/OPEEstimators/__init__.py index e4fb6d3..5862810 100644 --- a/src/offline_rl_ope/OPEEstimators/__init__.py +++ b/src/offline_rl_ope/OPEEstimators/__init__.py @@ -1,3 +1,4 @@ -from .DirectMethod import D3rlpyQlearnDM +from .DirectMethod import DirectMethodBase, D3rlpyQlearnDM from .DoublyRobust import DREstimator -from .IS import ISEstimator \ No newline at end of file +from .IS import ISEstimatorBase, ISEstimator +from .base import OPEEstimatorBase \ No newline at end of file diff --git a/src/offline_rl_ope/__init__.py b/src/offline_rl_ope/__init__.py index d1ed731..b16d0ab 100644 --- a/src/offline_rl_ope/__init__.py +++ b/src/offline_rl_ope/__init__.py @@ -1,6 +1,12 @@ import logging import os +from ._version import __version__ + +from . import ( + OPEEstimators, api, LowerBounds, components +) + logging_name = "offline_rl_ope" class CustomFormatter(logging.Formatter): @@ -26,7 +32,7 @@ def format(self, record): return formatter.format(record) logger = logging.getLogger(logging_name) -logger.setLevel(logging.DEBUG) +logger.setLevel(logging.INFO) # create console handler with a higher log level console_handler = logging.StreamHandler() diff --git a/src/offline_rl_ope/_version.py b/src/offline_rl_ope/_version.py new file mode 100644 index 0000000..dac7778 --- /dev/null +++ b/src/offline_rl_ope/_version.py @@ -0,0 +1 @@ +__version__ = "2.1.0" \ No newline at end of file diff --git a/src/offline_rl_ope/api/__init__.py b/src/offline_rl_ope/api/__init__.py new file mode 100644 index 0000000..9b6c25a --- /dev/null +++ b/src/offline_rl_ope/api/__init__.py @@ -0,0 +1,3 @@ +from . import ( + d3rlpy +) \ No newline at end of file diff --git a/src/offline_rl_ope/api/d3rlpy/__init__.py b/src/offline_rl_ope/api/d3rlpy/__init__.py index dd06847..08ddc54 100644 --- a/src/offline_rl_ope/api/d3rlpy/__init__.py +++ b/src/offline_rl_ope/api/d3rlpy/__init__.py @@ -1,4 +1,8 @@ from .DMScorer import FQECallback -from .ISScorer import ISCallback, ISEstimatorScorer, ISDiscreteActionDistScorer -from .utils import EpochCallbackHandler +from .ISScorer import ( + ISCallback, ISEstimatorScorer, ISDiscreteActionDistScorer, + D3RlPyTorchAlgoPredict) +from .utils import ( + EpochCallbackHandler, OPECallbackBase, QueryCallbackBase, + OPEEstimatorScorerBase) from .misc_scorers import (QueryScorer, DiscreteValueByActionCallback) \ No newline at end of file diff --git a/src/offline_rl_ope/components/__init__.py b/src/offline_rl_ope/components/__init__.py index 559c9a7..1ce4e16 100644 --- a/src/offline_rl_ope/components/__init__.py +++ b/src/offline_rl_ope/components/__init__.py @@ -1 +1,3 @@ -from . import ImportanceSampler, Policy \ No newline at end of file +from .Policy import Policy, D3RlPyDeterministic, BehavPolicy, LinearMixedPolicy +from .ImportanceSampler import ( + ISWeightCalculator, ISWeightOrchestrator, PerDecisionIS, VanillaIS) \ No newline at end of file diff --git a/tests/OPEEstimators/test_DoublyRobust.py b/tests/OPEEstimators/test_DoublyRobust.py new file mode 100644 index 0000000..16a5eec --- /dev/null +++ b/tests/OPEEstimators/test_DoublyRobust.py @@ -0,0 +1,133 @@ +import unittest +from unittest.mock import MagicMock +import torch +import logging +import numpy as np +from offline_rl_ope.OPEEstimators.DoublyRobust import DREstimator +from ..base import (test_reward_values, weight_test_res, test_dm_s_values, + test_dm_sa_values, test_state_vals, test_action_vals, + msk_test_res) + +gamma = 0.99 + + +class MockDMModel: + + def __init__(self) -> None: + pass + + def get_v(self, *args, **kwargs): + pass + + def get_q(self, *args, **kwargs): + pass + +class DREstimatorTest(unittest.TestCase): + + def test_update_step_ignore(self): + + is_est = DREstimator(dm_model=MockDMModel(), norm_weights=False, + clip=None, ignore_nan=True) + v_dr_t = torch.tensor(0) + v_t = torch.tensor(test_dm_s_values[0][-1]) + p_t = weight_test_res[0,-1] + r_t = torch.tensor(test_reward_values[0][-1]) + q_t = torch.tensor(test_dm_sa_values[0][-1]) + pred_res:torch.Tensor = is_est._DREstimator__update_step( + v_t, p_t, r_t, v_dr_t, gamma, q_t + ) + test_res:torch.Tensor = v_t + p_t*(r_t+torch.tensor(gamma)*v_dr_t-q_t) + tol = test_res/1000 + np.testing.assert_allclose(pred_res.numpy(), test_res.numpy(), + atol=tol.numpy().item()) + + def test_get_traj_discnt_reward(self): + dm_model = MockDMModel() + def q_side_effect(state:torch.Tensor, action:torch.Tensor): + lkp = { + "_".join([str(torch.Tensor(s)), str(torch.Tensor(a))]): q + for s,a,q in zip(test_state_vals, test_action_vals, + test_dm_sa_values) + } + res = lkp["_".join([str(state), str(action)])] + return torch.Tensor(res) + def v_side_effect(state:torch.Tensor): + lkp = { + str(torch.Tensor(s)): v + for s,v in zip(test_state_vals, test_dm_s_values) + } + res = lkp[str(state)] + return torch.Tensor(res) + dm_model.get_q = MagicMock(side_effect=q_side_effect) + dm_model.get_v = MagicMock(side_effect=v_side_effect) + is_est = DREstimator(dm_model=dm_model, norm_weights=False, clip=None, + ignore_nan=True) + pred_res = [] + test_res = [] + for idx, traj in enumerate(zip(test_state_vals, weight_test_res, + test_reward_values, test_action_vals, + test_dm_sa_values, test_dm_s_values, + msk_test_res)): + s_t = torch.Tensor(traj[0]) + p_t = torch.masked_select(traj[1], traj[6]>0) + r_t = torch.Tensor(traj[2]) + a_t = torch.Tensor(traj[3]) + q_t = torch.Tensor(traj[4]) + v_t = torch.Tensor(traj[5]) + __pred_res = is_est.get_traj_discnt_reward( + reward_array=r_t, discount=gamma, state_array=s_t, + action_array=a_t, weight_array=p_t) + pred_res.append(__pred_res.numpy()) + __test_res_v = torch.tensor(0) + for i in np.arange(s_t.shape[0]-1, 0-1, -1): + __test_res_v = is_est._DREstimator__update_step( + v_t=v_t[i], q_t=q_t[i], p_t=p_t[i], r_t=r_t[i], + gamma=torch.tensor(gamma), v_dr_t=__test_res_v) + test_res.append(__test_res_v.numpy()) + pred_res = np.concatenate(pred_res) + test_res = np.concatenate(test_res) + tol = (test_res.mean()/1000).item() + np.testing.assert_allclose(pred_res, test_res, atol=tol) + + def test_predict(self): + dm_model = MockDMModel() + def q_side_effect(state:torch.Tensor, action:torch.Tensor): + lkp = { + "_".join([str(torch.Tensor(s)), str(torch.Tensor(a))]): q + for s,a,q in zip(test_state_vals, test_action_vals, + test_dm_sa_values) + } + res = lkp["_".join([str(state), str(action)])] + return torch.Tensor(res) + def v_side_effect(state:torch.Tensor): + lkp = { + str(torch.Tensor(s)): v + for s,v in zip(test_state_vals, test_dm_s_values) + } + res = lkp[str(state)] + return torch.Tensor(res) + dm_model.get_q = MagicMock(side_effect=q_side_effect) + dm_model.get_v = MagicMock(side_effect=v_side_effect) + is_est = DREstimator(dm_model=dm_model, norm_weights=False, clip=None, + ignore_nan=True) + rewards = [torch.Tensor(x) for x in test_reward_values] + states = [torch.Tensor(x) for x in test_state_vals] + actions = [torch.Tensor(x) for x in test_action_vals] + + test_res = [] + pred_res = is_est.predict(rewards=rewards, states=states, + actions=actions, weights=weight_test_res, + discount=gamma, is_msk=msk_test_res) + for idx, (r,s,a,w,msk) in enumerate(zip(rewards, states, actions, + weight_test_res, msk_test_res)): + p = torch.masked_select(w, msk>0) + __test_res = is_est.get_traj_discnt_reward( + reward_array=r, discount=gamma, state_array=s, action_array=a, + weight_array=p) + test_res.append(__test_res.numpy()) + test_res = np.concatenate(test_res).mean() + tol = (test_res/1000).item() + np.testing.assert_allclose(pred_res.numpy(),test_res, atol=tol) + + + \ No newline at end of file diff --git a/tests/base.py b/tests/base.py index 28c6ae8..d391036 100644 --- a/tests/base.py +++ b/tests/base.py @@ -31,6 +31,16 @@ [[-1],[-1], [-1]] ] +test_dm_s_values = [ + [[0.8],[-1], [0.5], [0.4]], + [[-2],[-1], [-0.5]] +] + +test_dm_sa_values = [ + [[0.7],[-3], [0.5], [0.6]], + [[-3],[-2], [-0.8]] +] + test_act_indiv_weights = [ np.array([1/0.9, 0.07/0.7, 0.89/0.66, 1/0.7]), np.array([ 0.75/0.54, 0.9/0.9, 0.2/0.5])