Home > Articles

This chapter is from the book

6.6 Training an A2C Agent

In this section we show how to train an Actor-Critic agent to play Atari Pong using different advantage estimates—first n-step returns, then GAE. Then, we apply A2C with GAE to a continuous-control environment BipedalWalker.

6.6.1 A2C with n-Step Returns on Pong

A spec file which configures an Actor-Critic agent with n-step returns advantage estimate is shown in Code 6.7. The file is available in SLM Lab at slm_lab/spec/benchmark/a2c/a2c_nstep_pong.json.

Code 6.7 A2C with n-step returns: spec file

 1  # slm_lab/spec/benchmark/a2c/a2c_nstep_pong.json
 2
 3   {
 4     "a2c_nstep_pong": {
 5       "agent": [{
 6         "name": "A2C",
 7         "algorithm": {
 8         "name": "ActorCritic",
 9         "action_pdtype": "default",
10         "action_policy": "default",
11         "explore_var_spec": null,
12         "gamma": 0.99,
13         "lam": null,
14         "num_step_returns": 11,
15         "entropy_coef_spec": {
16           "name": "no_decay",
17           "start_val": 0.01,
18           "end_val": 0.01,
19           "start_step": 0,
20           "end_step": 0
21         },
22         "val_loss_coef": 0.5,
23         "training_frequency": 5
24       },
25       "memory": {
26         "name": "OnPolicyBatchReplay"
27       },
28       "net": {
29         "type": "ConvNet",
30         "shared": true,
31         "conv_hid_layers": [
32           [32, 8, 4, 0, 1],
33           [64, 4, 2, 0, 1],
34           [32, 3, 1, 0, 1]
35         ],
36         "fc_hid_layers": [512],
37         "hid_layers_activation": "relu",
38         "init_fn": "orthogonal_",
39         "normalize": true,
40         "batch_norm": false,
41         "clip_grad_val": 0.5,
42         "use_same_optim": false,
43         "loss_spec": {
44           "name": "MSELoss"
45         },
46         "actor_optim_spec": {
47           "name": "RMSprop",
48           "lr": 7e-4,
49           "alpha": 0.99,
50           "eps": 1e-5
51         },
52         "critic_optim_spec": {
53           "name": "RMSprop",
54           "lr": 7e-4,
55           "alpha": 0.99,
56           "eps": 1e-5
57         },
58         "lr_scheduler_spec": null,
59         "gpu": true
60         }
61       }],
62       "env": [{
63         "name": "PongNoFrameskip-v4",
64         "frame_op": "concat",
65         "frame_op_len": 4,
66         "reward_scale": "sign",
67         "num_envs": 16,
68         "max_t": null,
69         "max_frame": 1e7
70       }],
71       "body": {
72         "product": "outer",
73         "num": 1,
74       },
75       "meta": {
76         "distributed": false,
77         "log_frequency": 10000,
78         "eval_frequency": 10000,
79         "max_session": 4,
80         "max_trial": 1
81       }
82     }
83   }

Let’s walk through the main components.

  • Algorithm: The algorithm is Actor-Critic (line 8), the action policy is the default policy (line 10) for discrete action space (categorical distribution). γ is set on line 12. If lam is specified for λ (not null), then GAE is used to estimate the advantages. If num_step_returns is specified instead, then n-step returns is used (lines 13–14). The entropy coefficient and its decay during training is specified in lines 15–21. The value loss coefficient is specified in line 22.

  • Network architecture: Convolutional neural network with three convolutional layers and one fully connected layer with ReLU activation function (lines 29–37). The actor and critic use a shared network as specified in line 30. The network is trained on a GPU if available (line 59).

  • Optimizer: The optimizer is RMSprop [50] with a learning rate of 0.0007 (lines 46–51). If separate networks are used instead, it is possible to specify a different optimizer setting for the critic network (lines 52–57) by setting use_same_optim to false (line 42). Since the network is shared in this case, this is not used. There is no learning rate decay (line 58).

  • Training frequency: Training is batch-wise because we have selected OnPolicyBatchReplay memory (line 26) and the batch size is 5 × 16. This is controlled by the training_frequency (line 23) and the number of parallel environments (line 67). Parallel environments are discussed in Chapter 8.

  • Environment: The environment is Atari Pong [14, 18] (line 63).

  • Training length: Training consists of 10 million time steps (line 69).

  • Evaluation: The agent is evaluated every 10,000 time steps (line 78).

To train this Actor-Critic agent using SLM Lab, run the commands shown in Code 6.8 in a terminal. The agent should start with the score of -21 and achieve close to the maximum score of 21 on average after 2 million frames.

Code 6.8 A2C with n-step returns: training an agent

1  conda activate lab
2   python run_lab.py slm_lab/spec/benchmark/a2c/a2c_nstep_pong.json
    ↪ a2c_nstep_pong train

This will run a training Trial with four Sessions to obtain an average result. The trial should take about half a day to complete when running on a GPU. The graph and its moving average are shown in Figure 6.2.

