Skip to content

Commit

Permalink
fixed bug with doubly robust. Added tests. Added license. Updated str…
Browse files Browse the repository at this point in the history
…ucture for pypi
  • Loading branch information
joshuaspear committed Jun 30, 2023
1 parent d5748d9 commit ab4bc42
Show file tree
Hide file tree
Showing 14 changed files with 238 additions and 18 deletions.
10 changes: 10 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -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.
16 changes: 11 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
1 change: 0 additions & 1 deletion _version.py

This file was deleted.

2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
Empty file.
55 changes: 50 additions & 5 deletions src/offline_rl_ope/OPEEstimators/DoublyRobust.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand All @@ -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)

Expand All @@ -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]
Expand All @@ -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
return reward_res
5 changes: 3 additions & 2 deletions src/offline_rl_ope/OPEEstimators/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from .DirectMethod import D3rlpyQlearnDM
from .DirectMethod import DirectMethodBase, D3rlpyQlearnDM
from .DoublyRobust import DREstimator
from .IS import ISEstimator
from .IS import ISEstimatorBase, ISEstimator
from .base import OPEEstimatorBase
8 changes: 7 additions & 1 deletion src/offline_rl_ope/__init__.py
Original file line number Diff line number Diff line change
@@ -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):
Expand All @@ -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()
Expand Down
1 change: 1 addition & 0 deletions src/offline_rl_ope/_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = "2.1.0"
3 changes: 3 additions & 0 deletions src/offline_rl_ope/api/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from . import (
d3rlpy
)
8 changes: 6 additions & 2 deletions src/offline_rl_ope/api/d3rlpy/__init__.py
Original file line number Diff line number Diff line change
@@ -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)
4 changes: 3 additions & 1 deletion src/offline_rl_ope/components/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
from . import ImportanceSampler, Policy
from .Policy import Policy, D3RlPyDeterministic, BehavPolicy, LinearMixedPolicy
from .ImportanceSampler import (
ISWeightCalculator, ISWeightOrchestrator, PerDecisionIS, VanillaIS)
133 changes: 133 additions & 0 deletions tests/OPEEstimators/test_DoublyRobust.py
Original file line number Diff line number Diff line change
@@ -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)



10 changes: 10 additions & 0 deletions tests/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down

0 comments on commit ab4bc42

Please sign in to comment.