python
import torch
import torch.nn as nn
"""
Decision Transformer(連続の行動)を、論文の 3 節と Algorithm 1 どおりに小さく書いた例。
系列は (R^_1, s_1, a_1, R^_2, s_2, a_2, ...)。状態のトークンの出力から行動を予測する。
論文の Gym の実装は Hugging Face の GPT-2 を使っている。ここでは先を隠したエンコーダ層で GPT の代わりにする。
"""
class DecisionTransformer(nn.Module):
def __init__(self, state_dim, act_dim, d=128, n_layers=3, n_heads=1, max_timestep=1000, dropout=0.1):
super().__init__()
self.embed_t = nn.Embedding(max_timestep, d) # 時刻ごとの埋め込み(トークンごとではない)
self.embed_R = nn.Linear(1, d) # 種類ごとの線形層
self.embed_s = nn.Linear(state_dim, d)
self.embed_a = nn.Linear(act_dim, d)
self.ln = nn.LayerNorm(d)
layer = nn.TransformerEncoderLayer(d, n_heads, 4 * d, dropout, activation="relu", batch_first=True)
self.gpt = nn.TransformerEncoder(layer, n_layers)
self.pred_a = nn.Sequential(nn.Linear(d, act_dim), nn.Tanh()) # 行動の範囲が [-1, 1] の環境を想定
def forward(self, R, s, a, t):
# R: [B, K, 1]、s: [B, K, state_dim]、a: [B, K, act_dim]、t: [B, K](整数の時刻)
B, K, _ = s.shape
pos = self.embed_t(t) # 同じ時刻の 3 つのトークンに同じものを足す
tokens = torch.stack(
[self.embed_R(R) + pos, self.embed_s(s) + pos, self.embed_a(a) + pos], dim=2
).reshape(B, 3 * K, -1) # (R_1, s_1, a_1, R_2, ...) の順に並べる
tokens = self.ln(tokens)
causal = torch.triu(torch.ones(3 * K, 3 * K, dtype=torch.bool, device=s.device), diagonal=1)
h = self.gpt(tokens, mask=causal) # True の位置(自分より後ろ)は見ない
h = h.reshape(B, K, 3, -1)
return self.pred_a(h[:, :, 1]) # 状態 s_t のトークンの出力から a_t を予測
state_dim, act_dim, K = 11, 3, 20
model = DecisionTransformer(state_dim, act_dim)
opt = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=1e-4)
# 学習:記録された軌跡から長さ K の区間を取り出し、行動だけに二乗誤差をかける
model.train()
R = torch.randn(4, K, 1); s = torch.randn(4, K, state_dim)
a = torch.rand(4, K, act_dim) * 2 - 1; t = torch.arange(K).repeat(4, 1)
loss = ((model(R, s, a, t) - a) ** 2).mean()
opt.zero_grad(); loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 0.25)
opt.step()
# 推論:目標の収益から始め、得た報酬を引きながら 1 ステップずつ行動を出す
@torch.no_grad()
def run_episode(env, model, target_return, max_steps=1000):
model.eval()
s0 = torch.as_tensor(env.reset(), dtype=torch.float32)
Rs, ss = [torch.tensor([float(target_return)])], [s0]
acts, ts = [], [0]
total = 0.0
for step in range(max_steps):
acts.append(torch.zeros(act_dim)) # まだ決めていない a_t の場所(先を隠すので予測には使われない)
R_in = torch.stack(Rs[-K:]).unsqueeze(0)
s_in = torch.stack(ss[-K:]).unsqueeze(0)
a_in = torch.stack(acts[-K:]).unsqueeze(0)
t_in = torch.tensor(ts[-K:]).unsqueeze(0)
action = model(R_in, s_in, a_in, t_in)[0, -1]
acts[-1] = action
s_next, r, done, _ = env.step(action.numpy())
total += r
Rs.append(Rs[-1] - r) # 残りの収益を減らす
ss.append(torch.as_tensor(s_next, dtype=torch.float32))
ts.append(step + 1)
if done:
break
return total