├── .gitignore
├── LICENSE.txt
├── README.md
├── cupy_utils.py
├── embeddings.py
├── eval_analogy.py
├── eval_similarity.py
├── eval_translation.py
├── get_data.sh
├── lat_var.py
├── map_embeddings.py
├── normalize_embeddings.py
└── reproduce_emnlp2018.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | data/
2 | output/
3 | private/
4 |
5 | *~
6 | .DS_Store
7 | __pycache__/
8 | *.py[cod]
9 | *$py.class
10 | .idea/
11 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
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 | Latent-Variable VecMap (bilingual word embedding mappings)
2 | ==============
3 |
4 | This is an extension of the [vecmap framework](https://github.com/artetxem/vecmap) for learning bilingual word embedding mappings.
5 | The repository contains an implementation of a latent-variable model for learning bilingual word embedding mappings as
6 | described in the following paper:
7 |
8 | Sebastian Ruder*, Ryan Cotterell*, Yova Kementchedjhieva, Anders Søgaard. A Discriminative Latent-Variable Model for Bilingual Lexicon Induction. In _Proceedings of EMNLP 2018_, Brussels, Belgium.
9 |
10 | In addition to the requirements of the original repository, the implementation requires the `lap` [module](https://pypi.org/project/lap/), which
11 | implements the Jonker-Volgenant algorithm for solving dense and sparse matrices. The module can be installed by running:
12 | ```
13 | pip install lap
14 | ```
15 |
16 | If you use this repository for academic research, please cite the following paper:
17 | ```
18 | @inproceedings{ruder2018,
19 | author = {Ruder, Sebastian and Cotterell, Ryan and Kementchedjhieva, Yova and S{\o}gaard, Anders},
20 | title = {A Discriminative Latent-Variable Model for Bilingual Lexicon Induction},
21 | booktitle = {Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing},
22 | year = {2018}
23 | }
24 | ```
25 |
26 | See below for the README of the original [vecmap framework](https://github.com/artetxem/vecmap):
27 |
28 | Reproducing results
29 | --------
30 |
31 | For reproducing the results reported in the paper, simply clone the repository, download the datasets with the provided script, and run the experiment script as follows:
32 | ```
33 | git clone https://github.com/sebastianruder/latent-variable-vecmap.git
34 | cd latent-variable-vecmap
35 | ./get_data.sh
36 | ./reproduce_emnlp2018.sh
37 | ```
38 |
39 | This runs the latent-variable model with the best-performing hyper-parameters on
40 | English-Italian, English-German, and English-Finnish. For each language pair,
41 | it runs the method with the a 5000 word seed dictionary, a 25 word seed dictionary,
42 | using numerals as seed dictionary, and using identically spelled strings as seed dictionary.
43 | You can run the method on a subset of these by simply removing the other options from the script.
44 |
45 | You can also run the method with the following command if you use a dictionary:
46 | ```
47 | python3 map_embeddings.py --ruder_emnlp2018 -d TRAIN.DICT SRC.EMB TRG.EMB SRC_MAPPED.EMB TRG_MAPPED.EMB
48 | ```
49 | Similarly, you can use the following command for numerals as seed dictionary:
50 | ```
51 | python3 map_embeddings.py --ruder_emnlp2018 --init_numerals SRC.EMB TRG.EMB SRC_MAPPED.EMB TRG_MAPPED.EMB
52 | ```
53 | and the following command for identically spelled strings as seed dictionary:
54 | ```
55 | python3 map_embeddings.py --ruder_emnlp2018 --init_identical SRC.EMB TRG.EMB SRC_MAPPED.EMB TRG_MAPPED.EMB
56 | ```
57 |
58 | In practice, if the target language is morphologically rich and has multiple possible translations for each English word,
59 | we have found that we can achieve significantly higher performance if we perform the matching from target to source. You can
60 | run this model by using `--ruder_emnlp2018_backward` instead of `--ruder_emnlp2018`. For example:
61 | ```
62 | python3 map_embeddings.py --ruder_emnlp2018_backward -d TRAIN.DICT SRC.EMB TRG.EMB SRC_MAPPED.EMB TRG_MAPPED.EMB
63 | ```
64 |
65 | You can use `-v` (`--verbose`) to track the progress of the model during training.
66 |
67 | VecMap (cross-lingual word embedding mappings)
68 | ==============
69 |
70 | This is an open source implementation of our framework to learn cross-lingual word embedding mappings, described in the following papers:
71 | - Mikel Artetxe, Gorka Labaka, and Eneko Agirre. 2018. **[A robust self-learning method for fully unsupervised cross-lingual mappings of word embeddings](https://aclweb.org/anthology/P18-1073)**. In *Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)*.
72 | - Mikel Artetxe, Gorka Labaka, and Eneko Agirre. 2018. **[Generalizing and improving bilingual word embedding mappings with a multi-step framework of linear transformations](https://www.aaai.org/ocs/index.php/AAAI/AAAI18/paper/view/16935/16781)**. In *Proceedings of the Thirty-Second AAAI Conference on Artificial Intelligence (AAAI-18)*, pages 5012-5019.
73 | - Mikel Artetxe, Gorka Labaka, and Eneko Agirre. 2017. **[Learning bilingual word embeddings with (almost) no bilingual data](https://aclweb.org/anthology/P17-1042)**. In *Proceedings of the 55th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)*, pages 451-462.
74 | - Mikel Artetxe, Gorka Labaka, and Eneko Agirre. 2016. **[Learning principled bilingual mappings of word embeddings while preserving monolingual invariance](https://aclweb.org/anthology/D16-1250)**. In *Proceedings of the 2016 Conference on Empirical Methods in Natural Language Processing*, pages 2289-2294.
75 |
76 | The package includes a script to build cross-lingual word embeddings with or without parallel data as described in the papers, as well as evaluation tools in word translation induction, word similarity/relatedness and word analogy.
77 |
78 | If you use this software for academic research, [please cite the relevant paper(s)](#publications).
79 |
80 |
81 | Requirements
82 | --------
83 | - Python 3
84 | - NumPy
85 | - SciPy
86 | - CuPy (optional, only required for CUDA support)
87 |
88 |
89 | Usage
90 | --------
91 |
92 | In order to build your own cross-lingual word embeddings, you should first train monolingual word embeddings for each language using your favorite tool (e.g. [word2vec](https://github.com/tmikolov/word2vec) or [fasttext](https://github.com/facebookresearch/fastText)) and then map them to a common space with our software as described below. Having done that, you can evaluate the resulting cross-lingual embeddings using our included tools as discussed next.
93 |
94 | #### Mapping
95 |
96 | The mapping software offers 4 main modes with our recommended settings for different scenarios:
97 |
98 | - **Supervised** (recommended if you have a large training dictionary):
99 | ```
100 | python3 map_embeddings.py --supervised TRAIN.DICT SRC.EMB TRG.EMB SRC_MAPPED.EMB TRG_MAPPED.EMB
101 | ```
102 | - **Semi-supervised** (recommended if you have a small seed dictionary):
103 | ```
104 | python3 map_embeddings.py --semi_supervised TRAIN.DICT SRC.EMB TRG.EMB SRC_MAPPED.EMB TRG_MAPPED.EMB
105 | ```
106 | - **Identical** (recommended if you have no seed dictionary but can rely on identical words):
107 | ```
108 | python3 map_embeddings.py --identical SRC.EMB TRG.EMB SRC_MAPPED.EMB TRG_MAPPED.EMB
109 | ```
110 | - **Unsupervised** (recommended if you have no seed dictionary and do not want to rely on identical words):
111 | ```
112 | python3 map_embeddings.py --unsupervised SRC.EMB TRG.EMB SRC_MAPPED.EMB TRG_MAPPED.EMB
113 | ```
114 |
115 | `SRC.EMB` and `TRG.EMB` refer to the input monolingual embeddings, which should be in the word2vec text format, whereas `SRC_MAPPED.EMB` and `TRG_MAPPED.EMB` refer to the output cross-lingual embeddings. The training dictionary `TRAIN.DICT`, if any, should be given as a text file with one entry per line (source word + whitespace + target word).
116 |
117 | If you have a NVIDIA GPU, append the `--cuda` flag to the above commands to make things faster.
118 |
119 | For most users, the above settings should suffice. Choosing the right mode should be straightforward depending on the resources available: as a general rule, you should prefer the mode with the highest supervision for the resources you have, although it is advised to try different variants in case of doubt.
120 |
121 | In addition to these recommended modes, the software also offers additional options to adjust different aspects of the mapping method as described in the papers. While most users should not need to deal with those, you can learn more about them by running the tool with the `--help` flag. You can either use one of the recommended modes and modify a few options on top of it, or do not use any recommended mode and set all options yourself. In fact, if you dig into the code, you will see that the above modes simply set recommended defaults for all the different options.
122 |
123 | #### Evaluation
124 |
125 | You can evaluate your mapped embeddings in bilingual lexicon extraction (aka dictionary induction or word translation) as follows:
126 | ```
127 | python3 eval_translation.py SRC_MAPPED.EMB TRG_MAPPED.EMB -d TEST.DICT
128 | ```
129 | The above command uses standard nearest neighbor retrieval by default. For best results, it is recommended that you use CSLS retrieval instead:
130 | ```
131 | python3 eval_translation.py SRC_MAPPED.EMB TRG_MAPPED.EMB -d TEST.DICT --retrieval csls
132 | ```
133 | While better, CSLS is also significantly slower than nearest neighbor, so do not forget to append the `--cuda` flag to the above command if you have a NVIDIA GPU.
134 |
135 | In addition to bilingual lexicon extraction, you can also evaluate your mapped embeddings in cross-lingual word similarity as follows:
136 | ```
137 | python3 eval_similarity.py -l --backoff 0 SRC_MAPPED.EMB TRG_MAPPED.EMB -i TEST_SIMILARITY.TXT
138 | ```
139 |
140 | Finally, we also offer an evaluation tool for monolingual word analogies, which mimics the one included with word2vec but should run significantly faster:
141 | ```
142 | python3 eval_analogy.py -l SRC_MAPPED.EMB -i TEST_ANALOGIES.TXT -t 30000
143 | ```
144 |
145 |
146 | Dataset
147 | --------
148 | You can use the following script to download the main dataset used in our papers, which is an extension of that of [Dinu et al. (2014)](http://clic.cimec.unitn.it/~georgiana.dinu/down/):
149 | ```
150 | ./get_data.sh
151 | ```
152 |
153 |
154 | Reproducing results
155 | --------
156 |
157 | While we always recommend to use the above settings for best results when working with your own embeddings, we also offer additional modes to replicate the systems from our different papers as follows:
158 | - **ACL 2018** (currently equivalent to the unsupervised mode):
159 | ```
160 | python3 map_embeddings.py --acl2018 SRC.EMB TRG.EMB SRC_MAPPED.EMB TRG_MAPPED.EMB
161 | ```
162 | - **AAAI 2018** (currently equivalent to the supervised mode, except for minor differences in re-weighting, normalization and dimensionality reduction):
163 | ```
164 | python3 map_embeddings.py --aaai2018 TRAIN.DICT SRC.EMB TRG.EMB SRC_MAPPED.EMB TRG_MAPPED.EMB
165 | ```
166 | - **ACL 2017** (superseded by our ACL 2018 system; offers 2 modes depending on the initialization):
167 | ```
168 | python3 map_embeddings.py --acl2017 SRC.EMB TRG.EMB SRC_MAPPED.EMB TRG_MAPPED.EMB
169 | python3 map_embeddings.py --acl2017_seed TRAIN.DICT SRC.EMB TRG.EMB SRC_MAPPED.EMB TRG_MAPPED.EMB
170 | ```
171 | - **EMNLP 2016** (superseded by our AAAI 2018 system):
172 | ```
173 | python3 map_embeddings.py --emnlp2016 TRAIN.DICT SRC.EMB TRG.EMB SRC_MAPPED.EMB TRG_MAPPED.EMB
174 | ```
175 |
176 |
177 | FAQ
178 | --------
179 |
180 | ##### How long does training take?
181 |
182 | - The supervised mode (`--supervised`) should run in around 2 minutes in either CPU or GPU.
183 | - The rest of recommended modes (either `--semi_supervised`, `--identical` or `--unsupervised`) should run in around 5 hours in CPU, or 10 minutes in GPU (Titan Xp or similar).
184 |
185 |
186 | ##### This is running much slower for me! What can I do?
187 |
188 | 1. If you have a GPU, do not forget the `--cuda` flag.
189 | 2. Make sure that your NumPy installation is properly linked to BLAS/LAPACK. This is particularly important if you are working on CPU, as it can have a huge impact in performance if not properly set up.
190 | 3. There are different settings that affect the execution time of the algorithm and can thus be adjusted to make things faster: the batch size (`--batch_size`), the vocabulary cutoff (`--vocabulary_cutoff`), the stochastic dictionary induction settings (`--stochastic_initial`, `--stochastic_multiplier` and `--stochastic_interval`) and the convergence threshold (`--threshold`), among others. However, most of these settings will have a direct impact in the quality of the resulting embeddings, so you should not play with them unless you really know what you are doing.
191 |
192 |
193 | ##### Prior versions of this software included nice scripts to reproduce the exact same results reported in your papers. Why are those missing now?
194 |
195 | As the complexity of the software (and the number of publications/results to reproduce) increased, maintaining those nice scripts became very tedious. Moreover, with the inclusion of CUDA support and FP32 precision, reproducing the exact same results on different platforms became inviable due to minor numerical variations in the underlying computations, which were magnified by self-learning (e.g. the exact same command is likely to produce a slightly different output on CPU and GPU). While the effect in the final results is negligible (the observed variations are around 0.1-0.2 accuracy points), this made it unfeasible to reproduce the exact same results in different platforms.
196 |
197 | Instead of that, we now provide an [easy interface to run all the systems proposed in our different papers](#reproducing-results). We think that this might be even more useful than the previous approach: the most skeptical user should still be able to easily verify our results, while we also provide a simple interface to test our different systems in other datasets.
198 |
199 |
200 | ##### The ablation test in your ACL 2018 paper reports 0% accuracies for removing CSLS, but I am getting better results. Why is that?
201 |
202 | After publishing the paper, we discovered a bug in the code that was causing those 0% accuracies. Now that the bug is fixed, the effect of removing CSLS is not that dramatic, although it still has a big negative impact. At the same time, the effect of removing the bidirectional dictionary induction in that same ablation test is slightly smaller.
203 |
204 |
205 | See also
206 | --------
207 |
208 | VecMap is a basic building block of [Monoses](https://github.com/artetxem/monoses), our Unsupervised Statistical Machine Translation system. You can use them in combination to train your own machine translation model from monolingual corpora alone.
209 |
210 |
211 | Publications
212 | --------
213 |
214 | If you use this software for academic research, please cite the relevant paper(s) as follows (in case of doubt, please cite the ACL 2018 paper, or the AAAI 2018 paper if you use the supervised mode):
215 | ```
216 | @inproceedings{artetxe2018acl,
217 | author = {Artetxe, Mikel and Labaka, Gorka and Agirre, Eneko},
218 | title = {A robust self-learning method for fully unsupervised cross-lingual mappings of word embeddings},
219 | booktitle = {Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
220 | year = {2018},
221 | pages = {789--798}
222 | }
223 |
224 | @inproceedings{artetxe2018aaai,
225 | author = {Artetxe, Mikel and Labaka, Gorka and Agirre, Eneko},
226 | title = {Generalizing and improving bilingual word embedding mappings with a multi-step framework of linear transformations},
227 | booktitle = {Proceedings of the Thirty-Second AAAI Conference on Artificial Intelligence},
228 | year = {2018},
229 | pages = {5012--5019}
230 | }
231 |
232 | @inproceedings{artetxe2017acl,
233 | author = {Artetxe, Mikel and Labaka, Gorka and Agirre, Eneko},
234 | title = {Learning bilingual word embeddings with (almost) no bilingual data},
235 | booktitle = {Proceedings of the 55th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
236 | year = {2017},
237 | pages = {451--462}
238 | }
239 |
240 | @inproceedings{artetxe2016emnlp,
241 | author = {Artetxe, Mikel and Labaka, Gorka and Agirre, Eneko},
242 | title = {Learning principled bilingual mappings of word embeddings while preserving monolingual invariance},
243 | booktitle = {Proceedings of the 2016 Conference on Empirical Methods in Natural Language Processing},
244 | year = {2016},
245 | pages = {2289--2294}
246 | }
247 | ```
248 |
249 |
250 | License
251 | -------
252 |
253 | Copyright (C) 2016-2018, Mikel Artetxe
254 |
255 | Licensed under the terms of the GNU General Public License, either version 3 or (at your option) any later version. A full copy of the license can be found in LICENSE.txt.
256 |
--------------------------------------------------------------------------------
/cupy_utils.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2018 Mikel Artetxe
2 | #
3 | # This program is free software: you can redistribute it and/or modify
4 | # it under the terms of the GNU General Public License as published by
5 | # the Free Software Foundation, either version 3 of the License, or
6 | # (at your option) any later version.
7 | #
8 | # This program is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program. If not, see .
15 |
16 | import numpy
17 |
18 | try:
19 | import cupy
20 | except ImportError:
21 | cupy = None
22 |
23 |
24 | def supports_cupy():
25 | return cupy is not None
26 |
27 |
28 | def get_cupy():
29 | return cupy
30 |
31 |
32 | def get_array_module(x):
33 | if cupy is not None:
34 | return cupy.get_array_module(x)
35 | else:
36 | return numpy
37 |
38 |
39 | def asnumpy(x):
40 | if cupy is not None:
41 | return cupy.asnumpy(x)
42 | else:
43 | return numpy.asarray(x)
44 |
--------------------------------------------------------------------------------
/embeddings.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2016-2018 Mikel Artetxe
2 | #
3 | # This program is free software: you can redistribute it and/or modify
4 | # it under the terms of the GNU General Public License as published by
5 | # the Free Software Foundation, either version 3 of the License, or
6 | # (at your option) any later version.
7 | #
8 | # This program is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program. If not, see .
15 |
16 | from cupy_utils import *
17 |
18 | import numpy as np
19 |
20 |
21 | def read(file, threshold=0, vocabulary=None, dtype='float'):
22 | header = file.readline().split(' ')
23 | count = int(header[0]) if threshold <= 0 else min(threshold, int(header[0]))
24 | dim = int(header[1])
25 | words = []
26 | matrix = np.empty((count, dim), dtype=dtype) if vocabulary is None else []
27 | for i in range(count):
28 | word, vec = file.readline().split(' ', 1)
29 | if vocabulary is None:
30 | words.append(word)
31 | matrix[i] = np.fromstring(vec, sep=' ', dtype=dtype)
32 | elif word in vocabulary:
33 | words.append(word)
34 | matrix.append(np.fromstring(vec, sep=' ', dtype=dtype))
35 | return (words, matrix) if vocabulary is None else (words, np.array(matrix, dtype=dtype))
36 |
37 |
38 | def write(words, matrix, file):
39 | m = asnumpy(matrix)
40 | print('%d %d' % m.shape, file=file)
41 | for i in range(len(words)):
42 | print(words[i] + ' ' + ' '.join(['%.6g' % x for x in m[i]]), file=file)
43 |
44 |
45 | def length_normalize(matrix):
46 | xp = get_array_module(matrix)
47 | norms = xp.sqrt(xp.sum(matrix**2, axis=1))
48 | norms[norms == 0] = 1
49 | matrix /= norms[:, xp.newaxis]
50 |
51 |
52 | def mean_center(matrix):
53 | xp = get_array_module(matrix)
54 | avg = xp.mean(matrix, axis=0)
55 | matrix -= avg
56 |
57 |
58 | def length_normalize_dimensionwise(matrix):
59 | xp = get_array_module(matrix)
60 | norms = xp.sqrt(xp.sum(matrix**2, axis=0))
61 | norms[norms == 0] = 1
62 | matrix /= norms
63 |
64 |
65 | def mean_center_embeddingwise(matrix):
66 | xp = get_array_module(matrix)
67 | avg = xp.mean(matrix, axis=1)
68 | matrix -= avg[:, xp.newaxis]
69 |
70 |
71 | def normalize(matrix, actions):
72 | for action in actions:
73 | if action == 'unit':
74 | length_normalize(matrix)
75 | elif action == 'center':
76 | mean_center(matrix)
77 | elif action == 'unitdim':
78 | length_normalize_dimensionwise(matrix)
79 | elif action == 'centeremb':
80 | mean_center_embeddingwise(matrix)
81 |
--------------------------------------------------------------------------------
/eval_analogy.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2016-2018 Mikel Artetxe
2 | #
3 | # This program is free software: you can redistribute it and/or modify
4 | # it under the terms of the GNU General Public License as published by
5 | # the Free Software Foundation, either version 3 of the License, or
6 | # (at your option) any later version.
7 | #
8 | # This program is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program. If not, see .
15 |
16 | import embeddings
17 |
18 | import argparse
19 | import numpy as np
20 | import sys
21 |
22 |
23 | BATCH_SIZE = 1000
24 |
25 |
26 | def main():
27 | # Parse command line arguments
28 | parser = argparse.ArgumentParser(description='Evaluate embeddings in word analogy')
29 | parser.add_argument('embeddings', help='the word embeddings')
30 | parser.add_argument('-t', '--threshold', type=int, default=0, help='reduce vocabulary of the model for fast approximate evaluation (0 = off, otherwise typical value is 30,000)')
31 | parser.add_argument('-i', '--input', default=sys.stdin.fileno(), help='the test file (defaults to stdin)')
32 | parser.add_argument('-v', '--verbose', action='store_true', help='verbose output (give category specific results)')
33 | parser.add_argument('-l', '--lowercase', action='store_true', help='lowercase the words in the test file')
34 | parser.add_argument('--encoding', default='utf-8', help='the character encoding for input/output (defaults to utf-8)')
35 | parser.add_argument('--precision', choices=['fp16', 'fp32', 'fp64'], default='fp32', help='the floating-point precision (defaults to fp32)')
36 | args = parser.parse_args()
37 |
38 | # Choose the right dtype for the desired precision
39 | if args.precision == 'fp16':
40 | dtype = 'float16'
41 | elif args.precision == 'fp32':
42 | dtype = 'float32'
43 | elif args.precision == 'fp64':
44 | dtype = 'float64'
45 |
46 | # Read input embeddings
47 | f = open(args.embeddings, encoding=args.encoding, errors='surrogateescape')
48 | words, matrix = embeddings.read(f, threshold=args.threshold, dtype=dtype)
49 |
50 | # Build word to index map
51 | word2ind = {word: i for i, word in enumerate(words)}
52 |
53 | # Length normalize embeddings
54 | embeddings.length_normalize(matrix)
55 |
56 | # Parse test file
57 | f = open(args.input, encoding=args.encoding, errors='surrogateescape')
58 | categories = []
59 | src1 = []
60 | trg1 = []
61 | src2 = []
62 | trg2 = []
63 | for line in f:
64 | if line.startswith(': '):
65 | name = line[2:-1]
66 | is_syntactic = name.startswith('gram')
67 | categories.append({'name': name, 'is_syntactic': is_syntactic, 'total': 0, 'oov': 0})
68 | else:
69 | try:
70 | ind = [word2ind[word.lower() if args.lowercase else word] for word in line.split()]
71 | src1.append(ind[0])
72 | trg1.append(ind[1])
73 | src2.append(ind[2])
74 | trg2.append(ind[3])
75 | categories[-1]['total'] += 1
76 | except KeyError:
77 | categories[-1]['oov'] += 1
78 | total = len(src1)
79 |
80 | # Compute nearest neighbors using efficient matrix multiplication
81 | nn = []
82 | for i in range(0, total, BATCH_SIZE):
83 | j = min(i + BATCH_SIZE, total)
84 | similarities = (matrix[src2[i:j]] - matrix[src1[i:j]] + matrix[trg1[i:j]]).dot(matrix.T)
85 | similarities[range(j-i), src1[i:j]] = -1
86 | similarities[range(j-i), trg1[i:j]] = -1
87 | similarities[range(j-i), src2[i:j]] = -1
88 | nn += np.argmax(similarities, axis=1).tolist()
89 | nn = np.array(nn)
90 |
91 | # Compute and print accuracies
92 | semantic = {'correct': 0, 'total': 0, 'oov': 0}
93 | syntactic = {'correct': 0, 'total': 0, 'oov': 0}
94 | ind = 0
95 | for category in categories:
96 | current = syntactic if category['is_syntactic'] else semantic
97 | correct = np.sum(nn[ind:ind+category['total']] == trg2[ind:ind+category['total']])
98 | current['correct'] += correct
99 | current['total'] += category['total']
100 | current['oov'] += category['oov']
101 | ind += category['total']
102 | if args.verbose:
103 | print('Coverage:{0:7.2%} Accuracy:{1:7.2%} | {2}'.format(
104 | category['total'] / (category['total'] + category['oov']),
105 | correct / category['total'],
106 | category['name']))
107 | if args.verbose:
108 | print('-'*80)
109 | print('Coverage:{0:7.2%} Accuracy:{1:7.2%} (sem:{2:7.2%}, syn:{3:7.2%})'.format(
110 | (semantic['total'] + syntactic['total']) / (semantic['total'] + syntactic['total'] + semantic['oov'] + syntactic['oov']),
111 | (semantic['correct'] + syntactic['correct']) / (semantic['total'] + syntactic['total']),
112 | semantic['correct'] / semantic['total'],
113 | syntactic['correct'] / syntactic['total']))
114 |
115 |
116 | if __name__ == '__main__':
117 | main()
118 |
--------------------------------------------------------------------------------
/eval_similarity.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2017-2018 Mikel Artetxe
2 | #
3 | # This program is free software: you can redistribute it and/or modify
4 | # it under the terms of the GNU General Public License as published by
5 | # the Free Software Foundation, either version 3 of the License, or
6 | # (at your option) any later version.
7 | #
8 | # This program is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program. If not, see .
15 |
16 | import embeddings
17 |
18 | import argparse
19 | import numpy as np
20 | import os
21 | import scipy.stats
22 | import sys
23 |
24 |
25 | def main():
26 | # Parse command line arguments
27 | parser = argparse.ArgumentParser(description='Evaluate embeddings in word similarity/relatedness')
28 | parser.add_argument('src_embeddings', help='the source language embeddings')
29 | parser.add_argument('trg_embeddings', nargs='?', help='the target language embeddings')
30 | parser.add_argument('-i', '--input', default=[sys.stdin.fileno()], nargs='+', help='the input datasets (defaults to stdin)')
31 | parser.add_argument('-l', '--lowercase', action='store_true', help='lowercase the words in the test files')
32 | parser.add_argument('--backoff', default=None, type=float, help='use a backoff similarity score for OOV entries')
33 | parser.add_argument('--encoding', default='utf-8', help='the character encoding for input/output (defaults to utf-8)')
34 | parser.add_argument('--precision', choices=['fp16', 'fp32', 'fp64'], default='fp32', help='the floating-point precision (defaults to fp32)')
35 | parser.add_argument('--sim', nargs='*', help='the names of the datasets to include in the similarity results')
36 | parser.add_argument('--rel', nargs='*', help='the names of the datasets to include in the relatedness results')
37 | parser.add_argument('--all', nargs='*', help='the names of the datasets to include in the total results')
38 | args = parser.parse_args()
39 |
40 | # Choose the right dtype for the desired precision
41 | if args.precision == 'fp16':
42 | dtype = 'float16'
43 | elif args.precision == 'fp32':
44 | dtype = 'float32'
45 | elif args.precision == 'fp64':
46 | dtype = 'float64'
47 |
48 | # Parse test files
49 | word_pairs = []
50 | golds = []
51 | for filename in args.input:
52 | f = open(filename, encoding=args.encoding, errors='surrogateescape')
53 | word_pairs.append([])
54 | golds.append([])
55 | for line in f:
56 | if args.lowercase:
57 | line = line.lower()
58 | src, trg, score = line.split('\t')
59 | word_pairs[-1].append((src, trg))
60 | golds[-1].append(float(score))
61 |
62 | # Build vocabularies
63 | src_vocab = {pair[0] for pairs in word_pairs for pair in pairs}
64 | trg_vocab = {pair[1] for pairs in word_pairs for pair in pairs}
65 |
66 | # Read embeddings
67 | srcfile = open(args.src_embeddings, encoding=args.encoding, errors='surrogateescape')
68 | trgfile = open(args.src_embeddings if args.trg_embeddings is None else args.trg_embeddings, encoding=args.encoding, errors='surrogateescape')
69 | src_words, src_matrix = embeddings.read(srcfile, vocabulary=src_vocab, dtype=dtype)
70 | trg_words, trg_matrix = embeddings.read(trgfile, vocabulary=trg_vocab, dtype=dtype)
71 |
72 | # Length normalize embeddings so their dot product effectively computes the cosine similarity
73 | embeddings.length_normalize(src_matrix)
74 | embeddings.length_normalize(trg_matrix)
75 |
76 | # Build word to index map
77 | src_word2ind = {word: i for i, word in enumerate(src_words)}
78 | trg_word2ind = {word: i for i, word in enumerate(trg_words)}
79 |
80 | # Compute system scores and correlations
81 | results = []
82 | for i in range(len(golds)):
83 | system = []
84 | gold = []
85 | oov = 0
86 | for gold_score, (src, trg) in zip(golds[i], word_pairs[i]):
87 | try:
88 | cos = np.dot(src_matrix[src_word2ind[src]], trg_matrix[trg_word2ind[trg]])
89 | system.append(cos)
90 | gold.append(gold_score)
91 | except KeyError:
92 | if args.backoff is None:
93 | oov += 1
94 | else:
95 | system.append(args.backoff)
96 | gold.append(gold_score)
97 | name = os.path.splitext(os.path.basename(args.input[i]))[0]
98 | coverage = len(system) / (len(system) + oov)
99 | pearson = scipy.stats.pearsonr(gold, system)[0]
100 | spearman = scipy.stats.spearmanr(gold, system)[0]
101 | results.append((name, coverage, pearson, spearman))
102 | print('Coverage:{0:7.2%} Pearson:{1:7.2%} Spearman:{2:7.2%} | {3}'.format(coverage, pearson, spearman, name))
103 |
104 | # Compute and print total (averaged) results
105 | if len(results) > 1:
106 | print('-'*80)
107 | if args.sim is not None:
108 | sim = list(zip(*[res for res in results if res[0] in args.sim]))
109 | print('Coverage:{0:7.2%} Pearson:{1:7.2%} Spearman:{2:7.2%} | sim.'.format(np.mean(sim[1]), np.mean(sim[2]), np.mean(sim[3])))
110 | if args.rel is not None:
111 | rel = list(zip(*[res for res in results if res[0] in args.rel]))
112 | print('Coverage:{0:7.2%} Pearson:{1:7.2%} Spearman:{2:7.2%} | rel.'.format(np.mean(rel[1]), np.mean(rel[2]), np.mean(rel[3])))
113 | if args.all is not None:
114 | results = [res for res in results if res[0] in args.all]
115 | results = list(zip(*results))
116 | print('Coverage:{0:7.2%} Pearson:{1:7.2%} Spearman:{2:7.2%} | all'.format(np.mean(results[1]), np.mean(results[2]), np.mean(results[3])))
117 |
118 |
119 | if __name__ == '__main__':
120 | main()
121 |
--------------------------------------------------------------------------------
/eval_translation.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2016-2018 Mikel Artetxe
2 | #
3 | # This program is free software: you can redistribute it and/or modify
4 | # it under the terms of the GNU General Public License as published by
5 | # the Free Software Foundation, either version 3 of the License, or
6 | # (at your option) any later version.
7 | #
8 | # This program is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program. If not, see .
15 |
16 | import embeddings
17 | from cupy_utils import *
18 |
19 | import argparse
20 | import collections
21 | import numpy as np
22 | import sys
23 |
24 |
25 | BATCH_SIZE = 500
26 |
27 |
28 | def topk_mean(m, k, inplace=False): # TODO Assuming that axis is 1
29 | xp = get_array_module(m)
30 | n = m.shape[0]
31 | ans = xp.zeros(n, dtype=m.dtype)
32 | if k <= 0:
33 | return ans
34 | if not inplace:
35 | m = xp.array(m)
36 | ind0 = xp.arange(n)
37 | ind1 = xp.empty(n, dtype=int)
38 | minimum = m.min()
39 | for i in range(k):
40 | m.argmax(axis=1, out=ind1)
41 | ans += m[ind0, ind1]
42 | m[ind0, ind1] = minimum
43 | return ans / k
44 |
45 |
46 | def main():
47 | # Parse command line arguments
48 | parser = argparse.ArgumentParser(description='Evaluate embeddings of two languages in a shared space in word translation induction')
49 | parser.add_argument('src_embeddings', help='the source language embeddings')
50 | parser.add_argument('trg_embeddings', help='the target language embeddings')
51 | parser.add_argument('-d', '--dictionary', default=sys.stdin.fileno(), help='the test dictionary file (defaults to stdin)')
52 | parser.add_argument('--retrieval', default='nn', choices=['nn', 'invnn', 'invsoftmax', 'csls'], help='the retrieval method (nn: standard nearest neighbor; invnn: inverted nearest neighbor; invsoftmax: inverted softmax; csls: cross-domain similarity local scaling)')
53 | parser.add_argument('--inv_temperature', default=1, type=float, help='the inverse temperature (only compatible with inverted softmax)')
54 | parser.add_argument('--inv_sample', default=None, type=int, help='use a random subset of the source vocabulary for the inverse computations (only compatible with inverted softmax)')
55 | parser.add_argument('-k', '--neighborhood', default=10, type=int, help='the neighborhood size (only compatible with csls)')
56 | parser.add_argument('--dot', action='store_true', help='use the dot product in the similarity computations instead of the cosine')
57 | parser.add_argument('--encoding', default='utf-8', help='the character encoding for input/output (defaults to utf-8)')
58 | parser.add_argument('--seed', type=int, default=0, help='the random seed')
59 | parser.add_argument('--precision', choices=['fp16', 'fp32', 'fp64'], default='fp32', help='the floating-point precision (defaults to fp32)')
60 | parser.add_argument('--cuda', action='store_true', help='use cuda (requires cupy)')
61 | args = parser.parse_args()
62 |
63 | # Choose the right dtype for the desired precision
64 | if args.precision == 'fp16':
65 | dtype = 'float16'
66 | elif args.precision == 'fp32':
67 | dtype = 'float32'
68 | elif args.precision == 'fp64':
69 | dtype = 'float64'
70 |
71 | # Read input embeddings
72 | srcfile = open(args.src_embeddings, encoding=args.encoding, errors='surrogateescape')
73 | trgfile = open(args.trg_embeddings, encoding=args.encoding, errors='surrogateescape')
74 | src_words, x = embeddings.read(srcfile, dtype=dtype)
75 | trg_words, z = embeddings.read(trgfile, dtype=dtype)
76 |
77 | # NumPy/CuPy management
78 | if args.cuda:
79 | if not supports_cupy():
80 | print('ERROR: Install CuPy for CUDA support', file=sys.stderr)
81 | sys.exit(-1)
82 | xp = get_cupy()
83 | x = xp.asarray(x)
84 | z = xp.asarray(z)
85 | else:
86 | xp = np
87 | xp.random.seed(args.seed)
88 |
89 | # Length normalize embeddings so their dot product effectively computes the cosine similarity
90 | if not args.dot:
91 | embeddings.length_normalize(x)
92 | embeddings.length_normalize(z)
93 |
94 | # Build word to index map
95 | src_word2ind = {word: i for i, word in enumerate(src_words)}
96 | trg_word2ind = {word: i for i, word in enumerate(trg_words)}
97 |
98 | # Read dictionary and compute coverage
99 | f = open(args.dictionary, encoding=args.encoding, errors='surrogateescape')
100 | src2trg = collections.defaultdict(set)
101 | oov = set()
102 | vocab = set()
103 | for line in f:
104 | src, trg = line.split()
105 | try:
106 | src_ind = src_word2ind[src]
107 | trg_ind = trg_word2ind[trg]
108 | src2trg[src_ind].add(trg_ind)
109 | vocab.add(src)
110 | except KeyError:
111 | oov.add(src)
112 | src = list(src2trg.keys())
113 | oov -= vocab # If one of the translation options is in the vocabulary, then the entry is not an oov
114 | coverage = len(src2trg) / (len(src2trg) + len(oov))
115 |
116 | # Find translations
117 | translation = collections.defaultdict(int)
118 | if args.retrieval == 'nn': # Standard nearest neighbor
119 | for i in range(0, len(src), BATCH_SIZE):
120 | j = min(i + BATCH_SIZE, len(src))
121 | similarities = x[src[i:j]].dot(z.T)
122 | nn = similarities.argmax(axis=1).tolist()
123 | for k in range(j-i):
124 | translation[src[i+k]] = nn[k]
125 | elif args.retrieval == 'invnn': # Inverted nearest neighbor
126 | best_rank = np.full(len(src), x.shape[0], dtype=int)
127 | best_sim = np.full(len(src), -100, dtype=dtype)
128 | for i in range(0, z.shape[0], BATCH_SIZE):
129 | j = min(i + BATCH_SIZE, z.shape[0])
130 | similarities = z[i:j].dot(x.T)
131 | ind = (-similarities).argsort(axis=1)
132 | ranks = asnumpy(ind.argsort(axis=1)[:, src])
133 | sims = asnumpy(similarities[:, src])
134 | for k in range(i, j):
135 | for l in range(len(src)):
136 | rank = ranks[k-i, l]
137 | sim = sims[k-i, l]
138 | if rank < best_rank[l] or (rank == best_rank[l] and sim > best_sim[l]):
139 | best_rank[l] = rank
140 | best_sim[l] = sim
141 | translation[src[l]] = k
142 | elif args.retrieval == 'invsoftmax': # Inverted softmax
143 | sample = xp.arange(x.shape[0]) if args.inv_sample is None else xp.random.randint(0, x.shape[0], args.inv_sample)
144 | partition = xp.zeros(z.shape[0])
145 | for i in range(0, len(sample), BATCH_SIZE):
146 | j = min(i + BATCH_SIZE, len(sample))
147 | partition += xp.exp(args.inv_temperature*z.dot(x[sample[i:j]].T)).sum(axis=1)
148 | for i in range(0, len(src), BATCH_SIZE):
149 | j = min(i + BATCH_SIZE, len(src))
150 | p = xp.exp(args.inv_temperature*x[src[i:j]].dot(z.T)) / partition
151 | nn = p.argmax(axis=1).tolist()
152 | for k in range(j-i):
153 | translation[src[i+k]] = nn[k]
154 | elif args.retrieval == 'csls': # Cross-domain similarity local scaling
155 | knn_sim_bwd = xp.zeros(z.shape[0])
156 | for i in range(0, z.shape[0], BATCH_SIZE):
157 | j = min(i + BATCH_SIZE, z.shape[0])
158 | knn_sim_bwd[i:j] = topk_mean(z[i:j].dot(x.T), k=args.neighborhood, inplace=True)
159 | for i in range(0, len(src), BATCH_SIZE):
160 | j = min(i + BATCH_SIZE, len(src))
161 | similarities = 2*x[src[i:j]].dot(z.T) - knn_sim_bwd # Equivalent to the real CSLS scores for NN
162 | nn = similarities.argmax(axis=1).tolist()
163 | for k in range(j-i):
164 | translation[src[i+k]] = nn[k]
165 |
166 | # Compute accuracy
167 | accuracy = np.mean([1 if translation[i] in src2trg[i] else 0 for i in src])
168 | print('Coverage:{0:7.2%} Accuracy:{1:7.2%}'.format(coverage, accuracy))
169 |
170 |
171 | if __name__ == '__main__':
172 | main()
173 |
--------------------------------------------------------------------------------
/get_data.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #
3 | # Copyright (C) 2017-2018 Mikel Artetxe
4 | #
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 | #
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU General Public License for more details.
14 | #
15 | # You should have received a copy of the GNU General Public License
16 | # along with this program. If not, see .
17 |
18 | ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
19 | DATA="$ROOT/data"
20 | mkdir -p "$DATA/analogies"
21 | mkdir -p "$DATA/similarity"
22 | mkdir -p "$DATA/dictionaries"
23 | mkdir -p "$DATA/embeddings"
24 |
25 | # Download English-Italian data from Dinu et al. (2015)
26 | wget -q http://clic.cimec.unitn.it/~georgiana.dinu/down/resources/transmat.zip -O "$DATA/transmat.zip"
27 | unzip -p "$DATA/transmat.zip" data/EN.200K.cbow1_wind5_hs0_neg10_size300_smpl1e-05.txt > "$DATA/embeddings/en.emb.txt"
28 | unzip -p "$DATA/transmat.zip" data/IT.200K.cbow1_wind5_hs0_neg10_size300_smpl1e-05.txt > "$DATA/embeddings/it.emb.txt"
29 | unzip -p "$DATA/transmat.zip" data/OPUS_en_it_europarl_train_5K.txt > "$DATA/dictionaries/en-it.train.txt"
30 | unzip -p "$DATA/transmat.zip" data/OPUS_en_it_europarl_test.txt > "$DATA/dictionaries/en-it.test.txt"
31 | rm -f "$DATA/transmat.zip"
32 |
33 | # Download word analogy data from Mikolov et al. (2013)
34 | wget -q https://storage.googleapis.com/google-code-archive-source/v2/code.google.com/word2vec/source-archive.zip -O "$DATA/word2vec.zip"
35 | unzip -p "$DATA/word2vec.zip" word2vec/trunk/questions-words.txt > "$DATA/analogies/questions-words.txt"
36 | rm -f "$DATA/word2vec.zip"
37 |
38 | # Download crosslingual word similarity data from Camacho-Collados et al. (2015)
39 | wget -q http://lcl.uniroma1.it/similarity-datasets/datasets/rg65_EN-DE.txt -O "$DATA/similarity/en-de.rg65.txt"
40 | wget -q http://lcl.uniroma1.it/similarity-datasets/datasets/MWS353_Cross-lingual_datasets.zip -O "$DATA/mws353.zip"
41 | unzip -p "$DATA/mws353.zip" MWS353_Cross-lingual_datasets/cross_en_de_MWS353.txt > "$DATA/similarity/en-de.mws353.txt"
42 | unzip -p "$DATA/mws353.zip" MWS353_Cross-lingual_datasets/cross_en_it_MWS353.txt > "$DATA/similarity/en-it.mws353.txt"
43 | rm -f "$DATA/mws353.zip"
44 |
45 | # Download remaining data from our own release
46 | wget -q http://ixa2.si.ehu.es/eneko/tmp/vecmap/de.emb.txt.gz -O "$DATA/embeddings/de.emb.txt.gz"
47 | wget -q http://ixa2.si.ehu.es/eneko/tmp/vecmap/fi.emb.txt.gz -O "$DATA/embeddings/fi.emb.txt.gz"
48 | wget -q http://ixa2.si.ehu.es/eneko/tmp/vecmap/es.emb.txt.gz -O "$DATA/embeddings/es.emb.txt.gz"
49 | wget -q http://ixa2.si.ehu.es/eneko/tmp/vecmap/dictionaries.tar.gz -O "$DATA/dictionaries.tar.gz"
50 | gunzip "$DATA/embeddings/de.emb.txt.gz"
51 | gunzip "$DATA/embeddings/fi.emb.txt.gz"
52 | gunzip "$DATA/embeddings/es.emb.txt.gz"
53 | tar -xzf "$DATA/dictionaries.tar.gz" -C "$DATA/dictionaries"
54 | rm -f "$DATA/dictionaries.tar.gz"
55 |
--------------------------------------------------------------------------------
/lat_var.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from lap import lapmod
3 |
4 |
5 | def lat_var(xp, sims, n_similar, n_repeats, batch_size, asym):
6 | """
7 | Run the matching in the E-step of the latent-variable model.
8 | :param xp: numpy or cupy, depending whether we run on CPU or GPU.
9 | :param xw: the xw matrix
10 | :param zw: the zw matrix
11 | :param sims: an matrix of shape (src_size, trg_size) where the similarity values
12 | between each source word and target words are stored
13 | :param best_sim_forward: an array of shape (src_size), which stores the best similarity
14 | scores for each
15 | :param n_similar:
16 | :param n_repeats:
17 | :param batch_size:
18 | :param asym:
19 | :return:
20 | """
21 | src_size = sims.shape[0]
22 | cc = np.empty(src_size * n_similar) # 1D array of all finite elements of the assignement cost matrix
23 | kk = np.empty(src_size * n_similar) # 1D array of the column indices. Must be sorted within one row.
24 | ii = np.empty((src_size * n_repeats + 1,), dtype=int) # 1D array of indices of the row starts in cc.
25 | ii[0] = 0
26 | # if each src id should be matched to trg id, then we need to double the source indices
27 | for i in range(1, src_size * n_repeats + 1):
28 | ii[i] = ii[i - 1] + n_similar
29 | for i in range(0, src_size, batch_size):
30 | # j = min(x.shape[0], i + batch_size)
31 | j = min(i + batch_size, src_size)
32 | sim = sims[i:j]
33 |
34 | trg_indices = xp.argpartition(sim, -n_similar)[:, -n_similar:] # get indices of n largest elements
35 | if xp != np:
36 | trg_indices = xp.asnumpy(trg_indices)
37 | trg_indices.sort() # sort the target indices
38 |
39 | trg_indices = trg_indices.flatten()
40 | row_indices = np.array([[i] * n_similar for i in range(j-i)]).flatten()
41 | sim_scores = sim[row_indices, trg_indices]
42 | costs = 1 - sim_scores
43 | if xp != np:
44 | costs = xp.asnumpy(costs)
45 | cc[i * n_similar:j * n_similar] = costs
46 | kk[i * n_similar:j * n_similar] = trg_indices
47 | if n_repeats > 1:
48 | # duplicate costs and target indices
49 | new_cc = cc
50 | new_kk = kk
51 | for i in range(1, n_repeats):
52 | new_cc = np.concatenate([new_cc, cc], axis=0)
53 | if asym == '1:2':
54 | # for 1:2, we don't duplicate the target indices
55 | new_kk = np.concatenate([new_kk, kk], axis=0)
56 | else:
57 | # update target indices so that they refer to new columns
58 | new_kk = np.concatenate([new_kk, kk + src_size * i], axis=0)
59 | cc = new_cc
60 | kk = new_kk
61 | # trg indices are targets assigned to each row id from 0-(n_rows-1)
62 | cost, trg_indices, _ = lapmod(src_size * n_repeats, cc, ii, kk)
63 | src_indices = np.concatenate([np.arange(src_size)] * n_repeats, 0)
64 | src_indices, trg_indices = xp.asarray(src_indices), xp.asarray(trg_indices)
65 |
66 | # remove the pairs in which a source word was connected to a target
67 | # which was not one of its k most similar words
68 | wrong_inds = []
69 | for i, trgind in enumerate(trg_indices):
70 | krow = ii[i]
71 | candidates = kk[krow:krow + n_similar]
72 | if trgind not in candidates:
73 | wrong_inds.append(i)
74 | trg_indices = np.delete(trg_indices, wrong_inds)
75 | src_indices = np.delete(src_indices, wrong_inds)
76 |
77 | for i in range(len(src_indices)):
78 | src_idx, trg_idx = src_indices[i], trg_indices[i]
79 | # we do this if args.n_repeats > 0 to assign the target
80 | # indices in the cost matrix to the correct idx
81 | while trg_idx >= src_size:
82 | # if we repeat, we have indices that are > n_rows
83 | trg_idx -= src_size
84 | trg_indices[i] = trg_idx
85 | return src_indices, trg_indices
86 |
--------------------------------------------------------------------------------
/map_embeddings.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2016-2018 Mikel Artetxe
2 | #
3 | # This program is free software: you can redistribute it and/or modify
4 | # it under the terms of the GNU General Public License as published by
5 | # the Free Software Foundation, either version 3 of the License, or
6 | # (at your option) any later version.
7 | #
8 | # This program is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program. If not, see .
15 |
16 | import embeddings
17 | from cupy_utils import *
18 |
19 | import argparse
20 | import collections
21 | import numpy as np
22 | import re
23 | import sys
24 | import time
25 | import lat_var
26 |
27 |
28 | def dropout(m, p):
29 | if p <= 0.0:
30 | return m
31 | else:
32 | xp = get_array_module(m)
33 | mask = xp.random.rand(*m.shape) >= p
34 | return m*mask
35 |
36 |
37 | def topk_mean(m, k, inplace=False): # TODO Assuming that axis is 1
38 | xp = get_array_module(m)
39 | n = m.shape[0]
40 | ans = xp.zeros(n, dtype=m.dtype)
41 | if k <= 0:
42 | return ans
43 | if not inplace:
44 | m = xp.array(m)
45 | ind0 = xp.arange(n)
46 | ind1 = xp.empty(n, dtype=int)
47 | minimum = m.min()
48 | for i in range(k):
49 | m.argmax(axis=1, out=ind1)
50 | ans += m[ind0, ind1]
51 | m[ind0, ind1] = minimum
52 | return ans / k
53 |
54 |
55 | def main():
56 | # Parse command line arguments
57 | parser = argparse.ArgumentParser(description='Map word embeddings in two languages into a shared space')
58 | parser.add_argument('src_input', help='the input source embeddings')
59 | parser.add_argument('trg_input', help='the input target embeddings')
60 | parser.add_argument('src_output', help='the output source embeddings')
61 | parser.add_argument('trg_output', help='the output target embeddings')
62 | parser.add_argument('--encoding', default='utf-8', help='the character encoding for input/output (defaults to utf-8)')
63 | parser.add_argument('--precision', choices=['fp16', 'fp32', 'fp64'], default='fp32', help='the floating-point precision (defaults to fp32)')
64 | parser.add_argument('--cuda', action='store_true', help='use cuda (requires cupy)')
65 | parser.add_argument('--batch_size', default=10000, type=int, help='batch size (defaults to 10000); does not affect results, larger is usually faster but uses more memory')
66 | parser.add_argument('--seed', type=int, default=0, help='the random seed (defaults to 0)')
67 | parser.add_argument('--test-dict', help='the test dictionary file')
68 |
69 | recommended_group = parser.add_argument_group('recommended settings', 'Recommended settings for different scenarios')
70 | recommended_type = recommended_group.add_mutually_exclusive_group()
71 | recommended_type.add_argument('--supervised', metavar='DICTIONARY', help='recommended if you have a large training dictionary')
72 | recommended_type.add_argument('--semi_supervised', metavar='DICTIONARY', help='recommended if you have a small seed dictionary')
73 | recommended_type.add_argument('--identical', action='store_true', help='recommended if you have no seed dictionary but can rely on identical words')
74 | recommended_type.add_argument('--unsupervised', action='store_true', help='recommended if you have no seed dictionary and do not want to rely on identical words')
75 | recommended_type.add_argument('--acl2018', action='store_true', help='reproduce our ACL 2018 system')
76 | recommended_type.add_argument('--aaai2018', metavar='DICTIONARY', help='reproduce our AAAI 2018 system')
77 | recommended_type.add_argument('--acl2017', action='store_true', help='reproduce our ACL 2017 system with numeral initialization')
78 | # Note: changed the argument so that dictionary is supplied with -d instead
79 | recommended_type.add_argument('--acl2017_seed', action='store_true', help='reproduce our ACL 2017 system with a seed dictionary')
80 | recommended_type.add_argument('--emnlp2016', metavar='DICTIONARY', help='reproduce our EMNLP 2016 system')
81 | # still requires specifying a seed dictionary or another init
82 | recommended_type.add_argument('--ruder_emnlp2018', action='store_true', help='reproduce EMNLP 2018 latent-variable model of Ruder et al.')
83 | recommended_type.add_argument('--ruder_emnlp2018_backward', action='store_true', help='reproduce Ruder et al. (EMNLP 2018) with matching in backward direction')
84 | recommended_type.add_argument('--ruder_emnlp2018_artetxe_acl2018_unsupervised', action='store_true', help='reproduce Ruder et al. (EMNLP 2018) with matching in backward direction')
85 | recommended_type.add_argument('--ruder_emnlp2018_artetxe_acl2018', action='store_true', help='reproduce Ruder et al. (EMNLP 2018) with matching in backward direction')
86 |
87 | init_group = parser.add_argument_group('advanced initialization arguments', 'Advanced initialization arguments')
88 | init_type = init_group.add_mutually_exclusive_group()
89 | init_type.add_argument('-d', '--init_dictionary', default=sys.stdin.fileno(), metavar='DICTIONARY', help='the training dictionary file (defaults to stdin)')
90 | init_type.add_argument('--init_identical', action='store_true', help='use identical words as the seed dictionary')
91 | init_type.add_argument('--init_numerals', action='store_true', help='use latin numerals (i.e. words matching [0-9]+) as the seed dictionary')
92 | init_type.add_argument('--init_unsupervised', action='store_true', help='use unsupervised initialization')
93 | init_group.add_argument('--unsupervised_vocab', type=int, default=0, help='restrict the vocabulary to the top k entries for unsupervised initialization')
94 |
95 | mapping_group = parser.add_argument_group('advanced mapping arguments', 'Advanced embedding mapping arguments')
96 | mapping_group.add_argument('--normalize', choices=['unit', 'center', 'unitdim', 'centeremb', 'none'], nargs='*', default=[], help='the normalization actions to perform in order')
97 | mapping_group.add_argument('--whiten', action='store_true', help='whiten the embeddings')
98 | mapping_group.add_argument('--src_reweight', type=float, default=0, nargs='?', const=1, help='re-weight the source language embeddings')
99 | mapping_group.add_argument('--trg_reweight', type=float, default=0, nargs='?', const=1, help='re-weight the target language embeddings')
100 | mapping_group.add_argument('--src_dewhiten', choices=['src', 'trg'], help='de-whiten the source language embeddings')
101 | mapping_group.add_argument('--trg_dewhiten', choices=['src', 'trg'], help='de-whiten the target language embeddings')
102 | mapping_group.add_argument('--dim_reduction', type=int, default=0, help='apply dimensionality reduction')
103 | mapping_type = mapping_group.add_mutually_exclusive_group()
104 | mapping_type.add_argument('-c', '--orthogonal', action='store_true', help='use orthogonal constrained mapping')
105 | mapping_type.add_argument('-u', '--unconstrained', action='store_true', help='use unconstrained mapping')
106 |
107 | self_learning_group = parser.add_argument_group('advanced self-learning arguments', 'Advanced arguments for self-learning')
108 | self_learning_group.add_argument('--self_learning', action='store_true', help='enable self-learning')
109 | self_learning_group.add_argument('--vocabulary_cutoff', type=int, default=0, help='restrict the vocabulary to the top k entries')
110 | self_learning_group.add_argument('--direction', choices=['forward', 'backward', 'union'], default='union', help='the direction for dictionary induction (defaults to union)')
111 | self_learning_group.add_argument('--csls', type=int, nargs='?', default=0, const=10, metavar='NEIGHBORHOOD_SIZE', dest='csls_neighborhood', help='use CSLS for dictionary induction')
112 | self_learning_group.add_argument('--threshold', default=0.000001, type=float, help='the convergence threshold (defaults to 0.000001)')
113 | self_learning_group.add_argument('--validation', default=None, metavar='DICTIONARY', help='a dictionary file for validation at each iteration')
114 | self_learning_group.add_argument('--stochastic_initial', default=0.1, type=float, help='initial keep probability stochastic dictionary induction (defaults to 0.1)')
115 | self_learning_group.add_argument('--stochastic_multiplier', default=2.0, type=float, help='stochastic dictionary induction multiplier (defaults to 2.0)')
116 | self_learning_group.add_argument('--stochastic_interval', default=50, type=int, help='stochastic dictionary induction interval (defaults to 50)')
117 | self_learning_group.add_argument('--log', help='write to a log file in tsv format at each iteration')
118 | self_learning_group.add_argument('-v', '--verbose', action='store_true', help='write log information to stderr at each iteration')
119 |
120 | lat_var_group = parser.add_argument_group('arguments for latent-variable model', 'Arguments for latent-variable model')
121 | lat_var_group.add_argument('--lat-var', action='store_true', help='use the latent-variable model')
122 | lat_var_group.add_argument('--n-similar', type=int, default=3, help='# of most similar trg indices used for sparsifying in latent-variable model')
123 | lat_var_group.add_argument('--n-repeats', default=1, type=int, help='repeats embeddings to get 2:2, 3:3, etc. alignment in latent-variable model')
124 | lat_var_group.add_argument('--asym', default='1:1', help='specify 1:2 or 2:1 for assymmetric matching in latent-variable model')
125 | args = parser.parse_args()
126 |
127 | if args.supervised is not None:
128 | parser.set_defaults(init_dictionary=args.supervised, normalize=['unit', 'center', 'unit'], whiten=True, src_reweight=0.5, trg_reweight=0.5, src_dewhiten='src', trg_dewhiten='trg', batch_size=1000)
129 | if args.semi_supervised is not None:
130 | parser.set_defaults(init_dictionary=args.semi_supervised, normalize=['unit', 'center', 'unit'], whiten=True, src_reweight=0.5, trg_reweight=0.5, src_dewhiten='src', trg_dewhiten='trg', self_learning=True, vocabulary_cutoff=20000, csls_neighborhood=10)
131 | if args.identical:
132 | parser.set_defaults(init_identical=True, normalize=['unit', 'center', 'unit'], whiten=True, src_reweight=0.5, trg_reweight=0.5, src_dewhiten='src', trg_dewhiten='trg', self_learning=True, vocabulary_cutoff=20000, csls_neighborhood=10)
133 |
134 | # reduce stochastic interval
135 | # note: just backward direction works surprisingly well
136 | if args.ruder_emnlp2018_artetxe_acl2018_unsupervised:
137 | parser.set_defaults(init_unsupervised=True, unsupervised_vocab=4000, normalize=['unit', 'center', 'unit'], whiten=True, src_reweight=0.5, trg_reweight=0.5, src_dewhiten='src', trg_dewhiten='trg', self_learning=True, vocabulary_cutoff=40000, csls_neighborhood=10, lat_var=True, n_similar=3, direction='union', stochastic_interval=3)
138 | if args.ruder_emnlp2018_artetxe_acl2018:
139 | parser.set_defaults(normalize=['unit', 'center', 'unit'], whiten=True, src_reweight=0.5, trg_reweight=0.5, src_dewhiten='src', trg_dewhiten='trg', self_learning=True, vocabulary_cutoff=40000, csls_neighborhood=10, lat_var=True, n_similar=3, direction='union', stochastic_interval=3)
140 | if args.ruder_emnlp2018:
141 | parser.set_defaults(orthogonal=True, normalize=['unit', 'center'], self_learning=True, direction='forward', stochastic_initial=1.0, stochastic_interval=1, batch_size=1000, lat_var=True, n_similar=3, vocabulary_cutoff=40000)
142 | if args.ruder_emnlp2018_backward:
143 | parser.set_defaults(orthogonal=True, normalize=['unit', 'center'], self_learning=True, direction='backward', stochastic_initial=1.0, stochastic_interval=1, batch_size=1000, lat_var=True, n_similar=3, vocabulary_cutoff=40000)
144 |
145 | if args.unsupervised or args.acl2018:
146 | parser.set_defaults(init_unsupervised=True, unsupervised_vocab=4000, normalize=['unit', 'center', 'unit'], whiten=True, src_reweight=0.5, trg_reweight=0.5, src_dewhiten='src', trg_dewhiten='trg', self_learning=True, vocabulary_cutoff=20000, csls_neighborhood=10)
147 | if args.aaai2018:
148 | parser.set_defaults(init_dictionary=args.aaai2018, normalize=['unit', 'center'], whiten=True, trg_reweight=1, src_dewhiten='src', trg_dewhiten='trg', batch_size=1000)
149 | if args.acl2017:
150 | parser.set_defaults(init_numerals=True, orthogonal=True, normalize=['unit', 'center'], self_learning=True, direction='forward', stochastic_initial=1.0, stochastic_interval=1, batch_size=1000)
151 | if args.acl2017_seed:
152 | parser.set_defaults(init_dictionary=args.init_dictionary, orthogonal=True, normalize=['unit', 'center'], self_learning=True, direction='forward', stochastic_initial=1.0, stochastic_interval=1, batch_size=1000)
153 | if args.emnlp2016:
154 | parser.set_defaults(init_dictionary=args.emnlp2016, orthogonal=True, normalize=['unit', 'center'], batch_size=1000)
155 | args = parser.parse_args()
156 |
157 | # Check command line arguments
158 | if (args.src_dewhiten is not None or args.trg_dewhiten is not None) and not args.whiten:
159 | print('ERROR: De-whitening requires whitening first', file=sys.stderr)
160 | sys.exit(-1)
161 |
162 | if args.verbose:
163 | print("Info: arguments\n\t" + "\n\t".join(
164 | ["{}: {}".format(a, v) for a, v in vars(args).items()]),
165 | file=sys.stderr)
166 |
167 | # Choose the right dtype for the desired precision
168 | if args.precision == 'fp16':
169 | dtype = 'float16'
170 | elif args.precision == 'fp32':
171 | dtype = 'float32'
172 | elif args.precision == 'fp64':
173 | dtype = 'float64'
174 |
175 | # Read input embeddings
176 | srcfile = open(args.src_input, encoding=args.encoding, errors='surrogateescape')
177 | trgfile = open(args.trg_input, encoding=args.encoding, errors='surrogateescape')
178 | src_words, x = embeddings.read(srcfile, dtype=dtype, threshold=200000)
179 | trg_words, z = embeddings.read(trgfile, dtype=dtype, threshold=200000)
180 |
181 | # NumPy/CuPy management
182 | if args.cuda:
183 | if not supports_cupy():
184 | print('ERROR: Install CuPy for CUDA support', file=sys.stderr)
185 | sys.exit(-1)
186 | xp = get_cupy()
187 | x = xp.asarray(x)
188 | z = xp.asarray(z)
189 | else:
190 | xp = np
191 | xp.random.seed(args.seed)
192 |
193 | # Build word to index map
194 | src_word2ind = {word: i for i, word in enumerate(src_words)}
195 | trg_word2ind = {word: i for i, word in enumerate(trg_words)}
196 |
197 | # STEP 0: Normalization
198 | embeddings.normalize(x, args.normalize)
199 | embeddings.normalize(z, args.normalize)
200 |
201 | # Build the seed dictionary
202 | src_indices = []
203 | trg_indices = []
204 | if args.init_unsupervised:
205 | if args.verbose:
206 | print('Using unsupervised initialization...')
207 | sim_size = min(x.shape[0], z.shape[0]) if args.unsupervised_vocab <= 0 else min(x.shape[0], z.shape[0], args.unsupervised_vocab)
208 | u, s, vt = xp.linalg.svd(x[:sim_size], full_matrices=False)
209 | xsim = (u*s).dot(u.T)
210 | u, s, vt = xp.linalg.svd(z[:sim_size], full_matrices=False)
211 | zsim = (u*s).dot(u.T)
212 | del u, s, vt
213 | xsim.sort(axis=1)
214 | zsim.sort(axis=1)
215 | embeddings.normalize(xsim, args.normalize)
216 | embeddings.normalize(zsim, args.normalize)
217 | sim = xsim.dot(zsim.T)
218 | if args.csls_neighborhood > 0:
219 | knn_sim_fwd = topk_mean(sim, k=args.csls_neighborhood)
220 | knn_sim_bwd = topk_mean(sim.T, k=args.csls_neighborhood)
221 | sim -= knn_sim_fwd[:, xp.newaxis]/2 + knn_sim_bwd/2
222 | if args.direction == 'forward':
223 | src_indices = xp.arange(sim_size)
224 | trg_indices = sim.argmax(axis=1)
225 | elif args.direction == 'backward':
226 | src_indices = sim.argmax(axis=0)
227 | trg_indices = xp.arange(sim_size)
228 | elif args.direction == 'union':
229 | src_indices = xp.concatenate((xp.arange(sim_size), sim.argmax(axis=0)))
230 | trg_indices = xp.concatenate((sim.argmax(axis=1), xp.arange(sim_size)))
231 | del xsim, zsim, sim
232 | elif args.init_numerals:
233 | if args.verbose:
234 | print('Using numerals as seeds...')
235 | numeral_regex = re.compile('^[0-9]+$')
236 | src_numerals = {word for word in src_words if numeral_regex.match(word) is not None}
237 | trg_numerals = {word for word in trg_words if numeral_regex.match(word) is not None}
238 | numerals = src_numerals.intersection(trg_numerals)
239 | for word in numerals:
240 | src_indices.append(src_word2ind[word])
241 | trg_indices.append(trg_word2ind[word])
242 | elif args.init_identical:
243 | identical = set(src_words).intersection(set(trg_words))
244 | if args.verbose:
245 | print('Using identical strings as seeds...')
246 | print(f'Found {len(identical)} identical strings.')
247 | for word in identical:
248 | src_indices.append(src_word2ind[word])
249 | trg_indices.append(trg_word2ind[word])
250 | else:
251 | f = open(args.init_dictionary, encoding=args.encoding, errors='surrogateescape')
252 | for line in f:
253 | src, trg = line.split()
254 | try:
255 | src_ind = src_word2ind[src]
256 | trg_ind = trg_word2ind[trg]
257 | src_indices.append(src_ind)
258 | trg_indices.append(trg_ind)
259 | except KeyError:
260 | print('WARNING: OOV dictionary entry ({0} - {1})'.format(src, trg), file=sys.stderr)
261 | print(f'Using a dictionary of size {len(src_indices)}.')
262 |
263 | # Read validation dictionary
264 | if args.validation is not None:
265 | f = open(args.validation, encoding=args.encoding, errors='surrogateescape')
266 | validation = collections.defaultdict(set)
267 | oov = set()
268 | vocab = set()
269 | for line in f:
270 | src, trg = line.split()
271 | try:
272 | src_ind = src_word2ind[src]
273 | trg_ind = trg_word2ind[trg]
274 | validation[src_ind].add(trg_ind)
275 | vocab.add(src)
276 | except KeyError:
277 | oov.add(src)
278 | oov -= vocab # If one of the translation options is in the vocabulary, then the entry is not an oov
279 | validation_coverage = len(validation) / (len(validation) + len(oov))
280 |
281 | # Create log file
282 | if args.log:
283 | log = open(args.log, mode='w', encoding=args.encoding, errors='surrogateescape')
284 |
285 | # Allocate memory
286 | xw = xp.empty_like(x)
287 | zw = xp.empty_like(z)
288 | src_size = x.shape[0] if args.vocabulary_cutoff <= 0 else min(x.shape[0], args.vocabulary_cutoff)
289 | trg_size = z.shape[0] if args.vocabulary_cutoff <= 0 else min(z.shape[0], args.vocabulary_cutoff)
290 | simfwd = xp.empty((args.batch_size, trg_size), dtype=dtype)
291 | simbwd = xp.empty((args.batch_size, src_size), dtype=dtype)
292 | if args.validation is not None:
293 | simval = xp.empty((len(validation.keys()), z.shape[0]), dtype=dtype)
294 |
295 | best_sim_forward = xp.full(src_size, -100, dtype=dtype)
296 | src_indices_forward = xp.arange(src_size)
297 | trg_indices_forward = xp.zeros(src_size, dtype=int)
298 | best_sim_backward = xp.full(trg_size, -100, dtype=dtype)
299 | src_indices_backward = xp.zeros(trg_size, dtype=int)
300 | trg_indices_backward = xp.arange(trg_size)
301 | knn_sim_fwd = xp.zeros(src_size, dtype=dtype)
302 | knn_sim_bwd = xp.zeros(trg_size, dtype=dtype)
303 |
304 | # Training loop
305 | best_objective = objective = -100.
306 | it = 1
307 | last_improvement = 0
308 | keep_prob = args.stochastic_initial
309 | t = time.time()
310 | end = not args.self_learning
311 | while True:
312 |
313 | # Increase the keep probability if we have not improve in args.stochastic_interval iterations
314 | if it - last_improvement > args.stochastic_interval:
315 | if keep_prob >= 1.0:
316 | end = True
317 | keep_prob = min(1.0, args.stochastic_multiplier*keep_prob)
318 | last_improvement = it
319 |
320 | # Update the embedding mapping
321 | if args.orthogonal or not end: # orthogonal mapping
322 | u, s, vt = xp.linalg.svd(z[trg_indices].T.dot(x[src_indices]))
323 | w = vt.T.dot(u.T)
324 | x.dot(w, out=xw)
325 | zw[:] = z
326 | elif args.unconstrained: # unconstrained mapping
327 | x_pseudoinv = xp.linalg.inv(x[src_indices].T.dot(x[src_indices])).dot(x[src_indices].T)
328 | w = x_pseudoinv.dot(z[trg_indices])
329 | x.dot(w, out=xw)
330 | zw[:] = z
331 | else: # advanced mapping
332 |
333 | # TODO xw.dot(wx2, out=xw) and alike not working
334 | xw[:] = x
335 | zw[:] = z
336 |
337 | # STEP 1: Whitening
338 | def whitening_transformation(m):
339 | u, s, vt = xp.linalg.svd(m, full_matrices=False)
340 | return vt.T.dot(xp.diag(1/s)).dot(vt)
341 | if args.whiten:
342 | wx1 = whitening_transformation(xw[src_indices])
343 | wz1 = whitening_transformation(zw[trg_indices])
344 | xw = xw.dot(wx1)
345 | zw = zw.dot(wz1)
346 |
347 | # STEP 2: Orthogonal mapping
348 | wx2, s, wz2_t = xp.linalg.svd(xw[src_indices].T.dot(zw[trg_indices]))
349 | wz2 = wz2_t.T
350 | xw = xw.dot(wx2)
351 | zw = zw.dot(wz2)
352 |
353 | # STEP 3: Re-weighting
354 | xw *= s**args.src_reweight
355 | zw *= s**args.trg_reweight
356 |
357 | # STEP 4: De-whitening
358 | if args.src_dewhiten == 'src':
359 | xw = xw.dot(wx2.T.dot(xp.linalg.inv(wx1)).dot(wx2))
360 | elif args.src_dewhiten == 'trg':
361 | xw = xw.dot(wz2.T.dot(xp.linalg.inv(wz1)).dot(wz2))
362 | if args.trg_dewhiten == 'src':
363 | zw = zw.dot(wx2.T.dot(xp.linalg.inv(wx1)).dot(wx2))
364 | elif args.trg_dewhiten == 'trg':
365 | zw = zw.dot(wz2.T.dot(xp.linalg.inv(wz1)).dot(wz2))
366 |
367 | # STEP 5: Dimensionality reduction
368 | if args.dim_reduction > 0:
369 | xw = xw[:, :args.dim_reduction]
370 | zw = zw[:, :args.dim_reduction]
371 |
372 | # Self-learning
373 | if end:
374 | break
375 | else:
376 | # Update the training dictionary
377 | sims = np.zeros((src_size, trg_size), dtype=dtype)
378 | if args.direction in ('forward', 'union'):
379 | if args.csls_neighborhood > 0:
380 | for i in range(0, trg_size, simbwd.shape[0]):
381 | j = min(i + simbwd.shape[0], trg_size)
382 | zw[i:j].dot(xw[:src_size].T, out=simbwd[:j-i])
383 | knn_sim_bwd[i:j] = topk_mean(simbwd[:j-i], k=args.csls_neighborhood, inplace=True)
384 | for i in range(0, src_size, simfwd.shape[0]):
385 | j = min(i + simfwd.shape[0], src_size)
386 | xw[i:j].dot(zw[:trg_size].T, out=simfwd[:j-i])
387 | simfwd[:j-i].max(axis=1, out=best_sim_forward[i:j])
388 | simfwd[:j-i] -= knn_sim_bwd/2 # Equivalent to the real CSLS scores for NN
389 | simfwd[:j-i] = dropout(simfwd[:j-i], 1 - keep_prob)
390 | if not args.lat_var:
391 | # we get a dimension mismatch here as lat_var may produce fewer seeds
392 | simfwd[:j-i].argmax(axis=1, out=trg_indices_forward[i:j])
393 | sims[i:j] = simfwd
394 | if args.lat_var:
395 | # TODO check if we can save memory by not storing a large sims matrix
396 | src_indices_forward, trg_indices_forward = lat_var.lat_var(
397 | xp, sims, args.n_similar, args.n_repeats, args.batch_size, args.asym)
398 | if args.direction in ('backward', 'union'):
399 | if args.csls_neighborhood > 0:
400 | for i in range(0, src_size, simfwd.shape[0]):
401 | j = min(i + simfwd.shape[0], src_size)
402 | xw[i:j].dot(zw[:trg_size].T, out=simfwd[:j-i])
403 | knn_sim_fwd[i:j] = topk_mean(simfwd[:j-i], k=args.csls_neighborhood, inplace=True)
404 | for i in range(0, trg_size, simbwd.shape[0]):
405 | j = min(i + simbwd.shape[0], trg_size)
406 | zw[i:j].dot(xw[:src_size].T, out=simbwd[:j-i])
407 | simbwd[:j-i].max(axis=1, out=best_sim_backward[i:j])
408 | simbwd[:j-i] -= knn_sim_fwd/2 # Equivalent to the real CSLS scores for NN
409 | simbwd[:j-i] = dropout(simbwd[:j-i], 1 - keep_prob)
410 | if not args.lat_var:
411 | simbwd[:j-i].argmax(axis=1,out=src_indices_backward[i:j])
412 | sims[i:j] = simbwd
413 | if args.lat_var:
414 | # swap the order of the indices
415 | trg_indices_backward, src_indices_backward = lat_var.lat_var(
416 | xp, sims, args.n_similar, args.n_repeats, args.batch_size, args.asym)
417 | if args.direction == 'forward':
418 | src_indices = src_indices_forward
419 | trg_indices = trg_indices_forward
420 | elif args.direction == 'backward':
421 | src_indices = src_indices_backward
422 | trg_indices = trg_indices_backward
423 | elif args.direction == 'union':
424 | src_indices = xp.concatenate((src_indices_forward, src_indices_backward))
425 | trg_indices = xp.concatenate((trg_indices_forward, trg_indices_backward))
426 | # elif args.direction == 'intersection':
427 | # fwd_pairs = zip(src_indices_forward, trg_indices_forward)
428 | # bwd_pairs = zip(src_indices_backward, trg_indices_backward)
429 | # src_indices, trg_indices = zip(*set(fwd_pairs).intersection(bwd_pairs))
430 | # src_indices, trg_indices = xp.array(src_indices), xp.array(trg_indices)
431 |
432 | # Objective function evaluation
433 | if args.direction == 'forward':
434 | objective = xp.mean(best_sim_forward).tolist()
435 | elif args.direction == 'backward':
436 | objective = xp.mean(best_sim_backward).tolist()
437 | elif args.direction == 'union':
438 | objective = (xp.mean(best_sim_forward) + xp.mean(best_sim_backward)).tolist() / 2
439 | if objective - best_objective >= args.threshold:
440 | last_improvement = it
441 | best_objective = objective
442 |
443 | # Accuracy and similarity evaluation in validation
444 | if args.validation is not None:
445 | src = list(validation.keys())
446 | xw[src].dot(zw.T, out=simval)
447 | nn = asnumpy(simval.argmax(axis=1))
448 | accuracy = np.mean([1 if nn[i] in validation[src[i]] else 0 for i in range(len(src))])
449 | similarity = np.mean([max([simval[i, j].tolist() for j in validation[src[i]]]) for i in range(len(src))])
450 |
451 | # Logging
452 | duration = time.time() - t
453 | if args.verbose:
454 | print(file=sys.stderr)
455 | print('ITERATION {0} ({1:.2f}s)'.format(it, duration), file=sys.stderr)
456 | print('\t- Objective: {0:9.4f}%'.format(100 * objective), file=sys.stderr)
457 | print('\t- Drop probability: {0:9.4f}%'.format(100 - 100*keep_prob), file=sys.stderr)
458 | if args.validation is not None:
459 | print('\t- Val. similarity: {0:9.4f}%'.format(100 * similarity), file=sys.stderr)
460 | print('\t- Val. accuracy: {0:9.4f}%'.format(100 * accuracy), file=sys.stderr)
461 | print('\t- Val. coverage: {0:9.4f}%'.format(100 * validation_coverage), file=sys.stderr)
462 | sys.stderr.flush()
463 | if args.log is not None:
464 | val = '{0:.6f}\t{1:.6f}\t{2:.6f}'.format(
465 | 100 * similarity, 100 * accuracy, 100 * validation_coverage) if args.validation is not None else ''
466 | print('{0}\t{1:.6f}\t{2}\t{3:.6f}'.format(it, 100 * objective, val, duration), file=log)
467 | log.flush()
468 |
469 | t = time.time()
470 | it += 1
471 |
472 | if args.test_dict:
473 | # save the embeddings for evaluation
474 | with open(args.src_output, mode='w', encoding=args.encoding, errors='surrogateescape') as srcfile,\
475 | open(args.trg_output, mode='w', encoding=args.encoding, errors='surrogateescape') as trgfile:
476 | embeddings.write(src_words, xw, srcfile)
477 | embeddings.write(trg_words, zw, trgfile)
478 |
479 | # EVALUATING TRANSLATION
480 | print('Evaluating translation...')
481 |
482 | # we skip length normalization here
483 |
484 | # Read dictionary and compute coverage
485 | f = open(args.test_dict, encoding=args.encoding,
486 | errors='surrogateescape')
487 | src2trg = collections.defaultdict(set)
488 | oov = set()
489 | vocab = set()
490 | for line in f:
491 | src, trg = line.split()
492 | try:
493 | src_ind = src_word2ind[src]
494 | trg_ind = trg_word2ind[trg]
495 | src2trg[src_ind].add(trg_ind)
496 | vocab.add(src)
497 | except KeyError:
498 | oov.add(src)
499 | src = list(src2trg.keys())
500 | oov -= vocab # If one of the translation options is in the vocabulary, then the entry is not an oov
501 | coverage = len(src2trg) / (len(src2trg) + len(oov))
502 |
503 | BATCH_SIZE = 500
504 |
505 | # Find translations
506 | translation = collections.defaultdict(int)
507 |
508 | # we just use nearest neighbour for retrieval
509 | for i in range(0, len(src), BATCH_SIZE):
510 | j = min(i + BATCH_SIZE, len(src))
511 | similarities = xw[src[i:j]].dot(zw.T)
512 | nn = similarities.argmax(axis=1).tolist()
513 | for k in range(j - i):
514 | translation[src[i + k]] = nn[k]
515 |
516 | # Compute accuracy
517 | accuracy = np.mean(
518 | [1 if translation[i] in src2trg[i] else 0 for i in src])
519 | print('Coverage:{0:7.2%} Accuracy:{1:7.2%}'.format(coverage, accuracy))
520 |
521 | # Write mapped embeddings
522 | with open(args.src_output, mode='w', encoding=args.encoding, errors='surrogateescape') as srcfile, \
523 | open(args.trg_output, mode='w', encoding=args.encoding, errors='surrogateescape') as trgfile:
524 | embeddings.write(src_words, xw, srcfile)
525 | embeddings.write(trg_words, zw, trgfile)
526 |
527 |
528 | if __name__ == '__main__':
529 | main()
530 |
--------------------------------------------------------------------------------
/normalize_embeddings.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2016-2018 Mikel Artetxe
2 | #
3 | # This program is free software: you can redistribute it and/or modify
4 | # it under the terms of the GNU General Public License as published by
5 | # the Free Software Foundation, either version 3 of the License, or
6 | # (at your option) any later version.
7 | #
8 | # This program is distributed in the hope that it will be useful,
9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | # GNU General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program. If not, see .
15 |
16 | import embeddings
17 |
18 | import argparse
19 | import sys
20 |
21 |
22 | def main():
23 | # Parse command line arguments
24 | parser = argparse.ArgumentParser(description='Normalize word embeddings')
25 | parser.add_argument('actions', choices=['unit', 'center', 'unitdim', 'centeremb'], nargs='*', default=[], help='the actions to perform in order')
26 | parser.add_argument('-i', '--input', default=sys.stdin.fileno(), help='the input word embedding file (defaults to stdin)')
27 | parser.add_argument('-o', '--output', default=sys.stdout.fileno(), help='the output word embedding file (defaults to stdout)')
28 | parser.add_argument('--encoding', default='utf-8', help='the character encoding for input/output (defaults to utf-8)')
29 | args = parser.parse_args()
30 |
31 | # Read input embeddings
32 | f = open(args.input, encoding=args.encoding, errors='surrogateescape')
33 | words, matrix = embeddings.read(f)
34 |
35 | # Perform normalization actions
36 | embeddings.normalize(matrix, args.actions)
37 |
38 | # Write normalized embeddings
39 | f = open(args.output, mode='w', encoding=args.encoding, errors='surrogateescape')
40 | embeddings.write(words, matrix, f)
41 |
42 |
43 | if __name__ == '__main__':
44 | main()
45 |
--------------------------------------------------------------------------------
/reproduce_emnlp2018.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #
3 | # Copyright (C) 2019 Sebastian Ruder
4 | #
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 | #
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU General Public License for more details.
14 | #
15 | # You should have received a copy of the GNU General Public License
16 | # along with this program. If not, see .
17 |
18 | ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
19 | DATA="$ROOT/data"
20 | OUTPUT="$ROOT/output/"
21 |
22 | METHOD_COUNT=1
23 | METHOD_NAMES=('Latent-variable')
24 | METHOD_TRAIN_ARGS=('--ruder_emnlp2018')
25 |
26 | LANGUAGE_COUNT=3
27 | LANGUAGE_SRCS=('en' 'en' 'en')
28 | LANGUAGE_TRGS=('it' 'de' 'fi')
29 | LANGUAGE_NAMES=('ENGLISH-ITALIAN' 'ENGLISH-GERMAN' 'ENGLISH-FINNISH')
30 |
31 | DICTIONARY_COUNT=4
32 | DICTIONARY_IDS=('5000' '25' 'numerals' 'identical')
33 | DICTIONARY_NAMES=('5,000 WORD DICTIONARY' '25 WORD DICTIONARY' 'NUMERAL DICTIONARY' 'IDENTICAL STRINGS DICTIONARY')
34 | DICTIONARY_SIZES=('5000' '25' '0' '0')
35 | DICTIONARY_TRAIN_ARGS=('' '' '--init_numerals' '--init_identical')
36 |
37 | SIMILARITY_DATASET_COUNT=2
38 | SIMILARITY_DATASET_IDS=('mws353' 'rg65')
39 | SIMILARITY_DATASET_NAMES=('MWS353' 'RG65')
40 |
41 | for ((i = 0; i < $LANGUAGE_COUNT; i++))
42 | do
43 | src=${LANGUAGE_SRCS[$i]}
44 | trg=${LANGUAGE_TRGS[$i]}
45 | echo '--------------------------------------------------------------------------------'
46 | echo ${LANGUAGE_NAMES[$i]}
47 | echo '--------------------------------------------------------------------------------'
48 | for ((j = 0; j < $DICTIONARY_COUNT; j++))
49 | do
50 | echo ${DICTIONARY_NAMES[$j]}
51 | for ((k = 0; k < $METHOD_COUNT; k++))
52 | do
53 | embedding_dir="$DATA/embeddings"
54 | output_dir="$OUTPUT/$src-$trg/${DICTIONARY_IDS[$j]}/${METHOD_NAMES[$k]}"
55 | mkdir -p "$output_dir"
56 | # adding cuda arguments; add verbose
57 | args="${METHOD_TRAIN_ARGS[$k]} ${DICTIONARY_TRAIN_ARGS[$j]} --precision fp32 -v"
58 | head -${DICTIONARY_SIZES[$j]} "$DATA/dictionaries/$src-$trg.train.shuf.txt" | python3 "$ROOT/map_embeddings.py" "$embedding_dir/$src.emb.txt" "$embedding_dir/$trg.emb.txt" "$output_dir/$src.emb.txt" "$output_dir/$trg.emb.txt" $args
59 | # evaluate translation with both nearest neighbour and CSLS retrieval
60 | echo -n " - ${METHOD_NAMES[$k]} | Translation NN"
61 | python3 "$ROOT/eval_translation.py" --retrieval nn -d "$DATA/dictionaries/$src-$trg.test.txt" "$output_dir/$src.emb.txt" "$output_dir/$trg.emb.txt" | grep -Eo ':[^:]+%' | tail -1 | tr -d '\n'
62 | echo -n " - ${METHOD_NAMES[$k]} | Translation CSLS"
63 | python3 "$ROOT/eval_translation.py" --retrieval csls -d "$DATA/dictionaries/$src-$trg.test.txt" "$output_dir/$src.emb.txt" "$output_dir/$trg.emb.txt" | grep -Eo ':[^:]+%' | tail -1 | tr -d '\n'
64 | for ((l = 0; l < $SIMILARITY_DATASET_COUNT; l++))
65 | do
66 | dataset="$DATA/similarity/$src-$trg.${SIMILARITY_DATASET_IDS[$l]}.txt"
67 | if [ -f "$dataset" ]
68 | then
69 | echo -n " ${SIMILARITY_DATASET_NAMES[$l]}"
70 | python3 "$ROOT/eval_similarity.py" -l --backoff 0 "$output_dir/$src.emb.txt" "$output_dir/$trg.emb.txt" -i "$dataset" | grep -Eo ':[^:]+%' | tail -1 | tr -d '\n'
71 | fi
72 | done
73 | echo
74 | done
75 | done
76 | echo
77 | done
78 |
--------------------------------------------------------------------------------