Skip to content

Commit

Permalink
Merge branch 'develop' into feature/one_action_forward_kl
Browse files Browse the repository at this point in the history
  • Loading branch information
YuriCat committed Jan 10, 2024
2 parents c0fee62 + 403ae35 commit 8d9f187
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 41 deletions.
3 changes: 1 addition & 2 deletions .github/workflows/action.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
python-version: [3.7, 3.8, 3.9]
python-version: ['3.8', '3.9', '3.10']
steps:
- name: Checkout
uses: actions/checkout@v2
Expand All @@ -24,7 +24,6 @@ jobs:
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
pip install -r handyrl/envs/kaggle/requirements.txt
- name: pytest
run: |
python -m pytest tests
19 changes: 10 additions & 9 deletions handyrl/evaluation.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def exec_match(env, agents, critic=None, show=False, game_args={}):
outcome = env.outcome()
if show:
print('final outcome = %s' % outcome)
return outcome
return {'result': outcome}


def exec_network_match(env, network_agents, critic=None, show=False, game_args={}):
Expand Down Expand Up @@ -138,7 +138,7 @@ def exec_network_match(env, network_agents, critic=None, show=False, game_args={
outcome = env.outcome()
for p, agent in network_agents.items():
agent.outcome(outcome[p])
return outcome
return {'result': outcome}


def build_agent(raw, env=None):
Expand Down Expand Up @@ -170,11 +170,11 @@ def execute(self, models, args):
else:
agents[p] = Agent(model)

outcome = exec_match(self.env, agents)
if outcome is None:
results = exec_match(self.env, agents)
if results is None:
print('None episode in evaluation!')
return None
return {'args': args, 'result': outcome, 'opponent': opponent}
return {'args': args, 'opponent': opponent, **results}


def wp_func(results):
Expand All @@ -196,10 +196,10 @@ def eval_process_mp_child(agents, critic, env_args, index, in_queue, out_queue,
print('*** Game %d ***' % g)
agent_map = {env.players()[p]: agents[ai] for p, ai in enumerate(agent_ids)}
if isinstance(list(agent_map.values())[0], NetworkAgent):
outcome = exec_network_match(env, agent_map, critic, show=show, game_args=game_args)
results = exec_network_match(env, agent_map, critic, show=show, game_args=game_args)
else:
outcome = exec_match(env, agent_map, critic, show=show, game_args=game_args)
out_queue.put((pat_idx, agent_ids, outcome))
results = exec_match(env, agent_map, critic, show=show, game_args=game_args)
out_queue.put((pat_idx, agent_ids, results))
out_queue.put(None)


Expand Down Expand Up @@ -246,7 +246,8 @@ def evaluate_mp(env, agents, critic, env_args, args_patterns, num_process, num_g
if ret is None:
finished_cnt += 1
continue
pat_idx, agent_ids, outcome = ret
pat_idx, agent_ids, results = ret
outcome = results.get('result')
if outcome is not None:
for idx, p in enumerate(env.players()):
agent_id = agent_ids[idx]
Expand Down
27 changes: 16 additions & 11 deletions handyrl/losses.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,38 +17,40 @@ def monte_carlo(values, returns):
return returns, returns - values


def temporal_difference(values, returns, rewards, lmb, gamma):
def temporal_difference(values, returns, rewards, lambda_, gamma):
target_values = deque([returns[:, -1]])
for i in range(values.size(1) - 2, -1, -1):
reward = rewards[:, i] if rewards is not None else 0
target_values.appendleft(reward + gamma * ((1 - lmb) * values[:, i + 1] + lmb * target_values[0]))
lamb = lambda_[:, i + 1]
target_values.appendleft(reward + gamma * ((1 - lamb) * values[:, i + 1] + lamb * target_values[0]))

target_values = torch.stack(tuple(target_values), dim=1)

return target_values, target_values - values


def upgo(values, returns, rewards, lmb, gamma):
def upgo(values, returns, rewards, lambda_, gamma):
target_values = deque([returns[:, -1]])
for i in range(values.size(1) - 2, -1, -1):
value = values[:, i + 1]
reward = rewards[:, i] if rewards is not None else 0
target_values.appendleft(reward + gamma * torch.max(value, (1 - lmb) * value + lmb * target_values[0]))
lamb = lambda_[:, i + 1]
target_values.appendleft(reward + gamma * torch.max(value, (1 - lamb) * value + lamb * target_values[0]))

target_values = torch.stack(tuple(target_values), dim=1)

return target_values, target_values - values


def vtrace(values, returns, rewards, lmb, gamma, rhos, cs):
def vtrace(values, returns, rewards, lambda_, gamma, rhos, cs):
rewards = rewards if rewards is not None else 0
values_t_plus_1 = torch.cat([values[:, 1:], returns[:, -1:]], dim=1)
deltas = rhos * (rewards + gamma * values_t_plus_1 - values)

# compute Vtrace value target recursively
vs_minus_v_xs = deque([deltas[:, -1]])
for i in range(values.size(1) - 2, -1, -1):
vs_minus_v_xs.appendleft(deltas[:, i] + gamma * lmb * cs[:, i] * vs_minus_v_xs[0])
vs_minus_v_xs.appendleft(deltas[:, i] + gamma * lambda_[:, i + 1] * cs[:, i] * vs_minus_v_xs[0])

vs_minus_v_xs = torch.stack(tuple(vs_minus_v_xs), dim=1)
vs = vs_minus_v_xs + values
Expand All @@ -58,18 +60,21 @@ def vtrace(values, returns, rewards, lmb, gamma, rhos, cs):
return vs, advantages


def compute_target(algorithm, values, returns, rewards, lmb, gamma, rhos, cs):
def compute_target(algorithm, values, returns, rewards, lmb, gamma, rhos, cs, masks):
if values is None:
# In the absence of a baseline, Monte Carlo returns are used.
return returns, returns

if algorithm == 'MC':
return monte_carlo(values, returns)
elif algorithm == 'TD':
return temporal_difference(values, returns, rewards, lmb, gamma)

lambda_ = lmb + (1 - lmb) * (1 - masks)

if algorithm == 'TD':
return temporal_difference(values, returns, rewards, lambda_, gamma)
elif algorithm == 'UPGO':
return upgo(values, returns, rewards, lmb, gamma)
return upgo(values, returns, rewards, lambda_, gamma)
elif algorithm == 'VTRACE':
return vtrace(values, returns, rewards, lmb, gamma, rhos, cs)
return vtrace(values, returns, rewards, lambda_, gamma, rhos, cs)
else:
print('No algorithm named %s' % algorithm)
36 changes: 20 additions & 16 deletions handyrl/train.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,24 +63,23 @@ def replace_none(a, b):

# data that is changed by training configuration
if args['turn_based_training'] and not args['observation']:
obs = [[m['observation'][m['turn'][0]]] for m in moments]
prob = np.array([[[m['selected_prob'][m['turn'][0]]]] for m in moments])
act = np.array([[m['action'][m['turn'][0]]] for m in moments], dtype=np.int64)[..., np.newaxis]
amask = np.array([[m['action_mask'][m['turn'][0]]] for m in moments])
players_list = [[m['turn'][0]] for m in moments]
else:
obs = [[replace_none(m['observation'][player], obs_zeros) for player in players] for m in moments]
prob = np.array([[[replace_none(m['selected_prob'][player], 1.0)] for player in players] for m in moments])
act = np.array([[replace_none(m['action'][player], 0) for player in players] for m in moments], dtype=np.int64)[..., np.newaxis]
amask = np.array([[replace_none(m['action_mask'][player], amask_zeros + 1e32) for player in players] for m in moments])
players_list = [players for m in moments]

obs = [[replace_none(m['observation'][player], obs_zeros) for player in players_] for m, players_ in zip(moments, players_list)]
prob = np.array([[[replace_none(m['selected_prob'][player], 1.0)] for player in players_] for m, players_ in zip(moments, players_list)])
act = np.array([[replace_none(m['action'][player], 0) for player in players_] for m, players_ in zip(moments, players_list)], dtype=np.int64)[..., np.newaxis]
amask = np.array([[replace_none(m['action_mask'][player], amask_zeros + 1e32) for player in players_] for m, players_ in zip(moments, players_list)])

# reshape observation
obs = rotate(rotate(obs)) # (T, P, ..., ...) -> (P, ..., T, ...) -> (..., T, P, ...)
obs = bimap_r(obs_zeros, obs, lambda _, o: np.array(o))

# datum that is not changed by training configuration
v = np.array([[replace_none(m['value'][player], [0]) for player in players] for m in moments], dtype=np.float32).reshape(len(moments), len(players), -1)
rew = np.array([[replace_none(m['reward'][player], [0]) for player in players] for m in moments], dtype=np.float32).reshape(len(moments), len(players), -1)
ret = np.array([[replace_none(m['return'][player], [0]) for player in players] for m in moments], dtype=np.float32).reshape(len(moments), len(players), -1)
v = np.array([[replace_none(m['value'][player], 0) for player in players] for m in moments], dtype=np.float32).reshape(len(moments), len(players), -1)
rew = np.array([[replace_none(m['reward'][player], 0) for player in players] for m in moments], dtype=np.float32).reshape(len(moments), len(players), -1)
ret = np.array([[replace_none(m['return'][player], 0) for player in players] for m in moments], dtype=np.float32).reshape(len(moments), len(players), -1)
oc = np.array([ep['outcome'][player] for player in players], dtype=np.float32).reshape(1, len(players), -1)

emask = np.ones((len(moments), 1, 1), dtype=np.float32) # episode mask
Expand Down Expand Up @@ -226,6 +225,9 @@ def compute_loss(batch, model, hidden, args):

actions = batch['action']
emasks = batch['episode_mask']
omasks = batch['observation_mask']
value_target_masks, return_target_masks = omasks, omasks

clip_rho_threshold, clip_c_threshold = 1.0, 1.0

log_selected_b_policies = torch.log(torch.clamp(batch['selected_prob'], 1e-16, 1)) * emasks
Expand All @@ -242,16 +244,18 @@ def compute_loss(batch, model, hidden, args):
if 'value' in outputs_nograd:
values_nograd = outputs_nograd['value']
if args['turn_based_training'] and values_nograd.size(2) == 2: # two player zerosum game
values_nograd_opponent = -torch.stack([values_nograd[:, :, 1], values_nograd[:, :, 0]], dim=2)
values_nograd = (values_nograd + values_nograd_opponent) / (batch['observation_mask'].sum(dim=2, keepdim=True) + 1e-8)
values_nograd_opponent = -torch.flip(values_nograd, dims=[2])
omasks_opponent = torch.flip(omasks, dims=[2])
values_nograd = (values_nograd * omasks + values_nograd_opponent * omasks_opponent) / (omasks + omasks_opponent + 1e-8)
value_target_masks = torch.clamp(omasks + omasks_opponent, 0, 1)
outputs_nograd['value'] = values_nograd * emasks + batch['outcome'] * (1 - emasks)

# compute targets and advantage
targets = {}
advantages = {}

value_args = outputs_nograd.get('value', None), batch['outcome'], None, args['lambda'], 1, clipped_rhos, cs
return_args = outputs_nograd.get('return', None), batch['return'], batch['reward'], args['lambda'], args['gamma'], clipped_rhos, cs
value_args = outputs_nograd.get('value', None), batch['outcome'], None, args['lambda'], 1, clipped_rhos, cs, value_target_masks
return_args = outputs_nograd.get('return', None), batch['return'], batch['reward'], args['lambda'], args['gamma'], clipped_rhos, cs, return_target_masks

targets['value'], advantages['value'] = compute_target(args['value_target'], *value_args)
targets['return'], advantages['return'] = compute_target(args['value_target'], *return_args)
Expand Down Expand Up @@ -435,7 +439,7 @@ def __init__(self, args, net=None, remote=False):
self.worker = WorkerServer(args) if remote else WorkerCluster(args)

# thread connection
self.trainer = Trainer(args, self.model)
self.trainer = Trainer(args, copy.deepcopy(self.model))

def model_path(self, model_id):
return os.path.join('models', str(model_id) + '.pth')
Expand Down
5 changes: 3 additions & 2 deletions scripts/win_rate_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,9 @@ def get_wp_list(path):
for opponent in opponents:
wp_list = averaged_wp_lists[opponent]
start = start_epoch[opponent]
# ax.plot(clipped_epoch_list[start:], wp_list[start:], label=opponent)
ax.plot(clipped_game_list[start:], wp_list[start:], label=opponent)
end = min(min(len(clipped_epoch_list), len(clipped_game_list)), len(wp_list))
# ax.plot(clipped_epoch_list[start:end], wp_list[start:end], label=opponent)
ax.plot(clipped_game_list[start:end], wp_list[start:end], label=opponent)
last_win_rate[opponent] = wp_list[-1]

ax.set_xlabel('Games', size=14)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
'tictactoe',
'geister',
'parallel_tictactoe',
'kaggle.hungry_geese',
# 'kaggle.hungry_geese',
]


Expand Down

0 comments on commit 8d9f187

Please sign in to comment.