-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathagent.go
262 lines (237 loc) · 6.6 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// Package her is an agent implementation of the Hindsight Experience Replay algorithm.
package her
import (
"fmt"
"math/rand"
"github.com/aunum/gold/pkg/v1/dense"
"github.com/aunum/goro/pkg/v1/model"
"github.com/aunum/gold/pkg/v1/track"
agentv1 "github.com/aunum/gold/pkg/v1/agent"
"github.com/aunum/gold/pkg/v1/common"
envv1 "github.com/aunum/gold/pkg/v1/env"
"github.com/aunum/log"
"gorgonia.org/tensor"
)
// Agent is a dqn+her agent.
type Agent struct {
// Base for the agent.
*agentv1.Base
// Hyperparameters for the dqn+her agent.
*Hyperparameters
Policy model.Model
TargetPolicy model.Model
Epsilon common.Schedule
env *envv1.Env
epsilon *track.TrackedScalarValue
updateTargetSteps int
batchSize int
memory *Memory
steps int
episodes int
successfulReward float32
}
// Hyperparameters for the dqn+her 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
// Epsilon is the rate at which the agent should exploit vs explore.
Epsilon common.Schedule
// UpdateTargetEpisodes determines how often the target network updates its parameters.
UpdateTargetEpisodes int
}
// DefaultHyperparameters are the default hyperparameters.
var DefaultHyperparameters = &Hyperparameters{
Epsilon: common.DefaultDecaySchedule(),
Gamma: 0.9,
UpdateTargetEpisodes: 50,
}
// AgentConfig is the config for a dqn+her agent.
type AgentConfig struct {
// Base for the agent.
Base *agentv1.Base
// Hyperparameters for the agent.
*Hyperparameters
// PolicyConfig for the agent.
PolicyConfig *PolicyConfig
// SuccessfulReward is the reward for reaching the goal.
SuccessfulReward float32
// MemorySize is the size of the memory.
MemorySize int
}
// DefaultAgentConfig is the default config for a dqn+her agent.
var DefaultAgentConfig = &AgentConfig{
Hyperparameters: DefaultHyperparameters,
PolicyConfig: DefaultPolicyConfig,
Base: agentv1.NewBase("HER"),
SuccessfulReward: 0,
MemorySize: 1e4,
}
// NewAgent returns a new dqn+her 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")
}
if c.Epsilon == nil {
c.Epsilon = common.DefaultDecaySchedule()
}
policy, err := MakePolicy("online", c.PolicyConfig, c.Base, env)
if err != nil {
return nil, err
}
c.PolicyConfig.Track = false
targetPolicy, err := MakePolicy("target", c.PolicyConfig, c.Base, env)
if err != nil {
return nil, err
}
epsilon := c.Base.Tracker.TrackValue("epsilon", c.Epsilon.Initial())
return &Agent{
Base: c.Base,
Hyperparameters: c.Hyperparameters,
memory: NewMemory(c.MemorySize),
Policy: policy,
TargetPolicy: targetPolicy,
Epsilon: c.Epsilon,
epsilon: epsilon.(*track.TrackedScalarValue),
env: env,
updateTargetSteps: c.UpdateTargetEpisodes,
batchSize: c.PolicyConfig.BatchSize,
successfulReward: c.SuccessfulReward,
}, nil
}
// Learn the agent.
func (a *Agent) Learn() error {
if a.memory.Len() < a.batchSize {
return nil
}
batch, err := a.memory.Sample(a.batchSize)
if err != nil {
return err
}
batchStates := []*tensor.Dense{}
batchQValues := []*tensor.Dense{}
for _, event := range batch {
qUpdate := float32(event.Reward)
if !event.Done {
obvGoal, err := event.Observation.Concat(1, event.Goal)
if err != nil {
return err
}
targetPred, err := a.TargetPolicy.Predict(obvGoal)
if err != nil {
return err
}
qValues := targetPred.(*tensor.Dense)
nextMax, err := dense.AMaxF32(qValues, 1)
if err != nil {
return err
}
qUpdate = event.Reward + (a.Gamma * nextMax)
}
stateGoal, err := event.State.Concat(1, event.Goal)
if err != nil {
return err
}
prediction, err := a.Policy.Predict(stateGoal)
if err != nil {
return err
}
qValues := prediction.(*tensor.Dense)
qValues.Set(event.Action, qUpdate)
batchStates = append(batchStates, stateGoal)
batchQValues = append(batchQValues, qValues)
}
states, err := dense.Concat(0, batchStates...)
if err != nil {
return err
}
qValues, err := dense.Concat(0, batchQValues...)
if err != nil {
return err
}
err = a.Policy.FitBatch(states, qValues)
if err != nil {
return err
}
a.episodes++
err = a.updateTarget()
if err != nil {
return err
}
return nil
}
// updateTarget copies the weights from the online network to the target network on the provided interval.
func (a *Agent) updateTarget() error {
if a.episodes%a.UpdateTargetEpisodes == 0 {
log.Infof("updating target model - current steps %v target update %v", a.steps, a.updateTargetSteps)
err := a.Policy.(*model.Sequential).CloneLearnablesTo(a.TargetPolicy.(*model.Sequential))
if err != nil {
return err
}
}
return nil
}
// Action selects the best known action for the given state.
func (a *Agent) Action(state, goal *tensor.Dense) (action int, err error) {
a.steps++
defer func() { a.epsilon.Set(a.Epsilon.Value()) }()
if rand.Float64() < a.epsilon.Scalar() {
// explore
action, err = a.env.SampleAction()
if err != nil {
return
}
log.Infov("taking random action", action)
return
}
action, err = a.action(state, goal)
log.Infov("taking action", action)
return
}
func (a *Agent) action(state, goal *tensor.Dense) (action int, err error) {
stateGoal, err := state.Concat(1, goal)
if err != nil {
return action, err
}
prediction, err := a.Policy.Predict(stateGoal)
if err != nil {
return
}
qValues := prediction.(*tensor.Dense)
actionIndex, err := qValues.Argmax(1)
if err != nil {
return action, err
}
action = actionIndex.GetI(0)
return
}
// Remember events.
func (a *Agent) Remember(event ...*Event) {
a.memory.Remember(event...)
}
// Hindsight applies hindsight to the memory.
func (a *Agent) Hindsight(episodeEvents Events) error {
log.Debug("running hindsight")
altBatch := episodeEvents.Copy()
finalEvent := altBatch[len(altBatch)-1]
for i, event := range altBatch {
event.Goal = finalEvent.Outcome.Observation
if i == len(altBatch)-1 {
event.Reward = a.successfulReward
event.Done = true
}
a.memory.Remember(event)
err := a.Learn()
if err != nil {
return err
}
}
return nil
}