├── LICENSE ├── README.md ├── SS_dataset.py ├── TestSet_BeamSearch_Outputs ├── HRED_Ubuntu_Baseline_Exp1_BeamSearch_5_GeneratedTestSamples ├── HRED_Ubuntu_Baseline_Exp1_BeamSearch_5_GeneratedTestSamples_First.txt ├── VHRED_Ubuntu_Exp5_BeamSearch_5_GeneratedTestSamples_MeanRandom ├── VHRED_Ubuntu_Exp5_BeamSearch_5_GeneratedTestSamples_MeanRandom_First.txt ├── VHRED_Ubuntu_Exp7_BeamSearch_5_GeneratedTestSamples_MeanRandom ├── VHRED_Ubuntu_Exp7_BeamSearch_5_GeneratedTestSamples_MeanRandom_First.txt ├── VHRED_Ubuntu_Exp9_BeamSearch_5_GeneratedTestSamples_MeanRandom └── VHRED_Ubuntu_Exp9_BeamSearch_5_GeneratedTestSamples_MeanRandom_First.txt ├── __init__.py ├── adam.py ├── convert-text2dict.py ├── data_iterator.py ├── dialog_encdec.py ├── model.py ├── numpy_compat.py ├── sample.py ├── search.py ├── state.py ├── tests └── data │ ├── MT_WordEmb.pkl │ ├── ttest.dialogues.pkl │ ├── ttest.semantic.pkl │ ├── ttrain.dialogues.pkl │ ├── ttrain.dict.pkl │ ├── ttrain.semantic.pkl │ ├── ttrain.txt │ ├── ttrain.txt~ │ ├── tvalid.dialogues.pkl │ ├── tvalid.semantic.pkl │ ├── tvalid.txt │ ├── tvalid_contexts.txt │ ├── tvalid_contexts.txt~ │ ├── tvalid_potential_responses.txt │ ├── tvalid_potential_responses.txt~ │ ├── tvalid_responses.txt │ └── tvalid_responses.txt~ ├── train.py └── utils.py /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 | 635 | Copyright (C) 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 | Copyright (C) 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 | ### Description 2 | This repository hosts the Latent Variable Hierarchical Recurrent Encoder-Decoder RNN model with Gaussian and piecewise constant latent variables for generative dialog modeling, as well as the HRED baseline model. These models were proposed in the paper "Piecewise Latent Variables for Neural Variational Text Processing" by Serban et al. 3 | 4 | 5 | ### Truncated BPTT 6 | All models are implemented using Truncated Backpropagation Through Time (Truncated BPTT). 7 | The truncated computation is carried out by splitting each document (dialogue) into shorter sequences (e.g. 80 tokens) and computing gradients for each sequence separately, such that the hidden state of the RNNs on each subsequence is initialized from the preceding sequence (i.e. the hidden states have been forward propagated through the previous states). 8 | 9 | 10 | ### Creating Datasets 11 | The script convert-text2dict.py can be used to generate model datasets based on text files with dialogues. 12 | It only requires that the document contains end-of-utterance tokens </s> which are used to construct the model graph, since the utterance encoder is only connected to the dialogue encoder at the end of each utterance. 13 | 14 | Prepare your dataset as a text file for with one document per line (e.g. one dialogue per line). The documents are assumed to be tokenized. If you have validation and test sets, they must satisfy the same requirements. 15 | 16 | Once you're ready, you can create the model dataset files by running: 17 | 18 | python convert-text2dict.py <training_file> --cutoff <vocabulary_size> Training 19 | python convert-text2dict.py <validation_file> --dict=Training.dict.pkl Validation 20 | python convert-text2dict.py <test_file> --dict=Training.dict.pkl <vocabulary_size> Test 21 | 22 | where <training_file>, <validation_file> and <test_file> are the training, validation and test files, and <vocabulary_size> is the number of tokens that you want to train on (all other tokens, but the most frequent <vocabulary_size> tokens, will be converted to <unk> symbols). 23 | 24 | NOTE: The script automatically adds the following special tokens specific to movie script dialogues: 25 | - end-of-utterance: </s> 26 | - end-of-dialogue: </d> 27 | - first speaker: <first_speaker> 28 | - second speaker: <second_speaker> 29 | - third speaker: <third_speaker> 30 | - minor speaker: <minor_speaker> 31 | - voice over: <voice_over> 32 | - off screen: <off_screen> 33 | - pause: <pause> 34 | 35 | If these do not exist in your dataset, you can safely ignore these. The model will learn to assign approximately zero probability mass to them. 36 | 37 | 38 | ### Model Training 39 | If you have Theano with GPU installed (bleeding edge version), you can train the model as follows: 40 | 1) Clone the Github repository 41 | 2) Unpack your dataset files into "Data" directory. 42 | 3) Create a new prototype inside state.py (look at prototype_test_variational for an example) 43 | 4) From the terminal, cd into the code directory and run: 44 | 45 | THEANO_FLAGS=mode=FAST_RUN,device=cuda,floatX=float32 python train.py --prototype > Model_Output.txt 46 | 47 | where <prototype_name> is a state (model configuration/architecture) defined inside state.py. 48 | Training a model to convergence on a modern GPU on the Ubuntu Dialogue Corpus with 46 million tokens takes about 2 weeks. If your GPU runs out of memory, you can adjust the batch size (bs) parameter in the model state, but training will be slower. You can also play around with the other parameters inside state.py. 49 | 50 | 51 | ### Model Sampling & Testing 52 | To generate model responses using beam search run: 53 | 54 | THEANO_FLAGS=mode=FAST_RUN,floatX=float32,device=cuda python sample.py --beam_search --n-samples= --ignore-unk --verbose 55 | 56 | where <model_name> is the name automatically generated during training, <contexts> is a file containing the dialogue contexts with one dialogue per line, and <beams> is the size of the beam search. The results are saved in the file <model_outputs>. 57 | 58 | 59 | ### Citation 60 | If you build on this work, we'd really appreciate it if you could cite our papers: 61 | 62 | Piecewise Latent Variables for Neural Variational Text Processing. Iulian V. Serban, Alexander G. Ororbia II, Joelle Pineau, Aaron Courville, Yoshua Bengio. 2017. https://arxiv.org/abs/1612.00377 63 | 64 | A Hierarchical Latent Variable Encoder-Decoder Model for Generating Dialogues. Iulian V. Serban, Alessandro Sordoni, Ryan Lowe, Laurent Charlin, Joelle Pineau, Aaron Courville, Yoshua Bengio. 2016. http://arxiv.org/abs/1605.06069 65 | 66 | Building End-To-End Dialogue Systems Using Generative Hierarchical Neural Network Models. Iulian V. Serban, Alessandro Sordoni, Yoshua Bengio, Aaron Courville, Joelle Pineau. 2016. AAAI. http://arxiv.org/abs/1507.04808. 67 | 68 | 69 | ### Reproducing Results in "Piecewise Latent Variables for Neural Variational Text Processing" 70 | The results reported in the paper "Piecewise Latent Variables for Neural Variational Text Processing" by Serban et al. are based on the following model states found inside state.py: 71 | 72 | prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Baseline_Exp1 (HRED baseline) 73 | prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp5 (P-VHRED) 74 | prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp7 (G-VHRED) 75 | prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp9 (H-VHRED) 76 | 77 | To reproduce these results from scratch, you must follow these steps: 78 | 79 | 1) Download and unpack the preprocessed Ubuntu dataset available from http://www.iulianserban.com/Files/UbuntuDialogueCorpus.zip. 80 | 81 | 2) a) Clone this Github repository locally on a machine. Use a machine with a fast GPU with large memory (preferably 12GB). 82 | 83 | b) Reconfigure the model states above in state.py appropriately: 84 | 1) Change 'train\_dialogues', 'valid\_dialogues', 'test\_dialogues' to the path for the Ubuntu dataset files. 85 | 2) Change 'dictionary' to the path for the dictionary. 86 | 87 | c) Train up the model. This takes about 2 weeks time! 88 | For example, for "prototype\_ubuntu\_GaussPiecewise\_NormOp\_VHRED\_Exp9" run: 89 | 90 | THEANO_FLAGS=mode=FAST_RUN,device=cuda,floatX=float32 python train.py --prototype prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp9 &> Model_Output.txt 91 | 92 | The model will be saved inside the directory Output/. 93 | If the machine runs out of GPU memory, reduce the batch size (bs) and maximum number of gradient steps (max_grad_steps) in the model state. 94 | 95 | d) Generate outputs using beam search with size 5 on the Ubuntu test set. 96 | To do this, run: 97 | 98 | THEANO_FLAGS=mode=FAST_RUN,device=cuda,floatX=float32 python sample.py --beam_search --n-samples=5 --n-turns=1 --verbose 99 | 100 | where <model_path_prefix> is the path to the saved model parameters excluding the postfix (e.g. Output/1482712210.89_UbuntuModel), 101 | <text_set_contexts> is the path to the Ubuntu test set contexts and <output_file> is where the beam outputs will be stored. 102 | 103 | e) Compute performance using activity- and entity-based metrics. 104 | Follow the instructions given here: https://github.com/julianser/Ubuntu-Multiresolution-Tools. 105 | 106 | 107 | Following all steps to reproduce the results requires a few weeks time and, depending on your setup, may also require changing your Theano configuraiton and the state file. Therefore, we have also made available the trained models and the generated model responses on the test set. 108 | 109 | You can find the trained models here: https://drive.google.com/open?id=0B06gib_77EnxaDg2VkV1N1huUjg. 110 | 111 | You can find the model responses generated using beam search in this repository inside "TestSet_BeamSearch_Outputs/". 112 | 113 | 114 | ### Datasets 115 | The pre-processed Ubuntu Dialogue Corpus and model responses used are available at: http://www.iulianserban.com/Files/UbuntuDialogueCorpus.zip. 116 | 117 | The original Ubuntu Dialogue Corpus as released by Lowe et al. (2015) can be found here: http://cs.mcgill.ca/~jpineau/datasets/ubuntu-corpus-1.0/ 118 | 119 | Unfortunately due to Twitter's terms of service we are not allowed to distribute Twitter content. Therefore we can only make available the tweet IDs, which can then be used with the Twitter API to build a similar dataset. The tweet IDs and model test responses can be found here: http://www.iulianserban.com/Files/TwitterDialogueCorpus.zip. 120 | 121 | ### References 122 | 123 | Piecewise Latent Variables for Neural Variational Text Processing. Iulian V. Serban, Alexander G. Ororbia II, Joelle Pineau, Aaron Courville, Yoshua Bengio. 2017. https://arxiv.org/abs/1612.00377 124 | 125 | A Hierarchical Latent Variable Encoder-Decoder Model for Generating Dialogues. Iulian Vlad Serban, Alessandro Sordoni, Ryan Lowe, Laurent Charlin, Joelle Pineau, Aaron Courville, Yoshua Bengio. 2016a. http://arxiv.org/abs/1605.06069 126 | 127 | Multiresolution Recurrent Neural Networks: An Application to Dialogue Response Generation. Iulian Vlad Serban, Tim Klinger, Gerald Tesauro, Kartik Talamadupula, Bowen Zhou, Yoshua Bengio, Aaron Courville. 2016b. http://arxiv.org/abs/1606.00776. 128 | 129 | Building End-To-End Dialogue Systems Using Generative Hierarchical Neural Network Models. Iulian V. Serban, Alessandro Sordoni, Yoshua Bengio, Aaron Courville, Joelle Pineau. 2016c. AAAI. http://arxiv.org/abs/1507.04808. 130 | 131 | Training End-to-End Dialogue Systems with the Ubuntu Dialogue Corpus. Ryan Lowe, Nissan Pow, Iulian V. Serban, Laurent Charlin, Chia-Wei Liu, Joelle Pineau. 2017. Dialogue & Discourse Journal. http://www.cs.mcgill.ca/~jpineau/files/lowe-dialoguediscourse-2017.pdf 132 | 133 | The Ubuntu Dialogue Corpus: A Large Dataset for Research in Unstructured Multi-Turn Dialogue Systems. Ryan Lowe, Nissan Pow, Iulian Serban, Joelle Pineau. 2015. SIGDIAL. http://arxiv.org/abs/1506.08909. 134 | -------------------------------------------------------------------------------- /SS_dataset.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | import os, gc 3 | import cPickle 4 | import copy 5 | import logging 6 | 7 | import threading 8 | import Queue 9 | 10 | import collections 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | class SSFetcher(threading.Thread): 15 | def __init__(self, parent, init_offset=0, init_reshuffle_count=1, eos_sym=-1, 16 | skip_utterance=False, skip_utterance_predict_both=False): 17 | threading.Thread.__init__(self) 18 | self.parent = parent 19 | self.rng = numpy.random.RandomState(self.parent.seed) 20 | self.indexes = numpy.arange(parent.data_len) 21 | 22 | self.init_offset = init_offset 23 | self.init_reshuffle_count = init_reshuffle_count 24 | self.offset = 0 25 | self.reshuffle_count = 0 26 | 27 | self.eos_sym = eos_sym 28 | self.skip_utterance = skip_utterance 29 | self.skip_utterance_predict_both = skip_utterance_predict_both 30 | 31 | def apply_reshuffle(self): 32 | self.rng.shuffle(self.indexes) 33 | self.offset = 0 34 | self.reshuffle_count += 1 35 | 36 | def run(self): 37 | diter = self.parent 38 | # Initialize to previously set reshuffles and offset position 39 | while (self.reshuffle_count < self.init_reshuffle_count): 40 | self.apply_reshuffle() 41 | 42 | self.offset = self.init_offset 43 | 44 | while not diter.exit_flag: 45 | last_batch = False 46 | dialogues = [] 47 | 48 | while len(dialogues) < diter.batch_size: 49 | if self.offset == diter.data_len: 50 | if not diter.use_infinite_loop: 51 | last_batch = True 52 | break 53 | else: 54 | # Infinite loop here, we reshuffle the indexes 55 | # and reset the self.offset 56 | self.apply_reshuffle() 57 | 58 | index = self.indexes[self.offset] 59 | s = diter.data[index] 60 | 61 | # Flatten if this is a list of lists 62 | if len(s) > 0: 63 | if isinstance(s[0], list): 64 | s = [item for sublist in s for item in sublist] 65 | 66 | # Standard dialogue preprocessing 67 | if not self.skip_utterance: 68 | # Append only if it is shorter than max_len 69 | if diter.max_len == -1 or len(s) <= diter.max_len: 70 | dialogues.append([s, self.offset, self.reshuffle_count]) 71 | 72 | # Skip-utterance preprocessing 73 | else: 74 | s = copy.deepcopy(s) 75 | eos_indices = numpy.where(numpy.asarray(s) == self.eos_sym)[0] 76 | 77 | if not s[0] == self.eos_sym: 78 | eos_indices = numpy.insert(eos_indices, 0, [self.eos_sym]) 79 | if not s[-1] == self.eos_sym: 80 | eos_indices = numpy.append(eos_indices, [self.eos_sym]) 81 | if len(eos_indices) > 2: 82 | # Compute forward and backward targets 83 | first_utterance_index = self.rng.randint(0, len(eos_indices)-2) 84 | s_forward = s[eos_indices[first_utterance_index]:eos_indices[first_utterance_index+2]+1] 85 | 86 | s_backward_a = s[eos_indices[first_utterance_index+1]:eos_indices[first_utterance_index+2]] 87 | s_backward_b = s[eos_indices[first_utterance_index]:eos_indices[first_utterance_index+1]+1] 88 | 89 | # Sometimes an end-of-utterance token is missing at the end. 90 | # Therefore, we need to insert it here. 91 | if s_backward_a[-1] == self.eos_sym or s_backward_b[0] == self.eos_sym: 92 | s_backward = s_backward_a + s_backward_b 93 | else: 94 | s_backward = s_backward_a + [self.eos_sym] + s_backward_b 95 | 96 | else: 97 | s_forward = [self.eos_sym] 98 | s_backward = [self.eos_sym] 99 | 100 | if self.skip_utterance_predict_both: 101 | # Append only if it is shorter than max_len 102 | if diter.max_len == -1 or len(s_forward) <= diter.max_len: 103 | dialogues.append([s_forward, self.offset, self.reshuffle_count]) 104 | if diter.max_len == -1 or len(s_backward) <= diter.max_len: 105 | dialogues.append([s_backward, self.offset, self.reshuffle_count]) 106 | else: 107 | # Append only if it is shorter than max_len 108 | if self.rng.randint(0, 2) == 0: 109 | if diter.max_len == -1 or len(s_forward) <= diter.max_len: 110 | dialogues.append([s_forward, self.offset, self.reshuffle_count]) 111 | else: 112 | if diter.max_len == -1 or len(s_backward) <= diter.max_len: 113 | dialogues.append([s_backward, self.offset, self.reshuffle_count]) 114 | 115 | self.offset += 1 116 | 117 | 118 | if len(dialogues): 119 | diter.queue.put(dialogues) 120 | 121 | if last_batch: 122 | diter.queue.put(None) 123 | return 124 | 125 | class SSIterator(object): 126 | def __init__(self, 127 | dialogue_file, 128 | batch_size, 129 | seed, 130 | max_len=-1, 131 | use_infinite_loop=True, 132 | init_offset=0, 133 | init_reshuffle_count=1, 134 | eos_sym=-1, 135 | skip_utterance=False, 136 | skip_utterance_predict_both=False): 137 | 138 | self.dialogue_file = dialogue_file 139 | self.batch_size = batch_size 140 | self.init_offset = init_offset 141 | self.init_reshuffle_count = init_reshuffle_count 142 | self.eos_sym = eos_sym 143 | self.skip_utterance = skip_utterance 144 | self.skip_utterance_predict_both = skip_utterance_predict_both 145 | 146 | args = locals() 147 | args.pop("self") 148 | self.__dict__.update(args) 149 | self.load_files() 150 | self.exit_flag = False 151 | 152 | def load_files(self): 153 | self.data = cPickle.load(open(self.dialogue_file, 'r')) 154 | self.data_len = len(self.data) 155 | logger.debug('Data len is %d' % self.data_len) 156 | 157 | def start(self): 158 | self.exit_flag = False 159 | self.queue = Queue.Queue(maxsize=1000) 160 | self.gather = SSFetcher(self, self.init_offset, self.init_reshuffle_count, 161 | self.eos_sym, self.skip_utterance, self.skip_utterance_predict_both) 162 | self.gather.daemon = True 163 | self.gather.start() 164 | 165 | def __del__(self): 166 | if hasattr(self, 'gather'): 167 | self.gather.exitFlag = True 168 | self.gather.join() 169 | 170 | def __iter__(self): 171 | return self 172 | 173 | def next(self): 174 | if self.exit_flag: 175 | return None 176 | 177 | batch = self.queue.get() 178 | if not batch: 179 | self.exit_flag = True 180 | return batch 181 | 182 | 183 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/julianser/hred-latent-piecewise/068478dd5b2aa9928168a62a479773e219505319/__init__.py -------------------------------------------------------------------------------- /adam.py: -------------------------------------------------------------------------------- 1 | """ 2 | The MIT License (MIT) 3 | 4 | Copyright (c) 2015 Alec Radford 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | """ 24 | 25 | import theano 26 | import theano.tensor as T 27 | 28 | def sharedX(value, name=None, borrow=False, dtype=None): 29 | if dtype is None: 30 | dtype = theano.config.floatX 31 | return theano.shared(theano._asarray(value, dtype=dtype), 32 | name=name, 33 | borrow=borrow) 34 | 35 | def Adam(grads, lr=0.0002, b1=0.1, b2=0.001, e=1e-8): 36 | updates = [] 37 | varlist = [] 38 | i = sharedX(0.) 39 | i_t = i + 1. 40 | fix1 = 1. - (1. - b1)**i_t 41 | fix2 = 1. - (1. - b2)**i_t 42 | lr_t = lr * (T.sqrt(fix2) / fix1) 43 | for p, g in grads.items(): 44 | m = sharedX(p.get_value() * 0., name=p.name + '_adam_optimizer_m') 45 | v = sharedX(p.get_value() * 0., name=p.name + '_adam_optimizer_v') 46 | m_t = (b1 * g) + ((1. - b1) * m) 47 | v_t = (b2 * T.sqr(g)) + ((1. - b2) * v) 48 | g_t = m_t / (T.sqrt(v_t) + e) 49 | p_t = p - (lr_t * g_t) 50 | 51 | updates.append((m, m_t)) 52 | updates.append((v, v_t)) 53 | updates.append((p, p_t)) 54 | 55 | varlist.append(m) 56 | varlist.append(v) 57 | 58 | updates.append((i, i_t)) 59 | return updates, varlist 60 | -------------------------------------------------------------------------------- /convert-text2dict.py: -------------------------------------------------------------------------------- 1 | """ 2 | Takes as input a dialogue file and creates a processed version of it. 3 | If given an external dictionary, the input dialogue file will be converted 4 | using that input dictionary. 5 | 6 | @author Alessandro Sordoni, Iulian Vlad Serban 7 | """ 8 | 9 | import collections 10 | import numpy 11 | import operator 12 | import os 13 | import sys 14 | import logging 15 | import cPickle 16 | 17 | from collections import Counter 18 | 19 | logging.basicConfig(level=logging.INFO) 20 | logger = logging.getLogger('text2dict') 21 | 22 | def safe_pickle(obj, filename): 23 | if os.path.isfile(filename): 24 | logger.info("Overwriting %s." % filename) 25 | else: 26 | logger.info("Saving to %s." % filename) 27 | 28 | with open(filename, 'wb') as f: 29 | cPickle.dump(obj, f, protocol=cPickle.HIGHEST_PROTOCOL) 30 | 31 | import argparse 32 | parser = argparse.ArgumentParser() 33 | parser.add_argument("input", type=str, help="Dialogue file; assumed shuffled with one document (e.g. one movie dialogue, or one Twitter conversation or one Ubuntu conversation) per line") 34 | parser.add_argument("--cutoff", type=int, default=-1, help="Vocabulary cutoff (optional)") 35 | parser.add_argument("--dict", type=str, default="", help="External dictionary (pkl file)") 36 | parser.add_argument("output", type=str, help="Prefix of the pickle binarized dialogue corpus") 37 | args = parser.parse_args() 38 | 39 | if not os.path.isfile(args.input): 40 | raise Exception("Input file not found!") 41 | 42 | unk = "" 43 | 44 | ############################### 45 | # Part I: Create the dictionary 46 | ############################### 47 | if args.dict != "": 48 | # Load external dictionary 49 | assert os.path.isfile(args.dict) 50 | vocab = dict([(x[0], x[1]) for x in cPickle.load(open(args.dict, "r"))]) 51 | 52 | # Check consistency 53 | assert '' in vocab 54 | assert '' in vocab 55 | assert '' in vocab 56 | 57 | # Also check special tags, which must exist in the Movie-Scriptolog dataset 58 | assert '' in vocab 59 | assert '' in vocab 60 | assert '' in vocab 61 | assert '' in vocab 62 | assert '' in vocab 63 | assert '' in vocab 64 | assert '' in vocab 65 | 66 | else: 67 | word_counter = Counter() 68 | 69 | 70 | for line in open(args.input, 'r'): 71 | line_words = line.strip().split() 72 | if line_words[len(line_words)-1] != '': 73 | line_words.append('') 74 | 75 | s = [x for x in line_words] 76 | word_counter.update(s) 77 | 78 | total_freq = sum(word_counter.values()) 79 | logger.info("Total word frequency in dictionary %d " % total_freq) 80 | 81 | if args.cutoff != -1: 82 | logger.info("Cutoff %d" % args.cutoff) 83 | vocab_count = word_counter.most_common(args.cutoff) 84 | else: 85 | vocab_count = word_counter.most_common() 86 | 87 | # Add special tokens to the vocabulary 88 | vocab = {'': 0, '': 1, '': 2, '': 3, \ 89 | '': 4, '': 5, '': 6, \ 90 | '': 7, '': 8, '': 9} 91 | 92 | # Add other tokens to vocabulary in the order of their frequency 93 | i = 10 94 | for (word, count) in vocab_count: 95 | if not word in vocab: 96 | vocab[word] = i 97 | i += 1 98 | 99 | logger.info("Vocab size %d" % len(vocab)) 100 | 101 | ################################# 102 | # Part II: Binarize the dialogues 103 | ################################# 104 | 105 | # Everything is loaded into memory for the moment 106 | binarized_corpus = [] 107 | # Some statistics 108 | unknowns = 0. 109 | num_terms = 0. 110 | freqs = collections.defaultdict(lambda: 0) 111 | 112 | # counts the number of dialogues each unique word exists in; also known as document frequency 113 | df = collections.defaultdict(lambda: 0) 114 | 115 | for line, dialogue in enumerate(open(args.input, 'r')): 116 | dialogue_words = dialogue.strip().split() 117 | if dialogue_words[len(dialogue_words)-1] != '': 118 | dialogue_words.append('') 119 | 120 | # Convert words to token ids and compute some statistics 121 | dialogue_word_ids = [] 122 | for word in dialogue_words: 123 | word_id = vocab.get(word, 0) 124 | dialogue_word_ids.append(word_id) 125 | unknowns += 1 * (word_id == 0) 126 | freqs[word_id] += 1 127 | 128 | num_terms += len(dialogue_words) 129 | 130 | # Compute document frequency statistics 131 | unique_word_indices = set(dialogue_word_ids) 132 | for word_id in unique_word_indices: 133 | df[word_id] += 1 134 | 135 | # Add dialogue to corpus 136 | binarized_corpus.append(dialogue_word_ids) 137 | 138 | safe_pickle(binarized_corpus, args.output + ".dialogues.pkl") 139 | 140 | if args.dict == "": 141 | safe_pickle([(word, word_id, freqs[word_id], df[word_id]) for word, word_id in vocab.items()], args.output + ".dict.pkl") 142 | 143 | logger.info("Number of unknowns %d" % unknowns) 144 | logger.info("Number of terms %d" % num_terms) 145 | logger.info("Mean document length %f" % float(sum(map(len, binarized_corpus))/len(binarized_corpus))) 146 | logger.info("Writing training %d dialogues (%d left out)" % (len(binarized_corpus), line + 1 - len(binarized_corpus))) 147 | -------------------------------------------------------------------------------- /data_iterator.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import theano 3 | import theano.tensor as T 4 | 5 | import sys, getopt 6 | import logging 7 | 8 | from state import * 9 | from utils import * 10 | from SS_dataset import * 11 | 12 | import itertools 13 | import sys 14 | import pickle 15 | import random 16 | import datetime 17 | import math 18 | import copy 19 | 20 | logger = logging.getLogger(__name__) 21 | 22 | 23 | def add_random_variables_to_batch(state, rng, batch, prev_batch, evaluate_mode): 24 | """ 25 | This is a helper function, which adds random variables to a batch. 26 | We do it this way, because we want to avoid Theano's random sampling both to speed up and to avoid 27 | known Theano issues with sampling inside scan loops. 28 | 29 | The random variable 'ran_var_gaussian_constutterance' is sampled from a standard Gaussian distribution, 30 | which remains constant during each utterance (i.e. between a pair of end-of-utterance tokens). 31 | 32 | The random variable 'ran_var_uniform_constutterance' is sampled from a uniform distribution [0, 1], 33 | which remains constant during each utterance (i.e. between a pair of end-of-utterance tokens). 34 | 35 | When not in evaluate mode, the random vector 'ran_decoder_drop_mask' is also sampled. 36 | This variable represents the input tokens which are replaced by unk when given to 37 | the decoder RNN. It is required for the noise addition trick used by Bowman et al. (2015). 38 | """ 39 | 40 | # If none return none 41 | if not batch: 42 | return batch 43 | 44 | # Variables to store random vector sampled at the beginning of each utterance 45 | Ran_Var_Gaussian_ConstUtterance = numpy.zeros((batch['x'].shape[0], batch['x'].shape[1], state['latent_gaussian_per_utterance_dim']), dtype='float32') 46 | Ran_Var_Uniform_ConstUtterance = numpy.zeros((batch['x'].shape[0], batch['x'].shape[1], state['latent_piecewise_per_utterance_dim']), dtype='float32') 47 | 48 | 49 | # Go through each sample, find end-of-utterance indices and sample random variables 50 | for idx in xrange(batch['x'].shape[1]): 51 | # Find end-of-utterance indices 52 | eos_indices = numpy.where(batch['x'][:, idx] == state['eos_sym'])[0].tolist() 53 | 54 | # Make sure we also sample at the beginning of the utterance, and that we stop appropriately at the end 55 | if len(eos_indices) > 0: 56 | if not eos_indices[0] == 0: 57 | eos_indices = [0] + eos_indices 58 | if not eos_indices[-1] == batch['x'].shape[0]: 59 | eos_indices = eos_indices + [batch['x'].shape[0]] 60 | else: 61 | eos_indices = [0] + [batch['x'].shape[0]] 62 | 63 | # Sample random variables using NumPy 64 | ran_gaussian_vectors = rng.normal(loc=0, scale=1, size=(len(eos_indices), state['latent_gaussian_per_utterance_dim'])) 65 | ran_uniform_vectors = rng.uniform(low=0.0, high=1.0, size=(len(eos_indices), state['latent_piecewise_per_utterance_dim'])) 66 | 67 | for i in range(len(eos_indices)-1): 68 | for j in range(eos_indices[i], eos_indices[i+1]): 69 | Ran_Var_Gaussian_ConstUtterance[j, idx, :] = ran_gaussian_vectors[i, :] 70 | Ran_Var_Uniform_ConstUtterance[j, idx, :] = ran_uniform_vectors[i, :] 71 | 72 | # If a previous batch is given, and the last utterance in the previous batch 73 | # overlaps with the first utterance in the current batch, then we need to copy over 74 | # the random variables from the last utterance in the last batch to remain consistent. 75 | if prev_batch: 76 | if ('x_reset' in prev_batch) and (not numpy.sum(numpy.abs(prev_batch['x_reset'])) < 1) \ 77 | and (('ran_var_gaussian_constutterance' in prev_batch) or ('ran_var_uniform_constutterance' in prev_batch)): 78 | prev_ran_gaussian_vector = prev_batch['ran_var_gaussian_constutterance'][-1,idx,:] 79 | prev_ran_uniform_vector = prev_batch['ran_var_uniform_constutterance'][-1,idx,:] 80 | if len(eos_indices) > 1: 81 | for j in range(0, eos_indices[1]): 82 | Ran_Var_Gaussian_ConstUtterance[j, idx, :] = prev_ran_gaussian_vector 83 | Ran_Var_Uniform_ConstUtterance[j, idx, :] = prev_ran_uniform_vector 84 | else: 85 | for j in range(0, batch['x'].shape[0]): 86 | Ran_Var_Gaussian_ConstUtterance[j, idx, :] = prev_ran_gaussian_vector 87 | Ran_Var_Uniform_ConstUtterance[j, idx, :] = prev_ran_uniform_vector 88 | 89 | # Add new random Gaussian variable to batch 90 | batch['ran_var_gaussian_constutterance'] = Ran_Var_Gaussian_ConstUtterance 91 | batch['ran_var_uniform_constutterance'] = Ran_Var_Uniform_ConstUtterance 92 | 93 | # Create word drop mask based on 'decoder_drop_previous_input_tokens_rate' option: 94 | if evaluate_mode: 95 | batch['ran_decoder_drop_mask'] = numpy.ones((batch['x'].shape[0], batch['x'].shape[1]), dtype='float32') 96 | else: 97 | if state.get('decoder_drop_previous_input_tokens', False): 98 | ran_drop = rng.uniform(size=(batch['x'].shape[0], batch['x'].shape[1])) 99 | batch['ran_decoder_drop_mask'] = (ran_drop <= state['decoder_drop_previous_input_tokens_rate']).astype('float32') 100 | else: 101 | batch['ran_decoder_drop_mask'] = numpy.ones((batch['x'].shape[0], batch['x'].shape[1]), dtype='float32') 102 | 103 | 104 | return batch 105 | 106 | 107 | def create_padded_batch(state, rng, x, force_end_of_utterance_token = False): 108 | # If flag 'do_generate_first_utterance' is off, then zero out the mask for the first utterance. 109 | do_generate_first_utterance = True 110 | if 'do_generate_first_utterance' in state: 111 | if state['do_generate_first_utterance'] == False: 112 | do_generate_first_utterance = False 113 | 114 | # Skip utterance model 115 | if state.get('skip_utterance', False): 116 | do_generate_first_utterance = False 117 | 118 | # x = copy.deepcopy(x) 119 | # for idx in xrange(len(x[0])): 120 | # eos_indices = numpy.where(numpy.asarray(x[0][idx]) == state['eos_sym'])[0] 121 | # if not x[0][idx][0] == state['eos_sym']: 122 | # eos_indices = numpy.insert(eos_indices, 0, state['eos_sym']) 123 | # if not x[0][idx][-1] == state['eos_sym']: 124 | # eos_indices = numpy.append(eos_indices, state['eos_sym']) 125 | # 126 | # if len(eos_indices) > 2: 127 | # first_utterance_index = rng.randint(0, len(eos_indices)-2) 128 | # 129 | # # Predict next or previous utterance 130 | # if state.get('skip_utterance_predict_both', False): 131 | # if rng.randint(0, 2) == 0: 132 | # x[0][idx] = x[0][idx][eos_indices[first_utterance_index]:eos_indices[first_utterance_index+2]+1] 133 | # else: 134 | # x[0][idx] = x[0][idx][eos_indices[first_utterance_index+1]:eos_indices[first_utterance_index+2]] + x[0][idx][eos_indices[first_utterance_index]:eos_indices[first_utterance_index+1]+1] 135 | # else: 136 | # 137 | # else: 138 | # x[0][idx] = [state['eos_sym']] 139 | 140 | 141 | # Find max length in batch 142 | mx = 0 143 | for idx in xrange(len(x[0])): 144 | mx = max(mx, len(x[0][idx])) 145 | 146 | # Take into account that sometimes we need to add the end-of-utterance symbol at the start 147 | mx += 1 148 | 149 | n = state['bs'] 150 | 151 | X = numpy.zeros((mx, n), dtype='int32') 152 | Xmask = numpy.zeros((mx, n), dtype='float32') 153 | 154 | # Variable to store each utterance in reverse form (for bidirectional RNNs) 155 | X_reversed = numpy.zeros((mx, n), dtype='int32') 156 | 157 | # Fill X and Xmask. 158 | # Keep track of number of predictions and maximum dialogue length. 159 | num_preds = 0 160 | max_length = 0 161 | for idx in xrange(len(x[0])): 162 | # Insert sequence idx in a column of matrix X 163 | dialogue_length = len(x[0][idx]) 164 | 165 | # Fiddle-it if it is too long .. 166 | if mx < dialogue_length: 167 | continue 168 | 169 | # Make sure end-of-utterance symbol is at beginning of dialogue. 170 | # This will force model to generate first utterance too 171 | if not x[0][idx][0] == state['eos_sym']: 172 | X[:dialogue_length+1, idx] = [state['eos_sym']] + x[0][idx][:dialogue_length] 173 | dialogue_length = dialogue_length + 1 174 | else: 175 | X[:dialogue_length, idx] = x[0][idx][:dialogue_length] 176 | 177 | # Keep track of longest dialogue 178 | max_length = max(max_length, dialogue_length) 179 | 180 | # Set the number of predictions == sum(Xmask), for cost purposes, minus one (to exclude first eos symbol) 181 | num_preds += dialogue_length - 1 182 | 183 | # Mark the end of phrase 184 | if len(x[0][idx]) < mx: 185 | if force_end_of_utterance_token: 186 | X[dialogue_length:, idx] = state['eos_sym'] 187 | 188 | # Initialize Xmask column with ones in all positions that 189 | # were just set in X (except for first eos symbol, because we are not evaluating this). 190 | # Note: if we need mask to depend on tokens inside X, then we need to 191 | # create a corresponding mask for X_reversed and send it further in the model 192 | Xmask[0:dialogue_length, idx] = 1. 193 | 194 | # Reverse all utterances 195 | # TODO: For backward compatibility. This should be removed in future versions 196 | # i.e. move all the x_reversed computations to the model itself. 197 | eos_indices = numpy.where(X[:, idx] == state['eos_sym'])[0] 198 | X_reversed[:, idx] = X[:, idx] 199 | prev_eos_index = -1 200 | for eos_index in eos_indices: 201 | X_reversed[(prev_eos_index+1):eos_index, idx] = (X_reversed[(prev_eos_index+1):eos_index, idx])[::-1] 202 | prev_eos_index = eos_index 203 | if prev_eos_index > dialogue_length: 204 | break 205 | 206 | 207 | 208 | if not do_generate_first_utterance: 209 | eos_index_to_start_cost_from = eos_indices[0] 210 | if (eos_index_to_start_cost_from == 0) and (len(eos_indices) > 1): 211 | eos_index_to_start_cost_from = eos_indices[1] 212 | Xmask[0:eos_index_to_start_cost_from+1, idx] = 0. 213 | 214 | if np.sum(Xmask[:, idx]) < 2.0: 215 | Xmask[:, idx] = 0. 216 | 217 | if do_generate_first_utterance: 218 | assert num_preds == numpy.sum(Xmask) - numpy.sum(Xmask[0, :]) 219 | 220 | batch = {'x': X, \ 221 | 'x_reversed': X_reversed, \ 222 | 'x_mask': Xmask, \ 223 | 'num_preds': num_preds, \ 224 | 'num_dialogues': len(x[0]), \ 225 | 'max_length': max_length \ 226 | } 227 | 228 | return batch 229 | 230 | class Iterator(SSIterator): 231 | def __init__(self, dialogue_file, batch_size, **kwargs): 232 | self.state = kwargs.pop('state', None) 233 | self.k_batches = kwargs.pop('sort_k_batches', 20) 234 | 235 | if ('skip_utterance' in self.state) and ('do_generate_first_utterance' in self.state): 236 | if self.state['skip_utterance']: 237 | assert not self.state.get('do_generate_first_utterance', False) 238 | 239 | # Store whether the iterator operates in evaluate mode or not 240 | self.evaluate_mode = kwargs.pop('evaluate_mode', False) 241 | print 'Data Iterator Evaluate Mode: ', self.evaluate_mode 242 | 243 | if self.evaluate_mode: 244 | SSIterator.__init__(self, dialogue_file, batch_size, \ 245 | seed=kwargs.pop('seed', 1234), \ 246 | max_len=kwargs.pop('max_len', -1), \ 247 | use_infinite_loop=kwargs.pop('use_infinite_loop', False), \ 248 | eos_sym=self.state['eos_sym'], \ 249 | skip_utterance=self.state.get('skip_utterance', False), \ 250 | skip_utterance_predict_both=self.state.get('skip_utterance_predict_both', False)) 251 | else: 252 | SSIterator.__init__(self, dialogue_file, batch_size, \ 253 | seed=kwargs.pop('seed', 1234), \ 254 | max_len=kwargs.pop('max_len', -1), \ 255 | use_infinite_loop=kwargs.pop('use_infinite_loop', False), \ 256 | init_offset=self.state['train_iterator_offset'], \ 257 | init_reshuffle_count=self.state['train_iterator_reshuffle_count'], \ 258 | eos_sym=self.state['eos_sym'], \ 259 | skip_utterance=self.state.get('skip_utterance', False), \ 260 | skip_utterance_predict_both=self.state.get('skip_utterance_predict_both', False)) 261 | 262 | 263 | self.batch_iter = None 264 | self.rng = numpy.random.RandomState(self.state['seed']) 265 | 266 | # Keep track of previous batch, because this is needed to specify random variables 267 | self.prev_batch = None 268 | 269 | 270 | 271 | self.last_returned_offset = 0 272 | 273 | def get_homogenous_batch_iter(self, batch_size = -1): 274 | while True: 275 | batch_size = self.batch_size if (batch_size == -1) else batch_size 276 | 277 | data = [] 278 | for k in range(self.k_batches): 279 | batch = SSIterator.next(self) 280 | if batch: 281 | data.append(batch) 282 | 283 | if not len(data): 284 | return 285 | 286 | number_of_batches = len(data) 287 | data = list(itertools.chain.from_iterable(data)) 288 | 289 | # Split list of words from the offset index and reshuffle count 290 | data_x = [] 291 | data_offset = [] 292 | data_reshuffle_count = [] 293 | for i in range(len(data)): 294 | data_x.append(data[i][0]) 295 | data_offset.append(data[i][1]) 296 | data_reshuffle_count.append(data[i][2]) 297 | 298 | if len(data_offset) > 0: 299 | self.last_returned_offset = data_offset[-1] 300 | self.last_returned_reshuffle_count = data_reshuffle_count[-1] 301 | 302 | x = numpy.asarray(list(itertools.chain(data_x))) 303 | 304 | lens = numpy.asarray([map(len, x)]) 305 | order = numpy.argsort(lens.max(axis=0)) 306 | 307 | for k in range(number_of_batches): 308 | indices = order[k * batch_size:(k + 1) * batch_size] 309 | full_batch = create_padded_batch(self.state, self.rng, [x[indices]]) 310 | 311 | if full_batch['num_dialogues'] < batch_size: 312 | print 'Skipping incomplete batch!' 313 | continue 314 | 315 | if full_batch['max_length'] < 3: 316 | print 'Skipping small batch!' 317 | continue 318 | 319 | 320 | # Then split batches to have size 'max_grad_steps' 321 | splits = int(math.ceil(float(full_batch['max_length']) / float(self.state['max_grad_steps']))) 322 | batches = [] 323 | for i in range(0, splits): 324 | batch = copy.deepcopy(full_batch) 325 | 326 | # Retrieve start and end position (index) of current mini-batch 327 | start_pos = self.state['max_grad_steps'] * i 328 | if start_pos > 0: 329 | start_pos = start_pos - 1 330 | 331 | # We need to copy over the last token from each batch onto the next, 332 | # because this is what the model expects. 333 | end_pos = min(full_batch['max_length'], self.state['max_grad_steps'] * (i + 1)) 334 | 335 | batch['x'] = full_batch['x'][start_pos:end_pos, :] 336 | batch['x_reversed'] = full_batch['x_reversed'][start_pos:end_pos, :] 337 | batch['x_mask'] = full_batch['x_mask'][start_pos:end_pos, :] 338 | batch['max_length'] = end_pos - start_pos 339 | batch['num_preds'] = numpy.sum(batch['x_mask']) - numpy.sum(batch['x_mask'][0,:]) 340 | 341 | # For each batch we compute the number of dialogues as a fraction of the full batch, 342 | # that way, when we add them together, we get the total number of dialogues. 343 | batch['num_dialogues'] = float(full_batch['num_dialogues']) / float(splits) 344 | batch['x_reset'] = numpy.ones(self.state['bs'], dtype='float32') 345 | 346 | batches.append(batch) 347 | 348 | if len(batches) > 0: 349 | batches[-1]['x_reset'] = numpy.zeros(self.state['bs'], dtype='float32') 350 | 351 | # Trim the last very short batch 352 | if batches[-1]['max_length'] < 3: 353 | del batches[-1] 354 | batches[-1]['x_reset'] = numpy.zeros(self.state['bs'], dtype='float32') 355 | logger.debug("Truncating last mini-batch...") 356 | 357 | for batch in batches: 358 | if batch: 359 | yield batch 360 | 361 | 362 | def start(self): 363 | SSIterator.start(self) 364 | self.batch_iter = None 365 | 366 | def next(self, batch_size = -1): 367 | """ 368 | We can specify a batch size, 369 | independent of the object initialization. 370 | """ 371 | # If there are no more batches in list, try to generate new batches 372 | if not self.batch_iter: 373 | self.batch_iter = self.get_homogenous_batch_iter(batch_size) 374 | 375 | try: 376 | # Retrieve next batch 377 | batch = next(self.batch_iter) 378 | 379 | # Add Gaussian random variables to batch. 380 | # We add them separetly for each batch to save memory. 381 | # If we instead had added them to the full batch before splitting into mini-batches, 382 | # the random variables would take up several GBs for big batches and long documents. 383 | batch = add_random_variables_to_batch(self.state, self.rng, batch, self.prev_batch, self.evaluate_mode) 384 | # Keep track of last batch 385 | self.prev_batch = batch 386 | except StopIteration: 387 | return None 388 | return batch 389 | 390 | 391 | def get_offset(self): 392 | return self.last_returned_offset 393 | 394 | def get_reshuffle_count(self): 395 | return self.last_returned_reshuffle_count 396 | 397 | 398 | def get_train_iterator(state): 399 | train_data = Iterator( 400 | state['train_dialogues'], 401 | int(state['bs']), 402 | state=state, 403 | seed=state['seed'], 404 | use_infinite_loop=True, 405 | max_len=state.get('max_len', -1), 406 | evaluate_mode=False) 407 | 408 | valid_data = Iterator( 409 | state['valid_dialogues'], 410 | int(state['bs']), 411 | state=state, 412 | seed=state['seed'], 413 | use_infinite_loop=False, 414 | max_len=state.get('max_len', -1), 415 | evaluate_mode=True) 416 | return train_data, valid_data 417 | 418 | def get_test_iterator(state): 419 | assert 'test_dialogues' in state 420 | 421 | test_data = Iterator( 422 | state.get('test_dialogues'), 423 | int(state['bs']), 424 | state=state, 425 | seed=state['seed'], 426 | use_infinite_loop=False, 427 | max_len=state.get('max_len', -1), 428 | evaluate_mode=True) 429 | return test_data 430 | -------------------------------------------------------------------------------- /model.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import numpy 3 | import theano 4 | logger = logging.getLogger(__name__) 5 | 6 | # This is the list of strings required to ignore, if we're going to take a pretrained HRED model 7 | # and fine-tune it as a variational model. 8 | # parameter_strings_to_ignore = ["latent_utterance_prior", "latent_utterance_approx_posterior", "Wd_", "bd_"] 9 | 10 | 11 | class Model(object): 12 | def __init__(self): 13 | self.floatX = theano.config.floatX 14 | # Parameters of the model 15 | self.params = [] 16 | 17 | def save(self, filename): 18 | """ 19 | Save the model to file `filename` 20 | """ 21 | vals = dict([(x.name, x.get_value()) for x in self.params]) 22 | numpy.savez(filename, **vals) 23 | 24 | def load(self, filename, parameter_strings_to_ignore=[]): 25 | """ 26 | Load the model. 27 | 28 | Any parameter which has one of the strings inside parameter_strings_to_ignore as a substring, 29 | will not be loaded from the file (but instead initialized as a new model, which usually means random). 30 | """ 31 | vals = numpy.load(filename) 32 | for p in self.params: 33 | load_parameter = True 34 | for string_to_ignore in parameter_strings_to_ignore: 35 | if string_to_ignore in p.name: 36 | logger.debug('Initializing parameter {} as in new model'.format(p.name)) 37 | load_parameter = False 38 | 39 | if load_parameter: 40 | if p.name in vals: 41 | logger.debug('Loading {} of {}'.format(p.name, p.get_value(borrow=True).shape)) 42 | if p.get_value().shape != vals[p.name].shape: 43 | raise Exception('Shape mismatch: {} != {} for {}'.format(p.get_value().shape, vals[p.name].shape, p.name)) 44 | p.set_value(vals[p.name]) 45 | else: 46 | logger.error('No parameter {} given: default initialization used'.format(p.name)) 47 | unknown = set(vals.keys()) - {p.name for p in self.params} 48 | if len(unknown): 49 | logger.error('Unknown parameters {} given'.format(unknown)) 50 | -------------------------------------------------------------------------------- /numpy_compat.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Compatibility with older numpy's providing argpartition replacement. 3 | 4 | ''' 5 | 6 | 7 | ''' 8 | Created on Sep 12, 2014 9 | 10 | @author: chorows 11 | ''' 12 | 13 | __all__ = ['argpartition'] 14 | 15 | import numpy 16 | import warnings 17 | 18 | if hasattr(numpy, 'argpartition'): 19 | argpartition = numpy.argpartition 20 | else: 21 | try: 22 | import bottleneck 23 | #warnings.warn('Your numpy is too old (You have %s, we need 1.7.1), but we have found argpartsort in bottleneck' % (numpy.__version__,)) 24 | def argpartition(a, kth, axis=-1): 25 | return bottleneck.argpartsort(a, kth, axis) 26 | except ImportError: 27 | warnings.warn('''Beam search will be slow! 28 | 29 | Your numpy is old (you have v. %s) and doesn't provide an argpartition function. 30 | Either upgrade numpy, or install bottleneck (https://pypi.python.org/pypi/Bottleneck). 31 | 32 | If you run this from within LISA lab you probably want to run: pip install bottleneck --user 33 | ''' % (numpy.__version__,)) 34 | def argpartition(a, kth, axis=-1, order=None): 35 | return numpy.argsort(a, axis=axis, order=order) 36 | -------------------------------------------------------------------------------- /sample.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import argparse 4 | import cPickle 5 | import traceback 6 | import logging 7 | import time 8 | import sys 9 | 10 | import os 11 | import numpy 12 | import codecs 13 | import search 14 | import utils 15 | 16 | from dialog_encdec import DialogEncoderDecoder 17 | from numpy_compat import argpartition 18 | from state import prototype_state 19 | 20 | logger = logging.getLogger(__name__) 21 | 22 | class Timer(object): 23 | def __init__(self): 24 | self.total = 0 25 | 26 | def start(self): 27 | self.start_time = time.time() 28 | 29 | def finish(self): 30 | self.total += time.time() - self.start_time 31 | 32 | def parse_args(): 33 | parser = argparse.ArgumentParser("Sample (with beam-search) from the session model") 34 | 35 | parser.add_argument("--ignore-unk", 36 | action="store_false", 37 | help="Disables the generation of unknown words ( tokens)") 38 | 39 | parser.add_argument("model_prefix", 40 | help="Path to the model prefix (without _model.npz or _state.pkl)") 41 | 42 | parser.add_argument("context", 43 | help="File of input contexts") 44 | 45 | parser.add_argument("output", 46 | help="Output file") 47 | 48 | parser.add_argument("--beam_search", 49 | action="store_true", 50 | help="Use beam search instead of random search") 51 | 52 | parser.add_argument("--n-samples", 53 | default="1", type=int, 54 | help="Number of samples") 55 | 56 | parser.add_argument("--n-turns", 57 | default=1, type=int, 58 | help="Number of dialog turns to generate") 59 | 60 | parser.add_argument("--verbose", 61 | action="store_true", default=False, 62 | help="Be verbose") 63 | 64 | parser.add_argument("changes", nargs="?", default="", help="Changes to state") 65 | return parser.parse_args() 66 | 67 | def main(): 68 | args = parse_args() 69 | state = prototype_state() 70 | 71 | state_path = args.model_prefix + "_state.pkl" 72 | model_path = args.model_prefix + "_model.npz" 73 | 74 | with open(state_path) as src: 75 | state.update(cPickle.load(src)) 76 | 77 | logging.basicConfig(level=getattr(logging, state['level']), format="%(asctime)s: %(name)s: %(levelname)s: %(message)s") 78 | 79 | state['compute_training_updates'] = False 80 | 81 | model = DialogEncoderDecoder(state) 82 | 83 | sampler = search.RandomSampler(model) 84 | if args.beam_search: 85 | sampler = search.BeamSampler(model) 86 | 87 | if os.path.isfile(model_path): 88 | logger.debug("Loading previous model") 89 | model.load(model_path) 90 | else: 91 | raise Exception("Must specify a valid model path") 92 | 93 | contexts = [[]] 94 | lines = open(args.context, "r").readlines() 95 | if len(lines): 96 | contexts = [x.strip() for x in lines] 97 | 98 | print('Sampling started...') 99 | context_samples, context_costs = sampler.sample(contexts, 100 | n_samples=args.n_samples, 101 | n_turns=args.n_turns, 102 | ignore_unk=args.ignore_unk, 103 | verbose=args.verbose) 104 | print('Sampling finished.') 105 | print('Saving to file...') 106 | 107 | # Write to output file 108 | output_handle = open(args.output, "w") 109 | for context_sample in context_samples: 110 | print >> output_handle, '\t'.join(context_sample) 111 | output_handle.close() 112 | print('Saving to file finished.') 113 | print('All done!') 114 | 115 | if __name__ == "__main__": 116 | main() 117 | 118 | -------------------------------------------------------------------------------- /search.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import argparse 4 | import cPickle 5 | import traceback 6 | import logging 7 | import time 8 | import sys 9 | 10 | import os 11 | import numpy 12 | import codecs 13 | 14 | from dialog_encdec import DialogEncoderDecoder 15 | from numpy_compat import argpartition 16 | from state import prototype_state 17 | logger = logging.getLogger(__name__) 18 | 19 | def sample_wrapper(sample_logic): 20 | def sample_apply(*args, **kwargs): 21 | sampler = args[0] 22 | contexts = args[1] 23 | 24 | verbose = kwargs.get('verbose', False) 25 | 26 | if verbose: 27 | logger.info("Starting {} : {} start sequences in total".format(sampler.name, len(contexts))) 28 | 29 | context_samples = [] 30 | context_costs = [] 31 | 32 | # Start loop for each utterance 33 | for context_id, context_utterances in enumerate(contexts): 34 | if verbose: 35 | logger.info("Searching for {}".format(context_utterances)) 36 | 37 | # Convert contextes into list of ids 38 | joined_context = [] 39 | if len(context_utterances) == 0: 40 | joined_context = [sampler.model.eos_sym] 41 | else: 42 | utterance_ids = sampler.model.words_to_indices(context_utterances.split()) 43 | # Add eos tokens 44 | if len(utterance_ids) > 0: 45 | if not utterance_ids[0] == sampler.model.eos_sym: 46 | utterance_ids = [sampler.model.eos_sym] + utterance_ids 47 | if not utterance_ids[-1] == sampler.model.eos_sym: 48 | utterance_ids += [sampler.model.eos_sym] 49 | 50 | else: 51 | utterance_ids = [sampler.model.eos_sym] 52 | 53 | joined_context += utterance_ids 54 | 55 | samples, costs = sample_logic(sampler, joined_context, **kwargs) 56 | 57 | # Convert back indices to list of words 58 | converted_samples = map(lambda sample : sampler.model.indices_to_words(sample, exclude_end_sym=kwargs.get('n_turns', 1) == 1), samples) 59 | # Join the list of words 60 | converted_samples = map(' '.join, converted_samples) 61 | 62 | if verbose: 63 | for i in range(len(converted_samples)): 64 | #print "Samples {}: {}".format(costs[i], converted_samples[i].encode('utf-8')) 65 | logger.info("Samples {}: {}".format(costs[i], converted_samples[i].encode('utf-8'))) 66 | 67 | context_samples.append(converted_samples) 68 | context_costs.append(costs) 69 | 70 | return context_samples, context_costs 71 | return sample_apply 72 | 73 | class Sampler(object): 74 | """ 75 | An abstract sampler class 76 | """ 77 | def __init__(self, model): 78 | # Compile beam search 79 | self.name = 'Sampler' 80 | self.model = model 81 | self.compiled = False 82 | self.max_len = 160 83 | 84 | def compile(self): 85 | self.next_probs_predictor = self.model.build_next_probs_function() 86 | self.compute_encoding = self.model.build_encoder_function() 87 | 88 | if not self.model.reset_utterance_decoder_at_end_of_utterance: 89 | self.compute_decoder_encoding = self.model.build_decoder_encoding() 90 | 91 | self.compiled = True 92 | 93 | def select_next_words(self, next_probs, step_num, how_many): 94 | pass 95 | 96 | def count_n_turns(self, utterance): 97 | return len([w for w in utterance \ 98 | if w == self.model.eos_sym]) 99 | 100 | @sample_wrapper 101 | def sample(self, *args, **kwargs): 102 | context = args[0] 103 | 104 | max_context_length = kwargs.get('max_context_length', 400) 105 | if len(context) > max_context_length: 106 | context = context[-max_context_length:] 107 | 108 | n_samples = kwargs.get('n_samples', 1) 109 | ignore_unk = kwargs.get('ignore_unk', True) 110 | min_length = kwargs.get('min_length', 1) 111 | max_length = kwargs.get('max_length', 30) 112 | beam_diversity = kwargs.get('beam_diversity', 1) 113 | normalize_by_length = kwargs.get('normalize_by_length', True) 114 | verbose = kwargs.get('verbose', False) 115 | n_turns = kwargs.get('n_turns', 1) 116 | 117 | if not self.compiled: 118 | self.compile() 119 | 120 | # Convert to matrix, each column is a context 121 | # [[1,1,1],[4,4,4],[2,2,2]] 122 | context = numpy.repeat(numpy.array(context, dtype='int32')[:,None], 123 | n_samples, axis=1) 124 | 125 | if context[-1, 0] != self.model.eos_sym: 126 | raise Exception('Last token of context, when present,' 127 | 'should be the end of utterance: %d' % self.model.eos_sym) 128 | 129 | # Generate the reversed context 130 | reversed_context = self.model.reverse_utterances(context) 131 | 132 | if self.model.direct_connection_between_encoders_and_decoder: 133 | if self.model.bidirectional_utterance_encoder: 134 | dialog_enc_size = self.model.sdim+self.model.qdim_encoder*2 135 | else: 136 | dialog_enc_size = self.model.sdim+self.model.qdim_encoder 137 | else: 138 | dialog_enc_size = self.model.sdim 139 | 140 | prev_hs = numpy.zeros((n_samples, dialog_enc_size), dtype='float32') 141 | 142 | prev_hd = numpy.zeros((n_samples, self.model.utterance_decoder.complete_hidden_state_size), dtype='float32') 143 | 144 | if not self.model.reset_utterance_decoder_at_end_of_utterance: 145 | assert self.model.bs >= context.shape[1] 146 | enlarged_context = numpy.zeros((context.shape[0], self.model.bs), dtype='int32') 147 | enlarged_context[:, 0:context.shape[1]] = context[:] 148 | enlarged_reversed_context = numpy.zeros((context.shape[0], self.model.bs), dtype='int32') 149 | enlarged_reversed_context[:, 0:context.shape[1]] = reversed_context[:] 150 | 151 | ran_gaussian_vector = self.model.rng.normal(size=(context.shape[0],n_samples,self.model.latent_gaussian_per_utterance_dim)).astype('float32') 152 | ran_uniform_vector = self.model.rng.uniform(low=0.0, high=1.0, size=(context.shape[0],n_samples,self.model.latent_piecewise_per_utterance_dim)).astype('float32') 153 | 154 | zero_mask = numpy.zeros((context.shape[0], self.model.bs), dtype='float32') 155 | zero_vector = numpy.zeros((self.model.bs), dtype='float32') 156 | ones_mask = numpy.zeros((context.shape[0], self.model.bs), dtype='float32') 157 | 158 | # Computes new utterance decoder hidden states (including intermediate utterance encoder and dialogue encoder hidden states) 159 | new_hd = self.compute_decoder_encoding(enlarged_context, enlarged_reversed_context, self.max_len, zero_mask, zero_vector, ran_gaussian_vector, ran_uniform_vector, ones_mask) 160 | 161 | 162 | prev_hd[:] = new_hd[0][-1][0:context.shape[1], :] 163 | 164 | fin_gen = [] 165 | fin_costs = [] 166 | 167 | gen = [[] for i in range(n_samples)] 168 | costs = [0. for i in range(n_samples)] 169 | beam_empty = False 170 | 171 | # Compute random vector as additional input 172 | ran_gaussian_vectors = self.model.rng.normal(size=(n_samples,self.model.latent_gaussian_per_utterance_dim)).astype('float32') 173 | ran_uniform_vectors = self.model.rng.uniform(low=0.0, high=1.0, size=(n_samples,self.model.latent_piecewise_per_utterance_dim)).astype('float32') 174 | 175 | # HACK 176 | #ran_uniform_vectors = numpy.greater(ran_uniform_vectors, 0.5).astype('float32') 177 | 178 | 179 | for k in range(max_length): 180 | if len(fin_gen) >= n_samples or beam_empty: 181 | break 182 | 183 | if verbose: 184 | logger.info("{} : sampling step {}, beams alive {}".format(self.name, k, len(gen))) 185 | 186 | # Here we aggregate the context and recompute the hidden state 187 | # at both session level and query level. 188 | # Stack only when we sampled something 189 | if k > 0: 190 | context = numpy.vstack([context, \ 191 | numpy.array(map(lambda g: g[-1], gen))]).astype('int32') 192 | reversed_context = numpy.copy(context) 193 | for idx in range(context.shape[1]): 194 | eos_indices = numpy.where(context[:, idx] == self.model.eos_sym)[0] 195 | prev_eos_index = -1 196 | for eos_index in eos_indices: 197 | reversed_context[(prev_eos_index+2):eos_index, idx] = (reversed_context[(prev_eos_index+2):eos_index, idx])[::-1] 198 | prev_eos_index = eos_index 199 | 200 | prev_words = context[-1, :] 201 | 202 | # Recompute encoder states, hs and random variables 203 | # only for those particular utterances that meet the end-of-utterance token 204 | indx_update_hs = [num for num, prev_word in enumerate(prev_words) 205 | if prev_word == self.model.eos_sym] 206 | 207 | if len(indx_update_hs): 208 | encoder_states = self.compute_encoding(context[:, indx_update_hs], reversed_context[:, indx_update_hs], self.max_len) 209 | prev_hs[indx_update_hs] = encoder_states[1][-1] 210 | ran_gaussian_vectors[indx_update_hs,:] = self.model.rng.normal(size=(len(indx_update_hs),self.model.latent_gaussian_per_utterance_dim)).astype('float32') 211 | ran_uniform_vectors[indx_update_hs,:] = self.model.rng.uniform(low=0.0, high=1.0, size=(len(indx_update_hs),self.model.latent_piecewise_per_utterance_dim)).astype('float32') 212 | 213 | 214 | # HACK 215 | #ran_uniform_vectors = numpy.greater(ran_uniform_vectors, 0.5).astype('float32') 216 | 217 | # ... done 218 | next_probs, new_hd = self.next_probs_predictor(prev_hs, prev_hd, prev_words, context, ran_gaussian_vectors, ran_uniform_vectors) 219 | 220 | 221 | 222 | assert next_probs.shape[1] == self.model.idim 223 | 224 | # Adjust log probs according to search restrictions 225 | if ignore_unk: 226 | next_probs[:, self.model.unk_sym] = 0 227 | if k <= min_length: 228 | next_probs[:, self.model.eos_sym] = 0 229 | next_probs[:, self.model.eod_sym] = 0 230 | 231 | # Update costs 232 | next_costs = numpy.array(costs)[:, None] - numpy.log(next_probs) 233 | 234 | # Select next words here 235 | (beam_indx, word_indx), costs = self.select_next_words(next_costs, next_probs, k, n_samples) 236 | 237 | # Update the stacks 238 | new_gen = [] 239 | new_costs = [] 240 | new_sources = [] 241 | 242 | for num, (beam_ind, word_ind, cost) in enumerate(zip(beam_indx, word_indx, costs)): 243 | if len(new_gen) > n_samples: 244 | break 245 | 246 | hypothesis = gen[beam_ind] + [word_ind] 247 | 248 | # End of utterance has been detected 249 | n_turns_hypothesis = self.count_n_turns(hypothesis) 250 | if n_turns_hypothesis == n_turns: 251 | if verbose: 252 | logger.debug("adding utterance {} from beam {}".format(hypothesis, beam_ind)) 253 | 254 | # We finished sampling 255 | fin_gen.append(hypothesis) 256 | fin_costs.append(cost) 257 | elif self.model.eod_sym in hypothesis: # End of dialogue detected 258 | new_hypothesis = [] 259 | for wrd in hypothesis: 260 | new_hypothesis += [wrd] 261 | if wrd == self.model.eod_sym: 262 | break 263 | hypothesis = new_hypothesis 264 | 265 | if verbose: 266 | logger.debug("adding utterance {} from beam {}".format(hypothesis, beam_ind)) 267 | 268 | # We finished sampling 269 | fin_gen.append(hypothesis) 270 | fin_costs.append(cost) 271 | else: 272 | # Hypothesis recombination 273 | # TODO: pick the one with lowest cost 274 | has_similar = False 275 | if self.hyp_rec > 0: 276 | has_similar = len([g for g in new_gen if \ 277 | g[-self.hyp_rec:] == hypothesis[-self.hyp_rec:]]) != 0 278 | 279 | if not has_similar: 280 | new_sources.append(beam_ind) 281 | new_gen.append(hypothesis) 282 | new_costs.append(cost) 283 | 284 | if verbose: 285 | for gen in new_gen: 286 | logger.debug("partial -> {}".format(' '.join(self.model.indices_to_words(gen)))) 287 | 288 | prev_hd = new_hd[new_sources] 289 | prev_hs = prev_hs[new_sources] 290 | ran_gaussian_vectors = ran_gaussian_vectors[new_sources,:] 291 | ran_uniform_vectors = ran_uniform_vectors[new_sources,:] 292 | context = context[:, new_sources] 293 | reversed_context = reversed_context[:, new_sources] 294 | gen = new_gen 295 | costs = new_costs 296 | beam_empty = len(gen) == 0 297 | 298 | # If we have not sampled anything 299 | # then force include stuff 300 | if len(fin_gen) == 0: 301 | fin_gen = gen 302 | fin_costs = costs 303 | 304 | # Normalize costs 305 | if normalize_by_length: 306 | fin_costs = [(fin_costs[num]/len(fin_gen[num])) \ 307 | for num in range(len(fin_gen))] 308 | 309 | fin_gen = numpy.array(fin_gen)[numpy.argsort(fin_costs)] 310 | fin_costs = numpy.array(sorted(fin_costs)) 311 | return fin_gen[:n_samples], fin_costs[:n_samples] 312 | 313 | class RandomSampler(Sampler): 314 | def __init__(self, model): 315 | Sampler.__init__(self, model) 316 | self.name = 'RandomSampler' 317 | self.hyp_rec = 0 318 | 319 | def select_next_words(self, next_costs, next_probs, step_num, how_many): 320 | # Choice is complaining 321 | next_probs = next_probs.astype("float64") 322 | word_indx = numpy.array([self.model.rng.choice(self.model.idim, p = x/numpy.sum(x)) 323 | for x in next_probs], dtype='int32') 324 | beam_indx = range(next_probs.shape[0]) 325 | 326 | args = numpy.ravel_multi_index(numpy.array([beam_indx, word_indx]), next_costs.shape) 327 | return (beam_indx, word_indx), next_costs.flatten()[args] 328 | 329 | class BeamSampler(Sampler): 330 | def __init__(self, model): 331 | Sampler.__init__(self, model) 332 | self.name = 'BeamSampler' 333 | self.hyp_rec = 3 334 | 335 | def select_next_words(self, next_costs, next_probs, step_num, how_many): 336 | # Pick only on the first line (for the beginning of sampling) 337 | # This will avoid duplicate token. 338 | if step_num == 0: 339 | flat_next_costs = next_costs[:1, :].flatten() 340 | else: 341 | # Set the next cost to infinite for finished utterances (they will be replaced) 342 | # by other utterances in the beam 343 | flat_next_costs = next_costs.flatten() 344 | 345 | voc_size = next_costs.shape[1] 346 | 347 | args = numpy.argpartition(flat_next_costs, how_many)[:how_many] 348 | args = args[numpy.argsort(flat_next_costs[args])] 349 | 350 | return numpy.unravel_index(args, next_costs.shape), flat_next_costs[args] 351 | 352 | 353 | -------------------------------------------------------------------------------- /tests/data/MT_WordEmb.pkl: -------------------------------------------------------------------------------- 1 | (lp1 2 | cnumpy.core.multiarray 3 | _reconstruct 4 | p2 5 | (cnumpy 6 | ndarray 7 | p3 8 | (I0 9 | tS'b' 10 | tRp4 11 | (I1 12 | (I23 13 | I10 14 | tcnumpy 15 | dtype 16 | p5 17 | (S'f8' 18 | I0 19 | I1 20 | tRp6 21 | (I3 22 | S'<' 23 | NNNI-1 24 | I-1 25 | I0 26 | tbI00 27 | S'\x1a\xe5t\n\xbd\xde\xfd\xbf`@\x92)\xe3\x1a\xc0\xbf\xe9"\x954\x14-\xd0\xbf\xce}y\xd1S\x90\xd6\xbfKm\xfe\xeb\r\xe0\xc1?\x12\xf3\xc93Z\xb0\xed\xbf\xf3\xfd\xf1\xd9\xe8\xa8\xff\xbfJV\xdaH=\x0e\xe0\xbf\xd3\x10a\xa2l\x87\xf6\xbf?]\xf3\xe1\x83u\xe3?\xca/5$l\x12\xaa\xbfS\x1d\xe7_%l\xe1\xbf\xa2\xb5\xb4=\xde\xb1\xd3?L\x06\x81\x81]\x04\xd1?\xc21\xc4/\xb6\xcb\xed?hs\xc4V\x123\xf0\xbf5\xa7\xc2\xfd\xc9V\xdc\xbf\xa5Q\xab$\xaa\xcf\x01\xc0;\xb8\xc1[\x0b:\xc4\xbf\x12\xc7\xf0\xd1\xbc\x07\xf2?\xe8\x07\xf3\x08\r:\xb5\xbf\xc6I\xf8i\xab\x0b\xc8\xbf\x8a\x1df\x1a\xdc\xb6\xf2?\x86\xba\xd9!\x99!\xd8?\xd8\xc3xt\xd9\xf1\xe1?\x9e\x83\xfev\xbb\xd2\xd1\xbf\xd2\xacJw\xa4\xc6\xde\xbf|-[\xa4Z\x8a\xf0?\xf8\xa4\xa7\x9b\xc9\xcf\xf4\xbf6\x07\xee`LE\xe9?\x96\xf3\x02\x83\xf3\x11\xec?R\xb5[\x17\xb5\xdd\xe1\xbf\x87\xb6\x01\xcdu\x86\xcf\xbf/\x1eo\t\xd8\n\xef\xbf\xcd\x0f\xd6jS\xe9\xc0\xbfE\xee\n\xd5-Y\xf9?\x8cz\x97\x1b\x0e\xf8\xe9\xbf\x87\x84\xfe\xea\xd5\x13\x05\xc0.1\x96\xd9n\xbc\xe5?4\xe1\x07\xfaK\xfe\x00@W}.G\xe4\x0f\xd6?:\x00\xd0\x0f\xf2X\xe4?o5;\x1dW\xbc\xe9\xbf\x9fz \x19\x15\xc4\xe6?\x98\x12\x7f\xe1[\xa7\xfa?\xe7\x1fu\x91\xca\xfa\xb1?i\xb1\xa3\xa1\x16\xbd\xd0\xbf\xab:\xaa\x1f\xf5T\xee?*\xa8\x9f\xffk\xe4\xf2\xbf\xe1\xafu\x08\x8b\xa7\xd6\xbf\xe9\xb9\x98\xc0\xb8J\xf7?kL\xbcvC\x8a\xd2\xbf\xe4m=KZt\xef\xbf\xafc"\x1c\xcb\xfb\x02\xc0}\xeb\x08\xa87\xfc\xf5\xbf\xc5tP\xb6gT\xd7?RD&\xc3\x91\xe7\xf3?w\xc0A\xd5\x11\x11\xbb\xbf\x07\xcb\xaf=9\xae\xcc?s\xe0u\xa4%\xca\x02\xc0\x9bENE\x05z\xd1\xbf\x91\x8aR\xde\x932\xfd?\x83\x81\xd2\xf6\xa2\x1c\xdf?\xc5{u\xbc\x1c\x9a\xd3?\x00G\xf1l-b\xec?\xb9\xb7+.\x8c\x0f\xe7\xbfJ\x93\xb1\xae\xf3#\xb9?u\x1d\\\x18\x1e\xbe\xdf?\xde\x8fx{\xb3\x00\xb6?\xa2\xa4y\xe6\xa6\x16\xe7?\xfa7\xe9\x95\xcb\x0c\xff?\xd8\xb31\xf7\x10v\xfe\xbf\x13\xb9\x10\xd2\xd1\t\xe4?\xac \x0c\x99~\xf1\xe1\xbf\xb5\x0f\xac\xde(\xb8\xdb?k\xc8f/\xb7c\xe4\xbf\xa2G\xb1\xcaB\xe1\xe6?\xad,\xe6\x8f!Y\xec\xbf\xbc6\x12\xd7\x87\x9c\xe7?\xd9\xed5\x9e\xf7k\xea\xbfB\xb2\xd9-\xca\xc2\xee?\x89A\xb6\x1e\xb1Y\xe8\xbf!c\xcc`\x8b\xd1\xed?A\x99\xe5\xa03*\xcc\xbf\xb0\xb3/\xd0)\x04\xf0\xbf\x91\xee\xbf\xe29E\xf0\xbf\x87\x96\xb3\x0bP\xfd\xd1?\xf1\xcd\xb5\x8f\xe9\x93\xe0?\x93\xc0.\'p\xc8\xcc?zE\xd0\xc0\x90\xba\xe5\xbf\xed\xb2\xd4\x14\xae\xa8\xe2?\x7f\xd0\x9bO\xd4a\xda\xbf7\x15\x1d^_\xf9\xe2\xbf\xac\xaf\xedg\xee\x12\xf2?1@8r\xf5W\xe3\xbfl\x19\x83o\x05\xd4\xa5\xbf?\x130\xfdWu\xb0?o{\xe8A\xb8\x04\xdb\xbf\xfd\xb3\xc3\x83\xf1G\x04@\xca\x81\xcc+\xcak\xf8\xbf\xe4\xe0t\xc6\xfd\xf7\xfa?\r\xc9z\xe4\x08\xa7\xf8?Ai\xcc\x0f6\x96\xea\xbf\xbf\xe7\xdc\x931\xd2\xf1?E\x8e\xdb\xfbP\xa2\xeb?\xbcA\x88+\xbd\x8c\xd6?\xd4\xd7\xc1*\x838\xdb?\xe7%\r$\xa8\x1c\x01@\xb6\xcd\x9a\x9f\x88\x1f\x93\xbf\xf7e\xe7%\x0e\xe9\xc5\xbf\xf2P,\xef\xbb\xdb\xc4\xbf,\xf0\xcf]I\xc0\xe0\xbf\xfdN\x1c\xf1$\xba\xe3\xbfPu4\xbf\xf3\x1c\xed\xbfE\xf5\'\xb9b\x1f\xf8\xbf\xcfv\x90\x07\x07\xa7\xe0\xbf\x93\x08\x1e"\x9c\xdb\xf1?\x19\xc0\x93\xae\x9dW\xb1?-+\r\x08,\x8e\xe8\xbf\x01\xb0\xe1\x97u\x86\xcc?\xc1fu:U\x95\xec?\xea\x85"\xd2\x00\x18\xcc?\xbd\x0c\x08\xe2\xcb\xdb\xf2?\tG\x8ep\x15Z\xc5?\x878\xee\x9f\xe7#\xe5\xbfQ\xe57\xc99\x9f\xd2?\xc6-~%\xea\x12\xdd\xbf\xdf\xcb\xc2\x80\xad-\xb9?D\x04[3]r\xea?\xdb2\xb5\x82\xf5S\xb7\xbf\x8b\xcc\xa3\xf5\xc0\xf3\x83\xbfF7\xbb\x91ZF\xc7?\xab\xc4o=A\xbf\xd9?\x9d\x15.\x9a\xa5\xae\xe5\xbfN\x9b\xbaB`\x19\xff?\x89\x97F^:o\xfa?S\xe0h\x0f\x97q\xa5\xbf\xe1\xab\xc4\xbc\x81>\xf8\xbf\x9f\xd6\x13O1\xed\xe2?\x984\xdah\xa6{\xce?\xbc\xf0.\xe2nD\xf0\xbfe\xa3\x05\x1c\xdc?\xdb?\t\x8bO\xaeD\xae\xe8\xbfa\xb5\xddd\x1do\xef\xbf\xb3\xfd\x03i\xa6+\xe3\xbf;\x1f\x0c\xeeH\x10\xd0?\x00KI\x07\xe6\x9d\x00@p\xfdh\xcf\xe2\xa0\xb6\xbf+\xd5\x1b\xa9\x82H\xe8?\x94\x9c\xff\x96\xf9\xf9\xfa\xbf\x00w\xdc5\x1f\xf9\xf2\xbf\x02D\x0b\xf1\xe9\x0e\xaa\xbf\xdc\xc7\xf8t\xa3q\x01@9.\xe0C&\x13\xe0?SZ\x1b\xb5\xfdz\xe8?i\x94~8\xc8V\xf6?A\xbc\xdb\x00\xb6d\xdf\xbf\xca"8\xf9\xc0M\xfb\xbfL\xfeeC\x97\xc0\x05\xc04\xe1\xa1\xe7aq\xdc\xbfg\xe0`\x8e\xa2\xed\xcf?Gq\x9d\x1eZ\x0f\xef?\xdb\x86l\xcf\x86\x0f\xe4\xbf}\xe4\xde\x83\xb1\\\xe1\xbfo\xdb\xf9\x0c&T\xf8?\x8d\xf0\xa9\x96\xc7Q\xf4?\xe5sd\xd9/Z\xf6\xbf\x87\x8b\xfa\xa6\xf4\xad\xe1\xbf|\xed@\xf911\xf5\xbf\x98\xc8\xd2\x1bo\x10\xc3?wY\xca{P\xf6\xe1\xbfA\x08\x8a\x88@\x9d\xb0\xbf\xe8m\x93\xa8\xa28\xcd?\x08\x07\xddP\x8f\x0e\xf0?\xe7Ha\xfe\x00\x88\xf6\xbf\x94j\rN\x9e\x04\xa0\xbfH\xa5J\xf6\x8dV\xd5?\xa5n\x7f\xf7u\x1e\xf5\xbfN\x8cD\xa3\x82\xa3\xe9\xbfk\xe6\x99b\xc0x\xf3?U\x91DHg\xe0\xb0\xbfIw\x8d\xe9\x84\xbc\xee?G/\xfa\xae{\x9e\x02@\x05\x119q:;\xbc\xbf\xdd\xe3\xd1\xa9\xd6\xb2\x06\xc0~\x9d&"MT\xd7\xbf\x85\xdaG\x8b5\xdf\xce\xbf\x11\x12"n\xd4\xcd\xfe\xbfng\xaa3\xc4\xf6\xd9\xbf\xab\xb9q4\x08\xd0\x03@i\xc2\x97\xec\x90\x01\xf6\xbff\xa2G(d\x0e\xed\xbf\xbeo\xccZ\x00\x05\xc2?\xfacbf(N\xd3?\xf8\x00{\xc5s\x99\xe5?\x16VF\x9a\xf5C\xde?A\xd9^qz\xce\xe5?\x08\xf7|{\x05\xf4\xd0?\tZ\x1d\xdc\x05\xba\xcf\xbf>P4\x0b{~\xd7?\x184\x99@\xb7\x86\xf9?Mg\xf1\x18\xc1\x16\xf4?\x9f\xf6\x12\xfd\xdd\xc5\xfa\xbf\xadf\xbept\xe8\xe1?W\xb1\xd1/1\xe3\xd6?7\xab\x11bR\xb2\xf3?b\xa57\xd4J\x1d\xef\xbfg\x7fD\x98\xa7G\xed?\xd5Ga\x01&\xeb\xe6\xbf\x19;\xd52|K\xc3?\x1b\x86\x90\x00\xfcO\xe4?\x90\xc7\xb3#\xfa\xf4\xcd\xbf4\x87\xbf\x03\x03_\xed\xbf\x18\x89\xf2b\x91\xdc\xc4?a\xd2\xa89\xcc\xd3\xf2?jF\x07\x16\x16\x13\xea\xbf\xbc\xa6\xe4\xce<\xc6\xb7?a\xe9Li\x19\x0e\xe2?QX\x9f\xdf\xd9}\x9f\xbf\xf1LD\x95\xe2\x9a\xff?\x8aN\xe6\x16#\x83\xf3?k\xcc\r\x91,Y\xf8\xbf\x10>\xe4~\xeeR\xe7\xbf\x8e\xef%\x82nK\xf7?\xaa\x85\xf9\xd7\xd5t\xb0\xbfC\xcf v:`\xeb\xbf\xdf;Z=:\x18\xd5\xbf\x1cS\xc0\xaf\xad\x10\xf9\xbf\xc6\xc7s\x8a\x8fn\xb0?\x1e\x0fi\xd0\xd5\xfa\xd6?' 28 | tbag2 29 | (g3 30 | (I0 31 | tS'b' 32 | tRp7 33 | (I1 34 | (I23 35 | I10 36 | tg6 37 | I00 38 | S'\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?' 39 | tba. -------------------------------------------------------------------------------- /tests/data/ttest.dialogues.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/julianser/hred-latent-piecewise/068478dd5b2aa9928168a62a479773e219505319/tests/data/ttest.dialogues.pkl -------------------------------------------------------------------------------- /tests/data/ttest.semantic.pkl: -------------------------------------------------------------------------------- 1 | (lp1 2 | (lp2 3 | I0 4 | aI1 5 | aa(lp3 6 | I1 7 | aI1 8 | aa. -------------------------------------------------------------------------------- /tests/data/ttrain.dialogues.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/julianser/hred-latent-piecewise/068478dd5b2aa9928168a62a479773e219505319/tests/data/ttrain.dialogues.pkl -------------------------------------------------------------------------------- /tests/data/ttrain.dict.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/julianser/hred-latent-piecewise/068478dd5b2aa9928168a62a479773e219505319/tests/data/ttrain.dict.pkl -------------------------------------------------------------------------------- /tests/data/ttrain.semantic.pkl: -------------------------------------------------------------------------------- 1 | (lp1 2 | (lp2 3 | I0 4 | aI1 5 | aa(lp3 6 | I1 7 | aI1 8 | aa. -------------------------------------------------------------------------------- /tests/data/ttrain.txt: -------------------------------------------------------------------------------- 1 | how are you ? fine thanks ! and you ? 2 | what are you doing ? nothing much . are you serious ? 3 | -------------------------------------------------------------------------------- /tests/data/ttrain.txt~: -------------------------------------------------------------------------------- 1 | how are you ? fine thanks ! and you ? 2 | what are you doing ? nothing much . are you serious ? 3 | -------------------------------------------------------------------------------- /tests/data/tvalid.dialogues.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/julianser/hred-latent-piecewise/068478dd5b2aa9928168a62a479773e219505319/tests/data/tvalid.dialogues.pkl -------------------------------------------------------------------------------- /tests/data/tvalid.semantic.pkl: -------------------------------------------------------------------------------- 1 | (lp1 2 | (lp2 3 | I0 4 | aI1 5 | aa(lp3 6 | I1 7 | aI1 8 | aa. -------------------------------------------------------------------------------- /tests/data/tvalid.txt: -------------------------------------------------------------------------------- 1 | how are you ? fine thanks ! and you ? 2 | what are you doing ? nothing much . are you serious ? 3 | -------------------------------------------------------------------------------- /tests/data/tvalid_contexts.txt: -------------------------------------------------------------------------------- 1 | how are you ? fine thanks ! and you ? 2 | what are you doing ? nothing much . are you serious ? 3 | you you you ? 4 | what what what ? 5 | -------------------------------------------------------------------------------- /tests/data/tvalid_contexts.txt~: -------------------------------------------------------------------------------- 1 | how are you ? fine thanks ! and you ? 2 | what are you doing ? nothing much . are you serious ? 3 | you you you ? 4 | what what what ? 5 | -------------------------------------------------------------------------------- /tests/data/tvalid_potential_responses.txt: -------------------------------------------------------------------------------- 1 | and you ? what about me ? 2 | leave me alone ! are you serious ? 3 | and you ? what about me ? 4 | leave me alone ! leave me alone ! 5 | -------------------------------------------------------------------------------- /tests/data/tvalid_potential_responses.txt~: -------------------------------------------------------------------------------- 1 | and you ? what about me ? 2 | leave me alone ! are you serious ? 3 | and you ? what about me ? 4 | leave me alone ! leave me alone ! 5 | -------------------------------------------------------------------------------- /tests/data/tvalid_responses.txt: -------------------------------------------------------------------------------- 1 | and you ? 2 | are you serious ? 3 | serious serious serious ? 4 | and and and ? 5 | -------------------------------------------------------------------------------- /tests/data/tvalid_responses.txt~: -------------------------------------------------------------------------------- 1 | and you ? 2 | are you serious ? 3 | serious serious serious ? 4 | and and and ? 5 | 6 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | #!/usr/bin/env python 3 | 4 | from data_iterator import * 5 | from state import * 6 | from dialog_encdec import * 7 | from utils import * 8 | 9 | import time 10 | import traceback 11 | import sys 12 | import argparse 13 | import cPickle 14 | import logging 15 | import search 16 | import pprint 17 | import numpy 18 | import collections 19 | import signal 20 | import math 21 | import gc 22 | 23 | import os 24 | import os.path 25 | 26 | # For certain clusters (e.g. Guillumin) we use flag 'DUMP_EXPERIMENT_LOGS_TO_DISC' 27 | # to force dumping log outputs to file. 28 | if 'DUMP_EXPERIMENT_LOGS_TO_DISC' in os.environ: 29 | if os.environ['DUMP_EXPERIMENT_LOGS_TO_DISC'] == '1': 30 | sys.stdout = open('Exp_Out.txt', 'a') 31 | sys.stderr = open('Exp_Err.txt', 'a') 32 | 33 | from os import listdir 34 | from os.path import isfile, join 35 | 36 | import matplotlib 37 | matplotlib.use('Agg') 38 | import pylab 39 | 40 | 41 | class Unbuffered: 42 | def __init__(self, stream): 43 | self.stream = stream 44 | 45 | def write(self, data): 46 | self.stream.write(data) 47 | self.stream.flush() 48 | 49 | def __getattr__(self, attr): 50 | return getattr(self.stream, attr) 51 | 52 | sys.stdout = Unbuffered(sys.stdout) 53 | logger = logging.getLogger(__name__) 54 | 55 | ### Unique RUN_ID for this execution 56 | RUN_ID = str(time.time()) 57 | 58 | ### Additional measures can be set here 59 | measures = ["train_cost", "train_misclass", "train_kl_divergence_cost", "train_posterior_gaussian_mean_variance", "valid_cost", "valid_misclass", "valid_posterior_gaussian_mean_variance", "valid_kl_divergence_cost", "valid_emi"] 60 | 61 | 62 | def init_timings(): 63 | timings = {} 64 | for m in measures: 65 | timings[m] = [] 66 | return timings 67 | 68 | def save(model, timings, train_iterator, post_fix = ''): 69 | print "Saving the model..." 70 | 71 | # ignore keyboard interrupt while saving 72 | start = time.time() 73 | s = signal.signal(signal.SIGINT, signal.SIG_IGN) 74 | 75 | model.state['train_iterator_offset'] = train_iterator.get_offset() + 1 76 | model.state['train_iterator_reshuffle_count'] = train_iterator.get_reshuffle_count() 77 | 78 | model.save(model.state['save_dir'] + '/' + model.state['run_id'] + "_" + model.state['prefix'] + post_fix + 'model.npz') 79 | cPickle.dump(model.state, open(model.state['save_dir'] + '/' + model.state['run_id'] + "_" + model.state['prefix'] + post_fix + 'state.pkl', 'w')) 80 | numpy.savez(model.state['save_dir'] + '/' + model.state['run_id'] + "_" + model.state['prefix'] + post_fix + 'timing.npz', **timings) 81 | signal.signal(signal.SIGINT, s) 82 | 83 | print "Model saved, took {}".format(time.time() - start) 84 | 85 | def load(model, filename, parameter_strings_to_ignore): 86 | print "Loading the model..." 87 | 88 | # ignore keyboard interrupt while saving 89 | start = time.time() 90 | s = signal.signal(signal.SIGINT, signal.SIG_IGN) 91 | model.load(filename, parameter_strings_to_ignore) 92 | signal.signal(signal.SIGINT, s) 93 | 94 | print "Model loaded, took {}".format(time.time() - start) 95 | 96 | def main(args): 97 | logging.basicConfig(level = logging.DEBUG, 98 | format = "%(asctime)s: %(name)s: %(levelname)s: %(message)s") 99 | 100 | state = eval(args.prototype)() 101 | timings = init_timings() 102 | 103 | auto_restarting = False 104 | if args.auto_restart: 105 | assert not args.save_every_valid_iteration 106 | assert len(args.resume) == 0 107 | 108 | directory = state['save_dir'] 109 | if not directory[-1] == '/': 110 | directory = directory + '/' 111 | 112 | auto_resume_postfix = state['prefix'] + '_auto_model.npz' 113 | 114 | if os.path.exists(directory): 115 | directory_files = [f for f in listdir(directory) if isfile(join(directory, f))] 116 | resume_filename = '' 117 | for f in directory_files: 118 | if len(f) > len(auto_resume_postfix): 119 | if f[len(f) - len(auto_resume_postfix):len(f)] == auto_resume_postfix: 120 | if len(resume_filename) > 0: 121 | print 'ERROR: FOUND MULTIPLE MODELS IN DIRECTORY:', directory 122 | assert False 123 | else: 124 | resume_filename = directory + f[0:len(f)-len('__auto_model.npz')] 125 | 126 | if len(resume_filename) > 0: 127 | logger.debug("Found model to automatically resume: %s" % resume_filename) 128 | auto_restarting = True 129 | # Setup training to automatically resume training with the model found 130 | args.resume = resume_filename + '__auto' 131 | # Disable training from reinitialization any parameters 132 | args.reinitialize_decoder_parameters = False 133 | args.reinitialize_latent_variable_parameters = False 134 | else: 135 | logger.debug("Could not find any model to automatically resume...") 136 | 137 | 138 | 139 | if args.resume != "": 140 | logger.debug("Resuming %s" % args.resume) 141 | 142 | state_file = args.resume + '_state.pkl' 143 | timings_file = args.resume + '_timing.npz' 144 | 145 | if os.path.isfile(state_file) and os.path.isfile(timings_file): 146 | logger.debug("Loading previous state") 147 | 148 | state = cPickle.load(open(state_file, 'r')) 149 | timings = dict(numpy.load(open(timings_file, 'r'))) 150 | for x, y in timings.items(): 151 | timings[x] = list(y) 152 | 153 | # Increment seed to make sure we get newly shuffled batches when training on large datasets 154 | state['seed'] = state['seed'] 155 | 156 | else: 157 | raise Exception("Cannot resume, cannot find files!") 158 | 159 | 160 | 161 | logger.debug("State:\n{}".format(pprint.pformat(state))) 162 | logger.debug("Timings:\n{}".format(pprint.pformat(timings))) 163 | 164 | if args.force_train_all_wordemb == True: 165 | state['fix_pretrained_word_embeddings'] = False 166 | 167 | model = DialogEncoderDecoder(state) 168 | rng = model.rng 169 | 170 | valid_rounds = 0 171 | save_model_on_first_valid = False 172 | 173 | if args.resume != "": 174 | filename = args.resume + '_model.npz' 175 | if os.path.isfile(filename): 176 | logger.debug("Loading previous model") 177 | 178 | parameter_strings_to_ignore = [] 179 | if args.reinitialize_decoder_parameters: 180 | parameter_strings_to_ignore += ['Wd_'] 181 | parameter_strings_to_ignore += ['bd_'] 182 | 183 | save_model_on_first_valid = True 184 | if args.reinitialize_latent_variable_parameters: 185 | parameter_strings_to_ignore += ['latent_utterance_prior'] 186 | parameter_strings_to_ignore += ['latent_utterance_approx_posterior'] 187 | parameter_strings_to_ignore += ['kl_divergence_cost_weight'] 188 | parameter_strings_to_ignore += ['latent_dcgm_encoder'] 189 | 190 | save_model_on_first_valid = True 191 | 192 | load(model, filename, parameter_strings_to_ignore) 193 | else: 194 | raise Exception("Cannot resume, cannot find model file!") 195 | 196 | if 'run_id' not in model.state: 197 | raise Exception('Backward compatibility not ensured! (need run_id in state)') 198 | 199 | else: 200 | # assign new run_id key 201 | model.state['run_id'] = RUN_ID 202 | 203 | logger.debug("Compile trainer") 204 | if not state["use_nce"]: 205 | if ('add_latent_gaussian_per_utterance' in state) and (state["add_latent_gaussian_per_utterance"]): 206 | logger.debug("Training using variational lower bound on log-likelihood") 207 | else: 208 | logger.debug("Training using exact log-likelihood") 209 | 210 | train_batch = model.build_train_function() 211 | else: 212 | logger.debug("Training with noise contrastive estimation") 213 | train_batch = model.build_nce_function() 214 | 215 | eval_batch = model.build_eval_function() 216 | 217 | gamma_bounding = model.build_gamma_bounding_function() 218 | 219 | random_sampler = search.RandomSampler(model) 220 | beam_sampler = search.BeamSampler(model) 221 | 222 | logger.debug("Load data") 223 | train_data, \ 224 | valid_data, = get_train_iterator(state) 225 | train_data.start() 226 | 227 | # Start looping through the dataset 228 | step = 0 229 | patience = state['patience'] 230 | start_time = time.time() 231 | 232 | train_cost = 0 233 | train_kl_divergence_cost = 0 234 | train_posterior_gaussian_mean_variance = 0 235 | train_misclass = 0 236 | train_done = 0 237 | train_dialogues_done = 0.0 238 | 239 | prev_train_cost = 0 240 | prev_train_done = 0 241 | 242 | ex_done = 0 243 | is_end_of_batch = True 244 | start_validation = False 245 | 246 | batch = None 247 | 248 | while (step < state['loop_iters'] and 249 | (time.time() - start_time)/60. < state['time_stop'] and 250 | patience >= 0): 251 | 252 | # Flush to log files 253 | sys.stderr.flush() 254 | sys.stdout.flush() 255 | 256 | ### Sampling phase 257 | if step % 200 == 0: 258 | # First generate stochastic samples 259 | for param in model.params: 260 | print "%s = %.4f" % (param.name, numpy.sum(param.get_value() ** 2) ** 0.5) 261 | 262 | samples, costs = random_sampler.sample([[]], n_samples=1, n_turns=3) 263 | print "Sampled : {}".format(samples[0]) 264 | 265 | 266 | ### Training phase 267 | batch = train_data.next() 268 | 269 | # Train finished 270 | if not batch: 271 | # Restart training 272 | logger.debug("Got None...") 273 | break 274 | 275 | logger.debug("[TRAIN] - Got batch %d,%d" % (batch['x'].shape[1], batch['max_length'])) 276 | 277 | x_data = batch['x'] 278 | x_data_reversed = batch['x_reversed'] 279 | max_length = batch['max_length'] 280 | x_cost_mask = batch['x_mask'] 281 | x_reset = batch['x_reset'] 282 | ran_gaussian_const_utterance = batch['ran_var_gaussian_constutterance'] 283 | ran_uniform_const_utterance = batch['ran_var_uniform_constutterance'] 284 | 285 | ran_decoder_drop_mask = batch['ran_decoder_drop_mask'] 286 | 287 | is_end_of_batch = False 288 | if numpy.sum(numpy.abs(x_reset)) < 1: 289 | # Print when we reach the end of an example (e.g. the end of a dialogue or a document) 290 | # Knowing when the training procedure reaches the end is useful for diagnosing training problems 291 | #print 'END-OF-BATCH EXAMPLE!' 292 | is_end_of_batch = True 293 | 294 | if state['use_nce']: 295 | y_neg = rng.choice(size=(10, max_length, x_data.shape[1]), a=model.idim, p=model.noise_probs).astype('int32') 296 | c, kl_divergence_cost, posterior_gaussian_mean_variance = train_batch(x_data, x_data_reversed, y_neg, max_length, x_cost_mask, x_reset, ran_gaussian_const_utterance, ran_uniform_const_utterance, ran_decoder_drop_mask) 297 | else: 298 | 299 | latent_piecewise_utterance_variable_approx_posterior_alpha = 0.0 300 | latent_piecewise_utterance_variable_prior_alpha = 0.0 301 | kl_divergences_between_piecewise_prior_and_posterior = 0.0 302 | kl_divergences_between_gaussian_prior_and_posterior = 0.0 303 | latent_piecewise_posterior_sample = 0.0 304 | posterior_gaussian_mean_variance = 0.0 305 | 306 | if model.add_latent_piecewise_per_utterance and model.add_latent_gaussian_per_utterance: 307 | c, kl_divergence_cost, posterior_gaussian_mean_variance, latent_piecewise_utterance_variable_approx_posterior_alpha, latent_piecewise_utterance_variable_prior_alpha, kl_divergences_between_piecewise_prior_and_posterior, kl_divergences_between_gaussian_prior_and_posterior, latent_piecewise_posterior_sample = train_batch(x_data, x_data_reversed, max_length, x_cost_mask, x_reset, ran_gaussian_const_utterance, ran_uniform_const_utterance, ran_decoder_drop_mask) 308 | elif model.add_latent_gaussian_per_utterance: 309 | c, kl_divergence_cost, posterior_gaussian_mean_variance, kl_divergences_between_gaussian_prior_and_posterior = train_batch(x_data, x_data_reversed, max_length, x_cost_mask, x_reset, ran_gaussian_const_utterance, ran_uniform_const_utterance, ran_decoder_drop_mask) 310 | elif model.add_latent_piecewise_per_utterance: 311 | c, kl_divergence_cost, kl_divergences_between_piecewise_prior_and_posterior = train_batch(x_data, x_data_reversed, max_length, x_cost_mask, x_reset, ran_gaussian_const_utterance, ran_uniform_const_utterance, ran_decoder_drop_mask) 312 | else: 313 | c = train_batch(x_data, x_data_reversed, max_length, x_cost_mask, x_reset, ran_gaussian_const_utterance, ran_uniform_const_utterance, ran_decoder_drop_mask) 314 | kl_divergence_cost = 0.0 315 | 316 | 317 | 318 | 319 | 320 | gamma_bounding() 321 | 322 | # Print batch statistics 323 | print 'cost_sum', c 324 | print 'cost_mean', c / float(numpy.sum(x_cost_mask)) 325 | 326 | if model.add_latent_piecewise_per_utterance or model.add_latent_gaussian_per_utterance: 327 | print 'kl_divergence_cost_sum', kl_divergence_cost 328 | print 'kl_divergence_cost_mean', kl_divergence_cost / float(len(numpy.where(x_data == model.eos_sym)[0])) 329 | 330 | if model.add_latent_gaussian_per_utterance: 331 | print 'posterior_gaussian_mean_variance', posterior_gaussian_mean_variance 332 | print 'kl_divergences_between_gaussian_prior_and_posterior', numpy.sum(kl_divergences_between_gaussian_prior_and_posterior), numpy.min(kl_divergences_between_gaussian_prior_and_posterior), numpy.max(kl_divergences_between_gaussian_prior_and_posterior) 333 | 334 | if model.add_latent_piecewise_per_utterance: 335 | print 'kl_divergences_between_piecewise_prior_and_posterior', numpy.sum(kl_divergences_between_piecewise_prior_and_posterior), numpy.min(kl_divergences_between_piecewise_prior_and_posterior), numpy.max(kl_divergences_between_piecewise_prior_and_posterior) 336 | 337 | 338 | if numpy.isinf(c) or numpy.isnan(c): 339 | logger.warn("Got NaN cost .. skipping") 340 | gc.collect() 341 | continue 342 | 343 | train_cost += c 344 | train_kl_divergence_cost += kl_divergence_cost 345 | train_posterior_gaussian_mean_variance += posterior_gaussian_mean_variance 346 | 347 | train_done += batch['num_preds'] 348 | train_dialogues_done += batch['num_dialogues'] 349 | 350 | this_time = time.time() 351 | if step % state['train_freq'] == 0: 352 | elapsed = this_time - start_time 353 | 354 | # Keep track of training cost for the last 'train_freq' batches. 355 | current_train_cost = train_cost/train_done 356 | if prev_train_done >= 1 and abs(train_done - prev_train_done) > 0: 357 | current_train_cost = float(train_cost - prev_train_cost)/float(train_done - prev_train_done) 358 | 359 | if numpy.isinf(c) or numpy.isnan(c): 360 | current_train_cost = 0 361 | 362 | prev_train_cost = train_cost 363 | prev_train_done = train_done 364 | 365 | h, m, s = ConvertTimedelta(this_time - start_time) 366 | 367 | # We need to catch exceptions due to high numbers in exp 368 | try: 369 | print ".. %.2d:%.2d:%.2d %4d mb # %d bs %d maxl %d acc_cost = %.4f acc_word_perplexity = %.4f cur_cost = %.4f cur_word_perplexity = %.4f acc_mean_word_error = %.4f acc_mean_kl_divergence_cost = %.8f acc_mean_posterior_variance = %.8f" % (h, m, s,\ 370 | state['time_stop'] - (time.time() - start_time)/60.,\ 371 | step, \ 372 | batch['x'].shape[1], \ 373 | batch['max_length'], \ 374 | float(train_cost/train_done), \ 375 | math.exp(float(train_cost/train_done)), \ 376 | current_train_cost, \ 377 | math.exp(current_train_cost), \ 378 | float(train_misclass)/float(train_done), \ 379 | float(train_kl_divergence_cost/train_done), \ 380 | float(train_posterior_gaussian_mean_variance/train_dialogues_done)) 381 | except: 382 | pass 383 | 384 | 385 | ### Inspection phase 386 | if (step % 20 == 0): 387 | if model.add_latent_gaussian_per_utterance and model.add_latent_piecewise_per_utterance: 388 | try: 389 | print 'posterior_gaussian_mean_combination', model.posterior_mean_combination.W.get_value() 390 | 391 | except: 392 | pass 393 | 394 | print 'latent_piecewise_utterance_variable_approx_posterior_alpha', numpy.mean(latent_piecewise_utterance_variable_approx_posterior_alpha), latent_piecewise_utterance_variable_approx_posterior_alpha 395 | 396 | print 'latent_piecewise_utterance_variable_prior_alpha', numpy.mean(latent_piecewise_utterance_variable_prior_alpha), latent_piecewise_utterance_variable_prior_alpha 397 | 398 | print 'latent_piecewise_utterance_variable_alpha_diff', (latent_piecewise_utterance_variable_approx_posterior_alpha-latent_piecewise_utterance_variable_prior_alpha) 399 | 400 | 401 | print 'latent_piecewise_posterior_sample', numpy.min(latent_piecewise_posterior_sample), numpy.max(latent_piecewise_posterior_sample), latent_piecewise_posterior_sample[0, 0, :] 402 | print 'ran_uniform_const_utterance', numpy.min(ran_uniform_const_utterance), numpy.max(ran_uniform_const_utterance), ran_uniform_const_utterance[0, 0, :] 403 | 404 | if model.utterance_decoder_gating.upper() == 'GRU' and model.decoder_bias_type.upper() == 'ALL': 405 | Wd_s_q = model.utterance_decoder.Wd_s_q.get_value() 406 | Wd_s_q_len = Wd_s_q.shape[0] 407 | print 'model.utterance_decoder Wd_s_q full', numpy.mean(numpy.abs(Wd_s_q)), numpy.mean(Wd_s_q**2) 408 | 409 | if model.add_latent_gaussian_per_utterance and model.add_latent_piecewise_per_utterance: 410 | Wd_s_q_gaussian = Wd_s_q[Wd_s_q_len-2*model.latent_piecewise_per_utterance_dim:Wd_s_q_len-model.latent_piecewise_per_utterance_dim, :] 411 | Wd_s_q_piecewise = Wd_s_q[Wd_s_q_len-model.latent_piecewise_per_utterance_dim:Wd_s_q_len, :] 412 | 413 | print 'model.utterance_decoder Wd_s_q gaussian', numpy.mean(numpy.abs(Wd_s_q_gaussian)), numpy.mean(Wd_s_q_gaussian**2) 414 | print 'model.utterance_decoder Wd_s_q piecewise', numpy.mean(numpy.abs(Wd_s_q_piecewise)), numpy.mean(Wd_s_q_piecewise**2) 415 | 416 | print 'model.utterance_decoder Wd_s_q piecewise/gaussian', numpy.mean(numpy.abs(Wd_s_q_piecewise))/numpy.mean(numpy.abs(Wd_s_q_gaussian)), numpy.mean(Wd_s_q_piecewise**2)/numpy.mean(Wd_s_q_gaussian**2) 417 | 418 | elif model.add_latent_gaussian_per_utterance: 419 | Wd_s_q_piecewise = Wd_s_q[Wd_s_q_len-model.latent_piecewise_per_utterance_dim:Wd_s_q_len, :] 420 | 421 | print 'model.utterance_decoder Wd_s_q piecewise', numpy.mean(numpy.abs(Wd_s_q_piecewise)), numpy.mean(Wd_s_q_piecewise**2) 422 | 423 | 424 | elif model.add_latent_piecewise_per_utterance: 425 | Wd_s_q_gaussian = Wd_s_q[Wd_s_q_len-model.latent_piecewise_per_utterance_dim:Wd_s_q_len, :] 426 | 427 | print 'model.utterance_decoder Wd_s_q gaussian', numpy.mean(numpy.abs(Wd_s_q_gaussian)), numpy.mean(Wd_s_q_gaussian**2) 428 | 429 | 430 | 431 | if model.utterance_decoder_gating.upper() == 'BOW' and model.decoder_bias_type.upper() == 'ALL': 432 | Wd_bow_W_in = model.utterance_decoder.Wd_bow_W_in.get_value() 433 | Wd_bow_W_in_len = Wd_bow_W_in.shape[0] 434 | print 'model.utterance_decoder Wd_bow_W_in full', numpy.mean(numpy.abs(Wd_bow_W_in)), numpy.mean(Wd_bow_W_in**2) 435 | 436 | if model.add_latent_gaussian_per_utterance and model.add_latent_piecewise_per_utterance: 437 | Wd_bow_W_in_gaussian = Wd_bow_W_in[Wd_bow_W_in_len-2*model.latent_piecewise_per_utterance_dim:Wd_bow_W_in_len-model.latent_piecewise_per_utterance_dim, :] 438 | Wd_bow_W_in_piecewise = Wd_bow_W_in[Wd_bow_W_in_len-model.latent_piecewise_per_utterance_dim:Wd_bow_W_in_len, :] 439 | 440 | print 'model.utterance_decoder Wd_bow_W_in gaussian', numpy.mean(numpy.abs(Wd_bow_W_in_gaussian)), numpy.mean(Wd_bow_W_in_gaussian**2) 441 | print 'model.utterance_decoder Wd_bow_W_in piecewise', numpy.mean(numpy.abs(Wd_bow_W_in_piecewise)), numpy.mean(Wd_bow_W_in_piecewise**2) 442 | 443 | print 'model.utterance_decoder Wd_bow_W_in piecewise/gaussian', numpy.mean(numpy.abs(Wd_bow_W_in_piecewise))/numpy.mean(numpy.abs(Wd_bow_W_in_gaussian)), numpy.mean(Wd_bow_W_in_piecewise**2)/numpy.mean(Wd_bow_W_in_gaussian**2) 444 | 445 | elif model.add_latent_gaussian_per_utterance: 446 | Wd_bow_W_in_piecewise = Wd_bow_W_in[Wd_bow_W_in_len-model.latent_piecewise_per_utterance_dim:Wd_bow_W_in_len, :] 447 | 448 | print 'model.utterance_decoder Wd_bow_W_in piecewise', numpy.mean(numpy.abs(Wd_bow_W_in_piecewise)), numpy.mean(Wd_bow_W_in_piecewise**2) 449 | 450 | 451 | elif model.add_latent_piecewise_per_utterance: 452 | Wd_bow_W_in_gaussian = Wd_bow_W_in[Wd_bow_W_in_len-model.latent_piecewise_per_utterance_dim:Wd_bow_W_in_len, :] 453 | 454 | print 'model.utterance_decoder Wd_bow_W_in gaussian', numpy.mean(numpy.abs(Wd_bow_W_in_gaussian)), numpy.mean(Wd_bow_W_in_gaussian**2) 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | ### Evaluation phase 465 | if valid_data is not None and\ 466 | step % state['valid_freq'] == 0 and step > 1: 467 | start_validation = True 468 | 469 | # Only start validation loop once it's time to validate and once all previous batches have been reset 470 | if start_validation and is_end_of_batch: 471 | start_validation = False 472 | valid_data.start() 473 | valid_cost = 0 474 | valid_kl_divergence_cost = 0 475 | valid_posterior_gaussian_mean_variance = 0 476 | 477 | valid_wordpreds_done = 0 478 | valid_dialogues_done = 0 479 | 480 | 481 | logger.debug("[VALIDATION START]") 482 | 483 | while True: 484 | batch = valid_data.next() 485 | 486 | # Validation finished 487 | if not batch: 488 | break 489 | 490 | 491 | logger.debug("[VALID] - Got batch %d,%d" % (batch['x'].shape[1], batch['max_length'])) 492 | 493 | x_data = batch['x'] 494 | x_data_reversed = batch['x_reversed'] 495 | max_length = batch['max_length'] 496 | x_cost_mask = batch['x_mask'] 497 | 498 | x_reset = batch['x_reset'] 499 | ran_gaussian_const_utterance = batch['ran_var_gaussian_constutterance'] 500 | ran_uniform_const_utterance = batch['ran_var_uniform_constutterance'] 501 | 502 | ran_decoder_drop_mask = batch['ran_decoder_drop_mask'] 503 | 504 | posterior_gaussian_mean_variance = 0.0 505 | 506 | c, c_list, kl_divergence_cost = eval_batch(x_data, x_data_reversed, max_length, x_cost_mask, x_reset, ran_gaussian_const_utterance, ran_uniform_const_utterance, ran_decoder_drop_mask) 507 | 508 | 509 | # Rehape into matrix, where rows are validation samples and columns are tokens 510 | # Note that we use max_length-1 because we don't get a cost for the first token 511 | # (the first token is always assumed to be eos) 512 | c_list = c_list.reshape((batch['x'].shape[1],max_length-1), order=(1,0)) 513 | c_list = numpy.sum(c_list, axis=1) 514 | 515 | words_in_dialogues = numpy.sum(x_cost_mask, axis=0) 516 | c_list = c_list / words_in_dialogues 517 | 518 | 519 | if numpy.isinf(c) or numpy.isnan(c): 520 | continue 521 | 522 | valid_cost += c 523 | valid_kl_divergence_cost += kl_divergence_cost 524 | valid_posterior_gaussian_mean_variance += posterior_gaussian_mean_variance 525 | 526 | # Print batch statistics 527 | print 'valid_cost', valid_cost 528 | print 'valid_kl_divergence_cost sample', kl_divergence_cost 529 | print 'posterior_gaussian_mean_variance', posterior_gaussian_mean_variance 530 | 531 | 532 | valid_wordpreds_done += batch['num_preds'] 533 | valid_dialogues_done += batch['num_dialogues'] 534 | 535 | logger.debug("[VALIDATION END]") 536 | 537 | valid_cost /= max(1.0, valid_wordpreds_done) 538 | valid_kl_divergence_cost /= max(1.0, valid_wordpreds_done) 539 | valid_posterior_gaussian_mean_variance /= max(1.0, valid_dialogues_done) 540 | 541 | if (len(timings["valid_cost"]) == 0) \ 542 | or (valid_cost < numpy.min(timings["valid_cost"])) \ 543 | or (save_model_on_first_valid and valid_rounds == 0): 544 | patience = state['patience'] 545 | 546 | # Save model if there is decrease in validation cost 547 | save(model, timings, train_data) 548 | print 'best valid_cost', valid_cost 549 | elif valid_cost >= timings["valid_cost"][-1] * state['cost_threshold']: 550 | patience -= 1 551 | 552 | if args.save_every_valid_iteration: 553 | save(model, timings, train_data, '_' + str(step) + '_') 554 | if args.auto_restart: 555 | save(model, timings, train_data, '_auto_') 556 | 557 | 558 | # We need to catch exceptions due to high numbers in exp 559 | try: 560 | print "** valid cost (NLL) = %.4f, valid word-perplexity = %.4f, valid kldiv cost (per word) = %.8f, valid mean posterior variance (per word) = %.8f, patience = %d" % (float(valid_cost), float(math.exp(valid_cost)), float(valid_kl_divergence_cost), float(valid_posterior_gaussian_mean_variance), patience) 561 | except: 562 | try: 563 | print "** valid cost (NLL) = %.4f, patience = %d" % (float(valid_cost), patience) 564 | except: 565 | pass 566 | 567 | 568 | timings["train_cost"].append(train_cost/train_done) 569 | timings["train_kl_divergence_cost"].append(train_kl_divergence_cost/train_done) 570 | timings["train_posterior_gaussian_mean_variance"].append(train_posterior_gaussian_mean_variance/train_dialogues_done) 571 | timings["valid_cost"].append(valid_cost) 572 | timings["valid_kl_divergence_cost"].append(valid_kl_divergence_cost) 573 | timings["valid_posterior_gaussian_mean_variance"].append(valid_posterior_gaussian_mean_variance) 574 | 575 | # Reset train cost, train misclass and train done metrics 576 | train_cost = 0 577 | train_done = 0 578 | prev_train_cost = 0 579 | prev_train_done = 0 580 | 581 | # Count number of validation rounds done so far 582 | valid_rounds += 1 583 | 584 | step += 1 585 | 586 | logger.debug("All done, exiting...") 587 | 588 | def parse_args(): 589 | parser = argparse.ArgumentParser() 590 | parser.add_argument("--resume", type=str, default="", help="Resume training from that state") 591 | 592 | parser.add_argument("--force_train_all_wordemb", action='store_true', help="If true, will force the model to train all word embeddings in the encoder. This switch can be used to fine-tune a model which was trained with fixed (pretrained) encoder word embeddings.") 593 | 594 | parser.add_argument("--save_every_valid_iteration", action='store_true', help="If true, will save a unique copy of the model at every validation round.") 595 | 596 | parser.add_argument("--auto_restart", action='store_true', help="If true, will maintain a copy of the current model parameters updated at every validation round. Upon initialization, the script will automatically scan the output directory and and resume training of a previous model (if such exists). This option is meant to be used for training models on clusters with hard wall-times. This option is incompatible with the \"resume\" and \"save_every_valid_iteration\" options.") 597 | 598 | parser.add_argument("--prototype", type=str, help="Prototype to use (must be specified)", default='prototype_state') 599 | 600 | parser.add_argument("--reinitialize-latent-variable-parameters", action='store_true', help="Can be used when resuming a model. If true, will initialize all latent variable parameters randomly instead of loading them from previous model.") 601 | 602 | parser.add_argument("--reinitialize-decoder-parameters", action='store_true', help="Can be used when resuming a model. If true, will initialize all parameters of the utterance decoder randomly instead of loading them from previous model.") 603 | 604 | args = parser.parse_args() 605 | return args 606 | 607 | if __name__ == "__main__": 608 | # Models only run with float32 609 | assert(theano.config.floatX == 'float32') 610 | 611 | args = parse_args() 612 | main(args) 613 | 614 | # grep 'valid cost' LSTM_Baseline_exp1/LOGS/python_train.py_prototype_twitter_LSTM_NormOp_ClusterExp1_2016-09-23_22-48-31.523628/dbi_146c0c3c23d.out-* | grep -o -P '(?<=word-perplexity = ).*(?=, valid kldiv)' 615 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | import adam 3 | import theano 4 | import theano.tensor as T 5 | from collections import OrderedDict 6 | 7 | PRINT_VARS = True 8 | 9 | def DPrint(name, var): 10 | if PRINT_VARS is False: 11 | return var 12 | 13 | return theano.printing.Print(name)(var) 14 | 15 | def sharedX(value, name=None, borrow=False, dtype=None): 16 | if dtype is None: 17 | dtype = theano.config.floatX 18 | return theano.shared(theano._asarray(value, dtype=dtype), 19 | name=name, 20 | borrow=borrow) 21 | 22 | def Adam(grads, lr=0.0002, b1=0.1, b2=0.001, e=1e-8): 23 | return adam.Adam(grads, lr, b1, b2, e) 24 | 25 | def Adagrad(grads, lr): 26 | updates = OrderedDict() 27 | for param in grads.keys(): 28 | # sum_square_grad := \sum g^2 29 | sum_square_grad = sharedX(param.get_value() * 0.) 30 | if param.name is not None: 31 | sum_square_grad.name = 'sum_square_grad_' + param.name 32 | 33 | # Accumulate gradient 34 | new_sum_squared_grad = sum_square_grad + T.sqr(grads[param]) 35 | 36 | # Compute update 37 | delta_x_t = (- lr / T.sqrt(numpy.float32(1e-5) + new_sum_squared_grad)) * grads[param] 38 | 39 | # Apply update 40 | updates[sum_square_grad] = new_sum_squared_grad 41 | updates[param] = param + delta_x_t 42 | return updates 43 | 44 | def Adadelta(grads, decay=0.95, epsilon=1e-6): 45 | updates = OrderedDict() 46 | for param in grads.keys(): 47 | # mean_squared_grad := E[g^2]_{t-1} 48 | mean_square_grad = sharedX(param.get_value() * 0.) 49 | # mean_square_dx := E[(\Delta x)^2]_{t-1} 50 | mean_square_dx = sharedX(param.get_value() * 0.) 51 | 52 | if param.name is not None: 53 | mean_square_grad.name = 'mean_square_grad_' + param.name 54 | mean_square_dx.name = 'mean_square_dx_' + param.name 55 | 56 | # Accumulate gradient 57 | new_mean_squared_grad = ( 58 | decay * mean_square_grad + 59 | (1 - decay) * T.sqr(grads[param]) 60 | ) 61 | 62 | # Compute update 63 | rms_dx_tm1 = T.sqrt(mean_square_dx + epsilon) 64 | rms_grad_t = T.sqrt(new_mean_squared_grad + epsilon) 65 | delta_x_t = - rms_dx_tm1 / rms_grad_t * grads[param] 66 | 67 | # Accumulate updates 68 | new_mean_square_dx = ( 69 | decay * mean_square_dx + 70 | (1 - decay) * T.sqr(delta_x_t) 71 | ) 72 | 73 | # Apply update 74 | updates[mean_square_grad] = new_mean_squared_grad 75 | updates[mean_square_dx] = new_mean_square_dx 76 | updates[param] = param + delta_x_t 77 | 78 | return updates 79 | 80 | def RMSProp(grads, lr, decay=0.95, eta=0.9, epsilon=1e-6): 81 | """ 82 | RMSProp gradient method 83 | """ 84 | updates = OrderedDict() 85 | for param in grads.keys(): 86 | # mean_squared_grad := E[g^2]_{t-1} 87 | mean_square_grad = sharedX(param.get_value() * 0.) 88 | mean_grad = sharedX(param.get_value() * 0.) 89 | delta_grad = sharedX(param.get_value() * 0.) 90 | 91 | if param.name is None: 92 | raise ValueError("Model parameters must be named.") 93 | 94 | mean_square_grad.name = 'mean_square_grad_' + param.name 95 | 96 | # Accumulate gradient 97 | 98 | new_mean_grad = (decay * mean_grad + (1 - decay) * grads[param]) 99 | new_mean_squared_grad = (decay * mean_square_grad + (1 - decay) * T.sqr(grads[param])) 100 | 101 | # Compute update 102 | scaled_grad = grads[param] / T.sqrt(new_mean_squared_grad - new_mean_grad ** 2 + epsilon) 103 | new_delta_grad = eta * delta_grad - lr * scaled_grad 104 | 105 | # Apply update 106 | updates[delta_grad] = new_delta_grad 107 | updates[mean_grad] = new_mean_grad 108 | updates[mean_square_grad] = new_mean_squared_grad 109 | updates[param] = param + new_delta_grad 110 | 111 | return updates 112 | 113 | class Maxout(object): 114 | def __init__(self, maxout_part): 115 | self.maxout_part = maxout_part 116 | 117 | def __call__(self, x): 118 | shape = x.shape 119 | if x.ndim == 2: 120 | shape1 = T.cast(shape[1] / self.maxout_part, 'int64') 121 | shape2 = T.cast(self.maxout_part, 'int64') 122 | x = x.reshape([shape[0], shape1, shape2]) 123 | x = x.max(2) 124 | else: 125 | shape1 = T.cast(shape[2] / self.maxout_part, 'int64') 126 | shape2 = T.cast(self.maxout_part, 'int64') 127 | x = x.reshape([shape[0], shape[1], shape1, shape2]) 128 | x = x.max(3) 129 | return x 130 | 131 | def UniformInit(rng, sizeX, sizeY, lb=-0.01, ub=0.01): 132 | """ Uniform Init """ 133 | return rng.uniform(size=(sizeX, sizeY), low=lb, high=ub).astype(theano.config.floatX) 134 | 135 | def OrthogonalInit(rng, sizeX, sizeY, sparsity=-1, scale=1): 136 | """ 137 | Orthogonal Initialization 138 | """ 139 | 140 | sizeX = int(sizeX) 141 | sizeY = int(sizeY) 142 | 143 | assert sizeX == sizeY, 'for orthogonal init, sizeX == sizeY' 144 | 145 | if sparsity < 0: 146 | sparsity = sizeY 147 | else: 148 | sparsity = numpy.minimum(sizeY, sparsity) 149 | 150 | values = numpy.zeros((sizeX, sizeY), dtype=theano.config.floatX) 151 | for dx in xrange(sizeX): 152 | perm = rng.permutation(sizeY) 153 | new_vals = rng.normal(loc=0, scale=scale, size=(sparsity,)) 154 | values[dx, perm[:sparsity]] = new_vals 155 | 156 | # Use SciPy: 157 | if sizeX*sizeY > 5000000: 158 | import scipy 159 | u,s,v = scipy.linalg.svd(values) 160 | else: 161 | u,s,v = numpy.linalg.svd(values) 162 | values = u * scale 163 | return values.astype(theano.config.floatX) 164 | 165 | def GrabProbs(classProbs, target, gRange=None): 166 | if classProbs.ndim > 2: 167 | classProbs = classProbs.reshape((classProbs.shape[0] * classProbs.shape[1], classProbs.shape[2])) 168 | else: 169 | classProbs = classProbs 170 | 171 | if target.ndim > 1: 172 | tflat = target.flatten() 173 | else: 174 | tflat = target 175 | return T.diag(classProbs.T[tflat]) 176 | 177 | def NormalInit(rng, sizeX, sizeY, scale=0.01, sparsity=-1): 178 | """ 179 | Normal Initialization 180 | """ 181 | 182 | sizeX = int(sizeX) 183 | sizeY = int(sizeY) 184 | 185 | if sparsity < 0: 186 | sparsity = sizeY 187 | 188 | sparsity = numpy.minimum(sizeY, sparsity) 189 | values = numpy.zeros((sizeX, sizeY), dtype=theano.config.floatX) 190 | for dx in xrange(sizeX): 191 | perm = rng.permutation(sizeY) 192 | new_vals = rng.normal(loc=0, scale=scale, size=(sparsity,)) 193 | values[dx, perm[:sparsity]] = new_vals 194 | 195 | return values.astype(theano.config.floatX) 196 | 197 | def NormalInit3D(rng, sizeX, sizeY, sizeZ, scale=0.01, sparsity=-1): 198 | """ 199 | Normal Initialization for 3D tensor 200 | """ 201 | 202 | sizeX = int(sizeX) 203 | sizeY = int(sizeY) 204 | sizeZ = int(sizeZ) 205 | values = numpy.zeros((sizeX, sizeY, sizeZ), dtype=theano.config.floatX) 206 | for i in range(sizeZ): 207 | values[:,:,i] = NormalInit(rng, sizeX, sizeY, scale, sparsity) 208 | 209 | return values.astype(theano.config.floatX) 210 | 211 | def ConvertTimedelta(seconds_diff): 212 | hours = seconds_diff // 3600 213 | minutes = (seconds_diff % 3600) // 60 214 | seconds = (seconds_diff % 60) 215 | return hours, minutes, seconds 216 | 217 | def SoftMax(x): 218 | x = T.exp(x - T.max(x, axis=x.ndim-1, keepdims=True)) 219 | return x / T.sum(x, axis=x.ndim-1, keepdims=True) 220 | 221 | def stable_log(x): 222 | return T.log(T.maximum(x, 0.0000000001)) 223 | 224 | 225 | 226 | # Performs either batch normalization or layer normalization 227 | def NormalizationOperator(normop_type, x, gamma, mask, estimated_mean=0.0, estimated_var=1.0): 228 | if normop_type.upper() == 'BN': 229 | if x.ndim == 3: 230 | return FeedforwardBatchNormalization(x, gamma, mask, estimated_mean=0.0, estimated_var=1.0) 231 | elif x.ndim == 2: 232 | return RecurrentBatchNormalization(x, gamma, mask, estimated_mean=0.0, estimated_var=1.0) 233 | elif normop_type.upper() == 'LN': 234 | return LayerNormalization(x, gamma, mask, estimated_mean=0.0, estimated_var=1.0) 235 | elif normop_type.upper() == 'NONE' or normop_type.upper() == '': 236 | assert x.ndim == 3 or x.ndim == 2 237 | 238 | output = x + 0.0*gamma 239 | if x.ndim == 3: 240 | x_mean = T.mean(x, axis=1).dimshuffle(0, 1, 'x') 241 | x_var = T.var(x, axis=1).dimshuffle(0, 1, 'x') 242 | else: 243 | x_mean = T.mean(x, axis=1).dimshuffle(0, 'x') 244 | x_var = T.var(x, axis=1).dimshuffle(0, 'x') 245 | 246 | return output, x_mean[0], x_var[0] 247 | else: 248 | raise ValueError("Error! normop_type must take a value in set {\'BN\', \'LN\', \'NONE\'}!") 249 | 250 | 251 | # Batch normalization of input variable on first and second tensor indices (time x batch example x hidden units) 252 | # Elements where mask is zero, will not be used to compute the mean and variance estimates, 253 | # however these elements will still be batch normalized. 254 | def FeedforwardBatchNormalization(x, gamma, mask, estimated_mean=0.0, estimated_var=1.0): 255 | assert x.ndim == 3 256 | if mask: 257 | assert mask.ndim == 2 258 | mask = mask.dimshuffle(0, 1, 'x') 259 | 260 | mask_nonzeros = T.sum(T.sum(mask, axis=0), axis=0) 261 | mask_nonzeros_weight = T.cast(T.minimum(1.0, T.sum(mask, axis=0)) / mask.shape[1], 'float32') 262 | 263 | x_masked = x*mask 264 | 265 | x_mean = (T.sum(T.sum(x_masked, axis=0), axis=0)/mask_nonzeros).dimshuffle('x', 'x', 0) 266 | x_mean_adjusted = mask_nonzeros_weight*x_mean + (1.0 - mask_nonzeros_weight)*estimated_mean 267 | x_zero_mean = x - x_mean_adjusted 268 | 269 | x_var = (T.sum(T.sum(x_zero_mean**2, axis=0), axis=0)/mask_nonzeros).dimshuffle('x', 'x', 0) 270 | x_var_adjusted = mask_nonzeros_weight*x_var + (1.0 - mask_nonzeros_weight)*estimated_var 271 | 272 | else: 273 | x_mean = estimated_mean.dimshuffle('x', 'x', 0) 274 | x_mean_adjusted = x_mean 275 | 276 | x_zero_mean = x - x_mean 277 | 278 | x_var = estimated_var.dimshuffle('x', 'x', 0) 279 | x_var_adjusted = x_var 280 | 281 | 282 | return gamma*(x_zero_mean / T.sqrt(x_var_adjusted+1e-7)), x_mean_adjusted[0, 0], x_var_adjusted[0, 0] 283 | 284 | # Batch normalization of input variable on first tensor index (time x batch example x hidden units) 285 | # Elements where mask is zero, will not be used to compute the mean and variance estimates, 286 | # however these elements will still be batch normalized. 287 | def RecurrentBatchNormalization(x, gamma, mask, estimated_mean=0.0, estimated_var=1.0): 288 | assert x.ndim == 2 289 | assert mask.ndim == 1 290 | 291 | 292 | mask = mask.dimshuffle(0, 'x') 293 | 294 | mask_nonzeros = T.sum(mask, axis=0) 295 | mask_nonzeros_weight = mask_nonzeros / T.sum(T.ones_like(mask), axis=0) 296 | 297 | x_masked = x*mask 298 | 299 | x_mean = (T.sum(x_masked, axis=0)/mask_nonzeros).dimshuffle('x', 0) 300 | x_mean_adjusted = mask_nonzeros_weight*x_mean + (1.0 - mask_nonzeros_weight)*estimated_mean 301 | 302 | x_zero_mean = x - x_mean_adjusted #x_zero_mean = x_masked - x_mean_adjusted 303 | 304 | x_var = T.sum(x_zero_mean**2, axis=0)/mask_nonzeros.dimshuffle('x', 0) 305 | x_var_adjusted = mask_nonzeros_weight*x_var + (1.0 - mask_nonzeros_weight)*estimated_var 306 | 307 | return gamma*(x_zero_mean / T.sqrt(x_var_adjusted+1e-7)), x_mean_adjusted[0], x_var_adjusted[0] 308 | 309 | # Performs layer normalization of input variable on last tensor index, 310 | # where we assume variable has shape (time x batch example x hidden units) or (batch example x hidden units). 311 | # Similar to batch normalization, the function also returns the mean and variance across hidden units. 312 | def LayerNormalization(x, gamma, mask, estimated_mean=0.0, estimated_var=1.0): 313 | assert x.ndim == 3 or x.ndim == 2 314 | if x.ndim == 3: 315 | x_mean = T.mean(x, axis=2).dimshuffle(0, 1, 'x') 316 | x_var = T.var(x, axis=2).dimshuffle(0, 1, 'x') 317 | return gamma*((x - x_mean) / T.sqrt(x_var+1e-7)), x_mean[0, 0], x_var[0, 0] 318 | 319 | elif x.ndim == 2: 320 | x_mean = T.mean(x, axis=1).dimshuffle(0, 'x') 321 | x_var = T.var(x, axis=1).dimshuffle(0, 'x') 322 | return gamma*((x - x_mean) / T.sqrt(x_var+1e-7)), x_mean[0], x_var[0] 323 | 324 | 325 | 326 | # Does theano.batched_dot. If last_axis is on it will loop over the last axis, otherwise it will loop over the first axis. 327 | def BatchedDot(x, y, last_axis=False): 328 | if last_axis==False: 329 | return T.batched_dot(x, y) 330 | elif last_axis: 331 | if x.ndim == 2: 332 | shuffled_x = x.dimshuffle(1,0) 333 | elif x.ndim == 3: 334 | shuffled_x = x.dimshuffle(2,0,1) 335 | elif x.ndim == 4: 336 | shuffled_x = x.dimshuffle(3,0,1,2) 337 | else: 338 | raise ValueError('BatchedDot inputs must have between 2-4 dimensions, but x has ' + str(x.ndim) + ' dimensions') 339 | 340 | if y.ndim == 2: 341 | shuffled_y = y.dimshuffle(1,0) 342 | elif y.ndim == 3: 343 | shuffled_y = y.dimshuffle(2,0,1) 344 | elif y.ndim == 4: 345 | shuffled_y = y.dimshuffle(3,0,1,2) 346 | else: 347 | raise ValueError('BatchedDot inputs must have between 2-4 dimensions, but y has ' + str(y.ndim) + ' dimensions') 348 | 349 | dot = T.batched_dot(shuffled_x, shuffled_y) 350 | if dot.ndim == 2: 351 | return dot.dimshuffle(1,0) 352 | elif dot.ndim == 3: 353 | return dot.dimshuffle(1,2,0) 354 | elif dot.ndim == 4: 355 | return dot.dimshuffle(1,2,3,0) 356 | 357 | 358 | --------------------------------------------------------------------------------