├── .gitignore
├── LICENSE
├── README.md
├── drlbox
├── common
│ ├── namescope.py
│ ├── policy.py
│ ├── replay.py
│ ├── tasker.py
│ └── util.py
├── evaluator
│ ├── __init__.py
│ ├── ac_eval.py
│ ├── acer_eval.py
│ ├── dqn_eval.py
│ ├── eval_base.py
│ └── make_evaluator.py
├── layer
│ └── noisy_dense.py
├── net
│ ├── __init__.py
│ ├── ac_net.py
│ ├── acer_net.py
│ ├── net_base.py
│ └── q_net.py
└── trainer
│ ├── __init__.py
│ ├── a3c_trainer.py
│ ├── acer_trainer.py
│ ├── dqn_trainer.py
│ ├── impala_trainer.py
│ ├── make_trainer.py
│ ├── rollout.py
│ ├── step_counter.py
│ └── trainer_base.py
├── examples
├── atari_wrappers
│ ├── __init__.py
│ ├── episodic_life.py
│ ├── history.py
│ ├── preprocess.py
│ └── reward.py
├── breakout_acer.py
└── cartpole_a3c.py
├── pylintrc
├── requirements.txt
├── setup.py
└── utils
└── learning_curve.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | __pycache__
3 | output
4 |
5 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DRLBox: Deep Reinforcement Learning as a (black) Box
2 | Supports *only Python3* (oops).
3 |
4 | ## Designing principle
5 | Most (deep) RL algorithms work by optimizing a neural network through interacting with a learning environment. The goal of this package is to **minimize** the implementation effort of RL practitioners. They only need to implement (or, more commonly, wrap) an **OpenAI-gym environment** and a neural network they want to use as a **`tf.keras` model** (along with an interface function that turns the `observation` from the gym environment into a format that can be fed into the `tf.keras` model), in order to run RL algorithms.
6 |
7 | ## Install
8 | `pip install -e .` in your favorite virtual env.
9 |
10 | ## Requirements
11 | - tensorflow>=1.5.0
12 | - gym>=0.9.6
13 | - gym[atari] (optional)
14 |
15 | ## Currently implemented RL algorithms
16 | - **Actor-critic family**
17 | - **A3C** (https://arxiv.org/abs/1602.01783) Actor-critic, using a critic-based advantage function as the baseline for variance reduction, asynchronous parallel.
18 | - **ACER** (https://arxiv.org/abs/1611.01224) A3C with uniform replay, using the Retrace off-policy correction. The critic becomes a state-action value function instead of a state-only function. The authors proposed a trust-region optimization scheme based on the KL divergence wrt a Polyak averaging policy network. This implementation however includes the KL divergence (with a tunable scale factor) in the total loss. This choice is less stable wrt change in hyperparameters, but simplifies the combination of ACER and ACKTR.
19 | - **IMPALA** (https://arxiv.org/abs/1802.01561) A3C with replay and another (actually, a simpler) flavor of off-policy correction called V-trace. This implementation is a lot more naive compared with the original distributed framework, however it gives an idea of how the off-policy correction is done and is much easier to integrate with ACKTR.
20 |
21 | - **DQN family**
22 | - **DQN** (https://arxiv.org/abs/1602.01783) Asynchronous multi-step Q-learning.
23 |
24 | - **Algorithm related options**
25 | - `noisynet='ig'` or `noisynet='fg'`: Based on the idea of **NoisyNet** (https://arxiv.org/abs/1706.10295), which introduces independent (`'ig'`) or factorized (`'fg'`) Gaussian noises to network weights. Allows the exploration strategy to change across different training stages and adapt to different parts of the state representation.
26 |
27 | # Usage
28 | ## Arguments
29 | - **Arguments shared by `trainer` and `evaluator` classes**
30 | - `env_maker`: *callable*. Returns a gym env on calling. Detailed in the **Gym Environment** section below. Default: `None`.
31 | - `state_to_input`: *callable*. Converts the `observation` from a gym env to some data (usually NumPy array) that can be fed into a `tf.keras` model. Detailed in the **Neural network** section below. Default: `None` (will set `self.state_to_input = lambda x: x` internally if set to `None`).
32 | - `load_model`: *`str`*. File name (full path) of a `h5py` file that contains a saved `tf.keras` model (usually saved through [`tf.keras.models.Model:save`](https://www.tensorflow.org/api_docs/python/tf/keras/Model#save)). If specified, training or evaluation will start from this model. Default: `None`.
33 | - `load_model_custom`: *`dict`*. As same as the `custom_objects` argument in [`tf.keras.models.load_model`](https://www.tensorflow.org/api_docs/python/tf/keras/models/load_model). Default: `None`.
34 | - `verbose`: *`bool`*. Whether or not to print training/evaluating information. Default: `False`.
35 | - **`trainer` classes common arguments**
36 | - `feature_maker`: *callable*. Takes in `env.observation_space` and returns `(inp_state, feature)`, a 2-tuple of a `tf.keras.layers.Input` layer and an arbitrary typed (e.g., `tf.keras.layes.Dense`) `tf.keras` layer. Detailed in the **Neural network** section below. Default: `None`.
37 | - `model_maker`: *callable*. Takes in a gym env and returns a `tf.keras` model. Detailed in the **Neural network** section below. The trainer will ignore `feature_maker` if `model_maker` is set. Default: `None`.
38 | - `num_parallel`: *`int`*. Number of parallel processes in training. Default: number of cpu (logical) core counts.
39 | - `port_begin`: *`int`*. Starting gRPC port number used by distributed tensorflow. Default: `2220`.
40 | - `discount`: *`float`*. Discount factor (gamma) in reinforcement learning. Default: `0.99`.
41 | - `train_steps`: *`int`*. Maximum number of gym env steps in training. Default: `1000000`.
42 | - `rollout_maxlen`: *`int`*. Maximum length of a rollout. Also the number of env steps in a rollout list. Please refer to the comments in [drlbox/trainer/trainer_base.py](drlbox/trainer/trainer_base.py) for detail explanation. Default: `32`.
43 | - `batch_size`: *`int`*. Number of rollout lists in a batch. Please refer to the comments in [drlbox/trainer/trainer_base.py](drlbox/trainer/trainer_base.py) for details. Default: `1`.
44 | - `online_learning`: *`bool`*. Whether or not to perform online learning on a newly collected batch. Default: `True`.
45 | - `replay_type`: *`None` or `str`*. Type of the replay memory. Choices are `[None, 'uniform']` where `None` means no replay memory. Default: `None` (note: some algorithms such as ACER and IMPALA will set `replay_type='uniform'` by default).
46 | - `replay_ratio`: *`int`*. After putting a newly collected online batch into the replay memory, a random integer number of offline, off-policy batch learnings will be performed, and the random integer number will be coming from a Poisson distribution using this argument as the Poisson parameter. Default: `4`.
47 | - `replay_kwargs`: *`dict`*. Keyword arguments that will be passed to the replay constructor after combining with the default replay keyword arguments `dict(maxlen=1000, minlen=100)`. Default: `{}`.
48 | - `optimizer`: *`str` or a `tf.train.Optimizer` instance*. `str` choices are `['adam']`. Default: `adam`.
49 | - `opt_clip_norm`: *`float`*. Maximum global gradient norm for gradient clipping. Default: `40.0`.
50 | - `opt_kwargs`: *`dict`*. Keyword arguments that will be passed to the optimizer constructor after combining with the default keyword arguments. For `'adam'`, the default keyword arguments are `dict(learning_rate=1e-4, epsilon=1e-4)`. Default: `{}`.
51 | - `noisynet`: *`None` or `str`*. Whether or not to enable NoisyNet in building the neural net. Detailed in the above **Algorithm related options** section. `str` choices are `['fg', 'ig']` corresponding to factorized and independent Gaussian noises, respectively. Default: `None`.
52 | - `save_dir`: *`str`*. Path to save intermediate `tf.keras` models during training. Will not save any model if set to `None`. Defaul: `None`.
53 | - `save_interval`: *`int`*. Number of (global) env steps between saving `tf.keras` models during training. Default: `10000`.
54 | - `catch_signal`: *`bool`*. Whether or not to catch `sigint` and `sigterm` during multiprocess training. Useful in cleaning up dangling processes when run in background but may prevent other parts of the program to respond to signals. Default: `False`.
55 | - **`algorithm='a3c'` introduces the following additional arguments**
56 | - `a3c_entropy_weight`: *`float`*. Weight of the entropy term in the A3C loss. When `noisynet` is not `None`, it is recommended to set this argument to `0.0`. Default: `1e-2`.
57 | - **`algorithm='acer'` introduces the following additional arguments**
58 | - `acer_kl_weight`: *`float`*. Weight of the KL divergence term wrt the average net in the ACER loss. Default: `1e-1`.
59 | - `acer_trunc_max`: *`float`*. Truncating threshold in ACER's modified Retrace off-policy correction. Default: `10.0`.
60 | - `acer_soft_update_ratio`: *`float`*. Soft update ratio to the average net. At each online network weight update, the weights in the average net will be a convex combination of the old average net weights and the new online network weights, and the coefficient of the new online network weights is this argument. Default: `0.05`.
61 | - **`algorithm='impala'` introduces the following additional arguments**
62 | - `impala_trunc_rho_max`: *`float`*. Truncating threshold *rho* in IMPALA's V-trace off-policy correction. Default: `1.0`.
63 | - `impala_trunc_c_max`: *`float`*. Truncating threshold *c* in IMPALA's V-trace off-policy correction. Default: `1.0`.
64 | - **`algorithm='dqn'` introduces the following additional arguments**
65 | - `dqn_double`: *`bool`*. Whether to perform double DQN update or regular DQN update. Default: `True`.
66 | - `dqn_dueling`: *`bool`*. Whether to setup the DQN network as a dueling network (https://arxiv.org/abs/1511.06581). Default: `False`.
67 | - `policy_eps_start`: *`float`*. Starting epsilon in the linearly decayed epsilon greedy policy. Default: `1.0`.
68 | - `policy_eps_end`: *`float`*. Ending epsilon in the linearly decayed epsilon greedy policy. Default: `0.01`.
69 | - `policy_eps_decay_steps`: *`int`*. Number of (per-process) env steps before the linearly decayed epsilon to reach its minimum. Default: `1000000`.
70 | - `sync_target_interval`: *`int`*. Number of online updates between two synchronizations of the target network. Default: `1000`.
71 | - **`evaluator` arguments**
72 | - `render_timestep`: *`None` or `float`*. Timestep between two `env.render()` calls. `None` means no rendering. Default: `None`.
73 | - `render_end`: *`bool`*. If set to `True`, will do one `env.render()` call after each episode ends. Default: `False`.
74 | - `num_episodes`: *`int`*. Number of evalution episodes. Default: `20`.
75 | - `policy_type`: *`str`*. Type of evaluation policy. Choices are `['stochastic', 'greedy']`. Default: `stochastic`.
76 | - `policy_eps`: *`float`*. Epsilon in the epsilon greedy policy when `policy_type='greedy'`. Default: `0.0`.
77 |
78 |
79 | ## Demo
80 | A minimal demo could be as simple as the following code snippet (in `examples/cartpole_a3c.py`). (A3C algorithm, `CartPole-v0` environment, and a 2-layer fully-connected net with 200/100 hidden units in each layer.)
81 | ```python
82 | '''
83 | cartpole_a3c.py
84 | '''
85 | import gym
86 | from tensorflow.python.keras.layers import Input, Dense, Activation
87 | from drlbox.trainer import make_trainer
88 |
89 |
90 | '''
91 | Input arguments:
92 | observation_space: Observation space of the environment;
93 | num_hid_list: List of hidden unit numbers in the fully-connected net.
94 | '''
95 | def make_feature(observation_space, num_hid_list):
96 | inp_state = Input(shape=observation_space.shape)
97 | feature = inp_state
98 | for num_hid in num_hid_list:
99 | feature = Dense(num_hid)(feature)
100 | feature = Activation('relu')(feature)
101 | return inp_state, feature
102 |
103 |
104 | '''
105 | A3C, CartPole-v0
106 | '''
107 | if __name__ == '__main__':
108 | trainer = make_trainer(
109 | algorithm='a3c',
110 | env_maker=lambda: gym.make('CartPole-v0'),
111 | feature_maker=lambda obs_space: make_feature(obs_space, [200, 100]),
112 | num_parallel=1,
113 | train_steps=1000,
114 | verbose=True,
115 | )
116 | trainer.run()
117 | ```
118 |
119 | ## Gym Environment
120 | ### Implementing an OpenAI-gym environment maker
121 | The user is supposed to implement a `env_maker` callable which returns **an OpenAI-gym environment**. Things like history stacking/frame skipping/reward engineering are usually handled here as well.
122 |
123 | The above code snippet contains a trivial example:
124 | ```python
125 | env_maker=lambda: gym.make('CartPole-v0')
126 | ```
127 | which is a callable that returns the `'CartPole-v0'` environment.
128 |
129 |
130 | ## Neural network
131 | ### Implementing (part of) a `tf.keras` model
132 | The user is supposed to implement a `feature_maker` callable which takes in an `observation_space` ([explanation](https://gym.openai.com/docs)) and returns `inp_state`, a `tf.keras.layers.Input` layer, and `feature`, a `tf.keras` layer or a tuple of 2 `tf.keras` layers. For example, with actor-critic algorithms, when `feature` is a `tf.keras` layer, the actor and the critic streams share a common stack of layers. When `feature` is a tuple of 2 `tf.keras` layers, the actor and the critic will be completely separated).
133 |
134 | #### Example
135 | The above code snippet `cartpole_a3c.py` also contains a trivial example for the part of a `tf.keras` model:
136 | ```python
137 | from tensorflow.python.keras.layers import Input, Dense, Activation
138 |
139 | '''
140 | Input arguments:
141 | observation_space: Observation space of the environment;
142 | num_hid_list: List of hidden unit numbers in the fully-connected net.
143 | '''
144 | def make_feature(observation_space, num_hid_list):
145 | inp_state = Input(shape=observation_space.shape)
146 | feature = inp_state
147 | for num_hid in num_hid_list:
148 | feature = Dense(num_hid)(feature)
149 | feature = Activation('relu')(feature)
150 | return inp_state, feature
151 | ```
152 | which makes a fully-connected neural network until the last layer before the policy/value layer. To use the default feature maker, simply let the feature-maker callable be `feature_maker=lambda obs_space: make_feature(obs_space, [200, 100])`.
153 |
154 | ### Implementing a full `tf.keras` model
155 | Alternatively, it is possible to specify a full `tf.keras` model by implementing a `model_maker` callable. `model_maker` should take in the full gym `env` and returns a `tf.keras` model that satisfies the output requirements for each kind of training algorithm. Its `model.inputs` should always be a 1-tuple like `(inp_state,)` where `inp_state` is a `tf.keras.layers.Input` layer. Its `model.outputs` should also be a tuple but the content varies according to the selected algorithm. For example, with `algorithm='a3c'`, `model.outputs` should be a 2-tuple of `(logits, value)`; with `algorithm='dqn'`, `model.outputs` should be a 1-tuple of `(q_values,)`.
156 |
157 | #### Example
158 | The following code snippet contains a trivial example for implementing a full `tf.keras` model for A3C or IMPALA:
159 | ```python
160 | from tensorflow.python.keras.initializers import RandomNormal
161 | from tensorflow.python.keras.layers import Input, Dense, Activation
162 | from tensorflow.python.keras.models import Model
163 |
164 | '''
165 | Input arguments:
166 | env: Gym env;
167 | num_hid_list: List of hidden unit numbers in the fully-connected net.
168 | '''
169 | def make_feature(env, num_hid_list):
170 | inp_state = Input(shape=env.observation_space.shape)
171 | feature = inp_state
172 | for num_hid in num_hid_list:
173 | feature = Dense(num_hid)(feature)
174 | feature = Activation('relu')(feature)
175 | logits_init = RandomNormal(stddev=1e-3)
176 | logits = Dense(env.action_space.n, kernel_initializer=logits_init)(feature)
177 | value = Dense(1)(feature)
178 | return Model(inputs=inp_state, outputs=[logits, value])
179 | ```
180 | A more detailed example can be found in `examples/breakout_acer.py`.
181 |
182 | ### Implementing an interface function
183 | The user is also supposed to implement a `state_to_input` callable which takes in the `observation` from the output of the OpenAI-gym environment's `reset` or `step` function ([explanation](https://gym.openai.com/docs)) and returns something that a `tf.keras` model can directly take in. Usually, this function does stuffs like `numpy` stackings/reshapings/etc. By default, `state_to_input` is set to `None`, in which case the a dummy callable `state_to_input = lambda x: x` will be created and used internally.
184 |
185 | **Note:** So long as `feature_maker` or `model_maker` is implemented correctly, the trainer will run. However, to utilize the saving/loading functionalities provided by Keras in a hassle-free manner, when writing `feature_maker` or `model_maker` it is recommended to only use combinations of Keras layers that already exist, plus some viable NumPy utilities such as `np.newaxis` (NumPy has to be imported as `import numpy as np` as this is the default importing method assumed by Keras in 'keras/layers/core.py'). It is discouraged to use other modules including plain TensorFlow, as the Keras model loading utility will literally "remember" your code of generating the Keras model and run through the code when it tries to load a saved model. If we really have to, try to import the needed functionalities **inside** `feature_maker` or `model_maker` so that it will be imported before execution. However, please do not import the entire TensorFlow (`from tensorflow import x` is fine but no `import tensorflow as tf`) in `feature_maker` or `model_maker` as it will cause circular importing.
186 |
187 |
188 |
--------------------------------------------------------------------------------
/drlbox/common/namescope.py:
--------------------------------------------------------------------------------
1 |
2 | TF_NAMESCOPE = 'drlbox'
3 |
--------------------------------------------------------------------------------
/drlbox/common/policy.py:
--------------------------------------------------------------------------------
1 | """Policies for discrete/continuous action spaces"""
2 | import numpy as np
3 | from drlbox.common.util import softmax
4 |
5 |
6 | class Policy:
7 | """Base policy class"""
8 |
9 | def select_action(self, *args, **kwargs):
10 | """Base class select_action method"""
11 | raise NotImplementedError('This method should be overriden.')
12 |
13 |
14 | class RandomPolicy(Policy):
15 | """Random policy for discrete action space"""
16 |
17 | def __init__(self, num_act):
18 | """
19 | Args:
20 | num_act: number of the discrete actions
21 | """
22 | assert num_act >= 1
23 | self.num_act = num_act
24 |
25 | def select_action(self):
26 | """Returns an integer representing the discrete action
27 | """
28 | return np.random.randint(0, self.num_act)
29 |
30 |
31 |
32 | class EpsGreedyPolicy(Policy):
33 | """Epsilon greedy for discrete action space
34 | With probability epsilon select a random action; otherwise greedy
35 | (so that when epsilon = 0.0 it falls back to greedy policy).
36 | Works only with discrete actions
37 | """
38 |
39 | def __init__(self, epsilon):
40 | self.epsilon = epsilon
41 |
42 | def select_action(self, action_values):
43 | """Returns an integer representing the discrete action
44 | """
45 | if np.random.rand() < self.epsilon:
46 | return np.random.randint(0, action_values.size)
47 | else:
48 | return action_values.argmax()
49 |
50 |
51 | class DecayEpsGreedyPolicy(EpsGreedyPolicy):
52 | """Epsilon greedy with linear decay, works only with discrete actions
53 | """
54 |
55 | def __init__(self, eps_start, eps_end, eps_delta):
56 | """
57 | Args:
58 | eps_start: float, starting value of epsilon
59 | eps_end: float, ending value of epsilon
60 | eps_delta: float, for every 'select_action' call, epsilon will be
61 | decreased by this quantity
62 | """
63 | self.epsilon = eps_start
64 | self.eps_end = eps_end
65 | self.eps_delta = eps_delta
66 |
67 | def select_action(self, action_values):
68 | """Returns an integer representing the discrete action
69 | """
70 | if np.random.rand() < self.epsilon:
71 | action = np.random.randint(0, action_values.size)
72 | else:
73 | action = action_values.argmax()
74 | self.epsilon = max(self.eps_end, self.epsilon - self.eps_delta)
75 | return action
76 |
77 |
78 | class SoftmaxPolicy(Policy):
79 | """Softmax policy for discrete action space"""
80 |
81 | def select_action(self, action_values):
82 | """Returns an integer representing the discrete action
83 | 'action_values' is supposed to be 'logits', i.e., before softmax
84 | """
85 | probs = softmax(action_values)
86 | return np.random.choice(len(probs), p=probs)
87 |
88 |
89 | class GaussianPolicy(Policy):
90 | """Gaussian policy for continuous action space"""
91 |
92 | min_var=1e-4
93 |
94 | def __init__(self, low, high):
95 | """
96 | Args:
97 | low: np.array, each entry is the lower bound on that dimension
98 | high: np.array, each entry is the higher bound on that dimension
99 | """
100 | self.low = low
101 | self.high = high
102 |
103 | def select_action(self, action_values):
104 | """Returns an np.array of floats representing the continuous action
105 | 'action_values' is supposed to be 'logits'. In continuous control,
106 | 'action_values' is interpreted as a spherical Gaussian signal where
107 | action_values[:-1] is the mean, and action_values[-1] is the variance.
108 | """
109 | dim_action = len(action_values) - 1
110 | mean, var_param = action_values[:-1], action_values[-1]
111 | var = max(np.logaddexp(var_param, 0.0), self.min_var) # softplus
112 | action = np.random.multivariate_normal(mean, var * np.eye(dim_action))
113 | return np.clip(action, a_min=self.low, a_max=self.high)
114 |
115 |
116 |
--------------------------------------------------------------------------------
/drlbox/common/replay.py:
--------------------------------------------------------------------------------
1 | """Replay memories, uniform and prioritized"""
2 | import random
3 | import pickle
4 |
5 |
6 | FILL_PERCENT = 0.1
7 |
8 |
9 | class Replay:
10 | """Ring-buffer uniformly sampled replay memory.
11 | Both 'append' and 'sample' are O(1)
12 | """
13 |
14 | def __init__(self, maxlen, minlen=None):
15 | self.maxlen = maxlen
16 | if minlen is None:
17 | self.minlen = FILL_PERCENT * self.maxlen
18 | else:
19 | self.minlen = minlen
20 | self.ring_buffer = [None] * self.maxlen
21 | self.index = 0
22 | self.length = 0
23 |
24 | def append(self, transition):
25 | self.ring_buffer[self.index] = transition
26 | self.index = (self.index + 1) % self.maxlen
27 | self.length = min(self.length + 1, self.maxlen)
28 |
29 | def extend(self, batch):
30 | for transition in batch:
31 | self.append(transition)
32 |
33 | def sample(self, batch_size):
34 | batch_idx = [random.randrange(len(self)) for _ in range(batch_size)]
35 | batch = [self.ring_buffer[i] for i in batch_idx]
36 | return batch, batch_idx, [None] * batch_size
37 |
38 | def __len__(self):
39 | return self.length
40 |
41 | def usable(self):
42 | return len(self) >= self.minlen
43 |
44 | def save(self, filepath):
45 | with open(filepath, 'wb') as save:
46 | pickle.dump(self, save, protocol=pickle.HIGHEST_PROTOCOL)
47 |
48 | @staticmethod
49 | def load(filepath):
50 | with open(filepath, 'rb') as save:
51 | replay = pickle.load(save)
52 | return replay
53 |
54 |
55 |
56 | class PriorityReplay(Replay):
57 | """Proportional prioritization with ring-buffer and sum-tree indexing."""
58 |
59 | priority_eps = 1e-8
60 |
61 | def __init__(self, maxlen, minlen=None, evict_rule='oldest',
62 | alpha=0.6, beta=0.4, beta_delta=1e-8):
63 | super().__init__(maxlen, minlen)
64 | size_sum_tree = 2 * self.maxlen - 1
65 | self.sum_tree = [0.0] * size_sum_tree
66 | self.evict_rule = evict_rule
67 | if evict_rule == 'sample':
68 | self.sum_tree_evict = [0.0] * size_sum_tree
69 | self.alpha = alpha
70 | self.beta = beta
71 | self.beta_delta = beta_delta
72 | self.max_un_prob = 1.0 # max priority we've ever seen so far
73 |
74 | def append(self, transition, priority=None):
75 | un_prob = self.exponent_priority(priority)
76 | if len(self) < self.maxlen or self.evict_rule == 'oldest':
77 | self.update_idx(self.index, un_prob)
78 | super().append(transition)
79 | elif self.evict_rule == 'sample':
80 | _, evict_idx, _ = self.sample_sum_tree(1, self.sum_tree_evict)
81 | evict_idx = evict_idx[0]
82 | self.update_idx(evict_idx, un_prob)
83 | self.ring_buffer[evict_idx] = transition
84 | else:
85 | raise TypeError('evict rule {} invalid'.format(self.evict_rule))
86 |
87 | def extend(self, batch, batch_priority=None):
88 | if batch_priority is None:
89 | batch_priority = [None] * len(batch)
90 | for transition, priority in zip(batch, batch_priority):
91 | self.append(transition, priority)
92 |
93 | def sample(self, batch_size):
94 | batch_result = self.sample_sum_tree(batch_size, self.sum_tree)
95 | self.beta = min(1.0, self.beta + self.beta_delta)
96 | return batch_result
97 |
98 | def sample_sum_tree(self, batch_size, sum_tree):
99 | len_seg = sum_tree[0] / batch_size
100 | rand_list = [(random.random() + i) * len_seg for i in range(batch_size)]
101 | batch, batch_idx, batch_weights = [], [], []
102 | for rand in rand_list:
103 | ring_idx, un_prob, transition = self.get_leaf(rand, sum_tree)
104 | batch.append(transition)
105 | batch_idx.append(ring_idx)
106 | weight = (un_prob / sum_tree[0])**(-self.beta)
107 | batch_weights.append(weight)
108 | max_weight = max(batch_weights)
109 | batch_weights = [w / max_weight for w in batch_weights]
110 | return batch, batch_idx, batch_weights
111 |
112 | def update_priority(self, batch_idx, batch_priority):
113 | for ring_idx, priority in zip(batch_idx, batch_priority):
114 | un_prob = self.exponent_priority(priority)
115 | self.update_idx(ring_idx, un_prob)
116 |
117 | def exponent_priority(self, priority):
118 | if priority is None:
119 | return self.max_un_prob
120 | else:
121 | un_prob = (abs(priority) + self.priority_eps)**self.alpha
122 | self.max_un_prob = max(self.max_un_prob, un_prob)
123 | return un_prob
124 |
125 | def update_idx(self, ring_idx, un_prob):
126 | self.update_sum_tree(ring_idx, un_prob, self.sum_tree)
127 | if self.evict_rule == 'sample':
128 | self.update_sum_tree(ring_idx, 1.0 / un_prob, self.sum_tree_evict)
129 |
130 | def update_sum_tree(self, ring_idx, un_prob, sum_tree):
131 | leaf_idx = ring_idx + (self.maxlen - 1)
132 | change = un_prob - sum_tree[leaf_idx]
133 | sum_tree[leaf_idx] = un_prob
134 | while leaf_idx:
135 | leaf_idx = (leaf_idx - 1) // 2
136 | sum_tree[leaf_idx] += change
137 |
138 | def get_leaf(self, value, sum_tree):
139 | """
140 | Tree structure and array storage:
141 | Tree index:
142 | 0 -> storing the sum of unnormalized probabilities
143 | / \
144 | 1 2
145 | / \ / \
146 | 3 4 5 6 -> storing unnormalized probabilities for transitions
147 | Array type for storing:
148 | [0, 1, 2, 3, 4, 5, 6]
149 | """
150 | parent = 0
151 | while True:
152 | left = 2 * parent + 1
153 | right = left + 1
154 | if left >= len(sum_tree): # reach bottom, end search
155 | leaf_idx = parent
156 | break
157 | else:
158 | if value <= sum_tree[left]:
159 | parent = left
160 | else:
161 | value -= sum_tree[left]
162 | parent = right
163 | ring_idx = leaf_idx - (self.maxlen - 1)
164 | return ring_idx, sum_tree[leaf_idx], self.ring_buffer[ring_idx]
165 |
166 |
--------------------------------------------------------------------------------
/drlbox/common/tasker.py:
--------------------------------------------------------------------------------
1 |
2 | import sys
3 | import h5py
4 | import json
5 | import tensorflow as tf
6 | from drlbox.layer.noisy_dense import NoisyDenseIG, NoisyDenseFG
7 |
8 |
9 | TASKER_KWARGS = dict(
10 | env_maker=None,
11 | state_to_input=None,
12 | load_model=None,
13 | load_model_custom=None,
14 | verbose=False,
15 | )
16 |
17 | class Tasker:
18 |
19 | KWARGS = TASKER_KWARGS
20 |
21 | def __init__(self, **kwargs):
22 | # combine arguments from self.KWARGS and kwargs and set arguments
23 | self.__dict__.update(self.KWARGS)
24 | self.__dict__.update(kwargs)
25 | self.print_kwargs(self.__dict__, 'All arguments', default=self.KWARGS)
26 |
27 | # set self.state_to_input to 'do nothing' if it is None
28 | if self.state_to_input is None:
29 | self.state_to_input = lambda x: x
30 |
31 | def print_kwargs(self, kwargs, header=None, default=None):
32 | self.print('#### {} ####'.format(header))
33 | for key, value in sorted(kwargs.items()):
34 | statement = ' {} = {}'.format(key, value)
35 | if default is not None:
36 | if key not in default:
37 | statement += ' (UNUSED)'
38 | print('Warning: {} = {} set but unused'.format(key, value),
39 | file=sys.stderr, flush=True)
40 | self.print(statement)
41 |
42 | def print(self, *args, **kwargs):
43 | if self.verbose:
44 | print(*args, **kwargs, flush=True)
45 |
46 | def do_load_model(self, load_weights=True):
47 | custom_objects = {'NoisyDenseIG': NoisyDenseIG,
48 | 'NoisyDenseFG': NoisyDenseFG}
49 | if self.load_model_custom is not None:
50 | custom_objects.update(self.load_model_custom)
51 | if load_weights:
52 | return tf.keras.models.load_model(self.load_model, custom_objects)
53 | else:
54 | return self.load_model_no_weights(self.load_model, custom_objects)
55 |
56 | def load_model_no_weights(self, filepath, custom_objects=None):
57 | if custom_objects is None:
58 | custom_objects = {}
59 | with h5py.File(filepath, mode='r') as f:
60 | # instantiate model
61 | model_config = f.attrs.get('model_config')
62 | if model_config is None:
63 | raise ValueError('No model found in config file.')
64 | model_config = json.loads(model_config.decode('utf-8'))
65 | model = tf.keras.models.model_from_config(model_config,
66 | custom_objects=custom_objects)
67 | return model
68 |
69 |
--------------------------------------------------------------------------------
/drlbox/common/util.py:
--------------------------------------------------------------------------------
1 |
2 | import sys
3 | import gym.spaces
4 | import numpy as np
5 |
6 |
7 | def discrete_action(action_space):
8 | return type(action_space) is gym.spaces.discrete.Discrete
9 |
10 | def continuous_action(action_space):
11 | return type(action_space) is gym.spaces.box.Box
12 |
13 | def softmax(logits, axis=-1):
14 | max_logits = logits.max(axis=axis, keepdims=True)
15 | sumexp_shifted = np.exp(logits - max_logits).sum(axis=axis, keepdims=True)
16 | logsumexp = max_logits + np.log(sumexp_shifted)
17 | probs = np.exp(logits - logsumexp)
18 | probs /= probs.sum(axis=axis, keepdims=True)
19 | return probs
20 |
21 | def softmax_with_minprob(logits, minprob, axis=-1):
22 | probs = softmax(logits, axis=axis)
23 | return np.maximum(minprob, probs - minprob / logits.shape[1])
24 |
25 |
26 |
--------------------------------------------------------------------------------
/drlbox/evaluator/__init__.py:
--------------------------------------------------------------------------------
1 |
2 | from .make_evaluator import make_evaluator
3 |
--------------------------------------------------------------------------------
/drlbox/evaluator/ac_eval.py:
--------------------------------------------------------------------------------
1 |
2 | from drlbox.net import ACNet
3 | from .eval_base import Evaluator
4 |
5 |
6 | class ACEvaluator(Evaluator):
7 | net_cls = ACNet
8 |
9 |
--------------------------------------------------------------------------------
/drlbox/evaluator/acer_eval.py:
--------------------------------------------------------------------------------
1 |
2 | from drlbox.net import ACERNet
3 | from .ac_eval import ACEvaluator
4 |
5 |
6 | class ACEREvaluator(ACEvaluator):
7 | net_cls = ACERNet
8 |
9 |
--------------------------------------------------------------------------------
/drlbox/evaluator/dqn_eval.py:
--------------------------------------------------------------------------------
1 |
2 | from drlbox.net import QNet
3 | from .eval_base import Evaluator
4 |
5 |
6 | class DQNEvaluator(Evaluator):
7 | net_cls = QNet
8 |
9 |
--------------------------------------------------------------------------------
/drlbox/evaluator/eval_base.py:
--------------------------------------------------------------------------------
1 |
2 | import time
3 | import tensorflow as tf
4 | from drlbox.common.tasker import Tasker
5 | from drlbox.common.util import discrete_action, continuous_action
6 | from drlbox.common.policy import SoftmaxPolicy, GaussianPolicy, EpsGreedyPolicy
7 |
8 |
9 | EVALUATOR_KWARGS = dict(
10 | render_timestep=None,
11 | render_end=False,
12 | num_episodes=20,
13 | policy_type='stochastic',
14 | policy_eps=0.0,
15 | )
16 |
17 | class Evaluator(Tasker):
18 |
19 | KWARGS = {**Tasker.KWARGS, **EVALUATOR_KWARGS}
20 |
21 | def run(self):
22 | assert callable(self.env_maker)
23 | env = self.env_maker()
24 |
25 | # setup policy
26 | self.policy_type = self.policy_type.lower()
27 | if self.policy_type == 'stochastic':
28 | if discrete_action(env.action_space):
29 | self.policy = SoftmaxPolicy()
30 | elif continuous_action(env.action_space):
31 | self.policy = GaussianPolicy(low=env.action_space.low,
32 | high=env.action_space.high)
33 | else:
34 | raise TypeError('Type of action_space not valid')
35 | elif self.policy_type == 'greedy':
36 | if not discrete_action(env.action_space):
37 | raise TypeError('greedy policy supports only discrete action.')
38 | self.policy = EpsGreedyPolicy(self.policy_eps)
39 | else:
40 | raise ValueError('policy type {} invalid.'.format(self.policy_type))
41 |
42 | # load model
43 | saved_model = self.do_load_model()
44 | net = self.net_cls()
45 | net.set_model(saved_model)
46 |
47 | # global_variables_initializer will re-initialize net.weights
48 | # and so we need to sync to saved_weights
49 | saved_weights = saved_model.get_weights()
50 | sess = tf.Session()
51 | net.set_session(sess)
52 | sess.run(tf.global_variables_initializer())
53 | net.set_sync_weights(saved_weights)
54 | net.sync()
55 |
56 | # evaluation
57 | all_total_rewards = []
58 | for _ in range(self.num_episodes):
59 | state = env.reset()
60 | self.render_env_at_timestep(env)
61 | total_rewards = 0.0
62 | while True:
63 | state = self.state_to_input(state)
64 | action_values = net.action_values([state])[0]
65 | action = self.policy.select_action(action_values)
66 | state, reward, done, info = env.step(action)
67 | self.render_env_at_timestep(env)
68 | total_rewards += reward
69 | if done:
70 | break
71 | if self.render_end:
72 | env.render()
73 | all_total_rewards.append(total_rewards)
74 | self.print('episode reward: {}'.format(total_rewards))
75 | average_reward = sum(all_total_rewards) / len(all_total_rewards)
76 | self.print('average episode reward: {}'.format(average_reward))
77 |
78 | def render_env_at_timestep(self, env):
79 | if self.render_timestep is not None:
80 | env.render()
81 | time.sleep(self.render_timestep)
82 |
83 |
84 |
--------------------------------------------------------------------------------
/drlbox/evaluator/make_evaluator.py:
--------------------------------------------------------------------------------
1 |
2 | from .ac_eval import ACEvaluator
3 | from .acer_eval import ACEREvaluator
4 | from .dqn_eval import DQNEvaluator
5 |
6 |
7 | EVALUATOR_CLS_DICT = {'ac': ACEvaluator,
8 | 'acer': ACEREvaluator,
9 | 'dqn': DQNEvaluator,
10 | }
11 |
12 | def make_evaluator(algorithm, **kwargs):
13 | algorithm = algorithm.lower()
14 | if algorithm not in EVALUATOR_CLS_DICT:
15 | raise ValueError('Algorithm "{}" not valid'.format(algorithm))
16 | return EVALUATOR_CLS_DICT[algorithm](**kwargs)
17 |
18 |
--------------------------------------------------------------------------------
/drlbox/layer/noisy_dense.py:
--------------------------------------------------------------------------------
1 |
2 | import numpy as np
3 | import tensorflow as tf
4 | from tensorflow.python.framework import tensor_shape
5 | from tensorflow.python.layers import base
6 | from tensorflow.python.ops.init_ops import Constant
7 |
8 |
9 | class NoisyDense(tf.keras.layers.Dense):
10 |
11 | def build(self, input_shape):
12 | input_shape = tensor_shape.TensorShape(input_shape)
13 | if input_shape[-1].value is None:
14 | raise ValueError('The last dimension of the inputs to `Dense` '
15 | 'should be defined. Found `None`.')
16 | self.input_spec = base.InputSpec(min_ndim=2,
17 | axes={-1: input_shape[-1].value})
18 | kernel_shape = [input_shape[-1].value, self.units]
19 | kernel_quiet = self.add_variable('kernel_quiet',
20 | shape=kernel_shape,
21 | initializer=self.kernel_initializer,
22 | regularizer=self.kernel_regularizer,
23 | constraint=self.kernel_constraint,
24 | dtype=self.dtype,
25 | trainable=True)
26 | scale_init = Constant(value=(0.5 / np.sqrt(kernel_shape[0])))
27 | kernel_noise_scale = self.add_variable('kernel_noise_scale',
28 | shape=kernel_shape,
29 | initializer=scale_init,
30 | dtype=self.dtype,
31 | trainable=True)
32 | kernel_noise = self.make_kernel_noise(shape=kernel_shape)
33 | self.kernel = kernel_quiet + kernel_noise_scale * kernel_noise
34 | if self.use_bias:
35 | bias_shape = [self.units,]
36 | bias_quiet = self.add_variable('bias_quiet',
37 | shape=bias_shape,
38 | initializer=self.bias_initializer,
39 | regularizer=self.bias_regularizer,
40 | constraint=self.bias_constraint,
41 | dtype=self.dtype,
42 | trainable=True)
43 | bias_noise_scale = self.add_variable(name='bias_noise_scale',
44 | shape=bias_shape,
45 | initializer=scale_init,
46 | dtype=self.dtype,
47 | trainable=True)
48 | bias_noise = self.make_bias_noise(shape=bias_shape)
49 | self.bias = bias_quiet + bias_noise_scale * bias_noise
50 | else:
51 | self.bias = None
52 | self.built = True
53 |
54 | def make_kernel_noise(self, shape):
55 | raise NotImplementedError
56 |
57 | def make_bias_noise(self, shape):
58 | raise NotImplementedError
59 |
60 |
61 | '''
62 | Noisy dense layer with independent Gaussian noise
63 | '''
64 | class NoisyDenseIG(NoisyDense):
65 |
66 | def make_kernel_noise(self, shape):
67 | noise = tf.random_normal(shape, dtype=self.dtype)
68 | kernel_noise = tf.Variable(noise, trainable=False, dtype=self.dtype)
69 | self.noise_list = [kernel_noise]
70 | return kernel_noise
71 |
72 | def make_bias_noise(self, shape):
73 | noise = tf.random_normal(shape, dtype=self.dtype)
74 | bias_noise = tf.Variable(noise, trainable=False, dtype=self.dtype)
75 | self.noise_list.append(bias_noise)
76 | return bias_noise
77 |
78 |
79 | '''
80 | Noisy dense layer with factorized Gaussian noise
81 | '''
82 | class NoisyDenseFG(NoisyDense):
83 |
84 | def make_kernel_noise(self, shape):
85 | kernel_noise_input = self.make_fg_noise(shape=[shape[0]])
86 | kernel_noise_output = self.make_fg_noise(shape=[shape[1]])
87 | self.noise_list = [kernel_noise_input, kernel_noise_output]
88 | kernel_noise = kernel_noise_input[:, tf.newaxis] * kernel_noise_output
89 | return kernel_noise
90 |
91 | def make_bias_noise(self, shape):
92 | return self.noise_list[1] # kernel_noise_output
93 |
94 | def make_fg_noise(self, shape):
95 | noise = tf.random_normal(shape, dtype=self.dtype)
96 | trans_noise = tf.sign(noise) * tf.sqrt(tf.abs(noise))
97 | return tf.Variable(trans_noise, trainable=False, dtype=self.dtype)
98 |
99 |
100 |
--------------------------------------------------------------------------------
/drlbox/net/__init__.py:
--------------------------------------------------------------------------------
1 |
2 | from .q_net import QNet
3 | from .ac_net import ACNet
4 | from .acer_net import ACERNet
5 |
--------------------------------------------------------------------------------
/drlbox/net/ac_net.py:
--------------------------------------------------------------------------------
1 | """Actor critic net"""
2 | import tensorflow as tf
3 | from drlbox.common.namescope import TF_NAMESCOPE
4 | from drlbox.net.net_base import RLNet
5 |
6 |
7 | class ACNet(RLNet):
8 | """Class for actor critic net"""
9 |
10 | LOGPI = 1.1447298858494002 # constant of log(pi)
11 |
12 | def set_model(self, model):
13 | """Set Keras model"""
14 | self.model = model
15 | self.weights = model.weights
16 | self.ph_state, = model.inputs
17 | self.tf_logits, tf_value = model.outputs
18 | self.tf_value = tf_value[:, 0] # shape [batch_size, 1] -> [batch_size]
19 |
20 | def set_loss(self, entropy_weight=0.01, min_var=None, policy_type=None):
21 | """Set the loss function to be minimized
22 | Args:
23 | entropy_weight: float, weight of the entropy regularization term.
24 | min_var: float, only used in continuous action space. When the
25 | action is parameterized as a Gaussian, it is the lower bound
26 | of the Gaussian variance.
27 | policy_type: string, 'softmax' or 'gaussian'.
28 | """
29 | with tf.name_scope(TF_NAMESCOPE):
30 | tf_logits = self.tf_logits
31 | ph_advantage = tf.placeholder(tf.float32, [None])
32 | ph_target = tf.placeholder(tf.float32, [None])
33 |
34 | if policy_type == 'softmax':
35 | kfac_policy_loss = 'categorical_predictive', (tf_logits,)
36 | ph_action = tf.placeholder(tf.int32, [None])
37 | log_probs = tf.nn.log_softmax(tf_logits)
38 | onehot_act = tf.one_hot(ph_action, depth=tf_logits.shape[1])
39 | log_probs_act = tf.reduce_sum(log_probs * onehot_act, axis=1)
40 | if entropy_weight:
41 | probs = tf.nn.softmax(tf_logits)
42 | neg_entropy = tf.reduce_sum(probs * log_probs, axis=1)
43 | elif policy_type == 'gaussian':
44 | assert min_var is not None
45 | dim_action = tf_logits.shape[1] - 1
46 | ph_action = tf.placeholder(tf.float32, [None, dim_action])
47 | self.tf_mean = tf_logits[:, :-1]
48 | tf_var = tf.nn.softplus(tf_logits[:, -1])
49 | self.tf_var = tf.maximum(tf_var, min_var)
50 | kfac_policy_loss = ('normal_predictive',
51 | (self.tf_mean, self.tf_var))
52 | two_var = 2.0 * self.tf_var
53 | act_minus_mean = ph_action - self.tf_mean
54 | log_norm = tf.reduce_sum(act_minus_mean**2, axis=1) / two_var
55 | log_2pv = self.LOGPI + tf.log(two_var)
56 | log_probs_act = -(log_norm + 0.5 * int(dim_action) * log_2pv)
57 | if entropy_weight:
58 | neg_entropy = 0.5 * (log_2pv + 1.0)
59 | else:
60 | raise ValueError('policy_type {} invalid'.format(policy_type))
61 |
62 | # loss
63 | policy_loss = -(log_probs_act * ph_advantage)
64 | value_loss = tf.squared_difference(ph_target, self.tf_value)
65 | self.tf_loss = policy_loss + value_loss
66 | if entropy_weight:
67 | self.tf_loss += neg_entropy * entropy_weight
68 |
69 | # error for prioritization: critic abs td error
70 | self.tf_error = tf.abs(ph_target - self.tf_value)
71 |
72 | # kfac loss register
73 | kfac_value_loss = 'normal_predictive', (self.tf_value,)
74 | self.kfac_loss_list = [kfac_policy_loss, kfac_value_loss]
75 |
76 | # placeholders
77 | self.ph_train_list = [self.ph_state, ph_action,
78 | ph_advantage, ph_target]
79 |
80 | def action_values(self, state):
81 | """Return the output of the policy network, i.e., 'logits'."""
82 | return self.sess.run(self.tf_logits, feed_dict={self.ph_state: state})
83 |
84 | def state_value(self, state):
85 | """Return the output of the value network."""
86 | return self.sess.run(self.tf_value, feed_dict={self.ph_state: state})
87 |
88 | def ac_values(self, state):
89 | """Return both outputs of the policy and value networks."""
90 | return self.sess.run([self.tf_logits, self.tf_value],
91 | feed_dict={self.ph_state: state})
92 |
93 |
94 |
--------------------------------------------------------------------------------
/drlbox/net/acer_net.py:
--------------------------------------------------------------------------------
1 | """Net class for ACER"""
2 | import tensorflow as tf
3 | from drlbox.common.namescope import TF_NAMESCOPE
4 | from drlbox.net.ac_net import ACNet
5 |
6 |
7 | class ACERNet(ACNet):
8 | """Class that handles loss/update in ACER. Assumes discrete action for now.
9 | """
10 |
11 | def set_model(self, model):
12 | """Set a Keras model"""
13 | self.model = model
14 | self.weights = model.weights
15 | self.ph_state, = model.inputs
16 | self.tf_logits, self.tf_value = model.outputs
17 |
18 | def set_loss(self, entropy_weight=0.01, kl_weight=0.1, trunc_max=10.0,
19 | policy_type=None):
20 | """Set the ACER loss function
21 | Args:
22 | entropy_weight: float; weight of the entropy regularization term
23 | kl_weight: float; weight of the KL divergence loss term, with
24 | respect to the Polyak averaging net
25 | trunc_max: float; maximum allowed value of the truncated
26 | importance sampling weight
27 | policy_type: None or 'softmax'; type of the stochastic policy
28 | """
29 | with tf.name_scope(TF_NAMESCOPE):
30 | # sample return and baseline placeholders
31 | ph_target = tf.placeholder(tf.float32, [None])
32 | ph_baseline = tf.placeholder(tf.float32, [None])
33 |
34 | if policy_type == 'softmax':
35 | kfac_policy_loss = 'categorical_predictive', (self.tf_logits,)
36 | num_act = self.tf_logits.shape[1]
37 | ph_action = tf.placeholder(tf.int32, [None])
38 | onehot_act = tf.one_hot(ph_action, depth=num_act)
39 |
40 | # importance sampling weight and trunc
41 | ph_lratio = tf.placeholder(tf.float32, [None, num_act])
42 | trunc = tf.minimum(trunc_max, ph_lratio)
43 | trunc_act = tf.reduce_sum(trunc * onehot_act, axis=1)
44 |
45 | # bootstrapped value placeholder
46 | ph_boot = tf.placeholder(tf.float32, [None, num_act])
47 |
48 | # log policy
49 | log_probs = tf.nn.log_softmax(self.tf_logits)
50 |
51 | # policy loss: sample return part
52 | log_probs_act = tf.reduce_sum(log_probs * onehot_act, axis=1)
53 | adv_ret = trunc_act * (ph_target - ph_baseline)
54 | policy_loss_ret = -(adv_ret * log_probs_act)
55 |
56 | # policy loss: bootstrapped value part
57 | probs = tf.nn.softmax(self.tf_logits)
58 | probs_c = tf.stop_gradient(probs)
59 | trunc = tf.maximum(0.0, 1.0 - trunc_max / ph_lratio)
60 | trunc_prob = trunc * probs_c
61 | adv_val = trunc_prob * (ph_boot - ph_baseline[:, tf.newaxis])
62 | policy_loss_val = -tf.reduce_sum(adv_val * log_probs, axis=1)
63 |
64 | # KL (wrt averaged policy net) loss
65 | if kl_weight:
66 | ph_avg_logits = tf.placeholder(tf.float32, [None, num_act])
67 | avg_probs = tf.nn.softmax(ph_avg_logits)
68 | avg_probs_log_probs = avg_probs * log_probs
69 | kl_avg_online = -tf.reduce_sum(avg_probs_log_probs, axis=1)
70 |
71 | # state-action value
72 | value_act = tf.reduce_sum(self.tf_value * onehot_act, axis=1)
73 |
74 | # entropy
75 | if entropy_weight:
76 | neg_entropy = tf.reduce_sum(probs * log_probs, axis=1)
77 | else:
78 | raise ValueError('policy_type must be softmax in ACER for now')
79 |
80 | # value (critic) loss
81 | value_loss = tf.squared_difference(ph_target, value_act)
82 |
83 | # total loss
84 | self.tf_loss = policy_loss_ret + policy_loss_val + value_loss
85 | if kl_weight:
86 | self.tf_loss += kl_avg_online * kl_weight
87 | if entropy_weight:
88 | self.tf_loss += neg_entropy * entropy_weight
89 |
90 | # error for prioritization: critic abs td error
91 | self.tf_error = tf.abs(ph_target - value_act)
92 |
93 | # kfac loss register
94 | kfac_value_loss = 'normal_predictive', (self.tf_value,)
95 | self.kfac_loss_list = [kfac_policy_loss, kfac_value_loss]
96 |
97 | # placeholders
98 | self.ph_train_list = [self.ph_state, ph_action, ph_lratio,
99 | ph_target, ph_boot, ph_baseline]
100 | if kl_weight:
101 | self.ph_train_list.append(ph_avg_logits)
102 |
103 | def set_soft_update(self, new_weights, update_ratio):
104 | """Set the soft update operation for the Polyak averaging net"""
105 | assign_list = []
106 | for wt, nwt in zip(self.weights, new_weights):
107 | upd = (1.0 - update_ratio) * wt + update_ratio * nwt
108 | assign_list.append(wt.assign(upd))
109 | self.op_soft_update = tf.group(*assign_list)
110 |
111 | def soft_update(self):
112 | """Perform the soft update operation for the Polyak averaging net"""
113 | self.sess.run(self.op_soft_update)
114 |
115 |
--------------------------------------------------------------------------------
/drlbox/net/net_base.py:
--------------------------------------------------------------------------------
1 | """Base class for a trainable neural net for RL"""
2 | import tensorflow as tf
3 | from drlbox.common.namescope import TF_NAMESCOPE
4 | from drlbox.layer.noisy_dense import NoisyDenseIG, NoisyDenseFG
5 |
6 |
7 | class RLNet:
8 | """Base class RLNet"""
9 |
10 | op_sync = None # tf operation of syncing to target weights
11 | kfac_loss_list = [] # list of losses used in K-FAC
12 |
13 | def set_model(self, model):
14 | """Set Keras model; to be overloaded in derived classes."""
15 | raise NotImplementedError
16 |
17 | def set_loss(self, *args, **kwargs):
18 | """Set loss; to be overloaded in derived classes."""
19 | raise NotImplementedError
20 |
21 | def action_values(self, state):
22 | """Return state-action values; to be overloaded by derived classes"""
23 | raise NotImplementedError
24 |
25 | def state_value(self, *args, **kwargs):
26 | """Return state-only value; to be overloaded in derived classes."""
27 | raise NotImplementedError
28 |
29 | def set_session(self, sess):
30 | """Set TensorFlow session"""
31 | self.sess = sess
32 |
33 | def set_sync_weights(self, sync_weights):
34 | """Set sync weight target. 'sync_weight' is a list of tf tensors."""
35 | with tf.name_scope(TF_NAMESCOPE):
36 | op_sync_list = [wt.assign(swt)
37 | for wt, swt in zip(self.weights, sync_weights)]
38 | self.op_sync = tf.group(*op_sync_list)
39 |
40 | def set_optimizer(self, opt, clip_norm=None, train_weights=None,
41 | priority_type=None, batch_size=None):
42 | """Set optimizer.
43 | Args:
44 | opt: an instance of tf.train.Optimizer
45 | clip_norm: None means no gradient clipping, otherwise it is
46 | the maximum norm of gradient clipping, i.e. the second argument
47 | to be passed to tf.clip_by_global_norm
48 | train_weights: (list of) neural network weights to be optimized
49 | priority_type: None, 'error', or 'differential'; priority type in
50 | prioritized experience replay
51 | batch_size: batch size for neural network optimization; only useful
52 | when priority_type == 'differential'
53 | """
54 | with tf.name_scope(TF_NAMESCOPE):
55 | self.ph_batch_weight = tf.placeholder(tf.float32, [None])
56 | tf_batch_loss = tf.reduce_sum(self.tf_loss * self.ph_batch_weight)
57 | grads_and_vars = opt.compute_gradients(tf_batch_loss, self.weights)
58 | grads = [g for g, v in grads_and_vars]
59 | if clip_norm is not None:
60 | grads, _ = tf.clip_by_global_norm(grads, clip_norm)
61 | if train_weights is None:
62 | train_weights = self.weights
63 | self.op_train = opt.apply_gradients(zip(grads, train_weights))
64 | self.op_result = [tf_batch_loss]
65 | self.op_periodic = []
66 | self.periodic_interval = None
67 | self.periodic_counter = 0
68 |
69 | # op_result should include priority term if requested
70 | if priority_type is not None:
71 | if priority_type == 'error':
72 | tf_batch_priority = [tf.reduce_mean(error)
73 | for error in tf.split(self.tf_error, batch_size)]
74 | elif priority_type == 'differential':
75 | tf_batch_priority = []
76 | for loss in tf.split(self.tf_loss, batch_size):
77 | grad_list = tf.gradients(loss, self.model.outputs)
78 | norm = sum(tf.norm(grad, ord=1) for grad in grad_list)
79 | tf_batch_priority.append(norm)
80 | else:
81 | message = 'priority_type={} invalid'.format(priority_type)
82 | raise ValueError(message)
83 | self.op_result.append(tf.stack(tf_batch_priority))
84 |
85 | def set_kfac(self, kfac, inv_upd_interval, **kwargs):
86 | """Set K-FAC optimizer
87 | Args:
88 | kfac: an instance of drlbox.net.kfac.optimizer.KfacOptimizerTV
89 | (derived from tf.contrib.kfac.optimizer.KfacOptimizer)
90 | inv_upd_interval: interval for updating the inverse of the Fisher
91 | information matrix
92 | kwargs: keyword arguments to be passed to
93 | """
94 | self.set_optimizer(kfac, **kwargs)
95 | self.op_train = [self.op_train, kfac.cov_update_op]
96 | self.op_periodic = kfac.inv_update_op
97 | self.periodic_interval = inv_upd_interval
98 |
99 | def train_on_batch(self, *args, batch_weight=None):
100 | """Train the neural network on a batch of rollouts
101 | Args:
102 | args: training arguments. Different in each child class.
103 | e.g., in A3C, args = states, actions, advantages, target_values
104 | in DQN, args = states, actions, target_values
105 | batch_weight: sample weight to be applied on each rollout
106 | """
107 | if batch_weight is None:
108 | # args[0] is input states, len(args[0]) is therefore batch size
109 | batch_weight = [1.0] * len(args[0])
110 | feed_dict = {ph: arg for ph, arg in zip(self.ph_train_list, args)}
111 | feed_dict[self.ph_batch_weight] = batch_weight
112 |
113 | # run training and result in order
114 | self.sess.run(self.op_train, feed_dict=feed_dict)
115 | result = self.sess.run(self.op_result, feed_dict=feed_dict)
116 | if self.periodic_interval is not None:
117 | if self.periodic_counter >= self.periodic_interval:
118 | self.sess.run(self.op_periodic)
119 | self.periodic_counter = 0
120 | self.periodic_counter += 1
121 | return result
122 |
123 | def sync(self):
124 | """Sync this net to the preset syncing target"""
125 | self.sess.run(self.op_sync)
126 |
127 | def set_noise_list(self):
128 | """Set a list of noise variables if NoisyNet is involved."""
129 | self.noise_list = []
130 | for layer in self.model.layers:
131 | if type(layer) in {NoisyDenseIG, NoisyDenseFG}:
132 | self.noise_list.extend(layer.noise_list)
133 |
134 | def sample_noise(self):
135 | """Resample noise variables in NoisyNet."""
136 | for noise in self.noise_list:
137 | self.sess.run(noise.initializer)
138 |
139 | def save_model(self, filename):
140 | """Save the Keras model to filename."""
141 | self.model.save(filename)
142 |
143 |
--------------------------------------------------------------------------------
/drlbox/net/q_net.py:
--------------------------------------------------------------------------------
1 |
2 | import tensorflow as tf
3 | from drlbox.common.namescope import TF_NAMESCOPE
4 | from drlbox.net.net_base import RLNet
5 |
6 |
7 | class QNet(RLNet):
8 |
9 | def set_model(self, model):
10 | self.model = model
11 | self.weights = model.weights
12 | self.ph_state, = model.inputs
13 | self.tf_values, = model.outputs
14 |
15 | def set_loss(self):
16 | with tf.name_scope(TF_NAMESCOPE):
17 | ph_action = tf.placeholder(tf.int32, [None])
18 | onehot_act = tf.one_hot(ph_action, depth=self.tf_values.shape[1])
19 | ph_target = tf.placeholder(tf.float32, [None])
20 | value_act = tf.reduce_sum(self.tf_values * onehot_act, axis=1)
21 |
22 | # loss
23 | self.tf_loss = tf.losses.huber_loss(ph_target, value_act,
24 | reduction=tf.losses.Reduction.NONE)
25 |
26 | # error for prioritization: abs td error
27 | self.tf_error = tf.abs(ph_target - value_act)
28 |
29 | # kfac loss list
30 | self.kfac_loss_list = [('normal_predictive', (self.tf_values,))]
31 |
32 | # placeholder list
33 | self.ph_train_list = [self.ph_state, ph_action, ph_target]
34 |
35 | def action_values(self, state):
36 | return self.sess.run(self.tf_values, feed_dict={self.ph_state: state})
37 |
38 |
--------------------------------------------------------------------------------
/drlbox/trainer/__init__.py:
--------------------------------------------------------------------------------
1 |
2 | from .make_trainer import make_trainer
3 |
--------------------------------------------------------------------------------
/drlbox/trainer/a3c_trainer.py:
--------------------------------------------------------------------------------
1 | """A3C trainer"""
2 | import numpy as np
3 | import tensorflow as tf
4 | from drlbox.net import ACNet
5 | from drlbox.common.policy import SoftmaxPolicy, GaussianPolicy
6 | from drlbox.trainer.trainer_base import Trainer
7 |
8 |
9 | A3C_KWARGS = dict(
10 | a3c_entropy_weight=1e-2,
11 | )
12 |
13 | class A3CTrainer(Trainer):
14 | """A3C trainer"""
15 |
16 | KWARGS = {**Trainer.KWARGS, **A3C_KWARGS}
17 | net_cls = ACNet
18 |
19 | def setup_algorithm(self):
20 | """Setup properties required by A3C."""
21 | if self.action_mode == 'discrete':
22 | policy_type = 'softmax'
23 | size_logits = self.action_dim
24 | size_value = 1
25 | logits_init = tf.keras.initializers.RandomNormal(stddev=1e-3)
26 | self.policy = SoftmaxPolicy()
27 | elif self.action_mode == 'continuous':
28 | policy_type = 'gaussian'
29 | size_logits = self.action_dim + 1
30 | size_value = 1
31 | logits_init = 'glorot_uniform'
32 | self.policy = GaussianPolicy(low=self.action_low,
33 | high=self.action_high)
34 | else:
35 | raise TypeError('action_mode {} invalid'.format(self.action_mode))
36 | self.loss_kwargs = dict(entropy_weight=self.a3c_entropy_weight,
37 | min_var=GaussianPolicy.min_var,
38 | policy_type=policy_type)
39 | self.model_kwargs = dict(size_logits=size_logits,
40 | size_value=size_value,
41 | logits_init=logits_init)
42 |
43 | def build_model(self, state, feature,
44 | size_logits=None, size_value=None, logits_init=None):
45 | """Return a Keras model."""
46 | if type(feature) in {tuple, list}:
47 | assert len(feature) == 2
48 | # separated logits/value streams when feature is a length 2 tuple
49 | feature_logits, feature_value = feature
50 | else:
51 | # feature is a single stream otherwise
52 | feature_logits = feature_value = feature
53 | logits_layer = self.dense_layer(size_logits,
54 | kernel_initializer=logits_init)
55 | logits = logits_layer(feature_logits)
56 | value = self.dense_layer(size_value)(feature_value)
57 | model = tf.keras.models.Model(inputs=state, outputs=[logits, value])
58 | return model
59 |
60 | def concat_bootstrap(self, cc_state, b_r_slice):
61 | """Return bootstrapped quantities for a concatenated batch."""
62 | cc_value = self.online_net.state_value(cc_state)
63 | return cc_value, # should return a tuple
64 |
65 | def rollout_feed(self, rollout, r_value):
66 | """Return feeds for a rollout."""
67 | r_action = np.array(rollout.action_list)
68 | r_target = self.rollout_target(rollout, r_value[-1])
69 | r_adv = r_target - r_value[:-1]
70 | return r_action, r_adv, r_target
71 |
--------------------------------------------------------------------------------
/drlbox/trainer/acer_trainer.py:
--------------------------------------------------------------------------------
1 |
2 | import numpy as np
3 | import tensorflow as tf
4 | from drlbox.net import ACERNet
5 | from drlbox.common.util import softmax_with_minprob
6 | from drlbox.common.policy import SoftmaxPolicy
7 | from .a3c_trainer import A3CTrainer
8 |
9 |
10 | ACER_KWARGS = dict(
11 | acer_trunc_max=10.0,
12 | acer_kl_weight=0.0,
13 | acer_soft_update_ratio=0.05,
14 | replay_type='uniform',
15 | )
16 |
17 | class ACERTrainer(A3CTrainer):
18 |
19 | KWARGS = {**A3CTrainer.KWARGS, **ACER_KWARGS}
20 | net_cls = ACERNet
21 | softmax_minprob = 1e-6
22 | retrace_max = 1.0
23 |
24 | def setup_algorithm(self):
25 | super().setup_algorithm()
26 | assert self.action_mode == 'discrete'
27 | self.loss_kwargs = dict(entropy_weight=self.a3c_entropy_weight,
28 | kl_weight=self.acer_kl_weight,
29 | trunc_max=self.acer_trunc_max,
30 | policy_type='softmax')
31 | self.model_kwargs['size_value'] = self.action_dim
32 | self.policy = SoftmaxPolicy()
33 |
34 | def setup_nets(self, worker_dev, rep_dev, env):
35 | super().setup_nets(worker_dev, rep_dev, env)
36 | if self.acer_kl_weight:
37 | with tf.device(rep_dev):
38 | self.average_net = self.build_net(env)
39 | self.average_net.set_sync_weights(self.global_net.weights)
40 | self.average_net.set_soft_update(self.global_net.weights,
41 | self.acer_soft_update_ratio)
42 |
43 | def set_session(self, sess):
44 | super().set_session(sess)
45 | if self.acer_kl_weight:
46 | self.average_net.set_session(sess)
47 | self.average_net.sync()
48 |
49 | def sync_to_global(self):
50 | super().sync_to_global()
51 | if self.acer_kl_weight and self.noisynet is not None:
52 | self.average_net.sample_noise()
53 |
54 | def train_on_batch(self, *args):
55 | batch_result = super().train_on_batch(*args)
56 | if self.acer_kl_weight:
57 | self.average_net.soft_update()
58 | return batch_result
59 |
60 | def concat_bootstrap(self, cc_state, rl_slice):
61 | cc_logits, cc_boot = self.online_net.ac_values(cc_state)
62 | if self.acer_kl_weight:
63 | cc_avg_logits = self.average_net.action_values(cc_state)
64 | return cc_logits, cc_boot, cc_avg_logits
65 | else:
66 | return cc_logits, cc_boot
67 |
68 | def rollout_feed(self, *args):
69 | if self.acer_kl_weight:
70 | rollout, r_logits, r_boot, r_avg_logits = args
71 | else:
72 | rollout, r_logits, r_boot = args
73 | r_action = np.array(rollout.action_list)
74 |
75 | # off-policy probabilities, length n
76 | r_off_logits = np.array(rollout.act_val_list)
77 | r_off_probs = softmax_with_minprob(r_off_logits, self.softmax_minprob)
78 |
79 | # on-policy probabilities and values, length n+1
80 | r_probs = softmax_with_minprob(r_logits, self.softmax_minprob)
81 |
82 | # likelihood ratio and retrace, length n
83 | r_lratio = r_probs[:-1] / r_off_probs
84 | r_retrace = np.minimum(self.retrace_max, r_lratio)
85 |
86 | # baseline, length n+1
87 | r_baseline = np.sum(r_probs * r_boot, axis=1)
88 |
89 | # return, length n
90 | reward_long = 0.0 if rollout.done else r_baseline[-1]
91 | r_target = np.zeros(len(rollout))
92 | for idx in reversed(range(len(rollout))):
93 | reward_long *= self.discount
94 | reward_long += rollout.reward_list[idx]
95 | r_target[idx] = reward_long
96 | act = r_action[idx]
97 | val = r_boot[idx, act]
98 | retrace = r_retrace[idx, act]
99 | reward_long = retrace * (reward_long - val) + r_baseline[idx]
100 |
101 | # logits from the average net, length n
102 | result = r_action, r_lratio, r_target, r_boot[:-1], r_baseline[:-1]
103 | if self.acer_kl_weight:
104 | return (*result, r_avg_logits[:-1])
105 | else:
106 | return result
107 |
108 |
--------------------------------------------------------------------------------
/drlbox/trainer/dqn_trainer.py:
--------------------------------------------------------------------------------
1 | """DQN trainer"""
2 | import numpy as np
3 | import tensorflow as tf
4 | from drlbox.net import QNet
5 | from drlbox.common.policy import DecayEpsGreedyPolicy
6 | from drlbox.trainer.trainer_base import Trainer
7 |
8 |
9 | DQN_KWARGS = dict(
10 | dqn_double=True,
11 | dqn_dueling=False,
12 | policy_eps_start=1.0,
13 | policy_eps_end=0.01,
14 | policy_eps_decay_steps=1000000,
15 | sync_target_interval=1000,
16 | )
17 |
18 | class DQNTrainer(Trainer):
19 | """DQN trainer"""
20 |
21 | KWARGS = {**Trainer.KWARGS, **DQN_KWARGS}
22 | net_cls = QNet
23 |
24 | def setup_algorithm(self):
25 | """Setup properties required by DQN."""
26 | self.loss_kwargs = {}
27 | assert self.action_mode == 'discrete'
28 |
29 | # epsilon greedy policy
30 | eps_start = self.policy_eps_start
31 | eps_end = self.policy_eps_end
32 | eps_delta = (eps_start - eps_end) / self.policy_eps_decay_steps
33 | self.policy = DecayEpsGreedyPolicy(eps_start, eps_end, eps_delta)
34 | self.model_kwargs = {}
35 |
36 | def setup_nets(self, worker_dev, rep_dev, env):
37 | """Setup the target network in DQN."""
38 | super().setup_nets(worker_dev, rep_dev, env)
39 | with tf.device(worker_dev):
40 | self.target_net = self.build_net(env)
41 | self.target_net.set_sync_weights(self.global_net.weights)
42 | self.batch_counter = 0
43 |
44 | def build_model(self, state, feature):
45 | """Return a Keras model."""
46 | assert self.action_mode == 'discrete'
47 | if self.dqn_dueling:
48 | if type(feature) is tuple:
49 | assert len(feature) == 2
50 | # separated adv/value streams when feature is a length 2 tuple
51 | feature_adv, feature_value = feature
52 | else:
53 | size_last_hid = feature.shape.as_list()[-1]
54 | assert size_last_hid % 2 == 0
55 | size_dueling = size_last_hid // 2
56 | # split feature in halves
57 | l_first_half = lambda x: x[..., :size_dueling]
58 | l_last_half = lambda x: x[..., size_dueling:]
59 | feature_adv = tf.keras.layers.Lambda(l_first_half)(feature)
60 | feature_value = tf.keras.layers.Lambda(l_last_half)(feature)
61 | hid_adv = tf.keras.layers.Dense(size_dueling)(feature_adv)
62 | hid_adv = tf.keras.layers.Activation('relu')(hid_adv)
63 | hid_value = tf.keras.layers.Dense(size_dueling)(feature_value)
64 | hid_value = tf.keras.layers.Activation('relu')(hid_value)
65 | adv = self.dense_layer(self.action_dim)(hid_adv)
66 | value = self.dense_layer(1)(hid_value)
67 | l_baseline = lambda x: -tf.reduce_mean(x, axis=-1, keepdims=True)
68 | baseline = tf.keras.layers.Lambda(l_baseline)(adv)
69 | q_value = tf.keras.layers.Add()([value, baseline, adv])
70 | else:
71 | q_value = self.dense_layer(self.action_dim)(feature)
72 | model = tf.keras.models.Model(inputs=state, outputs=q_value)
73 | return model
74 |
75 | def set_session(self, sess):
76 | """Setup a TensorFlow session."""
77 | super().set_session(sess)
78 | self.target_net.set_session(sess)
79 | self.target_net.sync()
80 |
81 | def sync_to_global(self):
82 | """Sync the local network to the global network and resample weight
83 | noises in the target network if necessary.
84 | """
85 | super().sync_to_global()
86 | if self.noisynet is not None:
87 | self.target_net.sample_noise()
88 |
89 | def train_on_batch(self, *args):
90 | """Train on a batch."""
91 | batch_result = super().train_on_batch(*args)
92 | self.batch_counter += 1
93 | if self.batch_counter >= self.sync_target_interval:
94 | self.batch_counter = 0
95 | self.target_net.sync()
96 | return batch_result
97 |
98 | def concat_bootstrap(self, cc_state, b_r_slice):
99 | """Return concatenated bootstrap training target values."""
100 | last_states = [cc_state[r_slice][-1] for r_slice in b_r_slice]
101 | last_states = np.array(last_states)
102 | concat_len = cc_state.shape[0]
103 | cc_target_value = concat_value(self.target_net, concat_len,
104 | last_states, b_r_slice)
105 | if self.dqn_double:
106 | cc_online_value = concat_value(self.online_net, concat_len,
107 | last_states, b_r_slice)
108 | return cc_target_value, cc_online_value
109 | else:
110 | return cc_target_value,
111 |
112 | def rollout_feed(self, rollout, r_target_value, r_online_value=None):
113 | """Return training targets for a rollout."""
114 | r_action = np.array(rollout.action_list)
115 | if self.dqn_double:
116 | greedy_last_value = r_online_value[-1]
117 | else:
118 | greedy_last_value = r_target_value[-1]
119 | target_last_q = r_target_value[-1][greedy_last_value.argmax()]
120 | r_target = self.rollout_target(rollout, target_last_q)
121 | return r_action, r_target
122 |
123 |
124 | def concat_value(net, concat_len, last_states, b_r_slice):
125 | """Return one type of concatenated value."""
126 | last_values = net.action_values(last_states)
127 | value_shape = concat_len, *last_values.shape[1:]
128 | cc_value = np.zeros(value_shape)
129 | for r_slice, last_val in zip(b_r_slice, last_values):
130 | cc_value[r_slice][-1] = last_val
131 | return cc_value
132 |
--------------------------------------------------------------------------------
/drlbox/trainer/impala_trainer.py:
--------------------------------------------------------------------------------
1 |
2 | import numpy as np
3 | from drlbox.common.util import softmax_with_minprob
4 | from .a3c_trainer import A3CTrainer
5 |
6 |
7 | IMPALA_KWARGS = dict(
8 | impala_trunc_rho_max=1.0,
9 | impala_trunc_c_max=1.0,
10 | replay_type='uniform',
11 | )
12 |
13 | class IMPALATrainer(A3CTrainer):
14 |
15 | KWARGS = {**A3CTrainer.KWARGS, **IMPALA_KWARGS}
16 | softmax_minprob = 1e-6
17 |
18 | def concat_bootstrap(self, cc_state, rl_slice):
19 | cc_logits, cc_value = self.online_net.ac_values(cc_state)
20 | return cc_logits, cc_value
21 |
22 | def rollout_feed(self, rollout, r_logits, r_value):
23 | r_action = np.array(rollout.action_list)
24 |
25 | # off-policy probabilities, length n
26 | r_off_logits = np.array(rollout.act_val_list)
27 | r_off_probs = softmax_with_minprob(r_off_logits, self.softmax_minprob)
28 | r_off_probs_act = r_off_probs[(range(len(r_off_probs)), r_action)]
29 |
30 | # on-policy probabilities, length n
31 | r_logits = r_logits[:-1]
32 | r_probs = softmax_with_minprob(r_logits, self.softmax_minprob)
33 | r_probs_act = r_probs[(range(len(r_probs)), r_action)]
34 |
35 | # likelihood ratio, length n
36 | r_lratio_act = r_probs_act / r_off_probs_act
37 | r_trunc_rho = np.minimum(self.impala_trunc_rho_max, r_lratio_act)
38 | r_trunc_c = np.minimum(self.impala_trunc_c_max, r_lratio_act)
39 |
40 | # v-trace target, length n+1
41 | r_reward = np.array(rollout.reward_list)
42 | if rollout.done:
43 | r_value[-1] = 0.0
44 | r_target = np.zeros(len(rollout) + 1)
45 | r_target[-1] = r_value[-1]
46 | for idx in reversed(range(len(rollout))):
47 | trunc_rho = r_trunc_rho[idx]
48 | trunc_c = r_trunc_c[idx]
49 | value = r_value[idx]
50 | reward = r_reward[idx]
51 | value_next = r_value[idx + 1]
52 | target_next = r_target[idx + 1]
53 | dv_rho = trunc_rho * (reward + self.discount * value_next - value)
54 | dv_c = trunc_c * self.discount * (target_next - value_next)
55 | r_target[idx] = value + dv_rho + dv_c
56 |
57 | # advantage
58 | r_adv = r_reward + self.discount * r_target[1:] - r_value[:-1]
59 | return r_action, r_adv, r_target[:-1]
60 |
61 |
--------------------------------------------------------------------------------
/drlbox/trainer/make_trainer.py:
--------------------------------------------------------------------------------
1 |
2 | from .a3c_trainer import A3CTrainer
3 | from .acer_trainer import ACERTrainer
4 | from .impala_trainer import IMPALATrainer
5 | from .dqn_trainer import DQNTrainer
6 |
7 |
8 | TRAINER_CLS_DICT = {'a3c': A3CTrainer,
9 | 'acer': ACERTrainer,
10 | 'impala': IMPALATrainer,
11 | 'dqn': DQNTrainer,}
12 |
13 | def make_trainer(algorithm, **kwargs):
14 | algorithm = algorithm.lower()
15 | if algorithm not in TRAINER_CLS_DICT:
16 | raise ValueError('Algorithm "{}" not valid'.format(algorithm))
17 | return TRAINER_CLS_DICT[algorithm](**kwargs)
18 |
19 |
--------------------------------------------------------------------------------
/drlbox/trainer/rollout.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | class Rollout:
4 |
5 | '''
6 | Usage: rollout = Rollout(state)
7 | '''
8 | def __init__(self, state):
9 | self.state_list = [state]
10 | self.action_list = []
11 | self.reward_list = []
12 | self.act_val_list = []
13 | self.done = False
14 |
15 | def append(self, state, action, reward, done, act_val):
16 | self.state_list.append(state)
17 | self.action_list.append(action)
18 | self.reward_list.append(reward)
19 | self.act_val_list.append(act_val)
20 | self.done = done
21 |
22 | '''
23 | Length of the rollout is (number of states - 1) or (number of rewards)
24 | '''
25 | def __len__(self):
26 | return len(self.reward_list)
27 |
28 |
--------------------------------------------------------------------------------
/drlbox/trainer/step_counter.py:
--------------------------------------------------------------------------------
1 |
2 | import tensorflow as tf
3 |
4 |
5 | class StepCounter:
6 |
7 | def __init__(self):
8 | self.tf_step_count = tf.Variable(0)
9 |
10 | def set_increment(self):
11 | ph_inc = tf.placeholder(tf.int32, ())
12 | self.ph_inc = ph_inc
13 | self.op_inc = self.tf_step_count.assign_add(ph_inc)
14 |
15 | def set_session(self, sess):
16 | self.sess = sess
17 |
18 | def increment(self, inc):
19 | self.sess.run(self.op_inc, feed_dict={self.ph_inc: inc})
20 |
21 | def step_count(self):
22 | return self.sess.run(self.tf_step_count)
23 |
--------------------------------------------------------------------------------
/drlbox/trainer/trainer_base.py:
--------------------------------------------------------------------------------
1 | """Base class of trainers
2 |
3 | Explanation of batched n-step training and arguments:
4 |
5 | 1. Rollout:
6 | The basic unit of training is a length-L "rollout" of the form
7 | { s_t, a_t, r_t, s_{t+1}, ..., s_{t+L} }
8 | which contains L transitions. In practice, L is not always a fixed length
9 | as a rollout must terminate at the end of an episode.
10 |
11 | Argument 'rollout_maxlen' is the maximum length a rollout can ever have,
12 | and is related with the number of bootstrap steps. For example, setting
13 | 'rollout_maxlen = 1' corresponds to 1-step bootstrapped TD learning.
14 | If we set 'rollout_maxlen = N', then the first state in the rollout will be
15 | subject to a N-step TD learning, the second state will be subject to
16 | a (N-1)-step TD learning, and so on.
17 |
18 | 2. Rollout list:
19 | "rollout_list" (abbr. "rlist") is a list of (various-length) rollouts
20 | and is guaranteed to contain a fixed number of transitions.
21 |
22 | Argument 'rollout_maxlen' is also this fixed number.
23 |
24 | 3. Batch:
25 | A "batch" is simply a fixed number of rollout lists. One training on
26 | a single batch executes exactly one update to the network weights.
27 |
28 | Argument 'batch_size' is the number of rollout lists.
29 | """
30 | from multiprocessing import Process, ProcessError, Event, cpu_count
31 | import socket
32 |
33 | import os
34 | import signal
35 | import time
36 | from datetime import timedelta
37 |
38 | import tensorflow as tf
39 | import numpy as np
40 | from drlbox.layer.noisy_dense import NoisyDenseIG, NoisyDenseFG
41 | from drlbox.common.replay import Replay, PriorityReplay
42 | from drlbox.common.util import discrete_action, continuous_action
43 | from drlbox.common.tasker import Tasker
44 | from drlbox.trainer.step_counter import StepCounter
45 | from drlbox.trainer.rollout import Rollout
46 | from drlbox.common.namescope import TF_NAMESCOPE
47 |
48 |
49 | LOCALHOST = 'localhost'
50 | JOBNAME = 'local'
51 |
52 | '''
53 | Optimizer related default kwargs
54 | '''
55 | ADAM_KWARGS = dict(
56 | learning_rate=1e-4,
57 | epsilon=1e-4,
58 | )
59 |
60 | '''
61 | Replay memory related default kwargs
62 | '''
63 | REPLAY_KWARGS = dict(
64 | maxlen=1000,
65 | minlen=100,
66 | )
67 |
68 | '''
69 | Trainer default kwargs
70 | '''
71 | TRAINER_KWARGS = dict(
72 | feature_maker=None,
73 | model_maker=None, # if set, ignores feature_maker
74 | num_parallel=None,
75 | port_begin=2220,
76 | discount=0.99,
77 | train_steps=1000000,
78 | rollout_maxlen=32,
79 | batch_size=1,
80 | online_learning=True, # whether or not to perform online learning
81 | replay_type=None, # None, 'uniform', 'prioritized'
82 | replay_ratio=4,
83 | replay_priority_type='differential', # None, 'error' 'differential'
84 | replay_kwargs={},
85 | optimizer='adam', # 'adam', tf.train.Optimizer instance
86 | opt_clip_norm=40.0,
87 | opt_kwargs={},
88 | noisynet=None, # None, 'ig', 'fg'
89 | save_dir=None, # directory to save tf.keras models
90 | save_interval=10000,
91 | catch_signal=False, # effective on multiprocessing only
92 | )
93 |
94 |
95 | class Trainer(Tasker):
96 | """Base class of trainers."""
97 |
98 | dense_layer = tf.keras.layers.Dense
99 | KWARGS = {**Tasker.KWARGS, **TRAINER_KWARGS}
100 |
101 | def run(self):
102 | """Run the training process."""
103 | # change default dense_layer to noisy layer if requested
104 | if self.noisynet is None:
105 | pass
106 | elif self.noisynet == 'ig':
107 | self.dense_layer = NoisyDenseIG
108 | self.print('Using independent Gaussian NoisyNet')
109 | elif self.noisynet == 'fg':
110 | self.dense_layer = NoisyDenseFG
111 | self.print('Using factorized Gaussian NoisyNet')
112 | else:
113 | raise ValueError('noisynet={} is invalid'.format(self.noisynet))
114 |
115 | if self.num_parallel is None:
116 | self.num_parallel = cpu_count()
117 | self.port_list = [self.port_begin + i
118 | for i in range(self.num_parallel)]
119 |
120 | # single process
121 | if self.num_parallel == 1:
122 | self.worker(0)
123 | return
124 |
125 | # multiprocess parallel training
126 | for port in self.port_list:
127 | if not port_available(LOCALHOST, port):
128 | raise NameError('port {} is not available'.format(port))
129 | self.print('Claiming {} port {} ...'.format(LOCALHOST, self.port_list))
130 | self.event_finished = Event()
131 | self.worker_list = []
132 | try:
133 | for wid in range(self.num_parallel):
134 | worker = Process(target=self.worker, args=(wid,))
135 | worker.start()
136 | self.worker_list.append(worker)
137 | except ProcessError:
138 | self.terminate_workers()
139 |
140 | # set handlers if requested
141 | if self.catch_signal:
142 | self.default_sigint_handler = signal.signal(signal.SIGINT,
143 | self.signal_handler)
144 | self.default_sigterm_handler = signal.signal(signal.SIGTERM,
145 | self.signal_handler)
146 | self.print('SIGINT and SIGTERM will be caught by drlbox')
147 |
148 | # terminates the entire training when the master worker terminates
149 | wait_counter = 0
150 | start_time = time.time()
151 | while not self.event_finished.is_set():
152 | wait_counter += 1
153 | if wait_counter >= 3000:
154 | wait_counter = 0
155 | elapsed = int(time.time() - start_time)
156 | time_str = str(timedelta(seconds=elapsed))
157 | self.print('Elapsed time:', time_str)
158 | time.sleep(0.1)
159 | self.print('A worker just terminated -- training should end soon')
160 | self.terminate_workers()
161 |
162 | # restore default handlers
163 | if self.catch_signal:
164 | signal.signal(signal.SIGINT, self.default_sigint_handler)
165 | signal.signal(signal.SIGTERM, self.default_sigterm_handler)
166 | self.print('SIGINT and SIGTERM default handlers reset to default')
167 | self.print('Asynchronous training has ended')
168 |
169 | def signal_handler(self, signum, frame):
170 | """Signal handler for SIGINT and SIGTERM."""
171 | self.event_finished.set()
172 |
173 | def terminate_workers(self):
174 | """Gracefully terminate workers (in backward order of spawning)."""
175 | for worker in self.worker_list[::-1]:
176 | while worker.is_alive():
177 | worker.terminate()
178 | time.sleep(0.01)
179 |
180 | def worker(self, wid):
181 | """Run a worker process."""
182 | assert callable(self.env_maker)
183 | env = self.env_maker()
184 |
185 | # determine action mode from env.action_space
186 | if discrete_action(env.action_space):
187 | self.action_mode = 'discrete'
188 | self.action_dim = env.action_space.n
189 | elif continuous_action(env.action_space):
190 | self.action_mode = 'continuous'
191 | self.action_dim = len(env.action_space.shape)
192 | self.action_low = env.action_space.low
193 | self.action_high = env.action_space.high
194 | else:
195 | raise TypeError('Invalid type of env.action_space')
196 |
197 | self.is_master = wid == 0
198 | if self.is_master and self.save_dir is not None:
199 | env_name = 'UnknownEnv-v0' if env.spec is None else env.spec.id
200 | self.output = self.get_output_dir(env_name)
201 | else:
202 | self.output = None
203 |
204 | # ports, cluster, and server
205 | cluster_list = ['{}:{}'.format(LOCALHOST, p) for p in self.port_list]
206 | cluster = tf.train.ClusterSpec({JOBNAME: cluster_list})
207 | tf.train.Server(cluster, job_name=JOBNAME, task_index=wid)
208 | self.print('Starting server #{}'.format(wid))
209 |
210 | self.setup_algorithm()
211 |
212 | # global/local devices
213 | worker_dev = '/job:{}/task:{}/cpu:0'.format(JOBNAME, wid)
214 | rep_dev = tf.train.replica_device_setter(worker_device=worker_dev,
215 | cluster=cluster)
216 |
217 | self.setup_nets(worker_dev, rep_dev, env)
218 | if self.replay_type is not None:
219 | replay_kwargs = {**REPLAY_KWARGS, **self.replay_kwargs}
220 | if self.is_master:
221 | self.print_kwargs(replay_kwargs, 'Replay memory arguments')
222 | if self.replay_type == 'uniform':
223 | self.replay = Replay(**replay_kwargs)
224 | elif self.replay_type == 'prioritized':
225 | self.replay = PriorityReplay(**replay_kwargs)
226 | else:
227 | message = 'replay type {} invalid'.format(self.replay_type)
228 | raise ValueError(message)
229 |
230 | # begin tensorflow session, build async RL agent and train
231 | port = self.port_list[wid]
232 | with tf.Session('grpc://{}:{}'.format(LOCALHOST, port)) as sess:
233 | sess.run(tf.global_variables_initializer())
234 | self.set_session(sess)
235 |
236 | # train the agent
237 | self.train_on_env(env)
238 |
239 | if self.num_parallel > 1:
240 | self.event_finished.set()
241 | if self.is_master:
242 | while True:
243 | time.sleep(1)
244 |
245 | def train_on_env(self, env):
246 | """Perform training on a Gym env."""
247 | step = self.step_counter.step_count()
248 | if self.is_master:
249 | last_save = step
250 | self.save_model(step)
251 |
252 | state = env.reset()
253 | ep_reward = 0.0
254 | while step <= self.train_steps:
255 | self.sync_to_global()
256 | batch = []
257 | for _ in range(self.batch_size):
258 | rlist = [Rollout(state)]
259 | for rlist_step in range(self.rollout_maxlen):
260 | net_input = self.state_to_input(state)
261 | act_val = self.online_net.action_values([net_input])[0]
262 | action = self.policy.select_action(act_val)
263 | state, reward, done, _ = env.step(action)
264 | ep_reward += reward
265 | rlist[-1].append(state, action, reward, done, act_val)
266 | if done:
267 | state = env.reset()
268 | if rlist_step < self.rollout_maxlen - 1:
269 | rlist.append(Rollout(state))
270 | self.print('episode reward {:5.2f}'.format(ep_reward))
271 | ep_reward = 0.0
272 | if len(rlist[-1]) >= self.rollout_maxlen:
273 | if rlist_step < self.rollout_maxlen - 1:
274 | rlist.append(Rollout(state))
275 | batch.append(rlist)
276 |
277 | if self.online_learning:
278 | # on-policy training on the newly collected rollout list
279 | batch_result = self.train_on_batch(batch)
280 | batch_loss_list = [batch_result[0]]
281 | else:
282 | batch_loss_list = []
283 |
284 | # off-policy training if there is a memory
285 | if self.replay_type is not None:
286 | if self.replay_type == 'prioritized' and self.online_learning:
287 | self.replay.extend(batch, batch_result[1])
288 | else:
289 | self.replay.extend(batch)
290 | if self.replay.usable():
291 | for _ in range(np.random.poisson(self.replay_ratio)):
292 | batch, index, weight = \
293 | self.replay.sample(self.batch_size)
294 | self.sync_to_global()
295 | if self.replay_type == 'prioritized':
296 | loss, priority = self.train_on_batch(batch, weight)
297 | self.replay.update_priority(index, priority)
298 | else:
299 | loss, = self.train_on_batch(batch)
300 | batch_loss_list.append(loss)
301 |
302 | # step, print, etc.
303 | self.step_counter.increment(self.batch_size * self.rollout_maxlen)
304 | step = self.step_counter.step_count()
305 | if self.is_master:
306 | if step - last_save > self.save_interval:
307 | self.save_model(step)
308 | last_save = step
309 | if batch_loss_list:
310 | loss_print = '{:3.3f}'.format(np.mean(batch_loss_list))
311 | else:
312 | loss_print = 'None'
313 | self.print('training step {}/{}, loss {}'
314 | .format(step, self.train_steps, loss_print))
315 | # save at the end of training
316 | if self.is_master:
317 | self.save_model(step)
318 |
319 | def build_net(self, env=None, is_global=False):
320 | """Build a neural net."""
321 | net = self.net_cls()
322 | if self.load_model is not None:
323 | if is_global:
324 | model = self.do_load_model()
325 | self.saved_weights = model.get_weights()
326 | else:
327 | model = self.do_load_model(load_weights=False)
328 | else:
329 | if self.model_maker is None:
330 | assert callable(self.feature_maker)
331 | state, feature = self.feature_maker(env.observation_space)
332 | model = self.build_model(state, feature, **self.model_kwargs)
333 | else:
334 | assert callable(self.model_maker)
335 | model = self.model_maker(env)
336 | net.set_model(model)
337 | if self.noisynet is not None:
338 | net.set_noise_list()
339 | return net
340 |
341 | def set_online_optimizer(self):
342 | """Set optimizer for the online network."""
343 | if self.replay_type == 'prioritized':
344 | opt_rep_kwargs = dict(priority_type=self.replay_priority_type,
345 | batch_size=self.batch_size)
346 | else:
347 | opt_rep_kwargs = {}
348 |
349 | if self.optimizer == 'adam':
350 | adam_kwargs = {**ADAM_KWARGS, **self.opt_kwargs}
351 | if self.is_master:
352 | self.print_kwargs(adam_kwargs, 'Adam arguments')
353 | adam = tf.train.AdamOptimizer(**adam_kwargs)
354 | self.online_net.set_optimizer(adam, self.opt_clip_norm,
355 | self.global_net.weights,
356 | **opt_rep_kwargs)
357 | elif isinstance(self.optimizer, tf.train.Optimizer):
358 | # if self.optimizer is a (subclass) instance of tf.train.Optimizer
359 | self.online_net.set_optimizer(self.optimizer, self.opt_clip_norm,
360 | self.global_net.weights)
361 | else:
362 | raise ValueError('Optimizer {} invalid'.format(self.optimizer))
363 |
364 | def get_output_dir(self, env_name):
365 | """Get an output directory for saving Keras models."""
366 | if not os.path.isdir(self.save_dir):
367 | os.makedirs(self.save_dir, exist_ok=True)
368 | self.print('Made output dir', self.save_dir)
369 | save_dir = self.save_dir
370 | experiment_id = 0
371 | for folder_name in os.listdir(save_dir):
372 | if not os.path.isdir(os.path.join(save_dir, folder_name)):
373 | continue
374 | try:
375 | folder_name = int(folder_name.split('-run')[-1])
376 | if folder_name > experiment_id:
377 | experiment_id = folder_name
378 | except ValueError:
379 | pass
380 | experiment_id += 1
381 | save_dir = os.path.join(save_dir, env_name)
382 | save_dir += '-run{}'.format(experiment_id)
383 | os.makedirs(save_dir, exist_ok=True)
384 | return save_dir
385 |
386 | def save_model(self, step):
387 | """Save a Keras model."""
388 | if self.output is not None:
389 | filename = os.path.join(self.output, 'model_{}.h5'.format(step))
390 | self.online_net.save_model(filename)
391 | self.print('keras model written to {}'.format(filename))
392 |
393 | # Methods subject to overloading
394 | def setup_algorithm(self):
395 | """Setup properties needed by the algorithm."""
396 | raise NotImplementedError
397 |
398 | def setup_nets(self, worker_dev, rep_dev, env):
399 | """Setup all neural networks."""
400 | # global net
401 | with tf.device(rep_dev):
402 | self.global_net = self.build_net(env, is_global=True)
403 | if self.is_master and self.verbose:
404 | self.global_net.model.summary()
405 | self.step_counter = StepCounter()
406 |
407 | if self.num_parallel > 1:
408 | # local net
409 | with tf.device(worker_dev):
410 | self.online_net = self.build_net(env)
411 | self.online_net.set_loss(**self.loss_kwargs)
412 | self.set_online_optimizer()
413 | self.online_net.set_sync_weights(self.global_net.weights)
414 | self.step_counter.set_increment()
415 | else:
416 | self.online_net = self.global_net
417 | self.online_net.set_loss(**self.loss_kwargs)
418 | self.set_online_optimizer()
419 | self.step_counter.set_increment()
420 |
421 | def build_model(self, state, feature, **kwargs):
422 | """Return a Keras model."""
423 | raise NotImplementedError
424 |
425 | def set_session(self, sess):
426 | """Set TensorFlow session for networks and step counter."""
427 | for obj in self.global_net, self.online_net, self.step_counter:
428 | obj.set_session(sess)
429 | if self.load_model is not None:
430 | self.global_net.set_sync_weights(self.saved_weights)
431 | self.global_net.sync()
432 |
433 | def sync_to_global(self):
434 | """Synchronize the online network to the global network."""
435 | if self.num_parallel > 1:
436 | self.online_net.sync()
437 | if self.noisynet is not None:
438 | self.online_net.sample_noise()
439 |
440 | def train_on_batch(self, batch, batch_weight=None):
441 | """Train on a batch of rollout lists."""
442 | b_r_state = []
443 | b_r_slice = []
444 | last_index = 0
445 | b_rollout = []
446 | for rlist in batch:
447 | for rollout in rlist:
448 | b_rollout.append(rollout)
449 | r_state = []
450 | for state in rollout.state_list:
451 | r_state.append(self.state_to_input(state))
452 | r_state = np.array(r_state)
453 | b_r_state.append(r_state)
454 | index = last_index + len(r_state)
455 | b_r_slice.append(slice(last_index, index))
456 | last_index = index
457 | cc_state = np.concatenate(b_r_state)
458 |
459 | if batch_weight is None:
460 | cc_weight = None
461 | else:
462 | cc_weight = [weight for rlist, weight in zip(batch, batch_weight)
463 | for rollout in rlist for _ in range(len(rollout))]
464 |
465 | # cc_boots is a tuple of concatenated bootstrap quantities
466 | cc_boots = self.concat_bootstrap(cc_state, b_r_slice)
467 |
468 | # b_r_boots is a list of tuple of boostrap quantities
469 | # and each tuple corresponds to a rollout
470 | b_r_boots = [tuple(boot[r_slice] for boot in cc_boots)
471 | for r_slice in b_r_slice]
472 |
473 | # feed_list contains all arguments to train_on_batch
474 | feed_list = []
475 | for rollout, r_state, r_boot in zip(b_rollout, b_r_state, b_r_boots):
476 | r_input = r_state[:-1]
477 | r_feeds = self.rollout_feed(rollout, *r_boot)
478 | feed_list.append((r_input, *r_feeds))
479 |
480 | # concatenate individual types of feeds from the list
481 | cc_args = *(np.concatenate(fd) for fd in zip(*feed_list)), cc_weight
482 | batch_result = self.online_net.train_on_batch(*cc_args)
483 | return batch_result
484 |
485 | def concat_bootstrap(self, cc_state, b_r_slice):
486 | """Return bootstrapped quantities for a concatenated batch."""
487 | raise NotImplementedError
488 |
489 | def rollout_feed(self, rollout, *rollout_bootstraps):
490 | """Return feeds for a rollout."""
491 | raise NotImplementedError
492 |
493 | def rollout_target(self, rollout, value_last):
494 | """Return target value for a rollout."""
495 | reward_long = 0.0 if rollout.done else value_last
496 | r_target = np.zeros(len(rollout))
497 | for idx in reversed(range(len(rollout))):
498 | reward_long *= self.discount
499 | reward_long += rollout.reward_list[idx]
500 | r_target[idx] = reward_long
501 | return r_target
502 |
503 |
504 | def port_available(host, port):
505 | """Check availability of the given port on host."""
506 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
507 | return sock.connect_ex((host, port)) != 0
508 |
--------------------------------------------------------------------------------
/examples/atari_wrappers/__init__.py:
--------------------------------------------------------------------------------
1 | from .history import HistoryStacker
2 | from .reward import RewardClipper
3 | from .episodic_life import EpisodicLife
4 | from .preprocess import Preprocessor
5 |
--------------------------------------------------------------------------------
/examples/atari_wrappers/episodic_life.py:
--------------------------------------------------------------------------------
1 |
2 | import gym
3 |
4 | '''
5 | A shameless copy-paste from OpenAI baselines
6 | '''
7 | class EpisodicLife(gym.Wrapper):
8 | def __init__(self, env):
9 | """Make end-of-life == end-of-episode, but only reset on true game over.
10 | Done by DeepMind for the DQN and co. since it helps value estimation.
11 | """
12 | super().__init__(env)
13 | self.lives = 0
14 | self.was_real_done = True
15 |
16 | def step(self, action):
17 | obs, reward, done, info = self.env.step(action)
18 | self.was_real_done = done
19 | # check current lives, make loss of life terminal,
20 | # then update lives to handle bonus lives
21 | lives = info['ale.lives']
22 | if lives < self.lives and lives > 0:
23 | # for Qbert sometimes we stay in lives == 0 condtion for a few frames
24 | # so its important to keep lives > 0, so that we only reset once
25 | # the environment advertises done.
26 | done = True
27 | self.lives = lives
28 | return obs, reward, done, info
29 |
30 | def reset(self, **kwargs):
31 | """Reset only when lives are exhausted.
32 | This way all states are still reachable even though lives are episodic,
33 | and the learner need not know about any of this behind-the-scenes.
34 | """
35 | if self.was_real_done:
36 | obs = self.env.reset(**kwargs)
37 | self.lives = 0
38 | else:
39 | # no-op step to advance from terminal/lost life state
40 | obs, _, _, info = self.env.step(0)
41 | self.lives = info['ale.lives']
42 | return obs
43 |
44 |
--------------------------------------------------------------------------------
/examples/atari_wrappers/history.py:
--------------------------------------------------------------------------------
1 |
2 | import gym
3 | from collections import deque
4 |
5 |
6 | class HistoryStacker(gym.Wrapper):
7 | """
8 | A wrapper for history stacking.
9 | Stacks 'num_frames' most recent frames together,
10 | and performs action for 'act_steps' steps each time env.step is called.
11 | """
12 |
13 | '''
14 | Arguments for the constructor:
15 | env: Game environment to be history stacking wrapped;
16 | num_frames: Number of frames to be stacked together; integer;
17 | act_steps: Number of actions performed between states; integer.
18 | '''
19 | def __init__(self, env, num_frames=4, act_steps=2):
20 | super().__init__(env)
21 | obs_space = tuple([env.observation_space] * num_frames)
22 | self.observation_space = gym.spaces.Tuple(obs_space)
23 | self.num_frames = num_frames
24 | self.act_steps = act_steps
25 | self.viewer = None
26 |
27 | def reset(self):
28 | obs = self.env.reset()
29 | self.obs_list = deque([obs] * self.num_frames)
30 | return tuple(self.obs_list)
31 |
32 | def step(self, action):
33 | done = False
34 | total_reward = 0.0
35 | info = {}
36 | current_step = 0
37 | while current_step < self.act_steps and not done:
38 | obs, reward, done, info = self.env.step(action)
39 | self.obs_list.popleft()
40 | self.obs_list.append(obs)
41 | total_reward += reward
42 | current_step += 1
43 | return tuple(self.obs_list), total_reward, done, info
44 |
45 |
--------------------------------------------------------------------------------
/examples/atari_wrappers/preprocess.py:
--------------------------------------------------------------------------------
1 |
2 | import gym
3 | import numpy as np
4 | from PIL import Image
5 |
6 |
7 | '''
8 | Atari gaming screen preprocessor
9 | '''
10 | class Preprocessor(gym.Wrapper):
11 | """
12 | A wrapper for frame preprocessing.
13 | Will convert input image to grayscale and resize to 'shape'.
14 | """
15 |
16 | metadata = {'render.modes': ['human', 'wrapped', 'rgb_array']}
17 |
18 | '''
19 | Arguments for the constructor:
20 | env: Game environment to be preprocessed.
21 | shape: Tuple of 2 integers (height, width).
22 | '''
23 | def __init__(self, env, shape=(84, 84)):
24 | super().__init__(env)
25 | assert(isinstance(env.observation_space, gym.spaces.Box))
26 | assert(len(env.observation_space.shape) == 3)
27 | self.observation_space = gym.spaces.Box(low=0, high=255, shape=shape,
28 | dtype=np.uint8)
29 | self.viewer = None
30 | height, width = shape
31 | self.resize = width, height
32 |
33 | def step(self, action):
34 | obs, reward, done, info = self.env.step(action)
35 | self.preprocessed_obs = self.preprocess(obs)
36 | return self.preprocessed_obs, reward, done, info
37 |
38 | def reset(self):
39 | self.preprocessed_obs = self.preprocess(self.env.reset())
40 | return self.preprocessed_obs
41 |
42 | def render(self, mode='human'):
43 | if mode == 'rgb_array':
44 | return self.preprocessed_obs
45 | elif mode == 'human':
46 | self.env.render(mode='human')
47 | elif mode == 'wrapped':
48 | from gym.envs.classic_control import rendering
49 | if self.viewer is None:
50 | self.viewer = rendering.SimpleImageViewer()
51 | img = np.stack([self.preprocessed_obs] * 3, axis=-1)
52 | self.viewer.imshow(img)
53 |
54 | def close(self):
55 | self.unwrapped.close()
56 | if self.viewer is not None:
57 | self.viewer.close()
58 | self.viewer = None
59 |
60 | def preprocess(self, obs):
61 | img = Image.fromarray(obs)
62 | img = img.convert('L')
63 | img = img.resize(self.resize)
64 | return np.asarray(img)
65 |
66 |
67 |
--------------------------------------------------------------------------------
/examples/atari_wrappers/reward.py:
--------------------------------------------------------------------------------
1 |
2 | import gym
3 |
4 |
5 | class RewardClipper(gym.Wrapper):
6 | """
7 | A wrapper for reward clipping.
8 | """
9 |
10 | '''
11 | Arguments for the constructor:
12 | env: Game environment to be history stacking wrapped;
13 | lower: lower bound of reward; float;
14 | upper: upper bound of reward; float.
15 | '''
16 | def __init__(self, env, lower=-1.0, upper=1.0):
17 | super().__init__(env)
18 | self.lower = lower
19 | self.upper = upper
20 |
21 | def reset(self):
22 | return self.env.reset()
23 |
24 | def step(self, action):
25 | obs, reward, done, info = self.env.step(action)
26 | reward = min(max(reward, self.lower), self.upper)
27 | return obs, reward, done, info
28 |
29 |
30 |
--------------------------------------------------------------------------------
/examples/breakout_acer.py:
--------------------------------------------------------------------------------
1 |
2 | import gym
3 | import numpy as np
4 | import atari_wrappers as aw
5 | from tensorflow.python.keras import layers, initializers, models
6 | from drlbox.trainer import make_trainer
7 |
8 |
9 | '''
10 | Make a properly wrapped Atari env
11 | '''
12 | def make_env(name, num_frames=4, act_steps=2):
13 | env = gym.make(name)
14 | env = aw.Preprocessor(env, shape=(84, 84))
15 | env = aw.HistoryStacker(env, num_frames, act_steps)
16 | env = aw.RewardClipper(env, -1.0, 1.0)
17 | env = aw.EpisodicLife(env)
18 | return env
19 |
20 |
21 | '''
22 | When a state is represented by a list of frames, this interface converts it
23 | to a correctly shaped, correctly typed numpy array which can be fed into
24 | the convolutional neural network.
25 | '''
26 | def state_to_input(state):
27 | return np.stack(state, axis=-1).astype(np.float32)
28 |
29 |
30 | '''
31 | Build a convolutional actor-critic net that is similar to the Nature paper one.
32 | Input arguments:
33 | env: Atari environment.
34 | '''
35 | def make_model(env):
36 | num_frames = len(env.observation_space.spaces)
37 | height, width = env.observation_space.spaces[0].shape
38 | input_shape = height, width, num_frames
39 |
40 | # input state
41 | ph_state = layers.Input(shape=input_shape)
42 |
43 | # convolutional layers
44 | conv1 = layers.Conv2D(32, (8, 8), strides=(4, 4))(ph_state)
45 | conv1 = layers.Activation('relu')(conv1)
46 | conv2 = layers.Conv2D(64, (4, 4), strides=(2, 2))(conv1)
47 | conv2 = layers.Activation('relu')(conv2)
48 | conv3 = layers.Conv2D(64, (3, 3), strides=(1, 1))(conv2)
49 | conv3 = layers.Activation('relu')(conv3)
50 | conv_flat = layers.Flatten()(conv3)
51 | feature = layers.Dense(512)(conv_flat)
52 | feature = layers.Activation('relu')(feature)
53 |
54 | # actor (policy) and critic (value) streams
55 | size_logits = size_value = env.action_space.n
56 | logits_init = initializers.RandomNormal(stddev=1e-3)
57 | logits = layers.Dense(size_logits, kernel_initializer=logits_init)(feature)
58 | value = layers.Dense(size_value)(feature)
59 | return models.Model(inputs=ph_state, outputs=[logits, value])
60 |
61 |
62 | '''
63 | ACER on Breakout-v0
64 | '''
65 | if __name__ == '__main__':
66 | trainer = make_trainer('acer',
67 | env_maker=lambda: make_env('Breakout-v0'),
68 | model_maker=make_model,
69 | state_to_input=state_to_input,
70 | num_parallel=1,
71 | train_steps=1000,
72 | rollout_maxlen=4,
73 | batch_size=8,
74 | verbose=True,
75 | )
76 | trainer.run()
77 |
78 |
--------------------------------------------------------------------------------
/examples/cartpole_a3c.py:
--------------------------------------------------------------------------------
1 |
2 | import gym
3 | from tensorflow.python.keras.layers import Input, Dense, Activation
4 | from drlbox.trainer import make_trainer
5 |
6 |
7 | '''
8 | Input arguments:
9 | observation_space: Observation space of the environment;
10 | num_hid_list: List of hidden unit numbers in the fully-connected net.
11 | '''
12 | def make_feature(observation_space, num_hid_list):
13 | inp_state = Input(shape=observation_space.shape)
14 | feature = inp_state
15 | for num_hid in num_hid_list:
16 | feature = Dense(num_hid)(feature)
17 | feature = Activation('relu')(feature)
18 | return inp_state, feature
19 |
20 |
21 | '''
22 | A3C, CartPole-v0
23 | '''
24 | if __name__ == '__main__':
25 | trainer = make_trainer(
26 | algorithm='a3c',
27 | env_maker=lambda: gym.make('CartPole-v0'),
28 | feature_maker=lambda obs_space: make_feature(obs_space, [200, 100]),
29 | num_parallel=1,
30 | train_steps=1000,
31 | verbose=True,
32 | )
33 | trainer.run()
34 |
--------------------------------------------------------------------------------
/pylintrc:
--------------------------------------------------------------------------------
1 | [MESSAGES CONTROL]
2 | # E0203 access-member-before-definition
3 | # E0401 import-error
4 | # E1101 no-member
5 | # W0201 attribute-defined-outside-init
6 | disable=E0203,E0401,E1101,W0201
7 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | tensorflow>=1.5.0
2 | gym>=0.9.6
3 | h5py
4 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 |
2 | from setuptools import setup, find_packages
3 | from codecs import open
4 | from os import path
5 |
6 | here = path.abspath(path.dirname(__file__))
7 |
8 | # Get the long description from the README file
9 | with open(path.join(here, 'README.md'), encoding='utf-8') as f:
10 | long_description = f.read()
11 |
12 | setup(
13 | name='DRLBox',
14 | version='0.0.1',
15 | description="Deep Reinforcement Learning as a (black) Box",
16 | long_description=long_description,
17 | url='https://github.com/spring01/drlbox',
18 | author='Haichen Li',
19 | author_email='lihc2012@gmail.com',
20 | license='GPLv3',
21 | classifiers=[
22 | 'Development Status :: 3 - Alpha',
23 | 'Intended Audience :: Developers',
24 | 'Topic :: Scientific/Engineering :: Artificial Intelligence',
25 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
26 | 'Programming Language :: Python :: 3',
27 | 'Programming Language :: Python :: 3.5',
28 | ],
29 | keywords='deep reinforcement learning',
30 | packages=find_packages(),
31 | install_requires=['tensorflow', 'gym', 'h5py'],
32 | )
33 |
--------------------------------------------------------------------------------
/utils/learning_curve.py:
--------------------------------------------------------------------------------
1 |
2 | import argparse
3 | import re
4 | import numpy as np
5 | import matplotlib.pyplot as plt
6 | from collections import OrderedDict
7 |
8 |
9 | def padding(signal, window_size):
10 | pad = np.mean(signal[:window_size])
11 | return np.concatenate([[pad] * (window_size - 1), signal])
12 |
13 |
14 | if __name__ == '__main__':
15 | parser = argparse.ArgumentParser(description='Draw a learning curve')
16 | parser.add_argument('--window-small', default=100, type=int,
17 | help='Small averaging window for instantaneous performance')
18 | parser.add_argument('--window-large', default=1000, type=int,
19 | help='Large averaging window for average performance')
20 | parser.add_argument('--linewidth', default=3.0, type=float,
21 | help='Line width')
22 | parser.add_argument('--colors', default=None, type=str, nargs='+',
23 | help='Color list')
24 | parser.add_argument('--labels', default=None, type=str, nargs='+',
25 | help='Labels for making the legend')
26 |
27 | args, unknown_args = parser.parse_known_args()
28 |
29 | # colors
30 | if args.colors is None:
31 | color_list = ['b', 'g', 'r', 'c', 'm', 'y', 'k', '0.5']
32 | if len(color_list) < len(unknown_args):
33 | for _ in range(len(unknown_args) - len(color_list)):
34 | color_list.append(np.random.rand(3))
35 | else:
36 | color_list = []
37 | for color, number in zip(args.colors[:-1:2], args.colors[1::2]):
38 | color_list.extend([color] * int(number))
39 |
40 | # labels
41 | if args.labels is None:
42 | label_list = unknown_args
43 | else:
44 | label_list = []
45 | for label, number in zip(args.labels[:-1:2], args.labels[1::2]):
46 | label_list.extend([label] * int(number))
47 |
48 | # plot a learning curve for each file
49 | for filename, color, label in zip(unknown_args, color_list, label_list):
50 | # find rewards and steps
51 | step_reward = OrderedDict()
52 | step = 0
53 | with open(filename) as out:
54 | for line in out:
55 | if 'episode reward' in line:
56 | reward_list = re.findall('[+-]?\d+\.\d+', line)
57 | if reward_list:
58 | reward = float(reward_list[0])
59 | if step in step_reward:
60 | step_reward[step].append(reward)
61 | else:
62 | step_reward[step] = [reward]
63 | if 'training step' in line:
64 | step_next = int(re.findall('\d+', line)[0])
65 | if step_next > step:
66 | step = step_next
67 |
68 | # interpolate steps to arrange episodic rewards
69 | step_list = list(step_reward.keys())
70 | int_step_reward = OrderedDict()
71 | for step, next_step in zip(step_list[:-1], step_list[1:]):
72 | int_step_array = np.linspace(step, next_step,
73 | len(step_reward[step]),
74 | endpoint=False)
75 | for int_step, reward in zip(int_step_array, step_reward[step]):
76 | int_step_reward[int_step] = reward
77 | all_steps = list(int_step_reward.keys())
78 | all_rewards = [int_step_reward[step] for step in all_steps]
79 |
80 | if args.window_small:
81 | win_small = np.ones(args.window_small) / args.window_small
82 | padded_small = padding(all_rewards, args.window_small)
83 | mean_small = np.convolve(padded_small, win_small, mode='valid')
84 | plt.plot(all_steps, mean_small, color=color,
85 | linewidth=args.linewidth, alpha=0.1)
86 |
87 | if args.window_large:
88 | win_large = np.ones(args.window_large) / args.window_large
89 | padded_large = padding(all_rewards, args.window_large)
90 | mean_large = np.convolve(padded_large, win_large, mode='valid')
91 | plt.plot(all_steps, mean_large, color=color,
92 | linewidth=args.linewidth, label=label)
93 |
94 | plt.tight_layout(pad=0.1)
95 | plt.legend()
96 | plt.show()
97 |
98 |
--------------------------------------------------------------------------------