比较提交

...
此合并请求有变更与目标分支冲突。
/com.unity.ml-agents/CHANGELOG.md
/ml-agents/mlagents/trainers/optimizer/torch_optimizer.py
/ml-agents/mlagents/trainers/poca/optimizer_torch.py
/ml-agents/mlagents/trainers/buffer.py

9 次代码提交

作者 SHA1 备注 提交日期
Ervin Teng a9ca7b3b Do burn-in for PPO 4 年前
Ervin Teng 6e04aaf3 Fix poca test 4 年前
Ervin Teng 9fd4a81e Address comments 4 年前
Ervin Teng b3499848 Improve tests 4 年前
Ervin Teng a87b937f Update changelog 4 年前
Ervin Teng c05ec9af Fix groupmate obs, add tests 4 年前
Ervin Teng 81b74634 Fix additional bugs and POCA 4 年前
Ervin Teng d461a66a Fix padding in optimizer value estimate 4 年前
Ervin Teng d027de7f Pad buffer at the end 4 年前
共有 7 个文件被更改,包括 126 次插入123 次删除
  1. 2
      com.unity.ml-agents/CHANGELOG.md
  2. 69
      ml-agents/mlagents/trainers/optimizer/torch_optimizer.py
  3. 2
      ml-agents/mlagents/trainers/buffer.py
  4. 147
      ml-agents/mlagents/trainers/poca/optimizer_torch.py
  5. 8
      ml-agents/mlagents/trainers/tests/torch/test_ppo.py
  6. 12
      ml-agents/mlagents/trainers/tests/torch/test_poca.py
  7. 9
      ml-agents/mlagents/trainers/ppo/optimizer_torch.py

2
com.unity.ml-agents/CHANGELOG.md


