diff --git a/README.md b/README.md index e88e5012fffa4faaeef9758c037f11b0f0e4b960..f056183d0ef0cc393b363bb69cb1c1bb1d472ab0 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,13 @@ [COMPRISE](https://www.compriseh2020.eu) library for weakly supervised training of Speech-to-Text (STT) models -This initial version of the library provides two main components which represent the two approaches proposed in COMPRISE, namely +This library provides three main components which represent the approaches proposed in COMPRISE, namely 1. STT Error Detection driven Training (Err2Unk) 2. Weakly Supervised Training based on Dialogue States +3. Confusion Network based Language Model Training (CN2LM) -These initial library components focus on obtaining reliable transcriptions of un-transcribed speech data which can be used for training both STT Acoustic Model (AM) and Language Model (LM). It can be any type of AM, although we choose the state-of-the-art [Chain](https://kaldi-asr.org/doc/chain.html) models in our examples. Statistical n-gram LMs are chosen over other possible LMs to support limited data scenarios. +The first two components focus on obtaining reliable transcriptions of un-transcribed speech data which can be used for training both STT Acoustic Model (AM) and Language Model (LM). It can be any type of AM, although we choose the state-of-the-art [Chain](https://kaldi-asr.org/doc/chain.html) models in our examples. The third component features training of statistical n-gram LM and Recurrent Neural Network (RNN) LM from alternate and uncertain STT hypotheses obtained on un-transcribed speech data. -Readers interested in the high level design and experimental evaluation of these two components are directed to the [COMPRISE D4.2 deliverable report](https://www.compriseh2020.eu/deliverables/). This README provides details on typical usage of these two components. +Readers interested in the high level design and experimental evaluation of these two components are directed to the [COMPRISE D4.2 and D4.4 deliverable reports](https://www.compriseh2020.eu/deliverables/). This README provides details on typical usage of these components. ---- @@ -16,6 +17,8 @@ Readers interested in the high level design and experimental evaluation of these * [Typical Usage Steps](#typical-usage-steps) - [Err2Unk based training](#err2unk-based-training) - [Dialogue State based training](#dialogue-state-based-training) + - [CN2LM training](#cn2lm-training) +* [License](#license) ---- @@ -30,11 +33,14 @@ Readers interested in the high level design and experimental evaluation of these - Err2Unk based training requires: - Python 3.X (Python 2.7 not supported.) - Python sklearn library - - [Keras v2.3.1](https://keras.io/) and [Tensorflow v2.0.0](https://www.tensorflow.org) Python libraries to train neural network models for STT error detection. + - [Keras v2.3.1](https://keras.io/) and [Tensorflow v2.0.0](https://www.tensorflow.org) Python libraries to train neural network models for STT error detection. (An upcoming version will move this to Pytorch.) - the [kenlm](https://github.com/kpu/kenlm) Python module to extract language model related features for error detector. - Dialogue state based training requires: - the [SRILM](http://www.speech.sri.com/projects/srilm/) tool. If you have installed Kaldi, you can install the SRILM tool with the *tools/extras/install\_srilm.sh* script in your Kaldi installation. - speech dataset from a human-machine dialogue system where a dialog corresponding to each human utterance is already available, for example the [Let's Go dataset](https://dialrc.github.io/LetsGoDataset/). One could also use human-human conversations or any other speech dataset with any kind of weak (but relevant) utterance level labels. +- CN2LM training requires: + - [Numpy 1.19](https://numpy.org) + - [Pytorch 1.5.1](https://pytorch.org) to train CN2LM RNN version. ---- @@ -241,3 +247,84 @@ Dialog state based weakly supervised training of STT models will typically go th - Train new AM and LM on combined data directory using a Kaldi recipe similar to Step 1. </details> + +### CN2LM training +CN2LM training will typically go through the following steps. + +(Click on individual step for usage details.) + +<details> +<summary>Step 1. Train seed STT models</summary> + +- Supervised training data with reliable speech-transcript pairs are used to train the seed AM and LM. (Note that this step can be skipped if you already have pre-trained AM and LM). +- A sample Kaldi recipe to train the seed AM and LM on a subset of the [Let's Go dataset](https://dialrc.github.io/LetsGoDataset/) is made available in the [egs/](egs) directory. + +</details> + +<details> +<summary>Step 2. Prepare Confusion Networks</summary> + +- The seed AM and LM are used to decode the unsupervised speech and dev set into STT lattices. (Sample script in [egs/local/](egs/local) if you are relying on sample recipe from Step 1.) +- Obtain STT confusion networks from the lattices decoded on the unsupervised speech and dev set. The COMPRISE library assumes confusion networks are in Kaldi sausage format. Assuming your lattices are generated by Kaldi (as *lat.\*.gz*), you can use our script to generate STT confusion networks as follows: + + >`bash local/err2unk/getSaus.sh lattice_dir graph_dir lm_wt` + + 'graph_dir' is the one used by the Kaldi decoder, + 'lm_wt' is the LM weight which gives the best dev set WER + + Note that STT confusion networks, aka sausages, are generated in *<lattice_dir>/sau/* directory, referred as 'saus_dir' in the next steps. + +</details> + + +<details> +<summary>Step 3. Train CN2LM 3-gram LM</summary> + +- A 3-gram LM can be trained on the combined supervised training speech transcripts and confusion networks obtained on the unsupervised speech as follows: + + >`python local/cn2lm/ngramlm/build_cn2lm_arpa.py asr_vocab_file sup_text unsup_saus_dir out_3glm_dir` + + 'asr_vocab_file' is the vocabulary following [Kaldi's words.txt format](https://kaldi-asr.org/doc/data_prep.html#data_prep_lang_contents) + 'sup_text' is the supervised [reference transcription in Kaldi format](https://kaldi-asr.org/doc/data_prep.html#data_prep_data_yourself) + 'unsup_saus_dir' is the unsupervised speech confusion networks directory generated in previous step + 'out_3glm_dir' is the output directory to store the 3-gram arpa LM + + Note that this CN2LM component has built-in features to train interpolated modified-KN smoothed 3-gram LMs only on reference transcriptions or only on confusion networks. Moreover, it can also make use of error predictions on confusion networks to prune out the confusion network in non error predicted regions. Check *local/cn2lm/ngramlm/build_cn2lm_arpa.py* for relevant modifications. Moreover, it has features to prune the maximum number of arcs seen in confusion bins. Check global `MAX_ARCS` in *local/cn2lm/ngramlm/data.py*. + +</details> + +<details> +<summary>Step 4. Train CN2LM RNN LM</summary> + +- An RNN LM can be trained on the combined supervised training speech transcripts and confusion networks obtained on the unsupervised speech as follows: + + >`python local/cn2lm/rnnlm/train_cn2lm_rnn.py asr_vocab_file sup_text unsup_saus_dir dev_saus_dir dev_text out_rnnlm_dir` + + 'asr_vocab_file' is the vocabulary following [Kaldi's words.txt format](https://kaldi-asr.org/doc/data_prep.html#data_prep_lang_contents) + 'sup_text' is the supervised [reference transcription in Kaldi format](https://kaldi-asr.org/doc/data_prep.html#data_prep_data_yourself) + 'unsup_saus_dir' is the unsupervised speech confusion networks directory generated in previous step + 'dev_saus_dir' is the dev set confusion networks directory generated in previous step + 'out_rnnlm_dir' is the output directory to store the RNN LM model in [Pytorch's pth format](https://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-loading-model-for-inference) + + Note that this CN2LM component has built in features to train LSTM or GRU RNN LM, sharing of input-output word embedding layers and support for different pooling schemes over confusion bin arcs. Moreover, it has features to prune the maximum number of arcs seen in confusion bins. Check the globals defined in *local/cn2lm/rnnlm/models.py* and *local/cn2lm/rnnlm/data.py*. + +- Support is provided to convert CN2LM GRU RNN LM to Kaldi RNN LM format as follows: + + >`bash local/cn2lm/rnnlm/kaldi_support/pytorch_rnnlm_to_kaldi.sh asr_vocab_file kaldi_gru_lm_template_file pytorch_model out_kaldi_model_dir` + + 'asr_vocab_file' is the vocabulary following [Kaldi's words.txt format](https://kaldi-asr.org/doc/data_prep.html#data_prep_lang_contents) + 'kaldi_gru_lm_template_file' is Kaldi nnet3 format template file. A template for a single layer RNN LM with shared input-output embeddings and Pytorch GRU cell is provided in *local/cn2lm/rnnlm/kaldi_support/torch_gru.raw.tmp.txt* + 'pytorch_model' is the Pytorch format RNN LM trained in the previous step + 'out_kaldi_model_dir' will store Kaldi compatible RNN LM files + + Note that this step currently supports only single layer RNN LM with shared input-output embeddings and Pytorch GRU cell. Support for more RNN layers, LSTM cells, etc can be easily added if a suitable `kaldi_gru_lm_template_file` is created. + +</details> + +### License +Each of the components in COMPRISE library for weakly supervised training of Speech-to-Text (STT) models have been separately licensed. Refer to COPYING file in individual components: +- [CN2LM](local/cn2lm/COPYING) +- [DSLM](local/dsLMs/COPYING) +- [Err2Unk](local/err2unk/COPYING) + +The source code headers for each file specifies the individual authors and source material for that file as well the corresponding copyright notice. diff --git a/local/cn2lm/COPYING b/local/cn2lm/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..be3f7b28e564e7dd05eaf59d64adba1a4065ac0e --- /dev/null +++ b/local/cn2lm/COPYING @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +<https://www.gnu.org/licenses/>. diff --git a/local/cn2lm/ngramlm/build_cn2lm_arpa.py b/local/cn2lm/ngramlm/build_cn2lm_arpa.py new file mode 100755 index 0000000000000000000000000000000000000000..c2b4905ed3dcf35633eb4d3fa58a0a5ccfe8709f --- /dev/null +++ b/local/cn2lm/ngramlm/build_cn2lm_arpa.py @@ -0,0 +1,109 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- + +# Copyright © 2021 INRIA (Imran Sheikh) +# AGPL-3.0-only or AGPL-3.0-or-later (https://www.gnu.org/licenses/agpl-3.0.txt) + +# This file is part of CN2LM. +# +# CN2LM is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# CN2LM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with CN2LM. If not, see <https://www.gnu.org/licenses/>. + + +import argparse, os, sys, numpy + +from data import DataLoader +from cn2lm_trig import CN2LM + +parser = argparse.ArgumentParser() +parser.add_argument('asr_vocab_file', type=str, help='Path to ASR words.txt file') +parser.add_argument('sup_text', type=str, help='Path to sup text transcriptions') +parser.add_argument('unsup_saus_dir', type=str, help='Path to unsup saus dir') +parser.add_argument('out_dir', type=str, help='output dir') +args = parser.parse_args() + +if not os.path.isfile(args.asr_vocab_file): + raise IOError(args.asr_vocab_file) + +if not os.path.isfile(args.sup_text): + raise IOError(args.sup_text) + +if not os.path.isdir(args.unsup_saus_dir): + raise IOError(args.unsup_saus_dir) + +if not os.path.isdir(args.out_dir): + raise IOError(args.out_dir) + +def eprint(*args, **kwargs): + print(*args, file=sys.stderr, **kwargs) + +data = DataLoader(args.asr_vocab_file, args.sup_text, args.unsup_saus_dir) +#data = DataLoader(args.asr_vocab_file, args.sup_text, None) # support to train only on labeled reference +#data = DataLoader(args.asr_vocab_file, None, args.unsup_saus_dir) # support to train only on sausages +#data = DataLoader(args.asr_vocab_file, args.sup_text, args.unsup_saus_dir, args.unsup_errpreds) # support to incorporate error predictions +cnlm = CN2LM(data) + +with open(args.out_dir + '/cn2lm_3g.arpa', 'w') as fp: + fp.write("\\data\\\n") + fp.write("ngram 1="+ str(len(cnlm.ug_prob)) + "\n") + bg_cnt = 0 + for h in cnlm.bg_prob.keys(): + for w in cnlm.bg_prob[h].keys(): + p = cnlm.bg_prob[h][w] + if p != 0.0: + bg_cnt += 1 + fp.write("ngram 2=" + str(bg_cnt)+ "\n") + tg_cnt = 0 + for prev_bg_key in cnlm.tg_prob.keys(): + for j in cnlm.tg_prob[prev_bg_key].keys(): + p = cnlm.tg_prob[prev_bg_key][j] + if p != 0.0: + tg_cnt += 1 + fp.write("ngram 3=" + str(tg_cnt)+ "\n") + fp.write("\n\\1-grams:\n") + for w in cnlm.ug_prob.keys(): + p = cnlm.ug_prob[w] + if p == 0.0: + log_p = -99 + else: + log_p = numpy.log10(p) + if w in cnlm.ug_bow.keys(): + log_bow = numpy.log10(cnlm.ug_bow[w]) + fp.write("%f\t%s\t%f\n" % (log_p, w, log_bow)) + else: + fp.write("%f\t%s\n" % (log_p, w)) + fp.write("\n\\2-grams:\n") + for h in cnlm.bg_prob.keys(): + for w in cnlm.bg_prob[h].keys(): + p = cnlm.bg_prob[h][w] + if p == 0.0: + log_p = -99 + else: + log_p = numpy.log10(p) + + if h in cnlm.bg_bow and w in cnlm.bg_bow[h]: + log_bow = numpy.log10(cnlm.bg_bow[h][w]) + fp.write("%f\t%s %s\t%f\n" % (log_p, h, w, log_bow)) + else: + fp.write("%f\t%s %s\n" % (log_p, h, w)) + fp.write("\n\\3-grams:\n") + for prev_bg_key in cnlm.tg_prob.keys(): + h,i=prev_bg_key.split('-') + for j in cnlm.tg_prob[prev_bg_key].keys(): + p = cnlm.tg_prob[prev_bg_key][j] + if p == 0.0: + log_p = -99 + else: + log_p = numpy.log10(p) + fp.write("%f\t%s %s %s\n" % (log_p, cnlm.vocab_list[int(h)], cnlm.vocab_list[int(i)], j)) + fp.write("\n\\end\\\n") diff --git a/local/cn2lm/ngramlm/cn2lm_trig.py b/local/cn2lm/ngramlm/cn2lm_trig.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c623b01cd22648acca980a6df904c01419a3e4 --- /dev/null +++ b/local/cn2lm/ngramlm/cn2lm_trig.py @@ -0,0 +1,401 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- + +# Copyright © 2021 INRIA (Imran Sheikh) +# AGPL-3.0-only or AGPL-3.0-or-later (https://www.gnu.org/licenses/agpl-3.0.txt) + +# This file is part of CN2LM. +# +# CN2LM is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# CN2LM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with CN2LM. If not, see <https://www.gnu.org/licenses/>. + +import time, os, re, sys +import numpy +from tqdm import tqdm +from poisson_binomial import PB, PK_UPPER_LIMIT + +NO_DP = 1234.56789 +NO_E_CNT = NO_DP +SKIP_SYM_LIST = ['<eps>', '#0'] +UG_SKIP_SYM_LIST = ['<eps>', '#0', '<s>'] # skip in unigram prob calc + +class CN2LM: + def __init__(self, data): + self.data = data + self.vocab_dict = data.vocab_dict + self.vocab_list = data.vocab_list + self.N = len(self.vocab_dict) + + ### step 1 of 3.2 of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + ### step 1 of 4.6 of https://www.aclweb.org/anthology/P14-1072.pdf + print('Computing 3g pks ...') + self.tg_pk, self.bos_bg_pk = self.compute_tg_pks(data) # computed from scores of 3g paths in sausages + print('Computing 3g PB distributions ...') + self.tg_pb = self.compute_pb_distributions() # poisson-binomial count distribution + + print('Computing 3g expected counts ...') + ### E(cw) in step 2 of 3.2 of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + self.tg_E_cnt = self.compute_tg_E_cnt() # considering it as highest n-gram order + + ### E_nr (r>4) and E_nr+ reqd for step 1 of 4.6 of https://www.aclweb.org/anthology/P14-1072.pdf + ### other probs reqd in step 2 of 3.2 of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + # to rely on following function calls on ug_pb bg_pb + + ### step 3 of 4.6 of https://www.aclweb.org/anthology/P14-1072.pdf , Note: lower order is unigram in our case + ### step 3 of 3.2 of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/, Note lower order is unigram in our case + print('Computing 2g expected counts and PB distributions...') + self.bg_pb, self.bg_E_cnt = self.compute_bg_E_cnt() + print('Computing 1g expected counts and PB distributions...') + self.ug_pb, self.ug_E_cnt = self.compute_ug_E_cnt() + + print('Computing discount parameters...') + ug_E_nr = numpy.zeros(5) # E[n_r], where r in (0, 1, 2, 3, 4) + bg_E_nr = numpy.zeros(5) + tg_E_nr = numpy.zeros(5) + for r in range(5): + ug_E_nr[r] = self.compute_ug_E_nr(r) + bg_E_nr[r] = self.compute_bg_E_nr(r) + tg_E_nr[r] = self.compute_tg_E_nr(r) + + ### step 2 of 4.6 of https://www.aclweb.org/anthology/P14-1072.pdf + ### step 4 of 3.2 of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ + self.tg_D1, self.tg_D2, self.tg_D3 = self.compute_mod_kn_discounts(tg_E_nr) + self.bg_D1, self.bg_D2, self.bg_D3 = self.compute_mod_kn_discounts(bg_E_nr) + self.ug_D1, self.ug_D2, self.ug_D3 = self.compute_mod_kn_discounts(ug_E_nr) + self.tg_DP = self.compute_mod_kn_avg_discount(self.tg_pb, self.tg_D1, self.tg_D2, self.tg_D3) + self.bg_DP = self.compute_mod_kn_avg_discount(self.bg_pb, self.bg_D1, self.bg_D2, self.bg_D3) + self.ug_DP = self.compute_mod_kn_avg_discount(self.ug_pb, self.ug_D1, self.ug_D2, self.ug_D3) + + print('Computing ngram probs and bows...') + ### step 5 3.2 of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + self.ug_prob = self.compute_ug_probs() + self.disc_bg_E_cnt = self.compute_disc_bg_E_cnt() + self.ug_bow, self.bg_E_cnt_sum_for_prev_word = self.compute_ug_bow() + self.bg_prob = self.compute_bg_prob() + self.disc_tg_E_cnt = self.compute_disc_tg_E_cnt() + self.bg_bow, self.tg_E_cnt_sum_for_prev_bg = self.compute_bg_bow() + self.tg_prob = self.compute_tg_prob() + + def compute_tg_pks(self, data): + tg_pk = {} # score of kth occurence of trigrams + bos_bg_pk = {} + + bi = 0 + for batch in tqdm(data.yield_trig_batch(),total=data.total_trig_batches): + start_time = time.time() + for binngram in batch: + t=0 + for h, h_arc_scr in binngram[t]: + for i, i_arc_scr in binngram[t+1]: + if h == self.vocab_dict['<s>']: + bg_scr = h_arc_scr * i_arc_scr + key = i + try: + bos_bg_pk[key].append(bg_scr) + except: + bos_bg_pk[key] = [] + bos_bg_pk[key].append(bg_scr) + for j, j_arc_scr in binngram[t+2]: + tg_scr = h_arc_scr * i_arc_scr * j_arc_scr + key = "{}-{}-{}".format(h,i,j) + try: + tg_pk[key].append(tg_scr) + except: + tg_pk[key] = [] + tg_pk[key].append(tg_scr) + bi += 1 + #print("%d\t%.4f" % (bi, time.time() - start_time)) + return tg_pk, bos_bg_pk + + def compute_pb_distributions(self): + tg_pb = {} # poisson-binomial count distribution for trigrams + for k,v in tqdm(self.tg_pk.items()): + tg_pb[k] = PB(v) + return tg_pb + + def compute_tg_E_nr(self, r): # as per (26) of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + E_nr = 0.0 + for key in self.tg_pb.keys(): + pb = self.tg_pb[key] + E_nr += self.pb_prob_cnt_eq_r(pb,r) # as per 26 E[n_r] = \sum_{all_n-gram} p(c(n-gram) = r), for highest order + return E_nr + + def compute_bg_E_nr(self, r): # implied from (30) of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + E_nr = 0.0 + for key in self.bg_pb.keys(): + pb = self.bg_pb[key] + E_nr += self.pb_prob_cnt_eq_r(pb,r) #E[n_r(w_j)] = E[n_r(* w_j)] = \sum_{i} p(c(w_i w_j) = r) + return E_nr + + def compute_ug_E_nr(self, r): # implied from (30) of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + E_nr = 0.0 + for key in self.ug_pb.keys(): + pb = self.ug_pb[key] + E_nr += self.pb_prob_cnt_eq_r(pb,r) #E[n_r(w_j)] = E[n_r(* w_j)] = \sum_{i} p(c(w_i w_j) = r) + return E_nr + + def compute_tg_E_cnt(self): # considering it as highest n-gram order, see (23) and (38) of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + tg_E_cnt = {} + for k,v in tqdm(self.tg_pk.items()): + tg_E_cnt[k] = sum(v) + return tg_E_cnt + + def compute_bg_E_cnt(self): # from (35) and (38) of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + bg_E_cnt = {} + bg_pks = {} + bg_pb = {} + for key in self.tg_pb.keys(): + _h, bg_key = key.split('-',1) + pb = self.tg_pb[key] + pk = self.pb_prob_cnt_ge_r(pb,1) # p(c(w_h w_i w_j) > 0) = p(c(w_h w_i w_j) >= 1) + if pk <= 0.0: + print("pb_prob_cnt_ge_1 is {} for {} and tg_pks {} {}".format(pk, key, self.tg_pk[key], self.tg_pb[key].pks)) + elif pk > 1.0: + print('Warning: pk (' + str(pk) + ') > 1.0, setting to 0.99, for ' + self.vocab_list[int(_h)] + ' ' + self.vocab_list[int(bg_key.split('-')[0])] + ' ' + self.vocab_list[int(bg_key.split('-')[1])]) + pk = PK_UPPER_LIMIT + if bg_key not in bg_pks.keys(): + bg_pks[bg_key] = [] + bg_pks[bg_key].append(pk) + #for bg_key in bg_pks: + for k,v in tqdm(bg_pks.items()): + bg_pb[k] = PB(v) + bg_E_cnt[k] = sum(v) + for i in self.bos_bg_pk.keys(): + bg_key = "{}-{}".format(self.vocab_dict['<s>'],i) + bg_E_cnt[bg_key] = sum(self.bos_bg_pk[i]) + bg_pb[bg_key] = PB(self.bos_bg_pk[i]) + return bg_pb, bg_E_cnt + + def compute_ug_E_cnt(self): # from (35) and (38) of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + ug_E_cnt = {} + ug_pks = {} + ug_pb = {} + for key in self.bg_pb.keys(): + _i, ug_key = key.rsplit('-') + if self.vocab_list[int(ug_key)] in UG_SKIP_SYM_LIST: + ug_E_cnt[ug_key] = NO_E_CNT + else: + pb = self.bg_pb[key] + pk = self.pb_prob_cnt_ge_r(pb,1) # p(c(w_i w_j) > 0) = p(c(w_i w_j) >= 1) + if pk > 1.0: + print('Warning: pk (' + str(pk) + ') > 1.0, setting to 0.99, for ' + self.vocab_list[int(_i)] + ' ' + self.vocab_list[int(ug_key)]) + pk = PK_UPPER_LIMIT + if ug_key not in ug_pks.keys(): + ug_pks[ug_key] = [] + ug_pks[ug_key].append(pk) + for ug_key in ug_pks: + if self.vocab_list[int(ug_key)] not in UG_SKIP_SYM_LIST: + ug_E_cnt[ug_key] = sum(ug_pks[ug_key]) + ug_pb[ug_key] = PB(ug_pks[ug_key]) + return ug_pb, ug_E_cnt + + def compute_mod_kn_discounts(self, E_nr): # (28) of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + print(E_nr) + Y = E_nr[1] / (E_nr[1] + 2 * E_nr[2]) + D1 = 1 - 2 * Y * E_nr[2] / E_nr[1] + D2 = 2 - 3 * Y * E_nr[3] / E_nr[2] + D3 = 3 - 4 * Y * E_nr[4] / E_nr[3] + print("Discounts %f %f %f" % (D1, D2, D3)) + return D1, D2, D3 + + def compute_mod_kn_avg_discount(self, pb_dict, D1, D2, D3): # (20) of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + DP = {} + for key,pb in tqdm(pb_dict.items()): + p_cnt_eq_1 = self.pb_prob_cnt_eq_r(pb,1) + p_cnt_eq_2 = self.pb_prob_cnt_eq_r(pb,2) + pb_cnt_ge_3 = self.pb_prob_cnt_ge_r(pb,3) + DP[key] = p_cnt_eq_1 * D1 + p_cnt_eq_2 * D2 + pb_cnt_ge_3 * D3 + return DP + + def compute_ug_probs(self): # as per (49) of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + ug_probs = {} + disc_ug_probs = numpy.zeros(self.N) # unigram discounted probs + ug_E_cnt_sum = 0.0 + redistribute_cnt = 0 + for key in self.ug_E_cnt.keys(): + j = int(key) + if self.ug_E_cnt[key] < 0.0: # double check + print('Fatal Error: ug_E_cnt < 0 for ' + self.vocab_list[j]) + disc_ug_probs[j] = 0.0 + redistribute_cnt += 1 + elif self.vocab_list[j] in UG_SKIP_SYM_LIST: + disc_ug_probs[j] = 0.0 + elif self.ug_E_cnt[key] == NO_E_CNT: + disc_ug_probs[j] = 0.0 + redistribute_cnt += 1 + else: + ug_E_cnt_sum += self.ug_E_cnt[key] + disc_ug_probs[j] = (self.ug_E_cnt[key] - self.ug_DP[key]) # only numerator for discounted probs + redistribute_cnt += 1 + + disc_ug_probs = disc_ug_probs / ug_E_cnt_sum # coversion to discounted probs + left_over_prob_mass = 1.0 - numpy.sum(disc_ug_probs) + redistribute_prob = left_over_prob_mass / redistribute_cnt # redistribute uniformly to all + for j in range(self.N): + if self.vocab_list[j] in UG_SKIP_SYM_LIST: + if self.vocab_list[j] == '<s>': + ug_probs[self.vocab_list[j]] = 0.0 + else: + ug_probs[self.vocab_list[j]] = disc_ug_probs[j] + redistribute_prob + return ug_probs + + def compute_ug_bow(self): # as per (55) of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + ug_bow = {} + bg_E_cnt_sum_for_prev_word = {} + used_mass_for_prev_word = {} + for key in self.bg_E_cnt.keys(): + prev_w_key,j=key.split('-') + j=int(j) + i=int(prev_w_key) + if not(self.vocab_list[i] in (SKIP_SYM_LIST + ['</s>'])): + if prev_w_key not in bg_E_cnt_sum_for_prev_word.keys(): + bg_E_cnt_sum_for_prev_word[prev_w_key] = 0 + used_mass_for_prev_word[prev_w_key] = 0 + bg_E_cnt_sum_for_prev_word[prev_w_key] += self.bg_E_cnt[key] + used_mass_for_prev_word[prev_w_key] += self.disc_bg_E_cnt[key] + + for prev_w_key in bg_E_cnt_sum_for_prev_word: + i=int(prev_w_key) + if used_mass_for_prev_word[prev_w_key] >= 0.0 and bg_E_cnt_sum_for_prev_word[prev_w_key] > 0.0: + if used_mass_for_prev_word[prev_w_key] > bg_E_cnt_sum_for_prev_word[prev_w_key]: + print("used_mass %f > bg_E_cnt_sum_for_prev_word %f for %s" %(used_mass_for_prev_word[prev_w_key], bg_E_cnt_sum_for_prev_word[prev_w_key], self.vocab_list[i])) + else: + ug_bow[self.vocab_list[i]] = 1 - (used_mass_for_prev_word[prev_w_key] / bg_E_cnt_sum_for_prev_word[prev_w_key]) + else: + print("Problem with used_mass %f or bg_E_cnt_sum_for_prev_word %f for %s" %(used_mass_for_prev_word[prev_w_key], bg_E_cnt_sum_for_prev_word[prev_w_key], self.vocab_list[i])) + return ug_bow, bg_E_cnt_sum_for_prev_word + + def compute_bg_bow(self): # as per (55) of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + bg_bow = {} + tg_E_cnt_sum_for_prev_bg = {} + used_mass_for_prev_bg = {} + for key in self.tg_E_cnt.keys(): + prev_bg_key=key.rsplit('-',1)[0] + h,i,j=key.split('-') + h=int(h) + i=int(i) + j=int(j) + if not(self.vocab_list[h] in (SKIP_SYM_LIST + ['</s>'])): + if self.tg_E_cnt[key] != NO_E_CNT and self.disc_tg_E_cnt[key] != NO_E_CNT: + if prev_bg_key not in tg_E_cnt_sum_for_prev_bg.keys(): + tg_E_cnt_sum_for_prev_bg[prev_bg_key] = 0 + used_mass_for_prev_bg[prev_bg_key] = 0 + tg_E_cnt_sum_for_prev_bg[prev_bg_key] += self.tg_E_cnt[key] + used_mass_for_prev_bg[prev_bg_key] += self.disc_tg_E_cnt[key] + for prev_bg_key in tg_E_cnt_sum_for_prev_bg: + h,i=prev_bg_key.split('-') + h=int(h) + i=int(i) + wh=self.vocab_list[h] + wi=self.vocab_list[i] + if used_mass_for_prev_bg[prev_bg_key] >= 0.0 and tg_E_cnt_sum_for_prev_bg[prev_bg_key] > 0.0: + if used_mass_for_prev_bg[prev_bg_key] > tg_E_cnt_sum_for_prev_bg[prev_bg_key]: + print("used_mass %f > tg_E_cnt_sum_for_prev_word %f for %s" %(used_mass_for_prev_bg[prev_bg_key], tg_E_cnt_sum_for_prev_bg[prev_bg_key], self.vocab_list[h])) + else: + if wh not in bg_bow.keys(): + bg_bow[wh] = {} + bg_bow[wh][wi] = 1 - (used_mass_for_prev_bg[prev_bg_key] / tg_E_cnt_sum_for_prev_bg[prev_bg_key]) + else: + print("Problem with used_mass %f or tg_E_cnt_sum_for_prev_bg %f for %s" %(used_mass_for_prev_bg[prev_bg_key], tg_E_cnt_sum_for_prev_bg[prev_bg_key], self.vocab_list[h])) + return bg_bow, tg_E_cnt_sum_for_prev_bg + + def compute_bg_prob(self): # as per (54) of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + bg_probs = {} + for key in self.disc_bg_E_cnt.keys(): + prev_w_key,j=key.split('-') + i=int(prev_w_key) + j=int(j) + if not(self.vocab_list[i] in (SKIP_SYM_LIST + ['</s>'])): + if self.bg_E_cnt_sum_for_prev_word[prev_w_key] > 0.0: + if self.disc_bg_E_cnt[key] != NO_E_CNT: + wi = self.vocab_list[i] + wj = self.vocab_list[j] + if wi not in bg_probs.keys(): + bg_probs[wi] = {} + bg_probs[wi][wj] = (self.disc_bg_E_cnt[key] / self.bg_E_cnt_sum_for_prev_word[prev_w_key]) + (self.ug_bow[wi] * self.ug_prob[wj]) + else: + print("Problem with bg_E_cnt_sum_for_prev_word %f for %s" %(self.bg_E_cnt_sum_for_prev_word[prev_w_key], self.vocab_list[i])) + return bg_probs + + def compute_tg_prob(self): # as per (54) of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + tg_probs = {} + for key in self.tg_E_cnt.keys(): + prev_bg_key=key.rsplit('-',1)[0] + h,i,j=key.split('-') + h=int(h) + i=int(i) + j=int(j) + if not(self.vocab_list[h] in (SKIP_SYM_LIST + ['</s>'])): + if self.tg_E_cnt_sum_for_prev_bg[prev_bg_key] > 0.0: + if self.disc_tg_E_cnt[key] != NO_E_CNT: + wh = self.vocab_list[h] + wi = self.vocab_list[i] + wj = self.vocab_list[j] + if prev_bg_key not in tg_probs.keys(): + tg_probs[prev_bg_key] = {} + if (wi in self.bg_prob.keys()) and (wj in self.bg_prob[wi].keys()): + tg_probs[prev_bg_key][wj] = (self.disc_tg_E_cnt[key] / self.tg_E_cnt_sum_for_prev_bg[prev_bg_key]) + (self.bg_bow[wh][wi] * self.bg_prob[wi][wj]) + else: + tg_probs[prev_bg_key][wj] = (self.disc_tg_E_cnt[key] / self.tg_E_cnt_sum_for_prev_bg[prev_bg_key]) + (self.bg_bow[wh][wi] * self.ug_bow[wi] * self.ug_prob[wj]) + else: + print("Problem with tg_E_cnt_sum_for_prev_bg %f for %s %s" %(self.tg_E_cnt_sum_for_prev_bg[prev_bg_key], wh, wi)) + return tg_probs + + def compute_disc_bg_E_cnt(self): + disc_bg_E_cnt = {} + for key in self.bg_E_cnt.keys(): + i,j=key.split('-') + i=int(i) + j=int(j) + if self.bg_E_cnt[key] != NO_E_CNT: + disc_bg_E_cnt[key] = self.bg_E_cnt[key] - self.bg_DP[key] + if self.bg_DP[key] > self.bg_E_cnt[key]: + print("-ve disc_bg_E_cnt[key] %f - %f = %f for %s %s" %(self.bg_E_cnt[key], self.bg_DP[key], disc_bg_E_cnt[key], self.vocab_list[i], self.vocab_list[j])) + disc_bg_E_cnt[key] = 0.0 + else: + disc_bg_E_cnt[key] = NO_E_CNT + return disc_bg_E_cnt + + def compute_disc_tg_E_cnt(self): + disc_tg_E_cnt = {} + for key in self.tg_E_cnt.keys(): + h,i,j=key.split('-') + h=int(h) + i=int(i) + j=int(j) + if self.tg_E_cnt[key] != NO_E_CNT: + disc_tg_E_cnt[key] = self.tg_E_cnt[key] - self.tg_DP[key] + if self.tg_DP[key] > self.tg_E_cnt[key]: + print("-ve disc_tg_E_cnt[key] %f - %f = %f for %s %s %s" %(self.tg_E_cnt[key], self.tg_DP[key], disc_tg_E_cnt[key], self.vocab_list[h], self.vocab_list[i], self.vocab_list[j])) + disc_tg_E_cnt[key] = 0.0 + else: + disc_tg_E_cnt[key] = NO_E_CNT + return disc_tg_E_cnt + + def pb_prob_cnt_eq_r(self, pb, r): # (24) (25) of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + if pb.number_trials == 0 and r == 0: + return 1.0 + elif r>=0 and r<=pb.number_trials: + return pb.pmf(r) + else: + return 0.0 + + def pb_prob_cnt_ge_r(self, pb, r): # (31) of https://www.microsoft.com/en-us/research/uploads/prod/2018/06/ExpectedKneserNey-Tech-Report.pdf + _pb_prob_cnt_eq_r = self.pb_prob_cnt_eq_r(pb,r) + sum_prob_cnt_lt_r = 0.0 + _r = 0 + while _r < r: + sum_prob_cnt_lt_r += self.pb_prob_cnt_eq_r(pb,_r) + _r += 1 + _pb_prob_cnt_ge_r = 1 - sum_prob_cnt_lt_r + return max([_pb_prob_cnt_eq_r, _pb_prob_cnt_ge_r]) \ No newline at end of file diff --git a/local/cn2lm/ngramlm/data.py b/local/cn2lm/ngramlm/data.py new file mode 100644 index 0000000000000000000000000000000000000000..a3297311eaf752b75ad3e72ae73de9aad810ed42 --- /dev/null +++ b/local/cn2lm/ngramlm/data.py @@ -0,0 +1,184 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- + +# Copyright © 2021 INRIA (Imran Sheikh) +# AGPL-3.0-only or AGPL-3.0-or-later (https://www.gnu.org/licenses/agpl-3.0.txt) + +# This file is part of CN2LM. +# +# CN2LM is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# CN2LM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with CN2LM. If not, see <https://www.gnu.org/licenses/>. + +import os, re, sys + +ONLY_PROB = 1 +EQUI_PROB = False +SKIP_EPS = True +SKIP_NON_BEST_EPS = True +MAX_ARCS = 5 # set to 1 for BEST_SEQ +NGRAM_BATCH_SIZE = 500 + +class DataLoader: + def __init__(self, asr_vocab_file, sup_text=None, unsup_saus_dir=None, unsup_errpreds=None): + assert not(sup_text is None and unsup_saus_dir is None), "At least one of sup_text or unsup_saus_dir is required !!!" + self.asr_vocab_file = asr_vocab_file + self.sup_text = sup_text + self.unsup_saus_dir = unsup_saus_dir + + self.vocab_dict = {} + with open(self.asr_vocab_file) as fp: + for line in fp: + line = line.rstrip() + word, wid = line.split(' ') + self.vocab_dict[word] = int(wid) + self.vocab_list = [None] * len(self.vocab_dict) + for w in self.vocab_dict.keys(): + wid = self.vocab_dict[w] + self.vocab_list[wid] = w + + self.unk_token = '<unk>' + if '<UNK>' in self.vocab_dict: + self.unk_token = '<UNK>' + + self.obs_sequences = [] + if unsup_saus_dir is not None: + unsup_obs_seq = self.read_saus_dir(unsup_saus_dir, unsup_errpreds) + self.obs_sequences += unsup_obs_seq + + if sup_text is not None: + sup_obs_seq = self.read_sup_text(sup_text) + self.obs_sequences += sup_obs_seq + + total_trig_batches = 0 + for seq in self.obs_sequences: + total_trig_batches += len(seq)-2 + self.total_trig_batches = int(total_trig_batches/NGRAM_BATCH_SIZE + 1) + + def read_error_preds(self, errpreds_file): + err_preds = {} + with open(errpreds_file) as fp: + for line in fp: + uttid, preds = line.strip().split(', ') + err_preds[uttid] = [int(p) for p in preds.split(' ')] + return err_preds + + def read_saus_dir(self, saus_dir, unsup_errpreds): + err_preds = None + if unsup_errpreds is not None: + err_preds = self.read_error_preds(unsup_errpreds) + + allObsSeq = [] + for r, d, f in os.walk(saus_dir): + for file in f: + m = re.search(r'saus\-wtimes\.\d+$', file) + if m is not None: + _fnum = file.split('.')[-1] + with open(os.path.join(r, file)) as fp: + for line in fp: + line = line.replace('\n', ' ') + + uttid, binText = line.split(' ', 1) + binText = binText.lstrip(' [') + binText = binText.rstrip('] ') + tmp_bins = binText.split(' ] [ ') + _bins = [] + for bin in tmp_bins: + if bin != '0 1': + _bins.append(bin) + + if err_preds is not None: + if len(err_preds[uttid]) != len(_bins): + print("Error predictions for %s do match in length ! %d ! %d" %(uttid, len(err_preds[uttid]), len(_bins))) + sys.exit() + + binseq = [] + for binid in range(len(_bins)): + bin = _bins[binid] + vals = bin.split(' ') + vid = 0 + bestWrd = self.vocab_list[int(vals[0])] + bestScr = float(vals[1]) + ######## + if err_preds is not None and err_preds[uttid][binid]==2: # <eps> + continue + if bestWrd == '<eps>' and (bestScr > 0.85 or SKIP_EPS): # for both <error> and <no-error> + continue + else: + num_bin_arcs = 0 + binprobs = [] + no_break = True + while (num_bin_arcs < MAX_ARCS) and (vid < len(vals)) and no_break: + wid = int(vals[vid]) + wrd = self.vocab_list[wid] + vid += 1 + scr = float(vals[vid]) + vid += 1 + num_bin_arcs += 1 + if EQUI_PROB or (MAX_ARCS==1): + scr = ONLY_PROB + if SKIP_NON_BEST_EPS: + if (bestWrd != '<eps>' and wrd == '<eps>'): + continue + if (err_preds is not None) and (err_preds[uttid][binid]==1): # <no-error> + no_break = False + scr = ONLY_PROB + binprobs.append([wid, scr]) + assert len(binprobs) <= MAX_ARCS, "Fatal Error: len(binprobs) > MAX_ARCS ------ {}".format(binprobs) + binseq.append(binprobs) + aseq = [[[self.vocab_dict['<s>'], ONLY_PROB]]] + binseq + [[[self.vocab_dict['</s>'], ONLY_PROB]]] + if len(aseq)<=2: + #print(_uttid, aseq) + continue + allObsSeq.append(aseq) + return allObsSeq + + def read_sup_text(self, sup_text): + obsseq = [] + with open(sup_text) as fp: + for line in fp: + line = line.rstrip() + if ' ' not in line: + print('Skipping ' + line) + continue + _uttid, text = line.split(' ', 1) + wrds = text.split() + seq = [] + for token in wrds: + if token == '<heps>': + token = '<eps>' + if token != '<eps>': # exclude <eps> + if token in self.vocab_dict.keys(): + token_id = self.vocab_dict[token] + else: + # should be ignored as per srilm http://www.speech.sri.com/projects/srilm/manpages/srilm-faq.7.html but practically not so???? + token_id = self.vocab_dict[self.unk_token] + seq.append([[token_id, ONLY_PROB]]) # bin with 1 arc + aseq = [[[self.vocab_dict['<s>'], ONLY_PROB]]] + seq + [[[self.vocab_dict['</s>'], ONLY_PROB]]] + if len(aseq)<=2: + continue + obsseq.append(aseq) + return obsseq + + def yield_trig_batch(self): + obseq_batch = [] + cnt = 0 + for obsSeq in sorted(self.obs_sequences, key=len): + for t in range(len(obsSeq)-2): + obseq_batch.append(obsSeq[t:t+3]) + cnt += 1 + if cnt == NGRAM_BATCH_SIZE: + yield obseq_batch + obseq_batch = [] + cnt = 0 + if obseq_batch: + yield obseq_batch \ No newline at end of file diff --git a/local/cn2lm/ngramlm/poisson_binomial.py b/local/cn2lm/ngramlm/poisson_binomial.py new file mode 100644 index 0000000000000000000000000000000000000000..345f7b907ee0c6a6c5de51c8ca0c881274aaf431 --- /dev/null +++ b/local/cn2lm/ngramlm/poisson_binomial.py @@ -0,0 +1,52 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- + +# Copyright © 2021 INRIA (Imran Sheikh) +# AGPL-3.0-only or AGPL-3.0-or-later (https://www.gnu.org/licenses/agpl-3.0.txt) + +# This file is part of CN2LM. +# +# CN2LM is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# CN2LM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with CN2LM. If not, see <https://www.gnu.org/licenses/>. + +import numpy + +PK_EPS_VALUE = 0.01 +PK_UPPER_LIMIT = 0.99 +MAX_R = 7 + +class PB: + def __init__(self, pks): + self.pks = pks + self.number_trials = len(pks) + self.s_k_r = self.poibin_recursive(pks) + + def pmf(self, l): + return self.s_k_r[l] + + def poibin_recursive(self, pks): + s_k_r = numpy.zeros([len(pks)+1, MAX_R]) + for k in range(len(pks)+1): + for r in range(MAX_R): + if k==0 and r==0: + s_k_r[k,r] = 1.0 + else: + _k = k-1 + _r = r-1 + partA = s_k_r[_k,r] * (1-pks[_k]) + if _r < 0 or s_k_r[_k,_r] < PK_EPS_VALUE: + partB = 0 + else: + partB = s_k_r[_k,_r] * pks[_k] + s_k_r[k,r] = partA + partB + return s_k_r[-1,:] \ No newline at end of file diff --git a/local/cn2lm/rnnlm/data.py b/local/cn2lm/rnnlm/data.py new file mode 100755 index 0000000000000000000000000000000000000000..cda02ad4df84b2cb799848da2ac2572a9f82a763 --- /dev/null +++ b/local/cn2lm/rnnlm/data.py @@ -0,0 +1,327 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- + +# Copyright © 2021 INRIA (Imran Sheikh) +# AGPL-3.0-only or AGPL-3.0-or-later (https://www.gnu.org/licenses/agpl-3.0.txt) + +# This file is part of CN2LM. +# +# CN2LM is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# CN2LM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with CN2LM. If not, see <https://www.gnu.org/licenses/>. + +import torch +import torch.utils.data + +import os, re, sys, numpy + +from collections import Counter + +numpy.random.seed(0) +torch.manual_seed(0) +torch.backends.cudnn.deterministic = True +torch.backends.cudnn.benchmark = False + +EQUI_PROB = False +BEST_SEQ = False +SKIP_EPS = True +SKIP_NON_BEST_EPS = True +SAUS_POST_THRESH = 0.0 + +MAX_LEN = 15 +MAX_ARCS = 5 +EMB_DIM = 64 +NORM_POST_OVER_ARCS = True +MINI_BATCH_SIZE = 32 + +ARC_PAD_SYM = '#0' +SEQ_PAD_SYM = '</s>' + +class Config: + def __init__(self, vocab_dict): + self.vocab_dict = vocab_dict + self.vocab_list = [None] * len(vocab_dict) + for w in vocab_dict: + self.vocab_list[vocab_dict[w]] = w + self.embedding_dim = EMB_DIM + self.arcpadid = self.vocab_dict[ARC_PAD_SYM] + self.seqpadid = self.vocab_dict[SEQ_PAD_SYM] + if '<UNK>' in vocab_dict: + self.unk_sym = '<UNK>' + else: + self.unk_sym = '<unk>' + self.combine_method = "best" # "weighted-sum" #"avg"# + self.best_seq = BEST_SEQ + +def build_config(asr_vocab_file): + vocab_dict = {} + last_wid = 0 + with open(asr_vocab_file) as fp: + for line in fp: + line = line.rstrip() + word, wid = line.split(' ') + vocab_dict[word] = int(wid) + last_wid = int(wid) + vocab_dict['<brk>'] = last_wid+1 + config = Config(vocab_dict) + return config + +def get_unsup_obs_seqs(saus_dir, config, eval=False): + asr_vocab_list = config.vocab_list + vocab_dict = config.vocab_dict + obs_seq = [] + uttid_list = [] + for r, d, f in os.walk(saus_dir): + for file in f: + m = re.search(r'saus\-wtimes\.\d+$', file) + if m is not None: + _fnum = file.split('.')[-1] + with open(os.path.join(r, file)) as fp: + for line in fp: + line = line.replace('\n', ' ') + + uttid, bin_text = line.split(' ', 1) + + bin_text = bin_text.lstrip(' [') + bin_text = bin_text.rstrip('] ') + _bins = bin_text.split(' ] [ ') + + seq_bin_arc_probs = [] + seq_bin_arc_ids = [] + for bin in _bins: + if bin != '0 1': + vals = bin.split(' ') + vid = 0 + bin_probs = [] + arc_ids = [] + best_wrd = asr_vocab_list[int(vals[0])] + best_scr = float(vals[1]) + if best_wrd == '<eps>' and (best_scr > 0.85 or SKIP_EPS): + continue + else: + while vid < len(vals): + wrd = asr_vocab_list[int(vals[vid])] + vid += 1 + scr = float(vals[vid]) + vid += 1 + if EQUI_PROB: + scr = 1.0 + if SKIP_NON_BEST_EPS: + if (best_wrd != '<eps>' and wrd == '<eps>'): + continue + bin_probs.append(scr) + arc_ids.append(vocab_dict[wrd]) + if config.best_seq: + break + seq_bin_arc_probs.append(bin_probs) + seq_bin_arc_ids.append(arc_ids) + + seq_bin_arc_probs_nxt = seq_bin_arc_probs + [[1.0], [1.0]] + seq_bin_arc_ids_nxt = seq_bin_arc_ids + [[vocab_dict['</s>']], [vocab_dict[SEQ_PAD_SYM]]] + seq_bin_arc_probs = [[1.0]] + seq_bin_arc_probs + [[1.0]] + seq_bin_arc_ids = [[vocab_dict['<s>']]] + seq_bin_arc_ids + [[vocab_dict['</s>']]] + + assert len(seq_bin_arc_probs) == len(seq_bin_arc_probs_nxt), "len(seq_bin_arc_probs) != len(seq_bin_arc_probs_nxt)" + + if len(seq_bin_arc_probs) <= MAX_LEN: + obs_seq.append([seq_bin_arc_probs, seq_bin_arc_ids, seq_bin_arc_probs_nxt, seq_bin_arc_ids_nxt]) + uttid_list.append(uttid) + else: + begin = 0 + while begin < len(seq_bin_arc_probs): + red_seq_probs = seq_bin_arc_probs[begin:begin+MAX_LEN] + red_seq_ids = seq_bin_arc_ids[begin:begin+MAX_LEN] + red_seq_probs_nxt = seq_bin_arc_probs_nxt[begin:begin+MAX_LEN] + red_seq_ids_nxt = seq_bin_arc_ids_nxt[begin:begin+MAX_LEN] + if len(red_seq_probs) == 0: + break + elif len(red_seq_probs) < MAX_LEN: + red_seq_probs = seq_bin_arc_probs[-MAX_LEN:] + red_seq_ids = seq_bin_arc_ids[-MAX_LEN:] + red_seq_probs_nxt = seq_bin_arc_probs_nxt[-MAX_LEN:] + red_seq_ids_nxt = seq_bin_arc_ids_nxt[-MAX_LEN:] + obs_seq.append([red_seq_probs, red_seq_ids, red_seq_probs_nxt, red_seq_ids_nxt]) + begin += MAX_LEN + uttid_list.append(uttid) + return obs_seq, uttid_list + +def get_sup_dataset(config, textfile): + obs_seq = [] + uttid_list = [] + with open(textfile) as fp: + for line in fp: + line = line.rstrip() + uttid, text = line.split(' ', 1) + wrds = text.split() + seq = [] + for token in wrds: + if token == '<heps>': + token = '<eps>' + if token != '<eps>': # exclude <eps> + if token in config.vocab_dict: + seq.append([config.vocab_dict[token]]) + else: + # should be ignored as per srilm http://www.speech.sri.com/projects/srilm/manpages/srilm-faq.7.html but practically not so???? + seq.append([config.vocab_dict['<unk>']]) + seq_bin_arc_ids_nxt = seq + [[config.vocab_dict['</s>']], [config.vocab_dict[SEQ_PAD_SYM]]] + seq_bin_arc_ids = [[config.vocab_dict['<s>']]] + seq + [[config.vocab_dict['</s>']]] + seq_probs = [[1.0]] * len(seq_bin_arc_ids) + + if len(seq_bin_arc_ids) <= MAX_LEN: + obs_seq.append([seq_probs, seq_bin_arc_ids, seq_probs, seq_bin_arc_ids_nxt]) + uttid_list.append(uttid) + else: + begin = 0 + while begin < len(seq_bin_arc_ids): + red_seq_ids = seq_bin_arc_ids[begin:begin+MAX_LEN] + red_seq_ids_nxt = seq_bin_arc_ids_nxt[begin:begin+MAX_LEN] + red_seq_probs = [[1.0]] * len(red_seq_ids) + if len(red_seq_ids)==0: + break + elif len(red_seq_ids) < MAX_LEN: + red_seq_ids = seq[-MAX_LEN:] + obs_seq.append([red_seq_probs, red_seq_ids, red_seq_probs, red_seq_ids_nxt]) + uttid_list.append(uttid) + begin = begin + MAX_LEN + return obs_seq, uttid_list + +def get_saus_dataset(config, saus_dir, eval=False, sup_text=None): + probs_n_ids, uttid_list = get_unsup_obs_seqs(saus_dir, config, eval) + if sup_text is not None: + sup_probs_n_ids, sup_uttid_list = get_sup_dataset(config, sup_text) + probs_n_ids = sup_probs_n_ids + probs_n_ids + uttid_list = sup_uttid_list + uttid_list + shuffle_flag = True + if eval: + shuffle_flag=False + dataset = SausDataset(probs_n_ids, config, shuffle_flag) + return dataset, uttid_list + +class SausDataset(torch.utils.data.Dataset): + def __init__(self, probs_n_ids, config, shuffle_flag=True): + self.config = config + self.samples = probs_n_ids # list of bin seq, with word probs in each bin + pad = Pad(self.config) # function for generating a minibatch after padding + self.loader = torch.utils.data.DataLoader(self, batch_size=MINI_BATCH_SIZE, num_workers=1, shuffle=shuffle_flag, collate_fn=pad) + + def __len__(self): + return len(self.samples) + + def __getitem__(self, idx): + line = self.samples[idx] + return line + +class Pad: + def __init__(self, config): + self.N = len(config.vocab_dict) # num of states + self.arcpadid = config.arcpadid + self.seqpadid = config.seqpadid + + def __call__(self, batch): + """ + Returns a minibatch padded to have the same length. + """ + x_probs = [] + x_ids = [] + y_probs = [] + y_ids = [] + batch_size = len(batch) + for index in range(batch_size): + x_probs.append(batch[index][0]) + x_ids.append(batch[index][1]) + y_probs.append(batch[index][2]) + y_ids.append(batch[index][3]) + + # pad all sequences to have MAX_ARCS, MAX_LEN + x_probs_npy = numpy.zeros([batch_size, MAX_LEN, MAX_ARCS], dtype='float32') + x_ids_npy = numpy.zeros([batch_size, MAX_LEN, MAX_ARCS], dtype='int32') + self.arcpadid + x_mask_npy = numpy.zeros([batch_size, MAX_LEN, MAX_ARCS], dtype='float32') + y_probs_npy = numpy.zeros([batch_size, MAX_LEN, MAX_ARCS], dtype='float32') + y_ids_npy = numpy.zeros([batch_size, MAX_LEN, MAX_ARCS], dtype='int32') + self.arcpadid + y_mask_npy = numpy.zeros([batch_size, MAX_LEN, MAX_ARCS], dtype='float32') + for bid in range(batch_size): + for tid in range(MAX_LEN): + if tid < len(x_probs[bid]): + num_arcs = min(MAX_ARCS, len(x_probs[bid][tid])) + x_post_sum = 1.0 + if NORM_POST_OVER_ARCS: + x_post_sum = sum(x_probs[bid][tid][0:num_arcs]) + for aid in range(num_arcs): + x_probs_npy[bid, tid, aid] = x_probs[bid][tid][aid] / x_post_sum + x_mask_npy[bid, tid, aid] = 1.0 + x_ids_npy[bid, tid, aid] = x_ids[bid][tid][aid] + else: + x_probs_npy[bid, tid, 0] = 1.0 + x_mask_npy[bid, tid, 0] = 0.0 + x_ids_npy[bid, tid, 0] = self.seqpadid + + for tid in range(MAX_LEN): + if tid < len(y_probs[bid]): + num_arcs = min(MAX_ARCS, len(y_probs[bid][tid])) + y_post_sum = 1.0 + if NORM_POST_OVER_ARCS: + y_post_sum = sum(y_probs[bid][tid][0:num_arcs]) + for aid in range(num_arcs): + y_probs_npy[bid, tid, aid] = y_probs[bid][tid][aid] / y_post_sum + y_mask_npy[bid, tid, aid] = 1.0 + y_ids_npy[bid, tid, aid] = y_ids[bid][tid][aid] + else: + y_probs_npy[bid, tid, 0] = 1.0 + y_mask_npy[bid, tid, 0] = 0.0 + y_ids_npy[bid, tid, 0] = self.seqpadid + + # stack into single tensor + x_probs_torch = torch.from_numpy(x_probs_npy).float() + x_ids_torch = torch.from_numpy(x_ids_npy).long() + x_mask_torch = torch.from_numpy(x_mask_npy).float() + y_probs_torch = torch.from_numpy(y_probs_npy).float() + y_ids_torch = torch.from_numpy(y_ids_npy).long() + y_mask_torch = torch.from_numpy(y_mask_npy).float() + + return (x_probs_torch, x_ids_torch, x_mask_torch, y_probs_torch, y_ids_torch, y_mask_torch) + +def get_eval_sents(config, textfile): + vocab = config.vocab_dict + sents = [] + num_wrds = 0 + num_sents = 0 + + with open(textfile) as fp: + for line in fp: + seq = ['<s>'] + line = line.rstrip() + _uttid, text = line.split(' ', 1) + wrds = text.split() + for token in wrds: + if token == '<heps>': + token = '<eps>' + if token != '<eps>': + if token in vocab: + seq.append(token) + num_wrds +=1 + else: + # should be ignored as per srilm http://www.speech.sri.com/projects/srilm/manpages/srilm-faq.7.html but practically not so???? + seq.append(config.unk_sym) + num_wrds +=1 + seq.append('</s>') + + in_ids = [] + out_ids = [] + for i in range(1, len(seq)): + in_ids.append(vocab[seq[i-1]]) + out_ids.append(vocab[seq[i]]) + sents.append([torch.tensor(in_ids), torch.tensor(out_ids)]) + + num_sents += 1 + + return sents, num_wrds, num_sents + \ No newline at end of file diff --git a/local/cn2lm/rnnlm/kaldi_support/pytorch_grulm_to_kaldi.py b/local/cn2lm/rnnlm/kaldi_support/pytorch_grulm_to_kaldi.py new file mode 100644 index 0000000000000000000000000000000000000000..63199fa5af44c59e1e3f9e6be1779e983781d1a2 --- /dev/null +++ b/local/cn2lm/rnnlm/kaldi_support/pytorch_grulm_to_kaldi.py @@ -0,0 +1,143 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- + +# Copyright © 2021 INRIA (Imran Sheikh) +# AGPL-3.0-only or AGPL-3.0-or-later (https://www.gnu.org/licenses/agpl-3.0.txt) + +# This file is part of CN2LM. +# +# CN2LM is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# CN2LM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with CN2LM. If not, see <https://www.gnu.org/licenses/>. + +import torch, numpy, os, sys +currentdir = os.path.dirname(os.path.realpath(__file__)) +parentdir = os.path.dirname(currentdir) +sys.path.append(parentdir) + +from data import build_config +from models import SausRNN + +import argparse, os, sys + +torch.manual_seed(0) +torch.backends.cudnn.deterministic = True +torch.backends.cudnn.benchmark = False + +parser = argparse.ArgumentParser() +parser.add_argument('asr_vocab_file', type=str, help='Path to ASR words.txt') +parser.add_argument('kaldi_gru_lm_template_file', type=str, help='Path to Kaldi GRU LM template model text') +parser.add_argument('pytorch_model', type=str, help='Path to Pytorch GRU LM file') +parser.add_argument('out_kaldi_model_dir', type=str, help='output Kaldi GRU LM dir') +args = parser.parse_args() + +if not os.path.isfile(args.asr_vocab_file): + raise IOError(args.asr_vocab_file) + +if not os.path.isfile(args.kaldi_gru_lm_template_file): + raise IOError(args.kaldi_gru_lm_template_file) + +if not os.path.isfile(args.pytorch_model): + raise IOError(args.pytorch_model) + +if not os.path.isdir(args.out_kaldi_model_dir): + raise IOError(args.out_kaldi_model_dir) + +def eprint(*args, **kwargs): + print(*args, file=sys.stderr, **kwargs) + +# Initialize model +config = build_config(args.asr_vocab_file) +model = SausRNN(config) +model.load_checkpoint(args.pytorch_model) + +for param_tensor in model.state_dict(): + print(param_tensor, "\t", model.state_dict()[param_tensor].size()) + +emb = model.state_dict()['embedding.weight'].cpu().data.numpy() +weight_ih_l0 = model.state_dict()['rnn.weight_ih_l0'].cpu().data.numpy() +w_ir, w_iz, w_in = numpy.split(weight_ih_l0, 3, axis=0) +weight_hh_l0 = model.state_dict()['rnn.weight_hh_l0'].cpu().data.numpy() +w_hr, w_hz, w_hn = numpy.split(weight_hh_l0, 3, axis=0) + +bias_ih_l0 = model.state_dict()['rnn.bias_ih_l0'].cpu().data.numpy() +b_ir, b_iz, b_in = numpy.split(bias_ih_l0, 3, axis=0) +bias_hh_l0 = model.state_dict()['rnn.bias_hh_l0'].cpu().data.numpy() +b_hr, b_hz, b_hn = numpy.split(bias_hh_l0, 3, axis=0) + +def skip_lines_n_print_params(wt, b, in_fp, out_fp): + for i in range(wt.shape[0]): + for n in wt[i]: + print(" %f" % n, end='', file=out_fp) + if i==wt.shape[0]-1: + print(" ]", file=out_fp) + else: + print("", file=out_fp) + print("<BiasParams> [ ", end='', file=out_fp) + for n in b: + print(" %f" % n, end='', file=out_fp) + print(" ]", file=out_fp) + +def print_sig_lines(in_fp, out_fp, tanh=False): + print('<DerivAvg> [ ]', file=out_fp) + print('<Count> 0 <OderivRms> [ ]', file=out_fp) + if tanh: + print('<OderivCount> 0 <NumDimsSelfRepaired> 0 <NumDimsProcessed> 0 <SelfRepairScale> 1e-05 </TanhComponent>', file=out_fp) + else: + print('<OderivCount> 0 <NumDimsSelfRepaired> 0 <NumDimsProcessed> 0 <SelfRepairScale> 1e-05 </SigmoidComponent>', file=out_fp) + +cur_component = '' +out_fp = open(os.path.join(args.out_kaldi_model_dir, "final"), 'w') +with open(args.kaldi_gru_lm_template_file) as in_fp: + line = in_fp.readline() + while line: + if '<ComponentName> gru1.W_ir' in line: + print(line, end='', file=out_fp) + skip_lines_n_print_params(w_ir, b_ir, in_fp, out_fp) + elif '<ComponentName> gru1.W_hr' in line: + print(line, end='', file=out_fp) + skip_lines_n_print_params(w_hr, b_hr, in_fp, out_fp) + elif '<ComponentName> gru1.W_iz' in line: + print(line, end='', file=out_fp) + skip_lines_n_print_params(w_iz, b_iz, in_fp, out_fp) + elif '<ComponentName> gru1.W_hz' in line: + print(line, end='', file=out_fp) + skip_lines_n_print_params(w_hz, b_hz, in_fp, out_fp) + elif '<ComponentName> gru1.W_in' in line: + print(line, end='', file=out_fp) + skip_lines_n_print_params(w_in, b_in, in_fp, out_fp) + elif '<ComponentName> gru1.W_hn' in line: + print(line, end='', file=out_fp) + skip_lines_n_print_params(w_hn, b_hn, in_fp, out_fp) + elif '<ComponentName> gru1.Sig_r <SigmoidComponent>' in line: + print('<ComponentName> gru1.Sig_r <SigmoidComponent> <Dim> 64 <ValueAvg> [ ]', file=out_fp) + print_sig_lines(in_fp, out_fp) + elif '<ComponentName> gru1.Sig_z <SigmoidComponent>' in line: + print('<ComponentName> gru1.Sig_z <SigmoidComponent> <Dim> 64 <ValueAvg> [ ]', file=out_fp) + print_sig_lines(in_fp, out_fp) + elif '<ComponentName> gru1.Tan_n <TanhComponent>' in line: + print('<ComponentName> gru1.Tan_n <TanhComponent> <Dim> 64 <ValueAvg> [ ]', file=out_fp) + print_sig_lines(in_fp, out_fp, tanh=True) + else: + print(line, end='', file=out_fp) + line = in_fp.readline() +out_fp.close() + +out_fp = open(os.path.join(args.out_kaldi_model_dir, "word_embedding.final"), 'w') +print("[", file=out_fp) +for i in range(emb.shape[0]): + for n in emb[i]: + print(" %f" % n, end='', file=out_fp) + if i==emb.shape[0]-1: + print(" ]", file=out_fp) + else: + print("", file=out_fp) diff --git a/local/cn2lm/rnnlm/kaldi_support/pytorch_rnnlm_to_kaldi.sh b/local/cn2lm/rnnlm/kaldi_support/pytorch_rnnlm_to_kaldi.sh new file mode 100644 index 0000000000000000000000000000000000000000..b41319662800c613498350e9ea669db67aaa3dcd --- /dev/null +++ b/local/cn2lm/rnnlm/kaldi_support/pytorch_rnnlm_to_kaldi.sh @@ -0,0 +1,61 @@ +#!/bin/bash + +# Copyright © 2021 INRIA (Imran Sheikh) +# AGPL-3.0-only or AGPL-3.0-or-later (https://www.gnu.org/licenses/agpl-3.0.txt) + +# This file is part of CN2LM. +# +# CN2LM is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# CN2LM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with CN2LM. If not, see <https://www.gnu.org/licenses/>. + +echo "" +echo "$0 $@" # Print the command line for logging +echo "" + +[ -f ./path.sh ] && . ./path.sh + +if [ $# != 4 ]; then + echo "" + echo "USAGE: $0 asr_vocab_file kaldi_gru_lm_template_file pytorch_model out_kaldi_model_dir" + echo "" + exit 1; +fi + +vocab=$1 +rawtmp=$2 +torchmdl=$3 +dir=$4 + +for f in $vocab $rawtmp $torchmdl; do + [ ! -f $f ] && echo "$0: no such file $f" && exit 1; +done + +outdir=${dir}/kaldi-format +mkdir -p $outdir/config + +python -u local/cn2lm/rnnlm/kaldi_support/pytorch_grulm_to_kaldi.py $vocab $rawtmp $torchmdl $outdir || exit -1; + +nnet3-copy $outdir/final $outdir/final.raw +copy-matrix $outdir/word_embedding.final $outdir/word_embedding.final.mat + +brkid=`wc -l $vocab | cut -d" " -f1` +cp $vocab $outdir/config/words.txt +echo "<brk> $brkid" >> $outdir/config/words.txt + +eosid=`echo $brkid-1 | bc` +bosid=`echo $brkid-2 | bc` +echo "--bos-symbol=$bosid --eos-symbol=$eosid --brk-symbol=$brkid" > $outdir/special_symbol_opts.txt + +unksym=`grep -i "<UNK>" $vocab | cut -d" " -f1` +echo "$unksym" > $outdir/config/oov.txt + diff --git a/local/cn2lm/rnnlm/kaldi_support/torch_gru.raw.tmp.txt b/local/cn2lm/rnnlm/kaldi_support/torch_gru.raw.tmp.txt new file mode 100644 index 0000000000000000000000000000000000000000..b9ffed5c371eb6f25c7920c679a9dcb0981d267e --- /dev/null +++ b/local/cn2lm/rnnlm/kaldi_support/torch_gru.raw.tmp.txt @@ -0,0 +1,41 @@ +<Nnet3> +input-node name=input dim=64 +component-node name=gru1.r1 component=gru1.W_ir input=input +component-node name=gru1.r2 component=gru1.W_hr input=IfDefined(Offset(gru1.h_t, -1)) +component-node name=gru1.r_t component=gru1.Sig_r input=Sum(gru1.r1, gru1.r2) +component-node name=gru1.z1 component=gru1.W_iz input=input +component-node name=gru1.z2 component=gru1.W_hz input=IfDefined(Offset(gru1.h_t, -1)) +component-node name=gru1.z_t component=gru1.Sig_z input=Sum(gru1.z1, gru1.z2) +component-node name=gru1.n1 component=gru1.W_in input=input +component-node name=gru1.n22 component=gru1.W_hn input=IfDefined(Offset(gru1.h_t, -1)) +component-node name=gru1.n2 component=gru1.EMul_n input=Append(gru1.r_t, gru1.n22) +component-node name=gru1.n_t component=gru1.Tan_n input=Sum(gru1.n1, gru1.n2) +component-node name=gru1.y1 component=gru1.EMul_y1 input=Append(gru1.n_t, Sum(Scale(-1, gru1.z_t), Const(1, 64))) +component-node name=gru1.y2 component=gru1.EMul_y2 input=Append(IfDefined(Offset(gru1.h_t, -1)), gru1.z_t) +component-node name=gru1.y_t component=gru1.NOp input=Sum(gru1.y1, gru1.y2) +component-node name=gru1.h_t component=gru1.GTrunc input=gru1.y_t +output-node name=output input=gru1.h_t objective=linear + +<NumComponents> 14 +<ComponentName> gru1.W_ir <NaturalGradientAffineComponent> <MaxChange> 0.75 <LearningRate> 0.001 <LinearParams> [ +<RankIn> 20 <RankOut> 32 <UpdatePeriod> 4 <NumSamplesHistory> 2000 <Alpha> 4 </NaturalGradientAffineComponent> +<ComponentName> gru1.W_hr <NaturalGradientAffineComponent> <MaxChange> 0.75 <LearningRate> 0.001 <LinearParams> [ +<RankIn> 20 <RankOut> 32 <UpdatePeriod> 4 <NumSamplesHistory> 2000 <Alpha> 4 </NaturalGradientAffineComponent> +<ComponentName> gru1.Sig_r <SigmoidComponent> <Dim> 64 <ValueAvg> [ ] +<ComponentName> gru1.W_iz <NaturalGradientAffineComponent> <MaxChange> 0.75 <LearningRate> 0.001 <LinearParams> [ +<RankIn> 20 <RankOut> 32 <UpdatePeriod> 4 <NumSamplesHistory> 2000 <Alpha> 4 </NaturalGradientAffineComponent> +<ComponentName> gru1.W_hz <NaturalGradientAffineComponent> <MaxChange> 0.75 <LearningRate> 0.001 <LinearParams> [ +<RankIn> 20 <RankOut> 32 <UpdatePeriod> 4 <NumSamplesHistory> 2000 <Alpha> 4 </NaturalGradientAffineComponent> +<ComponentName> gru1.Sig_z <SigmoidComponent> <Dim> 64 <ValueAvg> [ ] +<ComponentName> gru1.W_in <NaturalGradientAffineComponent> <MaxChange> 0.75 <LearningRate> 0.001 <LinearParams> [ +<RankIn> 20 <RankOut> 32 <UpdatePeriod> 4 <NumSamplesHistory> 2000 <Alpha> 4 </NaturalGradientAffineComponent> +<ComponentName> gru1.W_hn <NaturalGradientAffineComponent> <MaxChange> 0.75 <LearningRate> 0.001 <LinearParams> [ +<RankIn> 20 <RankOut> 32 <UpdatePeriod> 4 <NumSamplesHistory> 2000 <Alpha> 4 </NaturalGradientAffineComponent> +<ComponentName> gru1.EMul_n <ElementwiseProductComponent> <InputDim> 128 <OutputDim> 64 </ElementwiseProductComponent> +<ComponentName> gru1.Tan_n <TanhComponent> <Dim> 64 <ValueAvg> [ ] +<ComponentName> gru1.EMul_y1 <ElementwiseProductComponent> <InputDim> 128 <OutputDim> 64 </ElementwiseProductComponent> +<ComponentName> gru1.EMul_y2 <ElementwiseProductComponent> <InputDim> 128 <OutputDim> 64 </ElementwiseProductComponent> +<ComponentName> gru1.NOp <NoOpComponent> <Dim> 64 <BackpropScale> 1 </NoOpComponent> +<ComponentName> gru1.GTrunc <BackpropTruncationComponent> <Dim> 64 <Scale> 1 <ClippingThreshold> 30 <ZeroingThreshold> 15 <ZeroingInterval> 20 <RecurrenceInterval> 1 <NumElementsClipped> 0 <NumElementsZeroed> 0 <NumElementsProcessed> 0 <NumZeroingBoundaries> 0 </BackpropTruncationComponent> +</Nnet3> + diff --git a/local/cn2lm/rnnlm/models.py b/local/cn2lm/rnnlm/models.py new file mode 100755 index 0000000000000000000000000000000000000000..5a19e664150669436202adad7245a2ae3cf787b2 --- /dev/null +++ b/local/cn2lm/rnnlm/models.py @@ -0,0 +1,205 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- + +# Copyright © 2021 INRIA (Imran Sheikh) +# AGPL-3.0-only or AGPL-3.0-or-later (https://www.gnu.org/licenses/agpl-3.0.txt) + +# This file is part of CN2LM. +# +# CN2LM is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# CN2LM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with CN2LM. If not, see <https://www.gnu.org/licenses/>. + +import torch, numpy, os, sys + +from data import MINI_BATCH_SIZE, MAX_LEN, MAX_ARCS + +numpy.random.seed(0) +torch.manual_seed(0) +torch.backends.cudnn.deterministic = True +torch.backends.cudnn.benchmark = False + +USE_GRU = True # needs to be True to use current support for Kaldi, can be false otherwise +SHARE_EMB = True # needs to be True to use current support for Kaldi, can be false otherwise + +class SausRNN(torch.nn.Module): + def __init__(self, config): + super(SausRNN, self).__init__() + self.vocab_size = len(config.vocab_dict) + self.embedding_dim = config.embedding_dim + self.combine_method = config.combine_method + if self.combine_method not in ["weighted-sum", "sum", "best", "avg"]: + raise ValueError(f"combine_method '{self.combine_method}' not supported") + + if SHARE_EMB: + emb_w = torch.Tensor(self.vocab_size, self.embedding_dim) + stdv = 1. / numpy.sqrt(emb_w.size(1)) # like in nn.Linear + emb_w.uniform_(-stdv, stdv) + self.embedding = torch.nn.Embedding.from_pretrained(emb_w, freeze=False, padding_idx=config.arcpadid) + else: + self.embedding = torch.nn.Embedding(num_embeddings = self.vocab_size, embedding_dim = self.embedding_dim, padding_idx=config.arcpadid) + + if USE_GRU: + self.rnn = torch.nn.GRU( + self.embedding_dim, + self.embedding_dim, + num_layers=1, + bias=True, + batch_first=True, + bidirectional=False + ) + else: + self.rnn = torch.nn.LSTM( + self.embedding_dim, + self.embedding_dim, + num_layers=1, + batch_first=True, + bidirectional=False + ) + + if SHARE_EMB: + self.hidden_to_target = torch.nn.Linear(self.embedding_dim, self.vocab_size, bias=False) + #self.hidden_to_target.weight.data = self.embedding.weight.data # creates problem!!! https://discuss.pytorch.org/t/how-to-use-shared-weights-in-different-layers-of-a-model/71263/2 + del self.hidden_to_target.weight + else: + self.hidden_to_target = torch.nn.Linear(self.embedding_dim, self.vocab_size) + + self.target_probs = torch.zeros((MINI_BATCH_SIZE * MAX_LEN, self.vocab_size)) + self.loss_mask = torch.zeros(MINI_BATCH_SIZE * MAX_LEN) + self.KLLoss = torch.nn.KLDivLoss(reduction = 'none') + + self.is_cuda = torch.cuda.is_available() + if self.is_cuda: + self.cuda() + self.target_probs = self.target_probs.cuda() + self.loss_mask = self.loss_mask.cuda() + + def forward(self, x_probs, x_ids, x_masks): + if self.is_cuda: + x_probs = x_probs.cuda() + x_ids = x_ids.cuda() + x_masks = x_masks.cuda() + device = x_probs.device + + bs, maxlen, maxarcs = x_probs.size() + + h = torch.zeros((1, bs, self.rnn.hidden_size)).to(device) + if not USE_GRU: + c = torch.zeros((1, bs, self.rnn.hidden_size)).to(device) + t_hs = [] + for t in range(maxlen): + inemb = self.embedding(x_ids[:,t,:].flatten()).view(bs * maxarcs, 1, self.embedding_dim) + h_repeated = h.repeat(1,1,maxarcs).view(1,bs*maxarcs,self.embedding_dim) + if not USE_GRU: + c_repeated = c.repeat(1,1,maxarcs).view(1,bs*maxarcs,self.embedding_dim) + _output, (hs, cs) = self.rnn(inemb, (h_repeated, c_repeated)) # output -> [bs * maxarcs, t=1, 1*self.embedding_dim] , h,c -> [1*1, bs * maxarcs, self.embedding_dim] + hs = hs.view(bs,maxarcs,self.embedding_dim) + cs = cs.view(bs,maxarcs,self.embedding_dim) + h, c = self.get_pooled_states(t, x_probs, hs, cs) # [bs,maxarcs,embedding_dim] -> [bs,embedding_dim] + else: + _output, hs = self.rnn(inemb, h_repeated) # output -> [bs * maxarcs, t=1, 1*self.embedding_dim] , h,c -> [1*1, bs * maxarcs, self.embedding_dim] + hs = hs.view(bs,maxarcs,self.embedding_dim) + h, _ = self.get_pooled_states(t, x_probs, hs) # [bs,maxarcs,embedding_dim] -> [bs,embedding_dim] + t_hs.append(h.view(bs,self.embedding_dim)) + + t_hs = torch.stack(t_hs,dim=1) # list([bs,embedding_dim]) * t -> [bs,t,embedding_dim] + lstm_outputs = t_hs.view(bs*maxlen, self.embedding_dim) + if SHARE_EMB: + self.hidden_to_target.weight = self.embedding.weight + linear_out = self.hidden_to_target(lstm_outputs) # [bs*t,embedding_dim] -> [bs*t,vocab_size] + log_probs = torch.nn.functional.log_softmax(linear_out,dim=1) # [bs*t,vocab_size] + + return log_probs + + def get_pooled_states(self, t, x_probs, hs, cs=None): + bs, _maxlen, maxarcs = x_probs.size() + cp = None + if self.combine_method == "best": + hp = hs[:,0,:] + if cs is not None: + cp = cs[:,0,:] + elif self.combine_method == "sum": + hp = hs.sum(dim=1) + if cs is not None: + cp = cs.sum(dim=1) + elif self.combine_method == "avg": + wts = x_probs[:,t,:].view(bs,maxarcs) + ones = torch.ones_like(wts) + wts = torch.where(wts>0,ones,wts) + hp = hs * wts.view(bs,maxarcs,1) + hp = hs.sum(dim=1) / wts.sum(1)[:,None] + if cs is not None: + cp = cs * wts.view(bs,maxarcs,1) + cp = cs.sum(dim=1)/ wts.sum(1)[:,None] + else: # "weighted-sum" + hp = hs * x_probs[:,t,:].view(bs,maxarcs,1) + hp = hp.sum(dim=1) + if cs is not None: + cp = cs * x_probs[:,t,:].view(bs,maxarcs,1) + cp = cp.sum(dim=1) + return hp,cp + + def compute_loss(self, y_pred_probs, y_probs, y_ids, y_masks): + self.target_probs.zero_() + self.loss_mask.zero_() + device = y_pred_probs.device + + log_prob_indices = torch.arange(y_pred_probs.shape[0]).view(-1,1).to(device) + vocab_indices = y_ids.view(MINI_BATCH_SIZE * MAX_LEN, MAX_ARCS).to(device) + vocab_probs = y_probs.view(MINI_BATCH_SIZE * MAX_LEN, MAX_ARCS).to(device) + self.target_probs[log_prob_indices, vocab_indices]=vocab_probs # note padded arcs will have zero probs, so taken care + self.loss_mask = y_masks.sum(dim=2).flatten().to(device) + self.loss_mask[torch.where(self.loss_mask>0)] = 1.0 + loss = self.KLLoss(y_pred_probs, self.target_probs) * self.loss_mask[:,None] # [bs*maxlen,vocab_size] + loss = loss.sum() / self.loss_mask.sum() + + return loss + + def sent_logp(self, in_ids, out_ids): + if self.is_cuda: + in_ids = in_ids.cuda() + out_ids = out_ids.cuda() + device = in_ids.device + + bs = 1 + maxlen = len(in_ids) + inemb = self.embedding(in_ids.view(bs,maxlen)) + h = torch.zeros((1, bs, self.rnn.hidden_size)).to(device) + if not USE_GRU: + c = torch.zeros((1, bs, self.rnn.hidden_size)).to(device) + output, (h, c) = self.rnn(inemb, (h, c)) # output -> [bs=1, len, 1*self.embedding_dim] + else: + output, h = self.rnn(inemb, h) # output -> [bs=1, len, 1*self.embedding_dim] + if SHARE_EMB: + self.hidden_to_target.weight = self.embedding.weight + linear_out = self.hidden_to_target(output.view(maxlen,self.rnn.hidden_size)) # [bs*t,embedding_dim] -> [bs*t,vocab_size] + log_probs = torch.nn.functional.log_softmax(linear_out,dim=1) # [bs*t,vocab_size] + pred_logp = torch.gather(log_probs, 1, out_ids.view(-1,1)).sum() + + return pred_logp + + def load_checkpoint(self, checkpoint_path): + self.hidden_to_target = torch.nn.Linear(self.embedding_dim, self.vocab_size, bias=False) + self.hidden_to_target.weight.data = self.embedding.weight.data + if os.path.isfile(os.path.join(checkpoint_path)): + try: + if self.is_cuda: + self.load_state_dict(torch.load(checkpoint_path)) + else: + self.load_state_dict(torch.load(checkpoint_path, map_location="cpu")) + except Exception as e: + print("Could not load previous model; Exitting") + print(e) + sys.exit() + else: + print("No previous model; Exitting") + sys.exit() diff --git a/local/cn2lm/rnnlm/train_cn2lm_rnn.py b/local/cn2lm/rnnlm/train_cn2lm_rnn.py new file mode 100755 index 0000000000000000000000000000000000000000..33c0258971642099f21cef84cc4b81478c880d1f --- /dev/null +++ b/local/cn2lm/rnnlm/train_cn2lm_rnn.py @@ -0,0 +1,83 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- + +# Copyright © 2021 INRIA (Imran Sheikh) +# AGPL-3.0-only or AGPL-3.0-or-later (https://www.gnu.org/licenses/agpl-3.0.txt) + +# This file is part of CN2LM. +# +# CN2LM is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# CN2LM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with CN2LM. If not, see <https://www.gnu.org/licenses/>. + +import torch +from models import SausRNN +from data import get_saus_dataset, build_config +from training import Trainer + +import argparse, os, sys + +torch.manual_seed(0) +torch.backends.cudnn.deterministic = True +torch.backends.cudnn.benchmark = False + +parser = argparse.ArgumentParser() +parser.add_argument('asr_vocab_file', type=str, help='Path to ASR words.txt file') +parser.add_argument('sup_text', type=str, help='Path to sup text file') +parser.add_argument('unsup_saus_dir', type=str, help='Path to unsup saus dir') +parser.add_argument('dev_saus_dir', type=str, help='Path to dev saus dir') +parser.add_argument('dev_text', type=str, help='Path to dev text file') +parser.add_argument('out_dir', type=str, help='output dir') +args = parser.parse_args() + +if not os.path.isfile(args.asr_vocab_file): + raise IOError(args.asr_vocab_file) + +if not os.path.isfile(args.sup_text): + raise IOError(args.sup_text) + +if not os.path.isdir(args.unsup_saus_dir): + raise IOError(args.unsup_saus_dir) + +if not os.path.isdir(args.dev_saus_dir): + raise IOError(args.dev_saus_dir) + +if not os.path.isfile(args.dev_text): + raise IOError(args.dev_text) + +if not os.path.isdir(args.out_dir): + raise IOError(args.out_dir) + +print('Preparing datasets ...') +config = build_config(args.asr_vocab_file) +train_dataset, _ = get_saus_dataset(config, args.unsup_saus_dir, eval=False, sup_text=args.sup_text) +valid_dataset, _ = get_saus_dataset(config, args.dev_saus_dir, eval=True, sup_text=None) +checkpoint_path = args.out_dir + +# Initialize and train the model +model = SausRNN(config) +num_epochs = 100 +trainer = Trainer(model, config, lr=0.001) +trainer.setup_ext_eval(config, args.dev_text) +trainer.load_checkpoint(checkpoint_path) + +pplist = [10000000] +for epoch in range(num_epochs): + print("========= Epoch %d of %d =========" % (epoch+1, num_epochs)) + train_loss = trainer.train(train_dataset) + valid_loss = trainer.test(valid_dataset) + ppl = trainer.ext_eval() + if ppl <= min(pplist): + trainer.save_checkpoint(epoch, checkpoint_path) + pplist.append(ppl) + print("========= Results: epoch %d of %d =========" % (epoch+1, num_epochs)) + print("Epoch %d |train::| loss: %.2f |valid::| loss: %.2f | ppl: %.2f" % (epoch+1, train_loss, valid_loss, ppl)) diff --git a/local/cn2lm/rnnlm/training.py b/local/cn2lm/rnnlm/training.py new file mode 100755 index 0000000000000000000000000000000000000000..d5aec3fb93a68cdf0bb5d24a8782a29614b74479 --- /dev/null +++ b/local/cn2lm/rnnlm/training.py @@ -0,0 +1,121 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- + +# Copyright © 2021 INRIA (Imran Sheikh) +# AGPL-3.0-only or AGPL-3.0-or-later (https://www.gnu.org/licenses/agpl-3.0.txt) + +# This file is part of CN2LM. +# +# CN2LM is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# CN2LM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with CN2LM. If not, see <https://www.gnu.org/licenses/>. + +import torch, numpy, sys, os +from tqdm import tqdm + +numpy.random.seed(0) +torch.manual_seed(0) +torch.backends.cudnn.deterministic = True +torch.backends.cudnn.benchmark = False + +from data import MINI_BATCH_SIZE, MAX_LEN, MAX_ARCS, get_eval_sents + +if torch.cuda.is_available(): + GPU_FLAG = True +else: + GPU_FLAG = False + +class Trainer: + def __init__(self, model, config, lr): + self.model = model + self.config = config + self.lr = lr + self.optimizer = torch.optim.Adam(model.parameters(), lr=self.lr) + self.scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizer, 'min') + + def load_checkpoint(self, checkpoint_path): + if os.path.isfile(os.path.join(checkpoint_path, "model_state.pth")): + try: + if self.model.is_cuda: + self.model.load_state_dict(torch.load(os.path.join(checkpoint_path, "model_state.pth"))) + else: + self.model.load_state_dict(torch.load(os.path.join(checkpoint_path, "model_state.pth"), map_location="cpu")) + except Exception as e: + print("Could not load previous model; starting from scratch") + print(e) + else: + print("No previous model; starting from scratch") + + def save_checkpoint(self, epoch, checkpoint_path): + try: + torch.save(self.model.state_dict(), os.path.join(checkpoint_path, "model_state.pth")) + except: + print("Could not save model") + + def train(self, dataset): + train_loss = 0 + num_samples = 0 + self.model.train() + for _idx, batch in enumerate(tqdm(dataset.loader)): + if batch[0].shape[0] < MINI_BATCH_SIZE: + break + else: + x_probs,x_ids,x_masks,y_probs,y_ids,y_masks = batch + batch_size = x_probs.size()[0] + num_samples += batch_size + ypred_probs = self.model(x_probs,x_ids,x_masks) # [bs*maxlen,vocab_size] + loss = self.model.compute_loss(ypred_probs, y_probs, y_ids, y_masks) + self.optimizer.zero_grad() + loss.backward() + self.optimizer.step() + train_loss += loss.cpu().data.numpy().item() * batch_size + train_loss /= num_samples + return train_loss + + def test(self, dataset, print_interval=20): + test_loss = 0 + num_samples = 0 + self.model.eval() + for _idx, batch in enumerate(dataset.loader): + if batch[0].shape[0] < MINI_BATCH_SIZE: + break + else: + x_probs,x_ids,x_masks,y_probs,y_ids,y_masks = batch + batch_size = x_probs.size()[0] + num_samples += batch_size + ypred_probs = self.model(x_probs,x_ids,x_masks) # [bs*maxlen,vocab_size] + loss = self.model.compute_loss(ypred_probs, y_probs, y_ids, y_masks) + test_loss += loss.cpu().data.numpy().item() * batch_size + test_loss /= num_samples + self.scheduler.step(test_loss) # if the validation loss hasn't decreased, lower the learning rate + return test_loss + + def calc_ppl(self, sents, NW, NS): + set_logp = 0.0 + self.model.eval() + for in_ids, out_ids in sents: + sent_logp = self.model.sent_logp(in_ids, out_ids) + set_logp += sent_logp.cpu().data.numpy().item() + logp = set_logp / numpy.log(10) # logn to log10 + ppl = 10.0**(-1 * logp / (NW + NS)) + ppl1 = 10.0**(-1 * logp / NW) + print("logp: %.2f | NW: %d | NS: %d | ppl: %.4f | ppl1: %.4f" % (logp, NW, NS, ppl, ppl1) ) + return ppl + + def setup_ext_eval(self, config, dev_text): + self.ext_eval_dataset = get_eval_sents(config, dev_text) + print('Done setting up extrinsic evaluation data ...') + + def ext_eval(self): + sents, NW, NS = self.ext_eval_dataset + ppl = self.calc_ppl(sents, NW, NS) + return ppl