-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathagent.go
187 lines (155 loc) · 4.34 KB
/
agent.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Package ppo is an agent implementation of the Proximal Policy Optimization algorithm.
package ppo
import (
"fmt"
"time"
"github.com/aunum/gold/pkg/v1/dense"
agentv1 "github.com/aunum/gold/pkg/v1/agent"
"github.com/aunum/gold/pkg/v1/common/num"
envv1 "github.com/aunum/gold/pkg/v1/env"
modelv1 "github.com/aunum/goro/pkg/v1/model"
"golang.org/x/exp/rand"
"gonum.org/v1/gonum/stat/distuv"
"gorgonia.org/tensor"
)
// Agent is a dqn agent.
type Agent struct {
// Base for the agent.
*agentv1.Base
// Hyperparameters for the dqn agent.
*Hyperparameters
// Actor chooses actions.
Actor modelv1.Model
// Critic updates params.
Critic modelv1.Model
// Memory of the agent.
Memory *Memory
env *envv1.Env
epsilon float32
steps int
ppoSteps int
}
// Hyperparameters for the dqn agent.
type Hyperparameters struct {
// Gamma is the discount factor (0≤γ≤1). It determines how much importance we want to give to future
// rewards. A high value for the discount factor (close to 1) captures the long-term effective award, whereas,
// a discount factor of 0 makes our agent consider only immediate reward, hence making it greedy.
Gamma float32
// Lambda is the smoothing factor which is used to reduce variance and stablilize training.
Lambda float32
}
// DefaultHyperparameters are the default hyperparameters.
var DefaultHyperparameters = &Hyperparameters{
Gamma: 0.99,
Lambda: 0.95,
}
// AgentConfig is the config for a dqn agent.
type AgentConfig struct {
// Base for the agent.
Base *agentv1.Base
// Hyperparameters for the agent.
*Hyperparameters
// ActorConfig is the actor model config.
ActorConfig *ModelConfig
// CriticConfig is the critic model config.
CriticConfig *ModelConfig
}
// DefaultAgentConfig is the default config for a dqn agent.
var DefaultAgentConfig = &AgentConfig{
Hyperparameters: DefaultHyperparameters,
Base: agentv1.NewBase("PPO"),
ActorConfig: DefaultActorConfig,
CriticConfig: DefaultCriticConfig,
}
// NewAgent returns a new dqn agent.
func NewAgent(c *AgentConfig, env *envv1.Env) (*Agent, error) {
if c == nil {
c = DefaultAgentConfig
}
if c.Base == nil {
c.Base = DefaultAgentConfig.Base
}
if env == nil {
return nil, fmt.Errorf("environment cannot be nil")
}
actor, err := MakeActor(c.ActorConfig, c.Base, env)
if err != nil {
return nil, err
}
critic, err := MakeCritic(c.CriticConfig, c.Base, env)
if err != nil {
return nil, err
}
return &Agent{
Base: c.Base,
Hyperparameters: c.Hyperparameters,
Actor: actor,
Critic: critic,
env: env,
}, nil
}
// Learn the agent.
func (a *Agent) Learn(event *Event) error {
err := a.Memory.Remember(event)
if err != nil {
return err
}
if a.ppoSteps > a.Memory.Len() {
return nil
}
events := a.Memory.Pop()
eventsBatch, err := events.Batch()
if err != nil {
return err
}
// Need one extra qValue for the GAE formula.
qValue, err := a.Critic.Predict(event.State)
if err != nil {
return err
}
events.QValues = append(events.QValues, qValue.(*tensor.Dense))
// calculate the advantages.
returns, advantages, err := GAE(events.QValues, events.Masks, events.Rewards, a.Gamma, a.Lambda)
if err != nil {
return err
}
err = a.Actor.Fit(modelv1.Values{
eventsBatch.States,
eventsBatch.ActionProbs,
advantages,
eventsBatch.Rewards,
eventsBatch.QValues,
}, eventsBatch.ActionOneHots)
if err != nil {
return err
}
err = a.Critic.Fit(eventsBatch.States, returns)
if err != nil {
return err
}
return nil
}
// Action selects the best known action for the given state.
func (a *Agent) Action(state *tensor.Dense) (action int, event *Event, err error) {
a.steps++
actionProbsVal, err := a.Actor.Predict(state)
if err != nil {
return action, event, err
}
actionProbs := actionProbsVal.(*tensor.Dense)
// Get action as a random value of the probability distribution.
weights := num.F32SliceToF64(actionProbs.Data().([]float32))
dist := distuv.NewCategorical(weights, rand.NewSource(uint64(time.Now().UnixNano())))
action = int(dist.Rand())
qv, err := a.Critic.Predict(state)
if err != nil {
return action, event, err
}
qValue := qv.(*tensor.Dense)
actionOneHot, err := dense.OneHotVector(action, actionProbs.Shape()[0], tensor.Float32)
if err != nil {
return action, event, err
}
event = NewEvent(state, actionProbs, actionOneHot, qValue)
return
}