### Bug Fixes
#### com.unity.ml-agents / com.unity.ml-agents.extensions (C#)
#### ml-agents / ml-agents-envs / gym-unity (Python)
- Fixed an issue with LSTM when used with POCA and `sequence_length` < `time_horizon`. Also improved behavior of LSTMs slightly. (#5206)
## [1.9.0-preview] - 2021-03-17
### Major Changes

69
ml-agents/mlagents/trainers/optimizer/torch_optimizer.py


from typing import Dict, Optional, Tuple, List
from mlagents.torch_utils import torch
import numpy as np
import math
from collections import defaultdict
from mlagents.trainers.buffer import AgentBuffer, AgentBufferField
from mlagents.trainers.trajectory import ObsUtil

"""
num_experiences = tensor_obs[0].shape[0]
all_next_memories = AgentBufferField()
# In the buffer, the 1st sequence are the ones that are padded. So if seq_len = 3 and
# trajectory is of length 10, the 1st sequence is [pad,pad,obs].
# Compute the number of elements in this padded seq.
leftover = num_experiences % self.policy.sequence_length
# Compute values for the potentially truncated initial sequence
seq_obs = []
first_seq_len = leftover if leftover > 0 else self.policy.sequence_length
for _obs in tensor_obs:
first_seq_obs = _obs[0:first_seq_len]
seq_obs.append(first_seq_obs)
# For the first sequence, the initial memory should be the one at the
# beginning of this trajectory.
for _ in range(first_seq_len):
all_next_memories.append(ModelUtils.to_numpy(initial_memory.squeeze()))
# When using LSTM, we need to divide the trajectory into sequences of even length. Sometimes,
# that division isn't even, and we must pad the leftover sequence.
# When it is added to the buffer, the last sequence will be padded. So if seq_len = 3 and
# trajectory is of length 10, the last sequence is [obs,pad,pad] once it is added to the buffer.
# Compute the number of elements in this sequence that will end up being padded.
leftover_seq_len = num_experiences % self.policy.sequence_length
init_values, _mem = self.critic.critic_pass(
seq_obs, initial_memory, sequence_length=first_seq_len
)
all_values = {
signal_name: [init_values[signal_name]]
for signal_name in init_values.keys()
}
all_values: Dict[str, List[np.ndarray]] = defaultdict(list)
_mem = initial_memory
for seq_num in range(
1, math.ceil((num_experiences) / (self.policy.sequence_length))
):
for seq_num in range(num_experiences // (self.policy.sequence_length)):
start = seq_num * self.policy.sequence_length - (
self.policy.sequence_length - leftover
)
end = (seq_num + 1) * self.policy.sequence_length - (
self.policy.sequence_length - leftover
)
start = seq_num * self.policy.sequence_length
end = (seq_num + 1) * self.policy.sequence_length
for _obs in tensor_obs:
seq_obs.append(_obs[start:end])
values, _mem = self.critic.critic_pass(

all_values[signal_name].append(_val)
# Compute values for the potentially truncated last sequence. Note that this
# sequence isn't padded yet, but will be.
seq_obs = []
if leftover_seq_len > 0:
for _obs in tensor_obs:
last_seq_obs = _obs[-leftover_seq_len:]
seq_obs.append(last_seq_obs)
# For the last sequence, the initial memory should be the one at the
# end of this trajectory.
for _ in range(leftover_seq_len):
all_next_memories.append(ModelUtils.to_numpy(_mem.squeeze()))
last_values, _mem = self.critic.critic_pass(
seq_obs, _mem, sequence_length=leftover_seq_len
)
for signal_name, _val in last_values.items():
all_values[signal_name].append(_val)
# Create one tensor per reward signal
all_value_tensors = {
signal_name: torch.cat(value_list, dim=0)

2
ml-agents/mlagents/trainers/buffer.py


else:
# We want to duplicate the last value in the array, multiplied by the padding_value.
padding = np.array(self[-1], dtype=np.float32) * self.padding_value
return [padding] * (training_length - leftover) + self[:]
return self[:] + [padding] * (training_length - leftover)
else:
return self[len(self) - batch_size * training_length :]

147
ml-agents/mlagents/trainers/poca/optimizer_torch.py


from typing import Dict, cast, List, Tuple, Optional
from collections import defaultdict
import math
from mlagents.torch_utils import torch, default_device
from mlagents.trainers.buffer import (

num_experiences = self_obs[0].shape[0]
all_next_value_mem = AgentBufferField()
all_next_baseline_mem = AgentBufferField()
# In the buffer, the 1st sequence are the ones that are padded. So if seq_len = 3 and
# trajectory is of length 10, the 1st sequence is [pad,pad,obs].
# When using LSTM, we need to divide the trajectory into sequences of even length. Sometimes,
# that division isn't even, and we must pad the leftover sequence.
# In the buffer, the last sequence are the ones that are padded. So if seq_len = 3 and
# trajectory is of length 10, the last sequence is [obs,pad,pad].
leftover = num_experiences % self.policy.sequence_length
leftover_seq_len = num_experiences % self.policy.sequence_length
# Compute values for the potentially truncated initial sequence
first_seq_len = leftover if leftover > 0 else self.policy.sequence_length
self_seq_obs = []
groupmate_seq_obs = []
groupmate_seq_act = []
seq_obs = []
for _self_obs in self_obs:
first_seq_obs = _self_obs[0:first_seq_len]
seq_obs.append(first_seq_obs)
self_seq_obs.append(seq_obs)
for groupmate_obs, groupmate_action in zip(obs, actions):
seq_obs = []
for _obs in groupmate_obs:
first_seq_obs = _obs[0:first_seq_len]
seq_obs.append(first_seq_obs)
groupmate_seq_obs.append(seq_obs)
_act = groupmate_action.slice(0, first_seq_len)
groupmate_seq_act.append(_act)
# For the first sequence, the initial memory should be the one at the
# beginning of this trajectory.
for _ in range(first_seq_len):
all_next_value_mem.append(ModelUtils.to_numpy(init_value_mem.squeeze()))
all_next_baseline_mem.append(
ModelUtils.to_numpy(init_baseline_mem.squeeze())
)
all_seq_obs = self_seq_obs + groupmate_seq_obs
init_values, _value_mem = self.critic.critic_pass(
all_seq_obs, init_value_mem, sequence_length=first_seq_len
)
all_values = {
signal_name: [init_values[signal_name]]
for signal_name in init_values.keys()
}
groupmate_obs_and_actions = (groupmate_seq_obs, groupmate_seq_act)
init_baseline, _baseline_mem = self.critic.baseline(
self_seq_obs[0],
groupmate_obs_and_actions,
init_baseline_mem,
sequence_length=first_seq_len,
)
all_baseline = {
signal_name: [init_baseline[signal_name]]
for signal_name in init_baseline.keys()
}
all_values: Dict[str, List[np.ndarray]] = defaultdict(list)
all_baseline: Dict[str, List[np.ndarray]] = defaultdict(list)
_baseline_mem = init_baseline_mem
_value_mem = init_value_mem
for seq_num in range(
1, math.ceil((num_experiences) / (self.policy.sequence_length))
):
for seq_num in range(num_experiences // self.policy.sequence_length):
for _ in range(self.policy.sequence_length):
all_next_value_mem.append(ModelUtils.to_numpy(_value_mem.squeeze()))
all_next_baseline_mem.append(

start = seq_num * self.policy.sequence_length - (
self.policy.sequence_length - leftover
)
end = (seq_num + 1) * self.policy.sequence_length - (
self.policy.sequence_length - leftover
)
start = seq_num * self.policy.sequence_length
end = (seq_num + 1) * self.policy.sequence_length
self_seq_obs = []
groupmate_seq_obs = []

seq_obs.append(_obs[start:end])
seq_obs.append(_self_obs[start:end])
for groupmate_obs, team_action in zip(obs, actions):
for groupmate_obs, groupmate_action in zip(obs, actions):
for (_obs,) in groupmate_obs:
first_seq_obs = _obs[start:end]
seq_obs.append(first_seq_obs)
for _obs in groupmate_obs:
sliced_seq_obs = _obs[start:end]
seq_obs.append(sliced_seq_obs)
_act = team_action.slice(start, end)
_act = groupmate_action.slice(start, end)
groupmate_seq_act.append(_act)
all_seq_obs = self_seq_obs + groupmate_seq_obs

all_values = {
signal_name: [init_values[signal_name]] for signal_name in values.keys()
}
for signal_name, _val in values.items():
all_values[signal_name].append(_val)
groupmate_obs_and_actions = (groupmate_seq_obs, groupmate_seq_act)
baselines, _baseline_mem = self.critic.baseline(

sequence_length=first_seq_len,
sequence_length=self.policy.sequence_length,
all_baseline = {
signal_name: [baselines[signal_name]]
for signal_name in baselines.keys()
}
for signal_name, _val in baselines.items():
all_baseline[signal_name].append(_val)
# Compute values for the potentially truncated initial sequence
if leftover_seq_len > 0:
self_seq_obs = []
groupmate_seq_obs = []
groupmate_seq_act = []
seq_obs = []
for _self_obs in self_obs:
last_seq_obs = _self_obs[-leftover_seq_len:]
seq_obs.append(last_seq_obs)
self_seq_obs.append(seq_obs)
for groupmate_obs, groupmate_action in zip(obs, actions):
seq_obs = []
for _obs in groupmate_obs:
last_seq_obs = _obs[-leftover_seq_len:]
seq_obs.append(last_seq_obs)
groupmate_seq_obs.append(seq_obs)
_act = groupmate_action.slice(len(_obs) - leftover_seq_len, len(_obs))
groupmate_seq_act.append(_act)
# For the last sequence, the initial memory should be the one at the
# beginning of this trajectory.
seq_obs = []
for _ in range(leftover_seq_len):
all_next_value_mem.append(ModelUtils.to_numpy(_value_mem.squeeze()))
all_next_baseline_mem.append(
ModelUtils.to_numpy(_baseline_mem.squeeze())
)
all_seq_obs = self_seq_obs + groupmate_seq_obs
last_values, _value_mem = self.critic.critic_pass(
all_seq_obs, _value_mem, sequence_length=leftover_seq_len
)
for signal_name, _val in last_values.items():
all_values[signal_name].append(_val)
groupmate_obs_and_actions = (groupmate_seq_obs, groupmate_seq_act)
last_baseline, _baseline_mem = self.critic.baseline(
self_seq_obs[0],
groupmate_obs_and_actions,
_baseline_mem,
sequence_length=leftover_seq_len,
)
for signal_name, _val in last_baseline.items():
all_baseline[signal_name].append(_val)
# Create one tensor per reward signal
all_value_tensors = {
signal_name: torch.cat(value_list, dim=0)

8
ml-agents/mlagents/trainers/tests/torch/test_ppo.py


optimizer = create_test_ppo_optimizer(
dummy_config, use_rnn=rnn, use_discrete=discrete, use_visual=visual
)
time_horizon = 15
# Time horizon is longer than sequence length, make sure to test
# process trajectory on multiple sequences in trajectory + some padding
time_horizon = 30
trajectory = make_fake_trajectory(
length=time_horizon,
observation_specs=optimizer.policy.behavior_spec.observation_specs,

for key, val in run_out.items():
assert type(key) is str
assert len(val) == 15
assert len(val) == time_horizon
assert len(all_memories) == 15
assert len(all_memories) == time_horizon
run_out, final_value_out, _ = optimizer.get_trajectory_value_estimates(
trajectory.to_agentbuffer(), trajectory.next_obs, done=True

12
ml-agents/mlagents/trainers/tests/torch/test_poca.py


}
trainer_settings.network_settings.memory = (
NetworkSettings.MemorySettings(sequence_length=16, memory_size=10)
NetworkSettings.MemorySettings(sequence_length=8, memory_size=10)
if use_rnn
else None
)

optimizer = create_test_poca_optimizer(
dummy_config, use_rnn=rnn, use_discrete=discrete, use_visual=visual
)
time_horizon = 15
time_horizon = 30
trajectory = make_fake_trajectory(
length=time_horizon,
observation_specs=optimizer.policy.behavior_spec.observation_specs,

)
for key, val in value_estimates.items():
assert type(key) is str
assert len(val) == 15
assert len(val) == time_horizon
assert len(val) == 15
assert len(val) == time_horizon
assert len(value_memories) == 15
assert len(baseline_memories) == 15
assert len(value_memories) == time_horizon
assert len(baseline_memories) == time_horizon
(
value_estimates,

9
ml-agents/mlagents/trainers/ppo/optimizer_torch.py


old_log_probs = ActionLogProbs.from_buffer(batch).flatten()
log_probs = log_probs.flatten()
loss_masks = ModelUtils.list_to_tensor(batch[BufferKey.MASKS], dtype=torch.bool)
seq_len = self.policy.sequence_length
if seq_len > 1:
# Do burn-in
_burn_in_percent = 0.2
burn_in_mask = torch.ones_like(loss_masks)
burn_in_amt = int(seq_len * _burn_in_percent)
for i in range(batch.num_experiences // seq_len):
burn_in_mask[seq_len * i : seq_len * i + burn_in_amt] = 0.0
loss_masks = loss_masks * burn_in_mask
value_loss = ModelUtils.trust_region_value_loss(
values, old_values, returns, decay_eps, loss_masks
)

正在加载...
取消
保存