|
| 1 | +import torch |
| 2 | +import torch.nn as nn |
| 3 | +import torch.nn.functional as F |
| 4 | +import numpy as np |
| 5 | + |
| 6 | +from config import gamma, max_kl |
| 7 | + |
| 8 | +def flat_grad(grads): |
| 9 | + grad_flatten = [] |
| 10 | + for grad in grads: |
| 11 | + grad_flatten.append(grad.view(-1)) |
| 12 | + grad_flatten = torch.cat(grad_flatten) |
| 13 | + return grad_flatten |
| 14 | + |
| 15 | +def flat_hessian(hessians): |
| 16 | + hessians_flatten = [] |
| 17 | + for hessian in hessians: |
| 18 | + hessians_flatten.append(hessian.contiguous().view(-1)) |
| 19 | + hessians_flatten = torch.cat(hessians_flatten).data |
| 20 | + return hessians_flatten |
| 21 | + |
| 22 | +def flat_params(model): |
| 23 | + params = [] |
| 24 | + for param in model.parameters(): |
| 25 | + params.append(param.data.view(-1)) |
| 26 | + params_flatten = torch.cat(params) |
| 27 | + return params_flatten |
| 28 | + |
| 29 | +def update_model(model, new_params): |
| 30 | + index = 0 |
| 31 | + for params in model.parameters(): |
| 32 | + params_length = len(params.view(-1)) |
| 33 | + new_param = new_params[index: index + params_length] |
| 34 | + new_param = new_param.view(params.size()) |
| 35 | + params.data.copy_(new_param) |
| 36 | + index += params_length |
| 37 | + |
| 38 | +def kl_divergence(policy, old_policy): |
| 39 | + kl = old_policy * torch.log(old_policy / policy) |
| 40 | + |
| 41 | + kl = kl.sum(1, keepdim=True) |
| 42 | + return kl |
| 43 | + |
| 44 | +def fisher_vector_product(net, states, p, cg_damp=0.1): |
| 45 | + policy = net(states) |
| 46 | + old_policy = net(states).detach() |
| 47 | + kl = kl_divergence(policy, old_policy) |
| 48 | + kl = kl.mean() |
| 49 | + kl_grad = torch.autograd.grad(kl, net.parameters(), create_graph=True) # create_graph is True if we need higher order derivative products |
| 50 | + kl_grad = flat_grad(kl_grad) |
| 51 | + |
| 52 | + kl_grad_p = (kl_grad * p.detach()).sum() |
| 53 | + kl_hessian_p = torch.autograd.grad(kl_grad_p, net.parameters()) |
| 54 | + kl_hessian_p = flat_hessian(kl_hessian_p) |
| 55 | + |
| 56 | + return kl_hessian_p + cg_damp * p.detach() |
| 57 | + |
| 58 | + |
| 59 | +def conjugate_gradient(net, states, loss_grad, n_step=10, residual_tol=1e-10): |
| 60 | + x = torch.zeros(loss_grad.size()) |
| 61 | + r = loss_grad.clone() |
| 62 | + p = loss_grad.clone() |
| 63 | + r_dot_r = torch.dot(r, r) |
| 64 | + |
| 65 | + for i in range(n_step): |
| 66 | + A_dot_p = fisher_vector_product(net, states, p) |
| 67 | + alpha = r_dot_r / torch.dot(p, A_dot_p) |
| 68 | + x += alpha * p |
| 69 | + r -= alpha * A_dot_p |
| 70 | + new_r_dot_r = torch.dot(r,r) |
| 71 | + betta = new_r_dot_r / r_dot_r |
| 72 | + p = r + betta * p |
| 73 | + r_dot_r = new_r_dot_r |
| 74 | + if r_dot_r < residual_tol: |
| 75 | + break |
| 76 | + return x |
| 77 | + |
| 78 | +class QNet(nn.Module): |
| 79 | + def __init__(self, num_inputs, num_outputs): |
| 80 | + super(QNet, self).__init__() |
| 81 | + self.t = 0 |
| 82 | + self.num_inputs = num_inputs |
| 83 | + self.num_outputs = num_outputs |
| 84 | + |
| 85 | + self.fc_1 = nn.Linear(num_inputs, 128) |
| 86 | + self.fc_2 = nn.Linear(128, num_outputs) |
| 87 | + |
| 88 | + for m in self.modules(): |
| 89 | + if isinstance(m, nn.Linear): |
| 90 | + nn.init.xavier_uniform(m.weight) |
| 91 | + |
| 92 | + def forward(self, input): |
| 93 | + x = torch.tanh(self.fc_1(input)) |
| 94 | + policy = F.softmax(self.fc_2(x)) |
| 95 | + |
| 96 | + return policy |
| 97 | + |
| 98 | + @classmethod |
| 99 | + def train_model(cls, net, transitions, k): |
| 100 | + states, actions, rewards, masks = transitions |
| 101 | + states = torch.stack(states) |
| 102 | + actions = torch.stack(actions) |
| 103 | + rewards = torch.Tensor(rewards) |
| 104 | + masks = torch.Tensor(masks) |
| 105 | + |
| 106 | + policy = net(states) |
| 107 | + policy = policy.view(-1, net.num_outputs) |
| 108 | + policy_action = (policy * actions.detach()).sum(dim=1) |
| 109 | + |
| 110 | + old_policy = net(states).detach() |
| 111 | + old_policy = old_policy.view(-1, net.num_outputs) |
| 112 | + old_policy_action = (old_policy * actions.detach()).sum(dim=1) |
| 113 | + |
| 114 | + surrogate_loss = ((policy_action / old_policy_action) * rewards).mean() |
| 115 | + |
| 116 | + surrogate_loss_grad = torch.autograd.grad(surrogate_loss, net.parameters()) |
| 117 | + surrogate_loss_grad = flat_grad(surrogate_loss_grad) |
| 118 | + |
| 119 | + step_dir = conjugate_gradient(net, states, surrogate_loss_grad.data) |
| 120 | + |
| 121 | + params = flat_params(net) |
| 122 | + shs = (step_dir * fisher_vector_product(net, states, step_dir)).sum(0, keepdim=True) |
| 123 | + step_size = torch.sqrt((2 * max_kl) / shs)[0] |
| 124 | + full_step = step_size * step_dir |
| 125 | + |
| 126 | + fraction = 1.0 |
| 127 | + for _ in range(10): |
| 128 | + new_params = params + fraction * full_step |
| 129 | + update_model(net, new_params) |
| 130 | + policy = net(states) |
| 131 | + policy = policy.view(-1, net.num_outputs) |
| 132 | + policy_action = (policy * actions.detach()).sum(dim=1) |
| 133 | + surrogate_loss = ((policy_action / old_policy_action) * rewards).mean() |
| 134 | + |
| 135 | + kl = kl_divergence(policy, old_policy) |
| 136 | + kl = kl.mean() |
| 137 | + |
| 138 | + if kl < max_kl: |
| 139 | + break |
| 140 | + fraction = fraction * 0.5 |
| 141 | + |
| 142 | + return -surrogate_loss |
| 143 | + |
| 144 | + def get_action(self, input): |
| 145 | + policy = self.forward(input) |
| 146 | + policy = policy[0].data.numpy() |
| 147 | + |
| 148 | + action = np.random.choice(self.num_outputs, 1, p=policy)[0] |
| 149 | + return action |
0 commit comments