FIGURE 6.2

FIGURE 6.2 Actor-Critic (with n-step returns) trial graphs from SLM Lab averaged over four sessions. The vertical axis shows the total rewards averaged over eight episodes during checkpoints, and the horizontal axis shows the total training frames. A moving average with a window of 100 evaluation checkpoints is shown on the right.

6.6.2 A2C with GAE on Pong

Next, to switch from n-step returns to GAE, simply modify the spec from Code 6.7 to specify a value for lam and set num_step_returns to null, as shown in Code 6.9. The file is also available in SLM Lab at slm_lab/spec/benchmark/a2c/a2c_gae_pong.json.

Code 6.9 A2C with GAE: spec file

 1 # slm_lab/spec/benchmark/a2c/a2c_gae_pong.json
 2
 3 {
 4     "a2c_gae_pong": {
 5       "agent": [{
 6         "name": "A2C",
 7         "algorithm": {
 8           ...
 9           "lam": 0.95,
10           "num_step_returns": null,
11           ...
12     }
13 }

Then, run the commands shown in Code 6.10 in a terminal to train an agent.

Code 6.10 A2C with GAE: training an agent

1 conda activate lab
2  python run_lab.py slm_lab/spec/benchmark/a2c/a2c_gae_pong.json a2c_gae_pong
   ↪ train

Similarly, this will run a training Trial to produce the graphs shown in Figure 6.3.

FIGURE 6.3

FIGURE 6.3 Actor-Critic (with GAE) trial graphs from SLM Lab averaged over four sessions.

6.6.3 A2C with n-Step Returns on BipedalWalker

So far, we have been training on discrete environments. Recall that policy-based method can also be applied directly to continuous-control problems. Now we will look at the BipedalWalker environment that was introduced in Section 1.1.

Code 6.11 shows a spec file which configures an A2C with n-step returns agent for the BipedalWalker environment. The file is available in SLM Lab at slm_lab/spec/benchmark/a2c/a2c_nstep_cont.json. In particular, note the changes in network architecture (lines 29–31) and environment (lines 54–57).

Code 6.11 A2C with n-step returns on BipedalWalker: spec file

 1  # slm_lab/spec/benchmark/a2c/a2c_nstep_cont.json
 2
 3   {
 4     "a2c_nstep_bipedalwalker": {
 5       "agent": [{
 6         "name": "A2C",
 7         "algorithm": {
 8           "name": "ActorCritic",
 9           "action_pdtype": "default",
10           "action_policy": "default",
11           "explore_var_spec": null,
12           "gamma": 0.99,
13           "lam": null,
14           "num_step_returns": 5,
15           "entropy_coef_spec": {
16            "name": "no_decay",
17            "start_val": 0.01,
18            "end_val": 0.01,
19            "start_step": 0,
20            "end_step": 0
21           },
22           "val_loss_coef": 0.5,
23           "training_frequency": 256
24         },
25         "memory": {
26           "name": "OnPolicyBatchReplay",
27       },
28       "net": {
29         "type": "MLPNet",
30         "shared": false,
31         "hid_layers": [256, 128],
32         "hid_layers_activation": "relu",
33         "init_fn": "orthogonal_",
34         "normalize": true,
35         "batch_norm": false,
36         "clip_grad_val": 0.5,
37         "use_same_optim": false,
38         "loss_spec": {
39           "name": "MSELoss"
40         },
41         "actor_optim_spec": {
42          "name": "Adam",
43          "lr": 3e-4,
44         },
45         "critic_optim_spec": {
46          "name": "Adam",
47          "lr": 3e-4,
48         },
49         "lr_scheduler_spec": null,
50         "gpu": false
51       }
52     }],
53     "env": [{
54       "name": "BipedalWalker-v2",
55       "num_envs": 32,
56       "max_t": null,
57       "max_frame": 4e6
58     }],
59     "body": {
60       "product": "outer",
61       "num": 1
62     },
63     "meta": {
64       "distributed": false,
65       "log_frequency": 10000,
66       "eval_frequency": 10000,
67       "max_session": 4,
68       "max_trial": 1
69     }
70   }
71  }

Run the commands shown in Code 6.12 in a terminal to train an agent.

Code 6.12 A2C with n-step returns on BipedalWalker: training an agent

1 conda activate lab
2  python run_lab.py slm_lab/spec/benchmark/a2c/a2c_nstep_cont.json
   ↪ a2c_nstep_bipedalwalker train

This will run a training Trial to produce the graphs shown in Figure 6.4.

FIGURE 6.4

FIGURE 6.4 Trial graphs of A2C with n-step returns on BipedalWalker from SLM Lab averaged over four sessions.

BipedalWalker is a challenging continuous environment that is considered solved when the total reward moving average is above 300. In Figure 6.4, our agent did not achieve this within 4 million frames. We will return to this problem in Chapter 7 with a better attempt.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020