Imitation Learning and GAIL

Imitation Learning and GAIL

Generative Adversarial Imitation Learning

A Brief Introduction.

Imitation Learning

It is often more intuitive to simply demonstrate the behavior we want an agent to perform, rather than attempting to have it learn via trial-and-error methods. For example, instead of training the medic by setting up its reward function, this mode allows providing real examples from a game controller on how the medic should behave. More specifically, in this mode, the Brain type during training is set to Player and all the actions performed with the controller (in addition to the agent observations) will be recorded and sent to the Python API. The imitation learning algorithm will then use these pairs of observations and actions from the human player to learn a policy.

Behavioral Cloning

There are a variety of possible imitation learning algorithms which can be used, the simplest one of them is Behavioral Cloning. It works by collecting training data from a teacher, and then simply uses it to directly learn a policy, in the same way the supervised learning for image classification or other traditional Machine Learning tasks work.

Principle of Maximum Casual entropy

Principle of maximum entropy prescribes the use of “the least committed probability distribution that is consistent with known problem constraints”

maxent

위 그림은 사람들이 이동한 여러개의 path로부터 어떻게 사람들이 이동할지 maximum casual entropy를 이용하여 예측한 결과입니다. 최근에 있었던 월드컵을 생각해 보시면 크리스티아누 호날두의 경우 주로 상대 골문 앞에 주로 분포를 하겠죠? 비슷한 맥락이라고 생각하시면 됩니다.

Inverse Reinforcement Learning

gailmotiv

IRL은 위와 같이 두가지 과정으로 이루어집니다. 즉 보통의 RL에서 주어지는 reward가 명확히 주어지지 않았기 때문에 그 cost function을 찾는 과정이 이루어집니다. 즉 여러개의 “cost function 세계”를 만들어가면서 그 안에서 RL을 계산하는 과정이 이루어집니다. 딱 보기에도 매우 expensive 해 보입니다.

Inverse Reinforcement Learning as Generative Model

GAIL 논문에서는 IRL - RL 문제가 결국 각 agent가 만드는 occupancy measure를 맞추는 문제와 동일하다는 결론을 냅니다. 자세한 내용은 논문을 참고하시면 됩니다. 일단은 먼저 논문의 취지를 설명드리기 위해 그림을 넣었습니다.

gaildist

Regularization Term

regularizer

IRL로 학습이 잘 되게 하기 위해서는 위와 같이 regularizer라고 하는 term을 집어 넣게 됩니다. Cost에 어떤 structure를 impose하고 unknown dynamics를 가진 high-dimensional continuous system에서 적용하기 위해서 입니다.

혹시 더 알고 싶으신 분들은 “Guided Cost Learning: Deep Inverse Optimal Control via Policy Optimization”라는 논문을 참고해 주시면 됩니다.

GA regularization term

다음과 같이 regularization term을 잡아주면 loss function은 다음과 같이 정리됩니다. 참 쉽죠?

ga_slide

이렇게 regularization term은 준 것은 다 loss function은 Generative Adversarial model들에서 보이는 꼴의 형태로 만들기 위해서였습니다.

즉, 어떤 policy에 의해 만들어진 경로, action들의 집합을 보고 이게 과연 전문가가 만들어낸 동작들인지, 아니면 Generator가 만들어낸 동작인지 구분하게 하는, 우리가 익숙한 GAN의 setting과 동일하게 됩니다.

The GAIL algorithm

그래서 결국 논문에서는 많은 수학을 동원해서 IRL-RL 문제와 GAN이 큰 그림 아래에서 비슷하다는 것을 보였지만, 결국 제시한 알고리즘은 다음과 같습니다.

gailalg

Expert trajectory가 주어져 있고, 또 TRPO에 의해 업데이트 되는 policy가 있습니다. Discrimator를 통해서 위와 같이 loss term이 주어지게 됩니다. 실제로 코드와 함께 살펴보게 되면

...
    observations = np.reshape(observations, newshape=[-1, 2])
    actions_list = np.array(actions_list).astype(dtype=np.int32)
    for i in range(2):
        sample_indices = (np.random.randint(expert_observations.shape[0], size=observations.shape[0]))
        inp = [expert_observations, expert_actions]
        sampled_inp = [np.take(a=a, indices=sample_indices, axis=0) for a in inp] # sample training data
        D.train(expert_s=sampled_inp[0],
                expert_a=sampled_inp[1],
                agent_s=observations,
                agent_a=actions_list)
    d_rewards = D.get_rewards(agent_s=observations, agent_a=actions_list)
    d_rewards = np.reshape(d_rewards, newshape=[-1]).astype(dtype=np.float32)
...

앞에서 Discrimator인 D를 정의하고 위와 같이 reward를 받아오는 것을 볼 수 있습니다. 실제로 이게 training 된다는게 신기할 따름입니다.

discriminator는 다음과 같은 구조로 되어있습니다.

def construct_network(self, input):
    layer_1 = tf.layers.dense(inputs=input, units=20, activation=tf.nn.tanh, name='layer1')
    layer_2 = tf.layers.dense(inputs=layer_1, units=20, activation=tf.nn.tanh, name='layer2')
    layer_3 = tf.layers.dense(inputs=layer_2, units=20, activation=tf.nn.tanh, name='layer3')
    prob = tf.layers.dense(inputs=layer_3, units=1, activation=tf.sigmoid, name='prob')
    return prob

source: https://github.com/chagmgang/gail 멋진 코드 작성해주신 차금강님 감사합니다 :)

실제 다양한 환경에서 동작하는 코드를 작성 및 리팩터링 중입니다.

InfoGAIL

사람들마다 같은 행동을 하더라도, 각자의 스타일이 다르게 있습니다. 프로게이머나 바둑기사를 예시로 들면, 각자의 스타일이나 승부의 방식이 있다는 것이지요. 어떤 프로게이머는 굉장히 공격적으로 플레이하기로 유명할 수도 있고, 어떤 바둑 기사는 느긋한 플레이를 한다거나 창의적으로 둔다거나 하는 것과 마찬가지로요.

InfoGAIL은 이러한 전문가들의 플레이 스타일을 분리해 낼 수 없을까에서 출발합니다. InfoGAN 논문을 보신 분이라면 대충 감이 오실 수도 있을 것 같습니다.

pass environment with different latent codes (0 or 1)

앞의 자동차를 추월하는 environment입니다. 같은 goal이지만 추월하는 방식에는 왼쪽, 오른쪽으로 추월하는 방식이 있습니다. InfoGAIL에서는 latent variable의 형태로 disentangle을 할 수 있는데요 위 데모에서 확인하실 수 있습니다.

turn environment with different latent codes (0 or 1)

turn 환경은 커브를 돌 때 안쪽으로 갈지 바깥으로 갈지를 latent code 0 또는 1의 형태로 분리합니다.

스타크래프트 환경에서는 다양한 리플레이 데이터로부터 다음과 같이 imitation learning을 시킬 수 있을 것 같습니다.

imitation_traj

각 유닛이 존재한 분포를 통해서 어떤 action들이 좋은 action인지 알 수 있을 것이라고 생각이 되네요.

이처럼 드넓은 action_space를 가진 환경에서 GAIL과 같은 imitation 방식을 사용하는 것은 당연해보입니다. 앞으로 잘 만들어서 멋진 스타크래프트 agent가 될 수 있도록 하겠습니다.

Author face

B-Boy Seiok

Pianist, B-Boy, street artist

Recent post