[
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Code of Conduct\n\nFacebook has adopted a Code of Conduct that we expect project participants to adhere to.\nPlease read the [full text](https://code.fb.com/codeofconduct/)\nso that you can understand what actions will and will not be tolerated.\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to this repo\n\n## Pull Requests\n\nIn order to accept your pull request, we need you to submit a CLA. You only need\nto do this once to work on any of Facebook's open source projects.\n\nComplete your CLA here: <https://code.facebook.com/cla>\n\n## Issues\nWe use GitHub issues to track public bugs. Please ensure your description is\nclear and has sufficient instructions to be able to reproduce the issue.\n\n## License\nBy contributing to this repo, you agree that your contributions will be licensed\nunder the LICENSE file in the root directory of this source tree.\n"
  },
  {
    "path": "LICENSE",
    "content": "Attribution-NonCommercial 4.0 International\n\n=======================================================================\n\nCreative Commons Corporation (\"Creative Commons\") is not a law firm and\ndoes not provide legal services or legal advice. Distribution of\nCreative Commons public licenses does not create a lawyer-client or\nother relationship. Creative Commons makes its licenses and related\ninformation available on an \"as-is\" basis. Creative Commons gives no\nwarranties regarding its licenses, any material licensed under their\nterms and conditions, or any related information. Creative Commons\ndisclaims all liability for damages resulting from their use to the\nfullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and\nconditions that creators and other rights holders may use to share\noriginal works of authorship and other material subject to copyright\nand certain other rights specified in the public license below. The\nfollowing considerations are for informational purposes only, are not\nexhaustive, and do not form part of our licenses.\n\n     Considerations for licensors: Our public licenses are\n     intended for use by those authorized to give the public\n     permission to use material in ways otherwise restricted by\n     copyright and certain other rights. Our licenses are\n     irrevocable. Licensors should read and understand the terms\n     and conditions of the license they choose before applying it.\n     Licensors should also secure all rights necessary before\n     applying our licenses so that the public can reuse the\n     material as expected. Licensors should clearly mark any\n     material not subject to the license. This includes other CC-\n     licensed material, or material used under an exception or\n     limitation to copyright. More considerations for licensors:\n     wiki.creativecommons.org/Considerations_for_licensors\n\n     Considerations for the public: By using one of our public\n     licenses, a licensor grants the public permission to use the\n     licensed material under specified terms and conditions. If\n     the licensor's permission is not necessary for any reason--for\n     example, because of any applicable exception or limitation to\n     copyright--then that use is not regulated by the license. Our\n     licenses grant only permissions under copyright and certain\n     other rights that a licensor has authority to grant. Use of\n     the licensed material may still be restricted for other\n     reasons, including because others have copyright or other\n     rights in the material. A licensor may make special requests,\n     such as asking that all changes be marked or described.\n     Although not required by our licenses, you are encouraged to\n     respect those requests where reasonable. More_considerations\n     for the public:\n\twiki.creativecommons.org/Considerations_for_licensees\n\n=======================================================================\n\nCreative Commons Attribution-NonCommercial 4.0 International Public\nLicense\n\nBy exercising the Licensed Rights (defined below), You accept and agree\nto be bound by the terms and conditions of this Creative Commons\nAttribution-NonCommercial 4.0 International Public License (\"Public\nLicense\"). To the extent this Public License may be interpreted as a\ncontract, You are granted the Licensed Rights in consideration of Your\nacceptance of these terms and conditions, and the Licensor grants You\nsuch rights in consideration of benefits the Licensor receives from\nmaking the Licensed Material available under these terms and\nconditions.\n\nSection 1 -- Definitions.\n\n  a. Adapted Material means material subject to Copyright and Similar\n     Rights that is derived from or based upon the Licensed Material\n     and in which the Licensed Material is translated, altered,\n     arranged, transformed, or otherwise modified in a manner requiring\n     permission under the Copyright and Similar Rights held by the\n     Licensor. For purposes of this Public License, where the Licensed\n     Material is a musical work, performance, or sound recording,\n     Adapted Material is always produced where the Licensed Material is\n     synched in timed relation with a moving image.\n\n  b. Adapter's License means the license You apply to Your Copyright\n     and Similar Rights in Your contributions to Adapted Material in\n     accordance with the terms and conditions of this Public License.\n\n  c. Copyright and Similar Rights means copyright and/or similar rights\n     closely related to copyright including, without limitation,\n     performance, broadcast, sound recording, and Sui Generis Database\n     Rights, without regard to how the rights are labeled or\n     categorized. For purposes of this Public License, the rights\n     specified in Section 2(b)(1)-(2) are not Copyright and Similar\n     Rights.\n  d. Effective Technological Measures means those measures that, in the\n     absence of proper authority, may not be circumvented under laws\n     fulfilling obligations under Article 11 of the WIPO Copyright\n     Treaty adopted on December 20, 1996, and/or similar international\n     agreements.\n\n  e. Exceptions and Limitations means fair use, fair dealing, and/or\n     any other exception or limitation to Copyright and Similar Rights\n     that applies to Your use of the Licensed Material.\n\n  f. Licensed Material means the artistic or literary work, database,\n     or other material to which the Licensor applied this Public\n     License.\n\n  g. Licensed Rights means the rights granted to You subject to the\n     terms and conditions of this Public License, which are limited to\n     all Copyright and Similar Rights that apply to Your use of the\n     Licensed Material and that the Licensor has authority to license.\n\n  h. Licensor means the individual(s) or entity(ies) granting rights\n     under this Public License.\n\n  i. NonCommercial means not primarily intended for or directed towards\n     commercial advantage or monetary compensation. For purposes of\n     this Public License, the exchange of the Licensed Material for\n     other material subject to Copyright and Similar Rights by digital\n     file-sharing or similar means is NonCommercial provided there is\n     no payment of monetary compensation in connection with the\n     exchange.\n\n  j. Share means to provide material to the public by any means or\n     process that requires permission under the Licensed Rights, such\n     as reproduction, public display, public performance, distribution,\n     dissemination, communication, or importation, and to make material\n     available to the public including in ways that members of the\n     public may access the material from a place and at a time\n     individually chosen by them.\n\n  k. Sui Generis Database Rights means rights other than copyright\n     resulting from Directive 96/9/EC of the European Parliament and of\n     the Council of 11 March 1996 on the legal protection of databases,\n     as amended and/or succeeded, as well as other essentially\n     equivalent rights anywhere in the world.\n\n  l. You means the individual or entity exercising the Licensed Rights\n     under this Public License. Your has a corresponding meaning.\n\nSection 2 -- Scope.\n\n  a. License grant.\n\n       1. Subject to the terms and conditions of this Public License,\n          the Licensor hereby grants You a worldwide, royalty-free,\n          non-sublicensable, non-exclusive, irrevocable license to\n          exercise the Licensed Rights in the Licensed Material to:\n\n            a. reproduce and Share the Licensed Material, in whole or\n               in part, for NonCommercial purposes only; and\n\n            b. produce, reproduce, and Share Adapted Material for\n               NonCommercial purposes only.\n\n       2. Exceptions and Limitations. For the avoidance of doubt, where\n          Exceptions and Limitations apply to Your use, this Public\n          License does not apply, and You do not need to comply with\n          its terms and conditions.\n\n       3. Term. The term of this Public License is specified in Section\n          6(a).\n\n       4. Media and formats; technical modifications allowed. The\n          Licensor authorizes You to exercise the Licensed Rights in\n          all media and formats whether now known or hereafter created,\n          and to make technical modifications necessary to do so. The\n          Licensor waives and/or agrees not to assert any right or\n          authority to forbid You from making technical modifications\n          necessary to exercise the Licensed Rights, including\n          technical modifications necessary to circumvent Effective\n          Technological Measures. For purposes of this Public License,\n          simply making modifications authorized by this Section 2(a)\n          (4) never produces Adapted Material.\n\n       5. Downstream recipients.\n\n            a. Offer from the Licensor -- Licensed Material. Every\n               recipient of the Licensed Material automatically\n               receives an offer from the Licensor to exercise the\n               Licensed Rights under the terms and conditions of this\n               Public License.\n\n            b. No downstream restrictions. You may not offer or impose\n               any additional or different terms or conditions on, or\n               apply any Effective Technological Measures to, the\n               Licensed Material if doing so restricts exercise of the\n               Licensed Rights by any recipient of the Licensed\n               Material.\n\n       6. No endorsement. Nothing in this Public License constitutes or\n          may be construed as permission to assert or imply that You\n          are, or that Your use of the Licensed Material is, connected\n          with, or sponsored, endorsed, or granted official status by,\n          the Licensor or others designated to receive attribution as\n          provided in Section 3(a)(1)(A)(i).\n\n  b. Other rights.\n\n       1. Moral rights, such as the right of integrity, are not\n          licensed under this Public License, nor are publicity,\n          privacy, and/or other similar personality rights; however, to\n          the extent possible, the Licensor waives and/or agrees not to\n          assert any such rights held by the Licensor to the limited\n          extent necessary to allow You to exercise the Licensed\n          Rights, but not otherwise.\n\n       2. Patent and trademark rights are not licensed under this\n          Public License.\n\n       3. To the extent possible, the Licensor waives any right to\n          collect royalties from You for the exercise of the Licensed\n          Rights, whether directly or through a collecting society\n          under any voluntary or waivable statutory or compulsory\n          licensing scheme. In all other cases the Licensor expressly\n          reserves any right to collect such royalties, including when\n          the Licensed Material is used other than for NonCommercial\n          purposes.\n\nSection 3 -- License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the\nfollowing conditions.\n\n  a. Attribution.\n\n       1. If You Share the Licensed Material (including in modified\n          form), You must:\n\n            a. retain the following if it is supplied by the Licensor\n               with the Licensed Material:\n\n                 i. identification of the creator(s) of the Licensed\n                    Material and any others designated to receive\n                    attribution, in any reasonable manner requested by\n                    the Licensor (including by pseudonym if\n                    designated);\n\n                ii. a copyright notice;\n\n               iii. a notice that refers to this Public License;\n\n                iv. a notice that refers to the disclaimer of\n                    warranties;\n\n                 v. a URI or hyperlink to the Licensed Material to the\n                    extent reasonably practicable;\n\n            b. indicate if You modified the Licensed Material and\n               retain an indication of any previous modifications; and\n\n            c. indicate the Licensed Material is licensed under this\n               Public License, and include the text of, or the URI or\n               hyperlink to, this Public License.\n\n       2. You may satisfy the conditions in Section 3(a)(1) in any\n          reasonable manner based on the medium, means, and context in\n          which You Share the Licensed Material. For example, it may be\n          reasonable to satisfy the conditions by providing a URI or\n          hyperlink to a resource that includes the required\n          information.\n\n       3. If requested by the Licensor, You must remove any of the\n          information required by Section 3(a)(1)(A) to the extent\n          reasonably practicable.\n\n       4. If You Share Adapted Material You produce, the Adapter's\n          License You apply must not prevent recipients of the Adapted\n          Material from complying with this Public License.\n\nSection 4 -- Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that\napply to Your use of the Licensed Material:\n\n  a. for the avoidance of doubt, Section 2(a)(1) grants You the right\n     to extract, reuse, reproduce, and Share all or a substantial\n     portion of the contents of the database for NonCommercial purposes\n     only;\n\n  b. if You include all or a substantial portion of the database\n     contents in a database in which You have Sui Generis Database\n     Rights, then the database in which You have Sui Generis Database\n     Rights (but not its individual contents) is Adapted Material; and\n\n  c. You must comply with the conditions in Section 3(a) if You Share\n     all or a substantial portion of the contents of the database.\n\nFor the avoidance of doubt, this Section 4 supplements and does not\nreplace Your obligations under this Public License where the Licensed\nRights include other Copyright and Similar Rights.\n\nSection 5 -- Disclaimer of Warranties and Limitation of Liability.\n\n  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE\n     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS\n     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\n     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,\n     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,\n     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR\n     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,\n     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT\n     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT\n     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n\n  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE\n     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,\n     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,\n     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,\n     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR\n     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN\n     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR\n     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR\n     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n\n  c. The disclaimer of warranties and limitation of liability provided\n     above shall be interpreted in a manner that, to the extent\n     possible, most closely approximates an absolute disclaimer and\n     waiver of all liability.\n\nSection 6 -- Term and Termination.\n\n  a. This Public License applies for the term of the Copyright and\n     Similar Rights licensed here. However, if You fail to comply with\n     this Public License, then Your rights under this Public License\n     terminate automatically.\n\n  b. Where Your right to use the Licensed Material has terminated under\n     Section 6(a), it reinstates:\n\n       1. automatically as of the date the violation is cured, provided\n          it is cured within 30 days of Your discovery of the\n          violation; or\n\n       2. upon express reinstatement by the Licensor.\n\n     For the avoidance of doubt, this Section 6(b) does not affect any\n     right the Licensor may have to seek remedies for Your violations\n     of this Public License.\n\n  c. For the avoidance of doubt, the Licensor may also offer the\n     Licensed Material under separate terms or conditions or stop\n     distributing the Licensed Material at any time; however, doing so\n     will not terminate this Public License.\n\n  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public\n     License.\n\nSection 7 -- Other Terms and Conditions.\n\n  a. The Licensor shall not be bound by any additional or different\n     terms or conditions communicated by You unless expressly agreed.\n\n  b. Any arrangements, understandings, or agreements regarding the\n     Licensed Material not stated herein are separate from and\n     independent of the terms and conditions of this Public License.\n\nSection 8 -- Interpretation.\n\n  a. For the avoidance of doubt, this Public License does not, and\n     shall not be interpreted to, reduce, limit, restrict, or impose\n     conditions on any use of the Licensed Material that could lawfully\n     be made without permission under this Public License.\n\n  b. To the extent possible, if any provision of this Public License is\n     deemed unenforceable, it shall be automatically reformed to the\n     minimum extent necessary to make it enforceable. If the provision\n     cannot be reformed, it shall be severed from this Public License\n     without affecting the enforceability of the remaining terms and\n     conditions.\n\n  c. No term or condition of this Public License will be waived and no\n     failure to comply consented to unless expressly agreed to by the\n     Licensor.\n\n  d. Nothing in this Public License constitutes or may be interpreted\n     as a limitation upon, or waiver of, any privileges and immunities\n     that apply to the Licensor or You, including from the legal\n     processes of any jurisdiction or authority.\n\n=======================================================================\n\nCreative Commons is not a party to its public\nlicenses. Notwithstanding, Creative Commons may elect to apply one of\nits public licenses to material it publishes and in those instances\nwill be considered the “Licensor.” The text of the Creative Commons\npublic licenses is dedicated to the public domain under the CC0 Public\nDomain Dedication. Except for the limited purpose of indicating that\nmaterial is shared under a Creative Commons public license or as\notherwise permitted by the Creative Commons policies published at\ncreativecommons.org/policies, Creative Commons does not authorize the\nuse of the trademark \"Creative Commons\" or any other trademark or logo\nof Creative Commons without its prior written consent including,\nwithout limitation, in connection with any unauthorized modifications\nto any of its public licenses or any other arrangements,\nunderstandings, or agreements concerning use of licensed material. For\nthe avoidance of doubt, this paragraph does not form part of the\npublic licenses.\n\nCreative Commons may be contacted at creativecommons.org.\n"
  },
  {
    "path": "README.md",
    "content": "# Maths from examples -  Learning advanced mathematical computations from examples\n\nThis is the source code and data sets relevant to the paper Learning advanced mathematical computations from examples, by Amaury hayat, François Charton and Guillaume Lample, published by ICLR 2021. https://arxiv.org/abs/2006.06462\n\nWe provide code for \n* data generation\n* model training\n* model evaluation\n\nWe also provide\n* 7 datasets\n* 7 pretrained models\n\n### Dependencies \n\n* Python (3.8+)\n* Numpy (1.16.4+)\n* Sympy (1.4+)\n* Pytorch (1.7.1+)\n* Control library (0.8.4, from conda-forge)\n* CUDA (i.e. a NVIDIA chip) if you intend to use a GPU\n* Apex for half-precision training\n\n\n## Important notes\n\n### Learning with and without GPU\nAll the code can run on CPU only (set parameter --cpu to true). Data generation is to be done on CPU only. Model training and model evaluation can be done on CPU, but training will be extremely slow. To train or evaluate with a GPU, you need a CUDA-enabled GPU (i.e. a NVIDIA chip).\n\nWe support: \n* Half-Precision (with NVIDIA Apex library): set parameters `--fp16 true --amp 2`, to disable, set `--fp16 false --amp -1`\n* Multi-GPU training: to run an experiment with several GPU on a unique machine, use \n```bash\nexport NGPU=8; python -m torch.distributed.launch --nproc_per_node=$NGPU train.py  # parameters for your experiment\n```\n* Multi-node training: using GPU on different machines is handled by SLURM (see code)\n\nOn GPU with limited video memory, you will need to reduce memory usage by adjusting `--batch_size`. Try to set it to the largest value that will fit in your CUDA memory. Since model optimization is performed at the end of each minibatch, smaller batch sizes will gratly slow learning. You can compensate for this by increasing `--accumulate_gradient`, which controls the number of mini-batches the model sees before optimizing the model.\n\n### Dump paths and experiment names\nAll paths should be absolute : `--dump_path ./mydump` might not work, `--dump_path c:/Users/me/mydump` should be fine.\nThe directories where your datasets, models, and logfiles will be generated are constructed from the parameters --dump_path --exp_name and --exp_id, as {dump_path}/{exp_name}/{exp_id}/, if you do not specify an exp_id, a random unique name will be created for you. If you reuse the same dump_path/exp/name/exp_id, generation or training will resume there (adding new examples, or loading the previous model for training).\n\nAll results will be logged in file `train.log`of the experiment path.\n\nAll models and datasets can be downloaded from https://dl.fbaipublicfiles.com/MathsFromExamples/. By convention, in all code examples, datasets and models use the path `/checkpoint/fcharton/dumped/`. You will need to adjust this to the correct path on your local machine. \n\n\n## Data sets\n\nWe provide 7 datasets, all can be found on https://dl.fbaipublicfiles.com/MathsFromExamples/data/ as tar.gz archives.\n \n### Stability : balanced sample of systems of degree 2 to 5 (50% stable), predicting speed of convergence at 0.01 (largest real part of eigenvalue): \nin archive https://dl.fbaipublicfiles.com/MathsFromExamples/data/ddss_stability_balanced.tar.gz\n* ddss_stability_balanced.prefix_counts.train : 25,544,975 systems\n* ddss_stability_balanced.prefix_counts.valid.final : 10,000 systems\n* ddss_stability_balanced.prefix_counts.test.final : 10,000 systems\n\n### Stability : random sample of systems of degree 2 to 6, predicting speed of convergence at 0.01\nin archive https://dl.fbaipublicfiles.com/MathsFromExamples/data/ddss_stability.tar.gz\n* ddss_stability.prefix_counts.train : 92,994,423 systems\n* ddss_stability.prefix_counts.valid.final : 10,000 systems\n* ddss_stability.prefix_counts.test.final : 10,000 systems\n\n### Controllability: balanced sample of systems of degree 3 to 5 (50% stable), predicting controllability (a binary value)\nin archive https://dl.fbaipublicfiles.com/MathsFromExamples/data/ddss_control.tar.gz\n* ddss_control.prefix_counts.train : 26,577,934 systems\n* ddss_control.prefix_counts.valid.final : 10,000 systems\n* ddss_control.prefix_counts.test.final : 10,000 systems\n\n### Controllability: sample of controllable systems of degree 3 to 6, predicting a control matrix\nin archive https://dl.fbaipublicfiles.com/MathsFromExamples/data/ddss_gram.tar.gz\n* ddss_gram.prefix_counts.train : 53,680,092 systems\n* ddss_gram.prefix_counts.valid.final : 10,000 systems\n* ddss_gram.prefix_counts.test.final : 10,000 systems\n\n### Non autonomous controllability: random sample (82.4% controllable) of systems of degree 2 and 3, predicting controllability\nin archive https://dl.fbaipublicfiles.com/MathsFromExamples/data/ddss_control_t.tar.gz\n* ddss_control_t.prefix_counts.train : 65,754,655 systems\n* ddss_control_t.prefix_counts.valid.final : 10,000 systems\n* ddss_control_t.prefix_counts.test.final : 10,000 systems\n\n### Non autonomous controllability: balanced sample (50/50) of systems of degree 2 and 3, predicting controllability\nin archive https://dl.fbaipublicfiles.com/MathsFromExamples/data/ddss_control_t_bal.tar.gz\n* ddss_control_t_bal.prefix_counts.train : 23,125,016 systems\n* ddss_control_t_bal.prefix_counts.valid.final : 10,000 systems\n* ddss_control_t_bal.prefix_counts.test.final : 10,000 systems\n\n### Partial differential equations with initial conditions, predicting existence of a solution and behavior at infinity\nin archive https://dl.fbaipublicfiles.com/MathsFromExamples/data/ddss_fourier.tar.gz\n* ddss_fourier.prefix_counts.train : 52,285,760 systems\n* ddss_fourier.prefix_counts.valid.final : 10,000 systems\n* ddss_fourier.prefix_counts.test.final : 10,000 systems\n\n## Training a model from a dataset\n\n```bash\npython train.py \n\n# experiment parameters \n# the full path of this experiment will be /checkpoint/fcharton/dumped/ddss_ctrl/exp_1\n--dump_path '/checkpoint/fcharton/dumped'   # path for log files and saved models, avoid ./ and other non absolute paths\n--exp_name ddss_ctrl                        # name\n--exp_id exp_1                              # id : randomly generated if absent\n\n# dataset\n--export_data false\n--tasks ode_control         # set to `ode_convergence_speed`, `ode_control` or `fourier_cond_init`\n# '{tasks},{train_file_path},{valid_file_path},{test_file_path}'\n--reload_data 'ode_control,/checkpoint/fcharton/dumped/ddss_gen_ctrl/ddss_control.prefix_counts.train,/checkpoint/fcharton/dumped/ddss_gen_ctrl/ddss_control.prefix_counts.valid.final,/checkpoint/fcharton/dumped/ddss_gen_ctrl/ddss_control.prefix_counts.test.final' \n--reload_size 40000000      # nr of records to load\n--max_len 512               # max length of input or output\n\n# model parameters\n--emb_dim 512 \n--n_enc_layers 6 \n--n_dec_layers 6 \n--n_heads 8 \n--optimizer 'adam_inverse_sqrt,warmup_updates=10000,lr=0.0001,weight_decay=0.01'\n\n# training parameters\n--batch_size 256        # minibatch size, reduce to fit available GPU memory\n--epoch_size 300000     # how often evaluation on validation set is performed\n--beam_eval 0           # use beam search for evaluation (set to 1 for quantitative tasks)\n--eval_size 10000       # size of validation set\n--batch_size_eval 256   # batchs for validation, reduce to adjust memory\n\n# validation metrics\n# valid_{task}_acc or valid_{task}_beam_acc depending on whether beam search is used  \n--validation_metrics valid_ode_control_acc \n# stop after no increase in 20 epochs\n--stopping_criterion 'valid_ode_control_acc,20' \n```\n\n## Generating your own data sets\n\nTo generate a dataset, use the parameters\n```bash \npython train.py --cpu true --export_data true  --reload_data '' --env_base_seed -1  --num_workers 20 --task # task specific parameters \n```\nGenerated data (exported as sequences of tokens) will be written in file data.prefix in the dump path of the experiment. To be used for training, these files need to be post-processed as shown in the examples below.\n\nIMPORTANT NOTE : Data generation is very slow, and sometimes results in errors that cause the program to abort and need to be relaunched. Typical generating speeds are one or a few systems per second. Whereas one might want to use this code to experiment with data generation, creating datasets on which our models can be trained (10 million examples or more) requires a lot of computing power (typically 200-300 experiments, with 20 CPU each, running for several days)\n\nImportant parameters for data generation are : \n* `--tasks` : ode_convergence_speed, ode_control or fourier_cond_init\n* `--cpu` : always set to true\n* `--num_workers` : set to the number of cores you can use\n* `--env_base_seed` : set to -1\n* `--min_degree` and `--max_degree` : bounds for the size of the systems generated  \nFor more details, see file 'envs/ode.py' in the source code\n\n### Predicting stability - balanced sample (50% stable), systems of degree 2 to 5\n\t\n```bash\n# Generation command\npython train.py --dump_path '/checkpoint/fcharton/dumped' --save_periodic 0 --fp16 false --amp -1 --emb_dim 128 --n_enc_layers 2 --n_dec_layers 2 --n_heads 8 --dropout 0 --attention_dropout 0 --share_inout_emb true --sinusoidal_embeddings false --max_len 512 --batch_size 32 --optimizer 'adam,lr=0.0001' --clip_grad_norm 5 --epoch_size 300000 --max_epoch 100000 --accumulate_gradients 1 --env_name ode --max_int 10 --precision 2 --skip_zero_gradient true --positive false --nonnull true --prob_int 0.3 --min_degree 2 --max_degree 5 --eval_value 0.01 --prob_positive 0.5 --num_workers 20 --cpu true --stopping_criterion '' --validation_metrics '' --export_data true --reload_data '' --tasks ode_convergence_speed --env_base_seed -1 --exp_name ddss_gen_stab_bal\n\n# Post-processing\n# assemble raw data file from prefixes\ncat */data.prefix \\\n| awk 'BEGIN{PROCINFO[\"sorted_in\"]=\"@val_num_desc\"}{c[$0]++}END{for (i in c) printf(\"%i|%s\\n\",c[i],i)}' \\\n> ddss_stability_balanced.prefix_counts\n\n# create train, valid and test samples\npython ~/MathsFromExamples/split_data.py ddss_stability_balanced.prefix_counts 10000\n\n# check valid and test for duplicates and remove them\nawk -F\"[|\\t]\" 'NR==FNR { lines[$2]=1; next } !($2 in lines)' ddss_stability_balanced.prefix_counts.train ddss_stability_balanced.prefix_counts.valid > ddss_stability_balanced.prefix_counts.valid.final\nawk -F\"[|\\t]\" 'NR==FNR { lines[$2]=1; next } !($2 in lines)' ddss_stability_balanced.prefix_counts.train ddss_stability_balanced.prefix_counts.test > ddss_stability_balanced.prefix_counts.test.final\n```\n\n### Predicting stability - random sample, systems of degree 2 to 6\n\n```bash\n# Generation command\npython train.py --dump_path '/checkpoint/fcharton/dumped' --save_periodic 0 --fp16 false --amp -1 --emb_dim 128 --n_enc_layers 2 --n_dec_layers 2 --n_heads 8 --dropout 0 --attention_dropout 0 --share_inout_emb true --sinusoidal_embeddings false --max_len 512 --batch_size 32 --optimizer 'adam,lr=0.0001' --clip_grad_norm 5 --epoch_size 300000 --max_epoch 100000 --accumulate_gradients 1 --env_name ode --max_int 10 --precision 2 --skip_zero_gradient true --positive false --nonnull true --prob_int 0.3 --min_degree 2 --max_degree 6 --eval_value 0.01 --num_workers 20 --cpu true --stopping_criterion '' --validation_metrics '' --export_data true --reload_data '' --tasks ode_convergence_speed --env_base_seed -1 --exp_name ddss_gen_stab\n\n# assemble raw data file from prefixes\ncat */data.prefix \\\n| awk 'BEGIN{PROCINFO[\"sorted_in\"]=\"@val_num_desc\"}{c[$0]++}END{for (i in c) printf(\"%i|%s\\n\",c[i],i)}' \\\n> ddss_stability.prefix_counts\n \n# create train, valid and test samples \npython ~/MathsFromExamples/split_data.py ddss_stability.prefix_counts 10000\n\n# check valid and test for duplicates and remove them\nawk -F\"[|\\t]\" 'NR==FNR { lines[$2]=1; next } !($2 in lines)' ddss_stability.prefix_counts.train ddss_stability.prefix_counts.valid > ddss_stability.prefix_counts.valid.final\nawk -F\"[|\\t]\" 'NR==FNR { lines[$2]=1; next } !($2 in lines)' ddss_stability.prefix_counts.train ddss_stability.prefix_counts.test > ddss_stability.prefix_counts.test.final\n```\n\n### Predicting controllability - balanced sample, systems of degree 3 to 6\n\n```bash\n# generation command \npython train.py --dump_path '/checkpoint/fcharton/dumped' --save_periodic 0 --fp16 false --amp -1 --emb_dim 128 --n_enc_layers 2 --n_dec_layers 2 --n_heads 8 --dropout 0 --attention_dropout 0 --share_inout_emb true --sinusoidal_embeddings false --max_len 512 --batch_size 32 --optimizer 'adam,lr=0.0001' --clip_grad_norm 5 --epoch_size 300000 --max_epoch 100000 --accumulate_gradients 1 --env_name ode --max_int 10 --precision 3 --skip_zero_gradient true --positive false --nonnull true --prob_int 0.3 --min_degree 3 --max_degree 6 --eval_value 0.9 --allow_complex false --jacobian_precision 3 --qualitative true --num_workers 20 --cpu true --stopping_criterion '' --validation_metrics '' --export_data true --reload_data '' --tasks ode_control --env_base_seed -1 --exp_name ddss_gen_ctrl\n\n# assemble non controllable cases from prefixes\ncat */data.prefix \\\n| grep '0$' \\\n| awk 'BEGIN{PROCINFO[\"sorted_in\"]=\"@val_num_desc\"}{c[$0]++}END{for (i in c) printf(\"%i|%s\\n\",c[i],i)}' \\\n> ddss_control.prefix_counts.0\n\n# count them\nwc -l ddss_control.prefix_counts.0   # 13,298,967\n\n# assemble controllable cases from prefixes\ncat */data.prefix \\\n| grep '1$' \\\n| awk 'BEGIN{PROCINFO[\"sorted_in\"]=\"@val_num_desc\"}{c[$0]++}END{for (i in c) printf(\"%i|%s\\n\",c[i],i)}' \\\n| head -n 13298967 > ddss_control.prefix_counts.1\n\n# assemble prefix_counts\ncat ddss_control.prefix_counts.0 ddss_control.prefix_counts.1 | shuf > ddss_control.prefix_counts\n\n# create train, valid and test samples\npython ~/MathsFromExamples/split_data.py ddss_control.prefix_counts 10000\n\n# check valid and test for duplicates and remove them\nawk -F\"[|\\t]\" 'NR==FNR { lines[$2]=1; next } !($2 in lines)' ddss_control.prefix_counts.train ddss_control.prefix_counts.valid > ddss_control.prefix_counts.valid.final\nawk -F\"[|\\t]\" 'NR==FNR { lines[$2]=1; next } !($2 in lines)' ddss_control.prefix_counts.train ddss_control.prefix_counts.test > ddss_control.prefix_counts.test.final\n```\n\n### Predicting non autonomous controllability: unbalanced sample, systems of 2 to 3 equations \n\n```bash\n# generation command \npython train.py --dump_path '/checkpoint/fcharton/dumped' --save_periodic 0 --fp16 false --amp -1 --emb_dim 128 --n_enc_layers 2 --n_dec_layers 2 --n_heads 8 --dropout 0 --attention_dropout 0 --share_inout_emb true --sinusoidal_embeddings false --max_len 512 --batch_size 32 --optimizer 'adam,lr=0.0001' --clip_grad_norm 5 --epoch_size 300000 --max_epoch 100000 --accumulate_gradients 1 --env_name ode --max_int 10 --precision 3 --skip_zero_gradient true --positive false --nonnull true --prob_int 0.3 --min_degree 2 --max_degree 3 --eval_value 0.5 --allow_complex false --jacobian_precision 3 --qualitative false --tau 1 --num_workers 20 --cpu true --stopping_criterion '' --validation_metrics '' --export_data true --reload_data '' --tasks ode_control --env_base_seed -1 --exp_name ddss_gen_ctrl_t\n\n# assemble raw data file from prefixes\ncat */data.prefix \\\n| awk 'BEGIN{PROCINFO[\"sorted_in\"]=\"@val_num_desc\"}{c[$0]++}END{for (i in c) printf(\"%i|%s\\n\",c[i],i)}' \\\n> ddss_control_t.prefix_counts\n\n# create train, valid and test samples\npython ~/MathsFromExamples/split_data.py ddss_control_t.prefix_counts 10000\n\n# check valid and test for duplicates and remove them\nawk -F\"[|\\t]\" 'NR==FNR { lines[$2]=1; next } !($2 in lines)' ddss_control_t.prefix_counts.train ddss_control_t.prefix_counts.valid > ddss_control_t.prefix_counts.valid.final\nawk -F\"[|\\t]\" 'NR==FNR { lines[$2]=1; next } !($2 in lines)' ddss_control_t.prefix_counts.train ddss_control_t.prefix_counts.test > ddss_control_t.prefix_counts.test.final\n```\n\n### Predicting non autonomous controllability: balanced sample, systems of 2 to 3 equations \n\n```bash\n# generation command \npython train.py --dump_path '/checkpoint/fcharton/dumped' --save_periodic 0 --fp16 false --amp -1 --emb_dim 128 --n_enc_layers 2 --n_dec_layers 2 --n_heads 8 --dropout 0 --attention_dropout 0 --share_inout_emb true --sinusoidal_embeddings false --max_len 512 --batch_size 32 --optimizer 'adam,lr=0.0001' --clip_grad_norm 5 --epoch_size 300000 --max_epoch 100000 --accumulate_gradients 1 --env_name ode --max_int 10 --precision 3 --skip_zero_gradient true --positive false --nonnull true --prob_int 0.3 --min_degree 2 --max_degree 3 --eval_value 0.5 --allow_complex false --jacobian_precision 3 --qualitative false --tau 1 --num_workers 20 --cpu true --stopping_criterion '' --validation_metrics '' --export_data true --reload_data '' --tasks ode_control --env_base_seed -1 --exp_name ddss_gen_ctrl_t\n\n# assemble non controllable cases from prefixes\ncat */data.prefix \\\n| grep '0$' \\\n| awk 'BEGIN{PROCINFO[\"sorted_in\"]=\"@val_num_desc\"}{c[$0]++}END{for (i in c) printf(\"%i|%s\\n\",c[i],i)}' \\\n> ddss_control_t.prefix_counts.0\n\n# count them\nwc -l ddss_control_t.prefix_counts.0   # 11,572,508\n\n# assemble controllable cases from prefixes\ncat */data.prefix \\\n| grep '1$' \\\n| awk 'BEGIN{PROCINFO[\"sorted_in\"]=\"@val_num_desc\"}{c[$0]++}END{for (i in c) printf(\"%i|%s\\n\",c[i],i)}' \\\n| head -n 11572508 > ddss_control_t.prefix_counts.1\n\n# assemble prefix_counts\ncat ddss_control_t.prefix_counts.0 ddss_control_t.prefix_counts.1 | shuf > ddss_control_t_bal.prefix_counts\n\n# create train, valid and test samples\npython ~/MathsFromExamples/split_data.py ddss_control_t_bal.prefix_counts 10000\n\n# check valid and test for duplicates and remove them\nawk -F\"[|\\t]\" 'NR==FNR { lines[$2]=1; next } !($2 in lines)' ddss_control_t_bal.prefix_counts.train ddss_control_t_bal.prefix_counts.valid > ddss_control_t_bal.prefix_counts.valid.final\nawk -F\"[|\\t]\" 'NR==FNR { lines[$2]=1; next } !($2 in lines)' ddss_control_t_bal.prefix_counts.train ddss_control_t_bal.prefix_counts.test > ddss_control_t_bal.prefix_counts.test.final\n```\n\n### Predicting control matrices - sample of controllable systems, of degree 3 to 6\n\n```bash\n# generation command\npython train.py --dump_path '/checkpoint/fcharton/dumped' --save_periodic 0 --fp16 false --amp -1 --emb_dim 128 --n_enc_layers 2 --n_dec_layers 2 --n_heads 8 --dropout 0 --attention_dropout 0 --share_inout_emb true --sinusoidal_embeddings false --max_len 512 --batch_size 32 --optimizer 'adam,lr=0.0001' --clip_grad_norm 5 --epoch_size 300000 --max_epoch 100000 --accumulate_gradients 1 --env_name ode --max_int 10 --precision 3 --skip_zero_gradient true --positive false --nonnull true --prob_int 0.3 --min_degree 3 --max_degree 6 --eval_value 0.5 --allow_complex false --jacobian_precision 2 --qualitative false --predict_gramian true --prob_positive 1.0 --num_workers 20 --cpu true --stopping_criterion '' --validation_metrics '' --export_data true --reload_data '' --tasks ode_control --env_base_seed -1 --exp_name ddss_gen_gram\n\n# assemble raw data file from prefixes\ncat */data.prefix \\\n| awk 'BEGIN{PROCINFO[\"sorted_in\"]=\"@val_num_desc\"}{c[$0]++}END{for (i in c) printf(\"%i|%s\\n\",c[i],i)}' \\\n> ddss_gram.prefix_counts\n \n# create train, valid and test samples \npython ~/MathsFromExamples/split_data.py ddss_gram.prefix_counts 10000\n\n# check valid and test for duplicates and remove them\nawk -F\"[|\\t]\" 'NR==FNR { lines[$2]=1; next } !($2 in lines)' ddss_gram.prefix_counts.train ddss_gram.prefix_counts.valid > ddss_gram.prefix_counts.valid.final\nawk -F\"[|\\t]\" 'NR==FNR { lines[$2]=1; next } !($2 in lines)' ddss_gram.prefix_counts.train ddss_gram.prefix_counts.test > ddss_gram.prefix_counts.test.final\n```\n\n### Predicting the existence of solutions of partial differential equations\n\n```bash\n# generation command\npython train.py --dump_path '/checkpoint/fcharton/dumped' --save_periodic 0 --fp16 false --amp -1 --emb_dim 128 --n_enc_layers 2 --n_dec_layers 2 --n_heads 8 --dropout 0 --attention_dropout 0 --share_inout_emb true --sinusoidal_embeddings false --max_len 512 --batch_size 32 --optimizer 'adam,lr=0.0001' --clip_grad_norm 5 --epoch_size 300000 --max_epoch 100000 --accumulate_gradients 1 --env_name ode --max_int 10 --precision 2 --jacobian_precision 2 --positive false --nonnull true --allow_complex false --predict_bounds true --skip_zero_gradient true --prob_int 0.3 --min_degree 2 --max_degree 6 --eval_value 0.01 --prob_positive -1.0 --num_workers 20 --cpu true --stopping_criterion '' --validation_metrics '' --export_data true --reload_data '' --tasks fourier_cond_init --env_base_seed -1 --exp_name ddss_gen_fourier\n\n# assemble raw data file from prefixes\ncat */data.prefix \\\n| awk 'BEGIN{PROCINFO[\"sorted_in\"]=\"@val_num_desc\"}{c[$0]++}END{for (i in c) printf(\"%i|%s\\n\",c[i],i)}' \\\n> ddss_fourier.prefix_counts\n \n# create train, valid and test samples \npython ~/MathsFromExamples/split_data.py ddss_fourier.prefix_counts 10000\n\n# check valid and test for duplicates and remove them\nawk -F\"[|\\t]\" 'NR==FNR { lines[$2]=1; next } !($2 in lines)' ddss_fourier.prefix_counts.train ddss_fourier.prefix_counts.valid > ddss_fourier.prefix_counts.valid.final\nawk -F\"[|\\t]\" 'NR==FNR { lines[$2]=1; next } !($2 in lines)' ddss_fourier.prefix_counts.train ddss_fourier.prefix_counts.test > ddss_fourier.prefix_counts.test.final\n```\n\n## Pre-trained models\nWe provide 7 pretrained models for the various problems. Below are the links, the dataset they were trained on, and the parameters used, and the performance on the validation set (valid.final in the same directory, 10 000 held-out examples).\n\n### Predicting stability (qualitative)\n* Model: https://dl.fbaipublicfiles.com/MathsFromExamples/models/ddss_stab_quali.pth\n* Training set: `ddss_stability_balanced.prefix_counts.train`\n* Accuracy over validation set: 97.1%\n* Training parameters (command line)\n```bash\npython train.py --dump_path '/checkpoint/fcharton/dumped' --save_periodic 0 --fp16 true --amp 2 --accumulate_gradients 1 --emb_dim 512 --batch_size 128 --batch_size_eval 256 --n_enc_layers 6 --n_dec_layers 6 --n_heads 8 --dropout 0 --attention_dropout 0 --share_inout_emb true --sinusoidal_embeddings false --max_len 512 --optimizer 'adam,lr=0.0001' --clip_grad_norm 5 --epoch_size 300000 --max_epoch 100000 --num_workers 1 --export_data false --env_name ode --max_int 10 --positive false --nonnull true --qualitative true --skip_zero_gradient true --prob_int 0.3 --max_degree 5 --min_degree 2 --eval_verbose 0 --beam_eval 0 --eval_size 10000 --tasks ode_convergence_speed --reload_data 'ode_convergence_speed,/checkpoint/fcharton/dumped/ddss_gen_stab_bal/ddss_stability_balanced.prefix_counts.train,/checkpoint/fcharton/dumped/ddss_gen_stab_bal/ddss_stability_balanced.prefix_counts.valid.final,/checkpoint/fcharton/dumped/ddss_gen_stab_bal/ddss_stability_balanced.prefix_counts.test.final' --reload_size 40000000 --stopping_criterion 'valid_ode_convergence_speed_acc,40' --validation_metrics valid_ode_convergence_speed_acc --env_base_seed -1 --exp_name ddss_stab_quali\n```\n\n### Stability:  computing convergence speed\n* Model: https://dl.fbaipublicfiles.com/MathsFromExamples/models/ddss_stab_quanti.pth\n* Training set:`ddss_stability.prefix_counts.train`\n* Accuracy over validation set: 87.4%\n* Training parameters (command line)\n```bash\npython train.py --dump_path '/checkpoint/fcharton/dumped' --save_periodic 0 --fp16 true --amp 2 --accumulate_gradients 1 --emb_dim 1024 --batch_size 128 --batch_size_eval 256 --n_enc_layers 8 --n_dec_layers 8 --n_heads 8 --dropout 0 --attention_dropout 0 --share_inout_emb true --sinusoidal_embeddings false --max_len 512 --optimizer 'adam_inverse_sqrt,warmup_updates=10000,lr=0.0001,weight_decay=0.01' --clip_grad_norm 5 --epoch_size 300000 --max_epoch 100000 --num_workers 1 --export_data false --env_name ode --max_int 10 --positive false --nonnull true --skip_zero_gradient true --prob_int 0.3 --max_degree 6 --min_degree 2 --eval_verbose 0 --beam_eval 1 --eval_size 10000 --tasks ode_convergence_speed --reload_data 'ode_convergence_speed,/checkpoint/fcharton/dumped/ddss_gen_stab/ddss_stability.prefix_counts.train,/checkpoint/fcharton/dumped/ddss_gen_stab/ddss_stability.prefix_counts.valid.final,/checkpoint/fcharton/dumped/ddss_gen_stab/ddss_stability.prefix_counts.test.final' --reload_size 40000000 --stopping_criterion 'valid_ode_convergence_speed_beam_acc,40' --validation_metrics valid_ode_convergence_speed_beam_acc --env_base_seed -1 --exp_name ddss_stab_quanti\n```\n\n### Predicting autonomous controllability\n* Model: https://dl.fbaipublicfiles.com/MathsFromExamples/models/ddss_ctrl.pth\n* Training set: `ddss_control.prefix_counts.train`\n* Accuracy over validation set: 97.4%\n* Training parameters (command line)\n```bash\n python train.py --dump_path '/checkpoint/fcharton/dumped' --save_periodic 0 --fp16 true --amp 2 --accumulate_gradients 1 --emb_dim 512 --batch_size 256 --batch_size_eval 256 --n_enc_layers 6 --n_dec_layers 6 --n_heads 8 --dropout 0 --attention_dropout 0 --share_inout_emb true --sinusoidal_embeddings false --max_len 512 --optimizer 'adam_inverse_sqrt,warmup_updates=10000,lr=0.0001,weight_decay=0.01' --clip_grad_norm 5 --epoch_size 300000 --max_epoch 100000 --num_workers 1 --export_data false --env_name ode --max_int 10 --positive false --nonnull true --skip_zero_gradient true --prob_int 0.3 --max_degree 6 --min_degree 3 --eval_value 0.9 --qualitative true --eval_verbose 0 --beam_eval 0 --eval_size 10000 --tasks ode_control --reload_data 'ode_control,/checkpoint/fcharton/dumped/ddss_gen_ctrl/ddss_control.prefix_counts.train,/checkpoint/fcharton/dumped/ddss_gen_ctrl/ddss_control.prefix_counts.valid.final,/checkpoint/fcharton/dumped/ddss_gen_ctrl/ddss_control.prefix_counts.test.final' --reload_size 40000000 --stopping_criterion 'valid_ode_control_acc,20' --validation_metrics valid_ode_control_acc --env_base_seed -1 --exp_name ddss_ctrl\n ```\n\n### Predicting non-autonomous controllability\n* Model: https://dl.fbaipublicfiles.com/MathsFromExamples/models/ddss_ctrl_t.pth\n* Training set: `ddss_control_t.prefix_counts.train`\n* Accuracy over validation set: 99.6%\n* Training parameters (command line)\n```bash\npython train.py --dump_path '/checkpoint/fcharton/dumped' --save_periodic 0 --fp16 true --amp 2 --accumulate_gradients 1 --emb_dim 512 --batch_size 256 --batch_size_eval 256 --n_enc_layers 6 --n_dec_layers 6 --n_heads 8 --dropout 0 --attention_dropout 0 --share_inout_emb true --sinusoidal_embeddings false --max_len 512 --optimizer 'adam_inverse_sqrt,warmup_updates=10000,lr=0.0001,weight_decay=0.01' --clip_grad_norm 5 --epoch_size 300000 --max_epoch 100000 --num_workers 1 --export_data false --env_name ode --max_int 10 --positive false --nonnull true --skip_zero_gradient true --prob_int 0.3 --max_degree 3 --min_degree 2 --eval_value 0.5 --qualitative false --tau 1 --eval_verbose 0 --beam_eval 0 --eval_size 10000 --tasks ode_control --reload_data 'ode_control,/checkpoint/fcharton/dumped/ddss_gen_ctrl_t/ddss_control_t.prefix_counts.train,/checkpoint/fcharton/dumped/ddss_gen_ctrl_t/ddss_control_t.prefix_counts.valid.final,/checkpoint/fcharton/dumped/ddss_gen_ctrl_t/ddss_control_t.prefix_counts.test.final' --reload_size 40000000 --stopping_criterion 'valid_ode_control_acc,60' --validation_metrics valid_ode_control_acc --env_base_seed -1 --exp_name ddss_ctrl_t\n```\n\n### Computing control matrices: predicting solution up to 10% \n* Model: https://dl.fbaipublicfiles.com/MathsFromExamples/models/ddss_gram_approx.pth\n* Training set: `ddss_gram.prefix_counts.train`\n* Accuracy over validation set: 24.5%\n* Training parameters (command line)\n```bash\npython /private/home/fcharton/workdir/ddss_gram/2021_03_18_12_05_11/train.py --dump_path '/checkpoint/fcharton/dumped' --save_periodic 0 --fp16 true --amp 2 --accumulate_gradients 1 --emb_dim 512 --batch_size 128 --batch_size_eval 128 --n_enc_layers 6 --n_dec_layers 6 --n_heads 8 --dropout 0 --attention_dropout 0 --share_inout_emb true --sinusoidal_embeddings false --max_len 512 --optimizer 'adam,lr=0.0001' --clip_grad_norm 5 --epoch_size 300000 --max_epoch 100000 --num_workers 1 --export_data false --env_name ode --max_int 10 --positive false --nonnull true --skip_zero_gradient true --prob_int 0.3 --max_degree 6 --min_degree 3 --eval_value 0.5 --predict_gramian true --euclidian_metric true --auxiliary_task false --eval_verbose 0 --beam_eval 1 --eval_size 10000 --tasks ode_control --reload_data 'ode_control,/checkpoint/fcharton/dumped/ddss_gen_gram/ddss_gram.prefix_counts.train,/checkpoint/fcharton/dumped/ddss_gen_gram/ddss_gram.prefix_counts.valid.final,/checkpoint/fcharton/dumped/ddss_gen_gram/ddss_gram.prefix_counts.test.final' --reload_size 50000000 --stopping_criterion 'valid_ode_control_beam_acc,40' --validation_metrics valid_ode_control_beam_acc --env_base_seed -1 --exp_name ddss_gram\n```\n\n### Computing control matrices: predicting a correct mathematical solution\n* Model: https://dl.fbaipublicfiles.com/MathsFromExamples/models/ddss_gram_math.pth\n* Training set: `ddss_gram.prefix_counts.train`\n* Accuracy over validation set: 63.5%\n* Training parameters (command line)\n```bash\npython /private/home/fcharton/workdir/ddss_gram/2021_03_09_12_09_38/train.py --dump_path '/checkpoint/fcharton/dumped' --save_periodic 0 --fp16 true --amp 2 --accumulate_gradients 1 --emb_dim 512 --batch_size 128 --batch_size_eval 128 --n_enc_layers 6 --n_dec_layers 6 --n_heads 8 --dropout 0 --attention_dropout 0 --share_inout_emb true --sinusoidal_embeddings false --max_len 512 --optimizer 'adam,lr=0.0001' --clip_grad_norm 5 --epoch_size 300000 --max_epoch 100000 --num_workers 1 --export_data false --env_name ode --max_int 10 --positive false --nonnull true --skip_zero_gradient true --prob_int 0.3 --max_degree 6 --min_degree 3 --eval_value 0.5 --predict_gramian true --euclidian_metric false --auxiliary_task false --eval_verbose 0 --beam_eval 1 --eval_size 10000 --tasks ode_control --reload_data 'ode_control,/checkpoint/fcharton/dumped/ddss_gen_gram/ddss_gram.prefix_counts.train,/checkpoint/fcharton/dumped/ddss_gen_gram/ddss_gram.prefix_counts.valid.final,/checkpoint/fcharton/dumped/ddss_gen_gram/ddss_gram.prefix_counts.test.final' --reload_size 40000000 --stopping_criterion 'valid_ode_control_beam_acc,20' --validation_metrics valid_ode_control_beam_acc --env_base_seed -1 --exp_name ddss_gram\n```\n\n### Predicting the existence of solutions of partial differential equations\n* Model: https://dl.fbaipublicfiles.com/MathsFromExamples/models/ddss_fourier.pth\n* Training set: `ddss_fourier.prefix_counts.train`\n* Accuracy over validation set: 98.6%\n* Training parameters (command line) \n```bash\npython train.py --dump_path '/checkpoint/fcharton/dumped' --save_periodic 0 --fp16 false --amp -1 --accumulate_gradients 1 --emb_dim 512 --n_enc_layers 8 --n_dec_layers 8 --batch_size 64 --batch_size_eval 64 --eval_size 10000 --predict_jacobian false --n_heads 8 --dropout 0 --attention_dropout 0 --share_inout_emb true --sinusoidal_embeddings false --max_len 1024 --optimizer 'adam_inverse_sqrt,warmup_updates=10000,lr=0.0001,weight_decay=0.01' --clip_grad_norm 5 --epoch_size 300000 --max_epoch 100000 --num_workers 1 --export_data false --env_name ode --max_int 10 --precision 3 --jacobian_precision 1 --positive false --nonnull true --prob_int '0.3' --max_degree 6 --eval_value 0.5 --allow_complex false --predict_bounds true --skip_zero_gradient true --eval_verbose 0 --beam_eval 0 --tasks fourier_cond_init --reload_data 'fourier_cond_init,/checkpoint/fcharton/dumped/ddss_gen_fourier/ddss_fourier.prefix_counts.train,/checkpoint/fcharton/dumped/ddss_gen_fourier/ddss_fourier.prefix_counts.valid,/checkpoint/fcharton/dumped/ddss_gen_fourier/ddss_fourier.prefix_counts.test' --reload_size 40000000 --stopping_criterion 'valid_fourier_cond_init_acc,20' --validation_metrics valid_fourier_cond_init_acc --env_base_seed -1 --exp_name ddss_fourier\n```\n\n## Evaluating trained models\nTo evaluate over a trained model `model.pth` on a specific test set `test.data`, run the model with the same parameters as training, setting `--eval_only true`and `--reload_model` to the path to your model (e.g. `--reload_model /model_path/model.pth`), and setting the second file `--reload_data`to your test data (e.g. ` --reload_data 'ode_control,/checkpoint/fcharton/dumped/ddss_gen_gram/ddss_gram.prefix_counts.train,/MYPATH/test.data,/checkpoint/fcharton/dumped/ddss_gen_gram/ddss_gram.prefix_counts.test.final'`). Set `--eval_size`to the size of your dataset. At present, only the validation dataset is used for evaluation, but you can change this by toggling comments on lines 367 and 368 of file `evaluator.py`.\n\n\n## Citation\nThis code is released under a Creative Commons License, see LICENCE file for more details. \nIf you use this code, consider citing\n\n@misc{charton2021learning,\n      title={Learning advanced mathematical computations from examples}, \n      author={François Charton and Amaury Hayat and Guillaume Lample},\n      year={2021},\n      eprint={2006.06462},\n      archivePrefix={arXiv},\n      primaryClass={cs.LG}\n}\n\n\n"
  },
  {
    "path": "split_data.py",
    "content": "# Copyright (c) 2020-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nimport io\nimport os\nimport sys\nimport math\n\n\nif __name__ == \"__main__\":\n\n    assert len(sys.argv) == 3\n\n    data_path = sys.argv[1]\n    trn_path = sys.argv[1] + \".train\"\n    vld_path = sys.argv[1] + \".valid\"\n    tst_path = sys.argv[1] + \".test\"\n    vld_tst_size = int(sys.argv[2])\n    assert not os.path.isfile(trn_path)\n    assert not os.path.isfile(vld_path)\n    assert not os.path.isfile(tst_path)\n    assert vld_tst_size > 0\n\n    print(f\"Reading data from {data_path} ...\")\n    with io.open(data_path, mode=\"r\", encoding=\"utf-8\") as f:\n        lines = [line for line in f]\n    total_size = len(lines)\n    print(f\"Read {total_size} lines.\")\n    assert 2 * vld_tst_size < total_size\n\n    alpha = math.log(total_size - 0.5) / math.log(2 * vld_tst_size)\n    assert int((2 * vld_tst_size) ** alpha) == total_size - 1\n    vld_tst_indices = [int(i ** alpha) for i in range(1, 2 * vld_tst_size + 1)]\n    vld_indices = set(vld_tst_indices[::2])\n    tst_indices = set(vld_tst_indices[1::2])\n    assert len(vld_tst_indices) == 2 * vld_tst_size\n    assert max(vld_tst_indices) == total_size - 1\n    assert len(vld_indices) == vld_tst_size\n    assert len(tst_indices) == vld_tst_size\n\n    # sanity check\n    total = 0\n    power = 0\n    while True:\n        a = 10 ** power\n        b = 10 * a\n        s = len([True for x in vld_tst_indices if a <= x < b and x <= total_size])\n        if s == 0:\n            break\n        print(\"[%12i %12i[: %i\" % (a, b, s))\n        total += s\n        power += 1\n    assert total == 2 * vld_tst_size\n\n    print(f\"Writing train data to {trn_path} ...\")\n    print(f\"Writing valid data to {vld_path} ...\")\n    print(f\"Writing test data to {tst_path} ...\")\n    f_train = io.open(trn_path, mode=\"w\", encoding=\"utf-8\")\n    f_valid = io.open(vld_path, mode=\"w\", encoding=\"utf-8\")\n    f_test = io.open(tst_path, mode=\"w\", encoding=\"utf-8\")\n\n    for i, line in enumerate(lines):\n        if i in vld_indices:\n            f_valid.write(line)\n        elif i in tst_indices:\n            f_test.write(line)\n        else:\n            f_train.write(line)\n        if i % 1000000 == 0:\n            print(i, end=\"...\", flush=True)\n\n    f_train.close()\n    f_valid.close()\n    f_test.close()\n"
  },
  {
    "path": "src/__init__.py",
    "content": ""
  },
  {
    "path": "src/envs/__init__.py",
    "content": "# Copyright (c) 2020-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nfrom logging import getLogger\n\nfrom .ode import ODEEnvironment\n\n\nlogger = getLogger()\n\n\nENVS = {\n    'ode': ODEEnvironment,\n}\n\n\ndef build_env(params):\n    \"\"\"\n    Build environment.\n    \"\"\"\n    env = ENVS[params.env_name](params)\n\n    # tasks\n    tasks = [x for x in params.tasks.split(',') if len(x) > 0]\n    assert len(tasks) == len(set(tasks)) > 0\n    assert all(task in env.TRAINING_TASKS for task in tasks)\n    params.tasks = tasks\n    logger.info(f'Training tasks: {\", \".join(tasks)}')\n\n    return env\n"
  },
  {
    "path": "src/envs/ode.py",
    "content": "# Copyright (c) 2020-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nfrom logging import getLogger\nimport os\nimport io\nimport sys\nfrom collections import OrderedDict\nimport numpy as np\nimport torch\nfrom torch.utils.data.dataset import Dataset\nfrom torch.utils.data import DataLoader\nimport sympy as sp\nfrom sympy.core.cache import clear_cache\nimport control as ctrl\nfrom scipy.linalg import expm\nfrom scipy.integrate import cumtrapz\nimport scipy.optimize as opt\n\nfrom ..utils import bool_flag\nfrom ..utils import timeout, TimeoutError\n\n\nCLEAR_SYMPY_CACHE_FREQ = 10000\n\nSPECIAL_WORDS = [\"<s>\", \"</s>\", \"<pad>\", \"(\", \")\"]\nSPECIAL_WORDS = SPECIAL_WORDS + [f\"<SPECIAL_{i}>\" for i in range(10)]\n\n\nlogger = getLogger()\n\n\nclass UnknownSymPyOperator(Exception):\n    pass\n\n\nclass InvalidPrefixExpression(Exception):\n    def __init__(self, data):\n        self.data = data\n\n    def __str__(self):\n        return repr(self.data)\n\n\ndef has_inf_nan(*args):\n    \"\"\"\n    Detect whether some SymPy expressions contain a NaN / Infinity symbol.\n    \"\"\"\n    for f in args:\n        if f.has(sp.nan) or f.has(sp.oo) or f.has(-sp.oo) or f.has(sp.zoo):\n            return True\n    return False\n\n\ndef second_index(x, bal):\n    if bal not in x:\n        return len(x)\n    p1 = x.index(bal)\n    if bal not in x[p1 + 1 :]:\n        return len(x)\n    p2 = x[p1 + 1 :].index(bal)\n    return p2 + p1\n\n\ndef simplify(f, seconds):\n    \"\"\"\n    Simplify an expression.\n    \"\"\"\n    assert seconds > 0\n\n    @timeout(seconds)\n    def _simplify(f):\n        try:\n            f2 = sp.simplify(f)\n            if any(s.is_Dummy for s in f2.free_symbols):\n                logger.warning(f\"Detected Dummy symbol when simplifying {f} to {f2}\")\n                return f\n            else:\n                return f2\n        except TimeoutError:\n            return f\n        except Exception as e:\n            logger.warning(f\"{type(e).__name__} exception when simplifying {f}\")\n            return f\n\n    return _simplify(f)\n\n\ndef expr_to_fun_real(x, fun, dimension):\n    # for i in range(dimension):\n    #     v='x'+str(i+1)\n    #     v=sp.symbols('x'+str(i))\n    #     f=f.subs(v,x[i])\n    Eval = OrderedDict({sp.Symbol(f\"x{i}\"): x[i] for i in range(dimension)})\n    fun = sp.re(fun.subs(Eval)).evalf()\n    fun = min(fun, 1e15)\n    fun = max(fun, -1e15)\n    return fun\n\n\nclass Node:\n    def __init__(self, value, children=None):\n        self.value = value\n        self.children = children if children else []\n\n    def push_child(self, child):\n        self.children.append(child)\n\n    def prefix(self):\n        s = str(self.value)\n        for c in self.children:\n            s += \", \" + c.prefix()\n        return s\n\n    # export to latex qtree format: prefix with \\Tree, use package qtree\n    def qtree_prefix(self):\n        s = \"[.$\" + str(self.value) + \"$ \"\n        for c in self.children:\n            s += c.qtree_prefix()\n        s += \"]\"\n        return s\n\n    def infix(self):\n        nb_children = len(self.children)\n        if nb_children <= 1:\n            s = str(self.value)\n            if nb_children == 1:\n                s += \"(\" + self.children[0].infix() + \")\"\n            return s\n        s = \"(\" + self.children[0].infix()\n        for c in self.children[1:]:\n            s = s + \" \" + str(self.value) + \" \" + c.infix()\n        return s + \")\"\n\n    def __len__(self):\n        lenc = 1\n        for c in self.children:\n            lenc += len(c)\n        return lenc\n\n    def __str__(self):\n        # infix a default print\n        return self.infix()\n\n\nclass ODEEnvironment(object):\n\n    TRAINING_TASKS = {\n        \"ode_convergence_speed\",\n        \"ode_control\",\n        \"fourier_cond_init\",\n    }\n\n    def __init__(self, params):\n\n        self.max_degree = params.max_degree\n        self.min_degree = params.min_degree\n        assert self.min_degree >= 2\n        assert self.max_degree >= self.min_degree\n\n        self.max_ops = 200\n\n        self.max_int = params.max_int\n        self.positive = params.positive\n        self.nonnull = params.nonnull\n        self.predict_jacobian = params.predict_jacobian\n        self.predict_gramian = params.predict_gramian\n        self.qualitative = params.qualitative\n        self.allow_complex = params.allow_complex\n        self.reversed_eval = params.reversed_eval\n        self.euclidian_metric = params.euclidian_metric\n        self.auxiliary_task = params.auxiliary_task\n        self.tau = params.tau\n        self.gramian_norm1 = params.gramian_norm1\n        self.gramian_tolerance = params.gramian_tolerance\n\n        self.min_expr_len_factor_cspeed = params.min_expr_len_factor_cspeed\n        self.max_expr_len_factor_cspeed = params.max_expr_len_factor_cspeed\n\n        self.custom_unary_probs = params.custom_unary_probs\n        self.prob_trigs = params.prob_trigs\n        self.prob_arc_trigs = params.prob_arc_trigs\n        self.prob_logs = params.prob_logs\n        self.prob_others = 1.0 - self.prob_trigs - self.prob_arc_trigs - self.prob_logs\n        assert self.prob_others >= 0.0\n\n        self.prob_int = params.prob_int\n        self.precision = params.precision\n        self.jacobian_precision = params.jacobian_precision\n\n        self.max_len = params.max_len\n        self.eval_value = params.eval_value\n        self.skip_zero_gradient = params.skip_zero_gradient\n        self.prob_positive = params.prob_positive\n\n        self.np_positive = np.zeros(self.max_degree + 1, dtype=int)\n        self.np_total = np.zeros(self.max_degree + 1, dtype=int)\n        self.complex_input = \"fourier\" in params.tasks\n\n        self.SYMPY_OPERATORS = {\n            # Elementary functions\n            sp.Add: \"+\",\n            sp.Mul: \"*\",\n            sp.Pow: \"^\",\n            sp.exp: \"exp\",\n            sp.log: \"ln\",\n            # sp.Abs: 'abs',\n            # sp.sign: 'sign',\n            # Trigonometric Functions\n            sp.sin: \"sin\",\n            sp.cos: \"cos\",\n            sp.tan: \"tan\",\n            # sp.cot: 'cot',\n            # sp.sec: 'sec',\n            # sp.csc: 'csc',\n            # Trigonometric Inverses\n            sp.asin: \"asin\",\n            sp.acos: \"acos\",\n            sp.atan: \"atan\",\n            # sp.acot: 'acot',\n            # sp.asec: 'asec',\n            # sp.acsc: 'acsc',\n            sp.DiracDelta: \"delta0\",\n        }\n\n        self.operators_conv = {\n            \"+\": 2,\n            \"-\": 2,\n            \"*\": 2,\n            \"/\": 2,\n            \"sqrt\": 1,\n            \"exp\": 1,\n            \"ln\": 1,\n            \"sin\": 1,\n            \"cos\": 1,\n            \"tan\": 1,\n            \"asin\": 1,\n            \"acos\": 1,\n            \"atan\": 1,\n        }\n\n        self.trig_ops = [\"sin\", \"cos\", \"tan\"]\n        self.arctrig_ops = [\"asin\", \"acos\", \"atan\"]\n        self.exp_ops = [\"exp\", \"ln\"]\n        self.other_ops = [\"sqrt\"]\n\n        self.operators_lyap = {\n            \"+\": 2,\n            \"-\": 2,\n            \"*\": 2,\n            \"/\": 2,\n            \"^\": 2,\n            \"sqrt\": 1,\n            \"exp\": 1,\n            \"ln\": 1,\n            \"sin\": 1,\n            \"cos\": 1,\n            \"tan\": 1,\n            \"asin\": 1,\n            \"acos\": 1,\n            \"atan\": 1,\n            \"delta0\": 1,\n        }\n\n        self.operators = (\n            self.operators_lyap if \"fourier\" in params.tasks else self.operators_conv\n        )\n        self.unaries = [o for o in self.operators.keys() if self.operators[o] == 1]\n        self.binaries = [o for o in self.operators.keys() if self.operators[o] == 2]\n        self.unary = len(self.unaries) > 0\n        self.predict_bounds = params.predict_bounds\n\n        assert self.max_int >= 1\n        assert self.precision >= 2\n\n        # variables\n        self.variables = OrderedDict(\n            {f\"x{i}\": sp.Symbol(f\"x{i}\") for i in range(2 * self.max_degree)}\n        )\n\n        self.eval_point = OrderedDict(\n            {\n                self.variables[f\"x{i}\"]: self.eval_value\n                for i in range(2 * self.max_degree)\n            }\n        )\n\n        # symbols / elements\n        self.constants = [\"pi\", \"E\"]\n\n        self.symbols = [\"I\", \"INT+\", \"INT-\", \"FLOAT+\", \"FLOAT-\", \".\", \"10^\"]\n        self.elements = [str(i) for i in range(10)]\n\n        # SymPy elements\n        self.local_dict = {}\n        for k, v in list(self.variables.items()):\n            assert k not in self.local_dict\n            self.local_dict[k] = v\n\n        # vocabulary\n        self.words = (\n            SPECIAL_WORDS\n            + self.constants\n            + list(self.variables.keys())\n            + list(self.operators.keys())\n            + self.symbols\n            + self.elements\n        )\n        self.id2word = {i: s for i, s in enumerate(self.words)}\n        self.word2id = {s: i for i, s in self.id2word.items()}\n        assert len(self.words) == len(set(self.words))\n\n        # number of words / indices\n        self.n_words = params.n_words = len(self.words)\n        self.eos_index = params.eos_index = 0\n        self.pad_index = params.pad_index = 1\n        self.func_separator = \"<SPECIAL_3>\"  # separate equations in a system\n        self.line_separator = \"<SPECIAL_4>\"  # separate lines in a matrix\n        self.list_separator = \"<SPECIAL_5>\"  # separate elements in a list\n        self.mtrx_separator = \"<SPECIAL_6>\"  # end of a matrix\n        self.neg_inf = \"<SPECIAL_7>\"  # negative infinity\n        self.pos_inf = \"<SPECIAL_8>\"  # positive infinity\n        logger.info(f\"words: {self.word2id}\")\n\n        # initialize distribution for binary and unary-binary trees\n        # self.max_ops + 1 should be enough\n        self.distrib = self.generate_dist(2 * self.max_ops)\n\n    def get_integer(self, cplex=False):\n        if cplex:\n            i1 = self.rng.randint(1, 100000) / 100000\n            sign = 1 if self.rng.randint(2) == 0 else -1\n            e = self.rng.randint(2)\n            if e == 0:\n                return i1 * sign\n            else:\n                return complex(0.0, i1 * sign)\n            # i2 = self.rng.randint(1, 100000) / 100000\n            # sign2 = 1 if self.rng.randint(2) == 0 else -1\n            # return complex(i1 * sign, i2 * sign2)\n\n        if self.positive and self.nonnull:\n            return self.rng.randint(1, self.max_int + 1)\n        if self.positive:\n            return self.rng.randint(0, self.max_int + 1)\n        if self.nonnull:\n            s = self.rng.randint(1, 2 * self.max_int + 1)\n            return s if s <= self.max_int else (self.max_int - s)\n\n        return self.rng.randint(-self.max_int, self.max_int + 1)\n\n    def generate_leaf(self, degree, index):\n        if self.rng.rand() < self.prob_int:\n            return self.get_integer()\n        elif degree == 1:\n            return self.variables[f\"x{index}\"]\n        else:\n            return self.variables[f\"x{self.rng.randint(degree)}\"]\n\n    def generate_ops(self, arity):\n        if arity == 1:\n            if self.custom_unary_probs:\n                w = [\n                    self.prob_trigs,\n                    self.prob_arc_trigs,\n                    self.prob_logs,\n                    self.prob_others,\n                ]\n                s = [self.trig_ops, self.arctrig_ops, self.exp_ops, self.other_ops]\n                return self.rng.choice(s, p=w)\n            else:\n                return self.rng.choice(self.unaries)\n\n        else:\n            return self.rng.choice(self.binaries)\n\n    def generate_dist(self, max_ops):\n        \"\"\"\n        `max_ops`: maximum number of operators\n        Enumerate the number of possible unary-binary trees\n        that can be generated from empty nodes.\n        D[e][n] represents the number of different binary trees with n nodes that\n        can be generated from e empty nodes, using the following recursion:\n            D(n, 0) = 0\n            D(0, e) = 1\n            D(n, e) = D(n, e - 1) + p_1 * D(n- 1, e) + D(n - 1, e + 1)\n        p1 =  if binary trees, 1 if unary binary\n        \"\"\"\n        p1 = 1 if self.unary else 0\n        # enumerate possible trees\n        D = []\n        D.append([0] + ([1 for i in range(1, 2 * max_ops + 1)]))\n        for n in range(1, 2 * max_ops + 1):  # number of operators\n            s = [0]\n            for e in range(1, 2 * max_ops - n + 1):  # number of empty nodes\n                s.append(s[e - 1] + p1 * D[n - 1][e] + D[n - 1][e + 1])\n            D.append(s)\n        assert all(len(D[i]) >= len(D[i + 1]) for i in range(len(D) - 1))\n        return D\n\n    def sample_next_pos(self, nb_empty, nb_ops):\n        \"\"\"\n        Sample the position of the next node (binary case).\n        Sample a position in {0, ..., `nb_empty` - 1}.\n        \"\"\"\n        assert nb_empty > 0\n        assert nb_ops > 0\n        probs = []\n        if self.unary:\n            for i in range(nb_empty):\n                probs.append(self.distrib[nb_ops - 1][nb_empty - i])\n        for i in range(nb_empty):\n            probs.append(self.distrib[nb_ops - 1][nb_empty - i + 1])\n        probs = [p / self.distrib[nb_ops][nb_empty] for p in probs]\n        probs = np.array(probs, dtype=np.float64)\n        e = self.rng.choice(len(probs), p=probs)\n        arity = 1 if self.unary and e < nb_empty else 2\n        e %= nb_empty\n        return e, arity\n\n    def generate_tree(self, nb_ops, degree, index=0):\n        tree = Node(0)\n        empty_nodes = [tree]\n        next_en = 0\n        nb_empty = 1\n        while nb_ops > 0:\n            next_pos, arity = self.sample_next_pos(nb_empty, nb_ops)\n            for n in empty_nodes[next_en : next_en + next_pos]:\n                n.value = self.generate_leaf(degree, index)\n            next_en += next_pos\n            empty_nodes[next_en].value = self.generate_ops(arity)\n            for _ in range(arity):\n                e = Node(0)\n                empty_nodes[next_en].push_child(e)\n                empty_nodes.append(e)\n            nb_empty += arity - 1 - next_pos\n            nb_ops -= 1\n            next_en += 1\n        for n in empty_nodes[next_en:]:\n            n.value = self.generate_leaf(degree, index)\n        return tree\n\n    def generate_polynomial(\n        self, nterm, max_factor, degree, unaries, noconstant=True, complex_coeffs=False\n    ):\n        pol = set()\n        for i in range(nterm):\n            nfactor = self.rng.randint(1, max_factor + 1)\n            vars = set()\n            for j in range(nfactor):\n                vars.add(\n                    (self.rng.randint(0, degree), self.rng.randint(0, len(unaries)))\n                )\n            pol.add(tuple(vars))\n        for i in range(len(pol)):\n            v = list(pol)[i]\n            for j in range(len(v)):\n                op = unaries[v[j][1]]\n                var = Node(self.variables[f\"x{v[j][0]}\"])\n                if op == \"id\":\n                    term = var\n                elif op == \"ln\":\n                    term = Node(\"ln\", [Node(\"+\", [Node(1), var])])\n                elif len(op) > 3 and op[:3] == \"pow\":\n                    term = Node(\"^\", [var, Node(int(op[3:]))])\n                else:\n                    term = Node(op, [var])\n                p = term if j == 0 else Node(\"*\", [p, term])\n            coeff = self.get_integer(complex_coeffs)\n            if complex_coeffs:\n                p = Node(\"*\", [Node(coeff), p])\n                tree = p if i == 0 else Node(\"+\", [tree, p])\n            else:\n                if abs(coeff) != 1:\n                    p = Node(\"*\", [Node(abs(coeff)), p])\n                tree = p if i == 0 else Node(\"+\" if coeff > 0 else \"-\", [tree, p])\n        if not noconstant:\n            coeff = self.get_integer(complex_coeffs)\n            if complex_coeffs:\n                tree = Node(\"+\", [tree, Node(coeff)])\n            else:\n                tree = Node(\"+\" if coeff > 0 else \"-\", [tree, Node(abs(coeff))])\n        return tree\n\n    def batch_sequences(self, sequences):\n        \"\"\"\n        Take as input a list of n sequences (torch.LongTensor vectors) and return\n        a tensor of size (slen, n) where slen is the length of the longest\n        sentence, and a vector lengths containing the length of each sentence.\n        \"\"\"\n        lengths = torch.LongTensor([len(s) + 2 for s in sequences])\n        sent = torch.LongTensor(lengths.max().item(), lengths.size(0)).fill_(\n            self.pad_index\n        )\n        assert lengths.min().item() > 2\n\n        sent[0] = self.eos_index\n        for i, s in enumerate(sequences):\n            sent[1 : lengths[i] - 1, i].copy_(s)\n            sent[lengths[i] - 1, i] = self.eos_index\n\n        return sent, lengths\n\n    def write_int(self, val):\n        \"\"\"\n        Convert a decimal integer to a representation in base 10.\n        \"\"\"\n        res = []\n        neg = val < 0\n        val = -val if neg else val\n        while True:\n            rem = val % 10\n            val = val // 10\n            res.append(str(rem))\n            if val == 0:\n                break\n        res.append(\"INT-\" if neg else \"INT+\")\n        return res[::-1]\n\n    def parse_int(self, lst):\n        \"\"\"\n        Parse a list that starts with an integer.\n        Return the integer value, and the position it ends in the list.\n        \"\"\"\n        if len(lst) < 2 or lst[0] not in [\"INT+\", \"INT-\"] or not lst[1].isdigit():\n            raise InvalidPrefixExpression(\"Invalid integer in prefix expression\")\n        val = int(lst[1])\n        i = 1\n        for x in lst[2:]:\n            if not x.isdigit():\n                break\n            val = val * 10 + int(x)\n            i += 1\n        if lst[0] == \"INT-\":\n            val = -val\n        return val, i + 1\n\n    def write_float(self, value, precision=None):\n        \"\"\"\n        Write a float number.\n        \"\"\"\n        precision = self.precision if precision is None else precision\n        assert value not in [-np.inf, np.inf]\n        res = [\"FLOAT+\"] if value >= 0.0 else [\"FLOAT-\"]\n        m, e = (f\"%.{precision}e\" % abs(value)).split(\"e\")\n        assert e[0] in [\"+\", \"-\"]\n        e = int(e[1:] if e[0] == \"+\" else e)\n        return res + list(m) + [\"10^\"] + self.write_int(e)\n\n    def parse_float(self, lst):\n        \"\"\"\n        Parse a list that starts with a float.\n        Return the float value, and the position it ends in the list.\n        \"\"\"\n        if len(lst) < 2 or lst[0] not in [\"FLOAT+\", \"FLOAT-\"]:\n            return np.nan, 0\n        sign = -1 if lst[0] == \"FLOAT-\" else 1\n        if not lst[1].isdigit():\n            return np.nan, 1\n        mant = 0.0\n        i = 1\n        for x in lst[1:]:\n            if not (x.isdigit()):\n                break\n            mant = mant * 10.0 + int(x)\n            i += 1\n        if len(lst) > i and lst[i] == \".\":\n            i += 1\n            mul = 0.1\n            for x in lst[i:]:\n                if not (x.isdigit()):\n                    break\n                mant += mul * int(x)\n                mul *= 0.1\n                i += 1\n        mant *= sign\n        if len(lst) > i and lst[i] == \"10^\":\n            i += 1\n            try:\n                exp, offset = self.parse_int(lst[i:])\n            except InvalidPrefixExpression:\n                return np.nan, i\n            i += offset\n        else:\n            exp = 0\n        return mant * (10.0 ** exp), i\n\n    def write_complex(self, value, precision=None):\n        \"\"\"\n        Write a complex number.\n        \"\"\"\n        if value == 0:\n            return self.write_float(0, precision)\n        res = []\n        if value.imag != 0:\n            res = self.write_float(value.imag, precision) + [\"I\"]\n        if value.real != 0:\n            res = res + self.write_float(value.real, precision)\n        return res\n\n    def parse_complex(self, lst):\n        \"\"\"\n        Parse a list that starts with a complex number.\n        Return the complex value, and the position it ends in the list.\n        \"\"\"\n        first_val, len1 = self.parse_float(lst)\n        if np.isnan(first_val):\n            return np.nan, len1\n        if len(lst) <= len1 or lst[len1] != \"I\":\n            return first_val, len1\n        second_val, len2 = self.parse_float(lst[len1 + 1 :])\n        if np.isnan(second_val):\n            return complex(0, first_val), len1 + 1\n        return complex(second_val, first_val), len1 + 1 + len2\n\n    def input_to_infix(self, lst):\n        res = \"\"\n        degree, offset = self.parse_int(lst)\n        res = str(degree) + \"|\"\n\n        offset += 1\n        l1 = lst[offset:]\n        if self.complex_input:\n            nr_eqs = 1\n        else:\n            nr_eqs = degree\n        for i in range(nr_eqs):\n            s, l2 = self.prefix_to_infix(l1)\n            res = res + s + \"|\"\n            l1 = l2[1:]\n        return res[:-1]\n\n    def output_to_infix(self, lst):\n        val, _ = self.parse_float(lst)\n        return str(val)\n\n    def prefix_to_infix(self, expr):\n        \"\"\"\n        Parse an expression in prefix mode, and output it in either:\n          - infix mode (returns human readable string)\n          - develop mode (returns a dictionary with the simplified expression)\n        \"\"\"\n        cplx = self.complex_input\n        if len(expr) == 0:\n            raise InvalidPrefixExpression(\"Empty prefix list.\")\n        t = expr[0]\n        if t in self.operators.keys():\n            args = []\n            l1 = expr[1:]\n            for _ in range(self.operators[t]):\n                i1, l1 = self.prefix_to_infix(l1)\n                args.append(i1)\n            if self.operators[t] == 1:\n                return f\"{t}({args[0]})\", l1\n            return f\"({args[0]}{t}{args[1]})\", l1\n            # return f'({args[0]}){t}({args[1]})', l1\n        elif t in self.variables or t in self.constants or t == \"I\":\n            return t, expr[1:]\n        elif t == \"FLOAT+\" or t == \"FLOAT-\":\n            if cplx:\n                val, i = self.parse_complex(expr)\n            else:\n                val, i = self.parse_float(expr)\n        else:\n            val, i = self.parse_int(expr)\n        return str(val), expr[i:]\n\n    def _sympy_to_prefix(self, op, expr):\n        \"\"\"\n        Parse a SymPy expression given an initial root operator.\n        \"\"\"\n        n_args = len(expr.args)\n\n        assert (\n            (op == \"+\" or op == \"*\")\n            and (n_args >= 2)\n            or (op != \"+\" and op != \"*\")\n            and (1 <= n_args <= 2)\n        )\n\n        # square root\n        if (\n            op == \"^\"\n            and isinstance(expr.args[1], sp.Rational)\n            and expr.args[1].p == 1\n            and expr.args[1].q == 2\n        ):\n            return [\"sqrt\"] + self.sympy_to_prefix(expr.args[0])\n\n        # parse children\n        parse_list = []\n        for i in range(n_args):\n            if i == 0 or i < n_args - 1:\n                parse_list.append(op)\n            parse_list += self.sympy_to_prefix(expr.args[i])\n\n        return parse_list\n\n    def sympy_to_prefix(self, expr):\n        \"\"\"\n        Convert a SymPy expression to a prefix one.\n        \"\"\"\n        if isinstance(expr, sp.Symbol):\n            return [str(expr)]\n        elif isinstance(expr, sp.Integer):\n            return self.write_int(int(str(expr)))\n        elif isinstance(expr, sp.Float):\n            return self.write_float(float(str(expr)))\n        elif isinstance(expr, sp.Rational):\n            return [\"/\"] + self.write_int(int(expr.p)) + self.write_int(int(expr.q))\n        elif expr == sp.E:\n            return [\"E\"]\n        elif expr == sp.pi:\n            return [\"pi\"]\n        elif expr == sp.I:\n            raise UnknownSymPyOperator(f\"Unknown SymPy operator: {expr}\")\n\n        # SymPy operator\n        for op_type, op_name in self.SYMPY_OPERATORS.items():\n            if isinstance(expr, op_type):\n                return self._sympy_to_prefix(op_name, expr)\n        # unknown operator\n        raise UnknownSymPyOperator(f\"Unknown SymPy operator: {expr}\")\n\n    def encode_expr(self, tree, cplx=False):\n        pref = tree.prefix().split(\", \")\n        res = []\n        for p in pref:\n            if (p.startswith(\"-\") and p[1:].isdigit()) or p.isdigit():\n                res.extend(self.write_int(int(p)))\n            elif cplx and (\n                (p.startswith(\"-\") and p[1:2].isdigit())\n                or p.startswith(\"(\")\n                or p[0:1].isdigit()\n            ):\n                res.extend(self.write_complex(complex(p)))\n            else:\n                res.append(p)\n        return res\n\n    @timeout(5)\n    def compute_gradient(self, expr, point, degree):\n        values = np.zeros(degree, dtype=complex)\n        try:\n            for i in range(degree):\n                grad = expr.diff(self.variables[f\"x{i}\"])\n                values[i] = grad.subs(point).evalf()\n        except TimeoutError:\n            raise\n        except Exception:\n            raise\n        return values\n\n    def gen_ode_system_convergence(self, return_system=False):\n        \"\"\"\n        Generate systems of functions, and the corresponding convergence speed in zero.\n        Start by generating a random system S, use SymPy to compute formal jacobian\n        and evaluate it in zero, find largest eigenvalue\n        Encode this as a prefix sensence\n        \"\"\"\n        degree = self.rng.randint(self.min_degree, self.max_degree + 1)\n        nb_ops = self.rng.randint(\n            self.min_expr_len_factor_cspeed * degree + 3,\n            self.max_expr_len_factor_cspeed * degree + 3,\n            size=(degree,),\n        )\n\n        while True:\n            system = []\n            i = 0\n            ngen = 0\n            while i < degree:\n                # generate expression\n                expr = self.generate_tree(nb_ops[i], degree)\n                ngen += 1\n                # sympy zone\n                try:\n                    expr_sp = sp.S(expr, locals=self.local_dict)\n                    # skip constant or invalid expressions\n                    if len(expr_sp.free_symbols) == 0 or has_inf_nan(expr_sp):\n                        continue\n                    # evaluate gradient in point\n                    values = self.compute_gradient(expr_sp, self.eval_point, degree)\n                    if np.isnan(values).any() or np.isinf(values).any():\n                        continue\n                    if self.skip_zero_gradient and not values.any():\n                        continue\n                except TimeoutError:\n                    continue\n                except (ValueError, TypeError):\n                    continue\n                except Exception as e:\n                    logger.error(\n                        \"An unknown exception of type {0} occurred in line {1} \"\n                        'for expression \"{2}\". Arguments:{3!r}.'.format(\n                            type(e).__name__,\n                            sys.exc_info()[-1].tb_lineno,\n                            expr_sp,\n                            e.args,\n                        )\n                    )\n                    continue\n\n                system.append(expr)\n                if i == 0:\n                    jacobian = values\n                else:\n                    jacobian = np.vstack((jacobian, values))\n                i += 1\n            if self.skip_zero_gradient:\n                skip = False\n                for i in range(degree):\n                    if not jacobian[:, [i]].any():\n                        skip = True\n                        break\n                if skip:\n                    continue\n\n            cspeed = -max(np.linalg.eigvals(jacobian).real)\n\n            if self.prob_positive == 0 and cspeed > 0:\n                continue\n            if self.prob_positive == 1 and cspeed <= 0:\n                continue\n            if (\n                self.prob_positive > 0\n                and self.prob_positive < 1\n                and self.np_total[degree] > 10\n            ):\n                proportion = self.np_positive[degree] / self.np_total[degree]\n                if cspeed > 0 and proportion > self.prob_positive:\n                    continue\n                if cspeed <= 0 and proportion < self.prob_positive:\n                    continue\n\n            self.np_total[degree] += 1\n            if cspeed > 0:\n                self.np_positive[degree] += 1\n            break\n\n        # # debug\n        # logger.info(str(cspeed))\n        # logger.info(str(cspeed) + \"\\t\" + \" ||||| \".join(str(s) for s in system[:3]))\n        # print(degree, str(ngen) + \" : \" + str((ngen - degree) / ngen * 100.0))\n\n        # encode input\n        x = self.write_int(degree)\n        for s in system:\n            x.append(self.func_separator)\n            x.extend(self.encode_expr(s))\n\n        # encode output: eigenvalue, and optionally the Jacobian matrix\n        eigenvalue = self.write_float(cspeed)\n        if self.predict_jacobian:\n            y = []\n            for row in jacobian:\n                for value in row:\n                    y.extend(\n                        self.write_complex(value, precision=self.jacobian_precision)\n                    )\n                    y.append(self.list_separator)\n                y.append(self.line_separator)\n            y.append(self.mtrx_separator)\n            y.extend(eigenvalue)\n        else:\n            y = eigenvalue\n\n        if return_system:\n            return x, y, system\n        else:\n            return x, y\n\n    @timeout(5)\n    def compute_gradient_control(self, expr, point, degree, p):\n        if self.allow_complex:\n            A = np.zeros(degree, dtype=complex)\n            B = np.zeros(p, dtype=complex)\n        else:\n            A = np.zeros(degree, dtype=float)\n            B = np.zeros(p, dtype=float)\n        try:\n            for i in range(degree + p):\n                grad = expr.diff(self.variables[f\"x{i}\"])\n                val = grad.subs(point).evalf()\n                if i < degree:\n                    A[i] = val\n                else:\n                    B[i - degree] = val\n        except TimeoutError:\n            raise\n        except Exception:\n            raise\n        return A, B\n\n    def gen_control(self, return_system=False, skip_unstable=False):\n        \"\"\"\n        Generate systems of functions, data for controlability\n        \"\"\"\n        degree = self.rng.randint(self.min_degree, self.max_degree + 1)\n        p = self.rng.randint(1, degree // 2 + 1)\n        nb_ops = self.rng.randint(degree + p, 2 * (degree + p) + 3, size=(degree,))\n        while True:\n            system = []\n            i = 0\n            ngen = 0\n            while i < degree:\n                # generate expression\n                expr = self.generate_tree(\n                    nb_ops[i], degree + p\n                )  # si tau>0 doit on garantir l'existence de t (x{degree + p})?\n                ngen += 1\n                # sympy zone\n                try:\n                    expr_sp = sp.S(expr, locals=self.local_dict)\n                    # skip constant or invalid expressions\n                    if len(expr_sp.free_symbols) == 0 or has_inf_nan(expr_sp):\n                        continue\n                    # evaluate gradient in point\n                    valA, valB = self.compute_gradient_control(\n                        expr_sp, self.eval_point, degree, p\n                    )\n                    if (\n                        np.isnan(valA).any()\n                        or np.isinf(valA).any()\n                        or np.isnan(valB).any()\n                        or np.isinf(valB).any()\n                    ):\n                        continue\n                    if self.skip_zero_gradient and not valA.any():\n                        continue\n                except TimeoutError:\n                    continue\n                except (ValueError, TypeError):\n                    continue\n                except Exception as e:\n                    logger.error(\n                        \"An unknown exception of type {0} occurred in line {1} \"\n                        'for expression \"{2}\". Arguments:{3!r}.'.format(\n                            type(e).__name__,\n                            sys.exc_info()[-1].tb_lineno,\n                            expr_sp,\n                            e.args,\n                        )\n                    )\n                    continue\n\n                system.append(expr)\n                if i == 0:\n                    A = valA\n                    B = valB\n                else:\n                    A = np.vstack((A, valA))\n                    B = np.vstack((B, valB))\n                i += 1\n            if self.skip_zero_gradient:\n                skip = False\n                for i in range(degree):\n                    if not A[:, [i]].any():\n                        skip = True\n                        break\n                for i in range(p):\n                    if not B[:, [i]].any():\n                        skip = True\n                        break\n                if skip:\n                    continue\n            try:\n                C = ctrl.ctrb(A, B)\n                d = degree - np.linalg.matrix_rank(C, 1.0e-6)\n                if d != 0 and (skip_unstable or self.prob_positive > 0.0):\n                    continue\n                if self.predict_gramian and d == 0:\n                    # C = ctrl.lyap(A, - B @ B.T)\n                    # K = - B.T @ np.linalg.inv(C)\n                    A = A / np.linalg.norm(A)\n                    B = B / np.linalg.norm(A)\n                    tau = 1\n                    yint = []\n                    # We want to integrate a matrix over [0,tau]\n                    # and all the integrate functions I found are for scalars.\n                    # So we do it term by term\n                    for i in range(degree):  # divide in row\n                        yint_line = []\n                        for j in range(degree):  # divide in column\n\n                            dt = np.linspace(\n                                0, tau, num=40\n                            )  # integration path [0,tau] and 40 points\n                            yint0 = []\n                            for k in range(len(dt)):\n                                # vector i with the component to be integrated (i,j),\n                                # evaluated at each point of the integration path\n                                res = (\n                                    (expm(A * (tau - dt[k])))\n                                    @ (B @ B.T)\n                                    @ (expm(A.T * (tau - dt[k])))\n                                )[i]\n                                yint0.append(\n                                    res[j]\n                                )  # vector of the component (i,j) along itegration path\n                            resline = (cumtrapz(yint0, dt, initial=0))[\n                                len(dt) - 1\n                            ]  # integration with cumulative trapezz\n                            yint_line.append(resline)  # reconstruct the line\n                        yint.append(yint_line)  # reconstruct the matrix\n                    if np.isnan(yint).any() or np.isinf(yint).any():\n                        continue\n                    Ctau = (\n                        expm(-tau * A) @ np.array(yint) @ expm(-tau * A.T)\n                    )  # From the gramian to the true C\n                    if np.isnan(Ctau).any() or np.isinf(Ctau).any():\n                        continue\n                    K = -B.T @ (np.linalg.inv(Ctau + 1e-6 * np.eye(degree)))\n                    if np.isnan(K).any() or np.isinf(K).any():\n                        continue\n\n                    with np.nditer(K, op_flags=[\"readwrite\"]) as it:\n                        for x in it:\n                            x[...] = float(f\"%.{self.jacobian_precision}e\" % x)\n\n                    if max(np.linalg.eigvals(A + B @ K).real) > 0:\n                        # Check that A+B@K is stable, which is equivalent to\n                        # check_gramian\n                        # print(\"UNSTABLE\")\n                        continue\n\n            except Exception:\n                # logger.error(\"An unknown exception of type {0} occurred\n                # in line {1} for expression \\\"{2}\\\". Arguments:{3!r}.\".format(\n                # type(e).__name__, sys.exc_info()[-1].tb_lineno, expr_sp, e.args))\n                continue\n            break\n        # # debug\n        # logger.info(str(cspeed))\n        # logger.info(str(cspeed) + \"\\t\" + \" ||||| \".join(str(s) for s in system[:3]))\n        # print(degree, str(ngen) + \" : \" + str((ngen - degree) / ngen * 100.0))\n\n        # encode input\n        x = self.write_int(degree)\n        for s in system:\n            x.append(self.func_separator)\n            x.extend(self.encode_expr(s))\n\n        # encode output: dimension of control subspace and optionally the Gramian matrix\n        if self.qualitative:\n            controlable = 1 if d == 0 else 0\n            y = self.write_int(controlable)\n        else:\n            y = self.write_int(d)\n            if self.predict_gramian and d == 0:\n                K = np.array(K)\n                y.append(self.mtrx_separator)\n                for row in K:\n                    for value in row:\n                        y.extend(self.write_complex(value, self.jacobian_precision))\n                        y.append(self.list_separator)\n                    y.append(self.line_separator)\n\n        if self.max_len > 0 and (len(x) >= self.max_len or len(y) >= self.max_len):\n            return None\n\n        if return_system:\n            return x, y, system, p\n        else:\n            return x, y\n\n    @timeout(5)\n    def compute_gradient_control_t(self, expr, point, degree, p):\n        A = []\n        B = []\n        try:\n            for i in range(degree + p):\n                grad = expr.diff(self.variables[f\"x{i}\"])\n                val = grad.subs(point).evalf()\n                val = simplify(val, 2)\n                if i < degree:\n                    A.append(val)\n                else:\n                    B.append(val)\n        except TimeoutError:\n            raise\n        except Exception:\n            raise\n        return A, B\n\n    @timeout(10)\n    def compute_rank(self, A, B, degree, p, val):\n        Bi = B\n        for i in range(1, int(val * degree / p) + 1):\n            E = B.diff(self.variables[f\"x{degree + p}\"])\n            B = E - A * B\n            Bi = Bi.row_join(B)\n        d = 1\n        for i in range(5):\n            value = (i + 1) * self.tau / 5 - 0.01\n            # D = w(value)\n            D = Bi.subs({self.variables[f\"x{degree + p}\"]: value})\n            D = np.array(D).astype(np.complex)\n            if np.isnan(D).any() or np.isinf(D).any():\n                continue\n            d = degree - np.linalg.matrix_rank(D, 1.0e-6)\n            if d == 0:\n                break\n        return d\n\n    # @timeout(20)\n    def gen_control_t(self):\n        \"\"\"\n        Generate systems of functions, data for controlability\n        \"\"\"\n        while True:\n            degree = self.rng.randint(self.min_degree, self.max_degree + 1)\n            p = self.rng.randint(1, degree // 2 + 1)\n            nb_ops = self.rng.randint(degree + p, 2 * (degree + p) + 3, size=(degree,))\n            ev_point = OrderedDict(\n                {self.variables[f\"x{i}\"]: self.eval_value for i in range(degree + p)}\n            )\n            system = []\n            i = 0\n            A = sp.Matrix()\n            B = sp.Matrix()\n            ngen = 0\n            while i < degree:\n                # generate expression\n                # si tau>0 doit on garantir l'existence de t (x{degree + p}) ?\n                expr = self.generate_tree(nb_ops[i], degree + p + 1)\n                ngen += 1\n                # sympy zone\n                try:\n                    expr_sp = sp.S(expr, locals=self.local_dict)\n                    # skip constant or invalid expressions\n                    if len(expr_sp.free_symbols) == 0 or has_inf_nan(expr_sp):\n                        continue\n                    # evaluate gradient in point\n                    valA, valB = self.compute_gradient_control_t(\n                        expr_sp, ev_point, degree, p\n                    )\n                    # print('valA', valA)\n                    # print('valB', valB)\n                    if any(has_inf_nan(a) for a in valA) or any(\n                        has_inf_nan(a) for a in valB\n                    ):\n                        continue\n                    if self.skip_zero_gradient and all(a == 0 for a in valA):\n                        continue\n                except TimeoutError:\n                    continue\n                except (ValueError, TypeError):\n                    continue\n                except Exception as e:\n                    logger.error(\n                        \"An unknown exception of type {0} occurred in line {1} \"\n                        'for expression \"{2}\". '\n                        \"Arguments:{3!r}.\".format(\n                            type(e).__name__,\n                            sys.exc_info()[-1].tb_lineno,\n                            expr_sp,\n                            e.args,\n                        )\n                    )\n                    continue\n\n                system.append(expr)\n                v1 = sp.Matrix(1, degree, valA)\n                v2 = sp.Matrix(1, p, valB)\n                A = A.col_join(v1)\n                B = B.col_join(v2)\n                i += 1\n\n            if self.skip_zero_gradient:\n                if any(all(A[j, i] == 0 for j in range(degree)) for i in range(degree)):\n                    continue\n                if any(all(B[j, i] == 0 for j in range(degree)) for i in range(p)):\n                    continue\n\n            try:\n                d = self.compute_rank(A, B, degree, p, 2)\n            except TimeoutError:\n                continue\n            # except FloatingPointError:\n            #     continue\n            except Exception as e:\n                logger.error(\n                    \"An unknown exception of type {0} occurred in line {1} \"\n                    'for expression \"{2}\". '\n                    \"Arguments:{3!r}.\".format(\n                        type(e).__name__, sys.exc_info()[-1].tb_lineno, expr_sp, e.args\n                    )\n                )\n                continue\n            break\n        # # debug\n        # logger.info(str(cspeed))\n        # logger.info(str(cspeed) + \"\\t\" + \" ||||| \".join(str(s) for s in system[:3]))\n        # print(degree, str(ngen) + \" : \" + str((ngen - degree) / ngen * 100.0))\n\n        # print(', '.join(f\"{s} {t:.3f}\" for s, t in times))\n\n        # encode input\n        x = self.write_int(degree)\n        for s in system:\n            x.append(self.func_separator)\n            x.extend(self.encode_expr(s))\n\n        # encode output: dimension of control subspace and optionally the Gramian matrix\n        controlable = 1 if d == 0 else 0\n        y = self.write_int(controlable)\n\n        if self.max_len > 0 and (len(x) >= self.max_len or len(y) >= self.max_len):\n            return None\n\n        return x, y\n\n    def generate_cond_init(self, max_delay, dimension, unariesexp, unariesfk):\n        pol = set()\n        nfactor = self.rng.randint(1, max_delay + 1)\n        # print(nfactor)\n        delay = np.zeros(dimension)\n        bounds = []\n        vars = set()\n        for j in range(nfactor):\n            vars.add(\n                (self.rng.randint(0, dimension), self.rng.randint(0, len(unariesexp)))\n            )\n        pol.add(tuple(vars))\n        # print(pol)\n        for i in range(len(pol)):\n            v = list(pol)[i]\n            # print(len(v))\n            # print(v[len(v)-1])\n            # print(v[len(v)-1][0])\n            # print(v[0][0])\n            # print(delay)\n            for j in range(len(v)):\n                op = unariesexp[v[j][1]]\n                var = Node(self.variables[f\"x{v[j][0]}\"])\n                if op == \"id\":\n                    term = var\n                elif len(op) > 3 and op[:3] == \"pow\":\n                    term = Node(\"^\", [var, Node(int(op[3:]))])\n                elif op == \"expi\":\n                    a_d = self.rng.randint(-100, 100)\n                    # b = self.rng.randint(-100, 100)#Not needed for now\n                    b_d = 0\n                    term = Node(\n                        \"exp\",\n                        [\n                            Node(\n                                \"+\",\n                                [\n                                    Node(\"*\", [Node(a_d), Node(\"*\", [Node(\"I\"), var])]),\n                                    Node(b_d),\n                                ],\n                            )\n                        ],\n                    )\n                    delay[v[j][0]] = delay[v[j][0]] + a_d\n                    # print(delay[v[j][0]])\n                else:\n                    term = Node(op, [var])\n                p = term if j == 0 else Node(\"*\", [p, term])\n        expr_delay = p\n        # print(sp.S(expr_delay))\n        for i in range(dimension):\n            k = self.rng.randint(0, len(unariesfk))\n            op = unariesfk[k]\n            var = Node(self.variables[f\"x{i}\"])\n            a = self.rng.randint(-100, 100)\n            # b = self.rng.randint(-100, 100)\n            # inclure b plus tard not needed now avec les delays\n            b = 0\n            var = Node(\"+\", [Node(\"*\", [Node(a), var]), Node(b)])\n            if op == \"sinc\":\n                bounds.append(\n                    [-abs(a) / (2 * np.pi), abs(a) / (2 * np.pi)]\n                )  # fouriertiser\n                term = Node(\"/\", [Node(\"sin\", [var]), var])\n                # print(sp.S(term))\n            elif op == \"1\":\n                bounds.append([0, 0])\n                term = Node(1)\n            elif op == \"delta0\":\n                bounds.append([-np.inf, np.inf])\n                term = Node(op, [var])\n            elif op == \"gauss\":\n                bounds.append([-np.inf, np.inf])\n                term = Node(\n                    \"exp\", [Node(\"*\", [Node(-1), Node(\"^\", [var, Node(2)])])]\n                )  # checker\n            else:\n                return None\n            # Message d'erreur\n            # print(sp.S(term))\n            p = term if i == 0 else Node(\"*\", [p, term])\n            bounds[i][0] = bounds[i][0] + delay[i] / (2 * np.pi)\n            bounds[i][1] = bounds[i][1] + delay[i] / (2 * np.pi)\n            # print(delay[i])\n        u0 = Node(\"*\", [expr_delay, p])\n        # u0f = Node('*', [exprf, pf])\n\n        return u0, bounds\n\n    def gen_fourier_cond_init(self):\n        while True:\n            try:\n                dimension = self.rng.randint(self.min_degree, self.max_degree + 1)\n                nb_ops = self.rng.randint(dimension, 2 * dimension + 3)\n                # Generate differential operator\n                unariesd = [\"id\", \"pow2\", \"pow4\"]\n                expr = self.generate_polynomial(\n                    nb_ops, 4, dimension, unariesd, True, False\n                )\n                # print(sp.S(expr))\n                # Fourier transform of the differential operator\n                PF = OrderedDict(\n                    {\n                        self.variables[f\"x{i}\"]: 2\n                        * np.pi\n                        * 1j\n                        * self.variables[f\"x{i}\"]\n                        for i in range(self.max_degree)\n                    }\n                )\n                poly_fourier = sp.S(expr).subs(PF)\n                # print(poly_fourier)\n                # Generate initial condition\n                unariesexp = [\"expi\"]\n                unariesfk = [\"1\", \"sinc\", \"delta0\", \"gauss\"]\n                max_delay_op = 2 * dimension\n                expr_u0, bounds = self.generate_cond_init(\n                    max_delay_op, dimension, unariesexp, unariesfk\n                )\n                # print(sp.S(expr_u0))\n                # print(bounds)\n                # Minimization of the Fourier transform of the differential operator\n                # on the frequency of the initial conditions\n                dum_point = np.zeros(dimension, dtype=float) + 0.5\n                max_f = opt.minimize(\n                    expr_to_fun_real,\n                    dum_point,\n                    args=(poly_fourier, dimension),\n                    method=\"TNC\",\n                    bounds=bounds,\n                    options={\"ftol\": 1e-15, \"gtol\": 1e-15},\n                )\n                # print(max_f.fun)\n                if not max_f.success:\n                    # logger.info(f'optimization error')\n                    continue\n                if max_f.fun < -1e14:\n                    reg = 0  # -1\n                    stab = 0\n                elif max_f.fun < 0:\n                    reg = 1  # 0\n                    stab = 0\n                elif max_f.fun >= 0:\n                    reg = 1\n                    stab = 1\n                else:\n                    # logger.info(f'optimization error in value')\n                    continue\n            except Exception as e:\n                print(e)\n                continue\n            break\n\n        # encode input\n        x = self.write_int(dimension)\n        x.append(self.func_separator)\n        x.extend(self.encode_expr(expr, True))\n        x.append(self.func_separator)\n        x.extend(self.encode_expr(expr_u0, True))\n\n        # encode output\n        y = self.write_int(reg)\n        y.append(self.func_separator)\n        y.extend(self.write_int(stab))\n        if self.predict_bounds:\n            y.append(self.func_separator)\n            for i in range(len(bounds)):\n                if bounds[i][0] == np.inf:\n                    y.append(self.pos_inf)\n                elif bounds[i][0] == -np.inf:\n                    y.append(self.neg_inf)\n                else:\n                    y.extend(self.write_float(bounds[i][0], 2))\n                y.append(self.list_separator)\n                if bounds[i][1] == np.inf:\n                    y.append(self.pos_inf)\n                elif bounds[i][1] == -np.inf:\n                    y.append(self.neg_inf)\n                else:\n                    y.extend(self.write_float(bounds[i][1], 2))\n                y.append(self.line_separator)\n\n        return x, y\n\n    def create_train_iterator(self, task, data_path, params):\n        \"\"\"\n        Create a dataset for this environment.\n        \"\"\"\n        logger.info(f\"Creating train iterator for {task} ...\")\n\n        dataset = EnvDataset(\n            self,\n            task,\n            train=True,\n            params=params,\n            path=(None if data_path is None else data_path[task][0]),\n        )\n        return DataLoader(\n            dataset,\n            timeout=(0 if params.num_workers == 0 else 1800),\n            batch_size=params.batch_size,\n            num_workers=(\n                params.num_workers\n                if data_path is None or params.num_workers == 0\n                else 1\n            ),\n            shuffle=False,\n            collate_fn=dataset.collate_fn,\n        )\n\n    def create_test_iterator(\n        self, data_type, task, data_path, batch_size, params, size\n    ):\n        \"\"\"\n        Create a dataset for this environment.\n        \"\"\"\n        assert data_type in [\"valid\", \"test\"]\n        logger.info(f\"Creating {data_type} iterator for {task} ...\")\n\n        dataset = EnvDataset(\n            self,\n            task,\n            train=False,\n            params=params,\n            path=(\n                None\n                if data_path is None\n                else data_path[task][1 if data_type == \"valid\" else 2]\n            ),\n            size=size,\n        )\n        return DataLoader(\n            dataset,\n            timeout=0,\n            batch_size=batch_size,\n            num_workers=1,\n            shuffle=False,\n            collate_fn=dataset.collate_fn,\n        )\n\n    @staticmethod\n    def register_args(parser):\n        \"\"\"\n        Register environment parameters.\n        \"\"\"\n        parser.add_argument(\n            \"--max_int\", type=int, default=10, help=\"Maximum integer value\"\n        )\n        parser.add_argument(\n            \"--precision\", type=int, default=3, help=\"Float numbers precision\"\n        )\n        parser.add_argument(\n            \"--jacobian_precision\",\n            type=int,\n            default=1,\n            help=\"Float numbers precision in the Jacobian\",\n        )\n        parser.add_argument(\n            \"--positive\",\n            type=bool_flag,\n            default=False,\n            help=\"Do not sample negative numbers\",\n        )\n        parser.add_argument(\n            \"--nonnull\", type=bool_flag, default=True, help=\"Do not sample zeros\"\n        )\n        parser.add_argument(\n            \"--predict_jacobian\",\n            type=bool_flag,\n            default=False,\n            help=\"Predict the Jacobian matrix\",\n        )\n        parser.add_argument(\n            \"--predict_gramian\",\n            type=bool_flag,\n            default=False,\n            help=\"Predict the Gramian matrix\",\n        )\n        parser.add_argument(\n            \"--qualitative\",\n            type=bool_flag,\n            default=False,\n            help=\"Binary output: system is stable or controllable\",\n        )\n        parser.add_argument(\n            \"--allow_complex\",\n            type=bool_flag,\n            default=False,\n            help=\"Allow complex values in A and B\",\n        )\n        parser.add_argument(\n            \"--reversed_eval\",\n            type=bool_flag,\n            default=False,\n            help=\"Validation set is dim whereas train set is test control\",\n        )\n        parser.add_argument(\n            \"--euclidian_metric\",\n            type=bool_flag,\n            default=False,\n            help=\"Simple metric for gramian comparison\",\n        )\n        parser.add_argument(\n            \"--auxiliary_task\",\n            type=bool_flag,\n            default=False,\n            help=\"Gramian as auxiliary task\",\n        )\n        parser.add_argument(\n            \"--tau\", type=int, default=0, help=\"if > 0 time span for controllability\"\n        )\n        parser.add_argument(\n            \"--gramian_norm1\",\n            type=bool_flag,\n            default=False,\n            help=\"Use norm1 as Euclidian distance for Gramian\",\n        )\n        parser.add_argument(\n            \"--gramian_tolerance\",\n            type=float,\n            default=0.1,\n            help=\"Tolerance level for Gramian euclidian distance\",\n        )\n        parser.add_argument(\n            \"--predict_bounds\",\n            type=bool_flag,\n            default=True,\n            help=\"Predict bounds for Fourier with initial conditions\",\n        )\n\n        parser.add_argument(\n            \"--prob_int\",\n            type=float,\n            default=0.3,\n            help=\"Probability of int vs variables\",\n        )\n        parser.add_argument(\n            \"--min_degree\",\n            type=int,\n            default=2,\n            help=\"Minimum degree of ode / nb of variables\",\n        )\n        parser.add_argument(\n            \"--max_degree\",\n            type=int,\n            default=6,\n            help=\"Maximum degree of ode / nb of variables\",\n        )\n\n        parser.add_argument(\n            \"--min_expr_len_factor_cspeed\",\n            type=int,\n            default=0,\n            help=\"In cspeed, min nr of operators in system eqs: 3+k degree\",\n        )\n        parser.add_argument(\n            \"--max_expr_len_factor_cspeed\",\n            type=int,\n            default=2,\n            help=\"In cspeed, min nr of operators in system eqs: 3+k degree\",\n        )\n\n        parser.add_argument(\n            \"--custom_unary_probs\",\n            type=bool_flag,\n            default=False,\n            help=\"Lyapunov function is a polynomial\",\n        )\n        parser.add_argument(\n            \"--prob_trigs\",\n            type=float,\n            default=0.333,\n            help=\"Probability of trig operators\",\n        )\n        parser.add_argument(\n            \"--prob_arc_trigs\",\n            type=float,\n            default=0.333,\n            help=\"Probability of inverse trig operators\",\n        )\n        parser.add_argument(\n            \"--prob_logs\",\n            type=float,\n            default=0.222,\n            help=\"Probability of logarithm and exponential operators\",\n        )\n\n        parser.add_argument(\n            \"--eval_value\",\n            type=float,\n            default=0.0,\n            help=\"Evaluation point for all variables\",\n        )\n        parser.add_argument(\n            \"--skip_zero_gradient\",\n            type=bool_flag,\n            default=False,\n            help=\"No gradient can be zero at evaluation point\",\n        )\n\n        parser.add_argument(\n            \"--prob_positive\",\n            type=float,\n            default=-1.0,\n            help=(\n                \"Proportion of positive convergence speed \"\n                \"(for all degrees, -1.0 = no control)\"\n            ),\n        )\n\n        parser.add_argument(\n            \"--eval_size\",\n            type=int,\n            default=10000,\n            help=\"Size and valid and test sample\",\n        )\n\n\nclass EnvDataset(Dataset):\n    def __init__(self, env, task, train, params, path, size=None):\n        super(EnvDataset).__init__()\n        self.env = env\n        self.train = train\n        self.task = task\n        self.batch_size = params.batch_size\n        self.env_base_seed = params.env_base_seed\n        self.path = path\n        self.global_rank = params.global_rank\n        self.count = 0\n        assert task in ODEEnvironment.TRAINING_TASKS\n        assert size is None or not self.train\n\n        # batching\n        self.num_workers = params.num_workers\n        self.batch_size = params.batch_size\n\n        # generation, or reloading from file\n        if path is not None:\n            assert os.path.isfile(path)\n            logger.info(f\"Loading data from {path} ...\")\n            with io.open(path, mode=\"r\", encoding=\"utf-8\") as f:\n                # either reload the entire file, or the first N lines\n                # (for the training set)\n                if not train:\n                    lines = [line.rstrip().split(\"|\") for line in f]\n                else:\n                    lines = []\n                    for i, line in enumerate(f):\n                        if i == params.reload_size:\n                            break\n                        if i % params.n_gpu_per_node == params.local_rank:\n                            lines.append(line.rstrip().split(\"|\"))\n            self.data = [xy.split(\"\\t\") for _, xy in lines]\n            self.data = [xy for xy in self.data if len(xy) == 2]\n            logger.info(f\"Loaded {len(self.data)} equations from the disk.\")\n\n            if task == \"ode_control\" and params.reversed_eval and not self.train:\n                self.data = [\n                    (x, \"INT+ 1\" if y == \"INT+ 0\" else \"INT+ 0\") for (x, y) in self.data\n                ]\n\n            if task == \"ode_convergence_speed\" and params.qualitative:\n                self.data = [\n                    (x, \"INT+ 1\" if y[:7] == \"FLOAT- \" else \"INT+ 0\")\n                    for (x, y) in self.data\n                ]\n\n            if (\n                task == \"fourier_cond_init\" and not params.predict_bounds\n            ):  # \"INT+ X <SPECIAL_3> INT+ X\"\n                self.data = [(x, y[:25]) for (x, y) in self.data]\n\n            # if we are not predicting the Jacobian, remove it\n            if task == \"ode_convergence_speed\" and not params.predict_jacobian:\n                self.data = [\n                    (x, y[y.index(env.mtrx_separator) + len(env.mtrx_separator) + 1 :])\n                    if env.mtrx_separator in y\n                    else (x, y)\n                    for (x, y) in self.data\n                ]\n\n        # dataset size: infinite iterator for train,\n        # finite for valid / test (default of 5000 if no file provided)\n        if self.train:\n            self.size = 1 << 60\n        elif size is None:\n            self.size = 5000 if path is None else len(self.data)\n        else:\n            assert size > 0\n            self.size = size\n\n    def collate_fn(self, elements):\n        \"\"\"\n        Collate samples into a batch.\n        \"\"\"\n        x, y = zip(*elements)\n        nb_eqs = [seq.count(self.env.func_separator) for seq in x]\n        x = [torch.LongTensor([self.env.word2id[w] for w in seq]) for seq in x]\n        y = [torch.LongTensor([self.env.word2id[w] for w in seq]) for seq in y]\n        x, x_len = self.env.batch_sequences(x)\n        y, y_len = self.env.batch_sequences(y)\n        return (x, x_len), (y, y_len), torch.LongTensor(nb_eqs)\n\n    def init_rng(self):\n        \"\"\"\n        Initialize random generator for training.\n        \"\"\"\n        if hasattr(self.env, \"rng\"):\n            return\n        if self.train:\n            worker_id = self.get_worker_id()\n            self.env.worker_id = worker_id\n            self.env.rng = np.random.RandomState(\n                [worker_id, self.global_rank, self.env_base_seed]\n            )\n            logger.info(\n                f\"Initialized random generator for worker {worker_id}, with seed \"\n                f\"{[worker_id, self.global_rank, self.env_base_seed]} \"\n                f\"(base seed={self.env_base_seed}).\"\n            )\n        else:\n            self.env.rng = np.random.RandomState(0)\n\n    def get_worker_id(self):\n        \"\"\"\n        Get worker ID.\n        \"\"\"\n        if not self.train:\n            return 0\n        worker_info = torch.utils.data.get_worker_info()\n        assert (worker_info is None) == (self.num_workers == 0)\n        return 0 if worker_info is None else worker_info.id\n\n    def __len__(self):\n        \"\"\"\n        Return dataset size.\n        \"\"\"\n        return self.size\n\n    def __getitem__(self, index):\n        \"\"\"\n        Return a training sample.\n        Either generate it, or read it from file.\n        \"\"\"\n        self.init_rng()\n        if self.path is None:\n            return self.generate_sample()\n        else:\n            return self.read_sample(index)\n\n    def read_sample(self, index):\n        \"\"\"\n        Read a sample.\n        \"\"\"\n        if self.train:\n            index = self.env.rng.randint(len(self.data))\n        x, y = self.data[index]\n        x = x.split()\n        y = y.split()\n        assert len(x) >= 1 and len(y) >= 1\n        return x, y\n\n    def generate_sample(self):\n        \"\"\"\n        Generate a sample.\n        \"\"\"\n        while True:\n            try:\n                if self.task == \"ode_convergence_speed\":\n                    xy = self.env.gen_ode_system_convergence()\n                elif self.task == \"ode_control\":\n                    if self.env.tau == 0:\n                        xy = self.env.gen_control()\n                    else:\n                        xy = self.env.gen_control_t()\n                elif self.task == \"fourier_cond_init\":\n                    xy = self.env.gen_fourier_cond_init()\n                else:\n                    raise Exception(f\"Unknown data type: {self.task}\")\n                if xy is None:\n                    continue\n                x, y = xy\n                break\n            except TimeoutError:\n                continue\n            except Exception as e:\n                logger.error(\n                    \"An unknown exception of type {0} occurred for worker {4} \"\n                    'in line {1} for expression \"{2}\". Arguments:{3!r}.'.format(\n                        type(e).__name__,\n                        sys.exc_info()[-1].tb_lineno,\n                        \"F\",\n                        e.args,\n                        self.get_worker_id(),\n                    )\n                )\n                continue\n        self.count += 1\n\n        # clear SymPy cache periodically\n        if CLEAR_SYMPY_CACHE_FREQ > 0 and self.count % CLEAR_SYMPY_CACHE_FREQ == 0:\n            logger.warning(f\"Clearing SymPy cache (worker {self.get_worker_id()})\")\n            clear_cache()\n\n        return x, y\n"
  },
  {
    "path": "src/evaluator.py",
    "content": "# Copyright (c) 2020-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nfrom logging import getLogger\nfrom collections import OrderedDict\nfrom concurrent.futures import ProcessPoolExecutor\nimport os\nimport time\nimport torch\nimport numpy as np\nimport sympy as sp\n\nfrom .utils import to_cuda  # , timeout\nfrom .utils import TimeoutError\nfrom .envs.ode import second_index\n\n\nTOLERANCE_THRESHOLD = 1e-1\n\n\nlogger = getLogger()\n\n\ndef check_fourier_cond_init(env, src, tgt, hyp):\n\n    try:\n        nx = src\n        dimension, pos = env.parse_int(nx)\n        nx = nx[pos:]\n        operateur, nx = env.prefix_to_infix(nx[1:])\n        cond_init, nx = env.prefix_to_infix(nx[1:])\n        if nx[1:] != []:\n            logger.info(\"wrong src\")\n            return False\n\n        # read tgt\n        reg, pos1 = env.parse_int(tgt)\n        stab, pos2 = env.parse_int(tgt[pos1 + 1 :])\n        tgt = tgt[pos1 + pos2 :]\n\n        # read hyp\n        reghyp, pos1 = env.parse_int(hyp)\n        stabhyp, pos2 = env.parse_int(hyp[pos1 + 1 :])\n        hyp = hyp[pos1 + pos2 :]\n\n        # compare hyp and tgt\n        if (\n            reghyp != reg or stabhyp != stab\n        ):  # First condition on existence and stability\n            # logger.error(\"Incorrect reg or stab\")\n            return False\n\n        # predict bounds is a subtask, used for training but not for evaluation,\n        # hence the comment, uncomment if bounds are to be used at evaluations\n        # if env.predict_bounds:\n\n        #     # read tgt\n        #     nr_bounds = tgt.count(env.list_separator)\n        #     nr_dimension = tgt.count(env.line_separator)\n        #     if nr_bounds != dimension or nr_dimension != dimension:\n        #         # logger.error(\"Incorrect form of tgt in read_fourier\")\n        #         return False\n        #     bounds = []\n        #     pos = 1\n        #     for i in range(dimension):\n        #         tgt = tgt[pos + 1:]\n        #         if tgt[0] == env.pos_inf:\n        #             bda = np.inf\n        #             pos = 1\n        #         elif tgt[0] == env.neg_inf:\n        #             bda = -np.inf\n        #             pos = 1\n        #         else:\n        #             bda, pos = env.parse_float(tgt)\n        #         tgt = tgt[pos + 1:]\n        #         if tgt[0] == env.pos_inf:\n        #             bdb = np.inf\n        #             pos = 1\n        #         elif tgt[0] == env.neg_inf:\n        #             bdb = -np.inf\n        #             pos = 1\n        #         else:\n        #             bdb, pos = env.parse_float(tgt)\n        #         bounds.append([bda, bdb])\n\n        #     # read hyp\n        #     nr_bounds = hyp.count(env.list_separator)\n        #     nr_dimension = hyp.count(env.line_separator)\n        #     if nr_bounds != dimension or nr_dimension != dimension:\n        #         # logger.error(\"Incorrect form of hyp in read_fourier\")\n        #         return False\n        #     bounds_hyp = []\n        #     pos = 1\n        #     for i in range(dimension):\n        #         hyp = hyp[pos + 1:]\n        #         if hyp[0] == env.pos_inf:\n        #             bda = np.inf\n        #             pos = 1\n        #         elif hyp[0] == env.neg_inf:\n        #             bda = -np.inf\n        #             pos = 1\n        #         else:\n        #             bda, pos = env.parse_float(hyp)\n        #         hyp = hyp[pos + 1:]\n        #         if hyp[0] == env.pos_inf:\n        #             bdb = np.inf\n        #             pos = 1\n        #         elif hyp[0] == env.neg_inf:\n        #             bdb = -np.inf\n        #             pos = 1\n        #         else:\n        #             bdb, pos = env.parse_float(hyp)\n        #         bounds_hyp.append([bda, bdb])\n\n        #     # compare hyp and tgt\n        #     for i in range(len(bounds)):\n        # # Second condition on frequency bounds of initial condition\n        #         for j in range(len(bounds[i])):\n        #             if abs(bounds[i][j]) == np.inf:\n        #                 if bounds[i][j] != bounds_hyp[i][j]:\n        #                     # logger.error(\"Incorrect inf bound prediction\")\n        #                     return False\n        #             elif abs(bounds[i][j]) == 0:\n        #                 if bounds_hyp[i][j] != 0:\n        #                     # logger.error(\"Incorrect 0 bound prediction\")\n        #                     return False\n        #             else:\n        #                 if (bounds[i][j] - bounds_hyp[i][j]) / bounds[i][j] > 0.1:\n        #                     # logger.error(\"Incorrect bound prediction\")\n        #                     return False\n\n    except Exception as e:\n        logger.info(f\"Exception {e} in top_test\")\n        return False\n\n    return True\n\n\ndef idx_to_infix(env, idx, input=True):\n    \"\"\"\n    Convert an indexed prefix expression to SymPy.\n    \"\"\"\n    prefix = [env.id2word[wid] for wid in idx]\n    infix = env.input_to_infix(prefix) if input else env.output_to_infix(prefix)\n    return infix\n\n\ndef compare_gramians(env, tgt, hyp, tolerance, norm1=False):\n    nr_lines = tgt.count(env.line_separator)\n    nr_cols = tgt.count(env.list_separator)\n    nr_cols = nr_cols // nr_lines\n    # read hypothesis\n    h = hyp\n    h_gramian = np.zeros((nr_lines, nr_cols), dtype=float)\n    for i in range(nr_lines):\n        for j in range(nr_cols):\n            val, pos = env.parse_float(h)\n            if np.isnan(val):\n                return False\n            if len(h) <= pos or h[pos] != env.list_separator:\n                return False\n            h_gramian[i][j] = val\n            h = h[pos + 1 :]\n        if len(h) == 0 or h[0] != env.line_separator:\n            return False\n        h = h[1:]\n    # read target\n    t = tgt\n    t_gramian = np.zeros((nr_lines, nr_cols), dtype=float)\n    for i in range(nr_lines):\n        for j in range(nr_cols):\n            val, pos = env.parse_float(t)\n            t_gramian[i][j] = val\n            t = t[pos + 1 :]\n        t = t[1:]\n    # compare\n    if norm1:\n        tot = 0\n        nb = 0\n        for i in range(nr_lines):\n            for j in range(nr_cols):\n                if t_gramian[i][j] != h_gramian[i][j]:\n                    den = h_gramian[i][j] if t_gramian[i][j] == 0 else t_gramian[i][j]\n                    delta = abs((t_gramian[i][j] - h_gramian[i][j]) / den)\n                    tot += delta\n                    nb += 1\n\n        return tot <= tolerance * nb\n    else:\n        for i in range(nr_lines):\n            for j in range(nr_cols):\n                if t_gramian[i][j] != h_gramian[i][j]:\n                    den = h_gramian[i][j] if t_gramian[i][j] == 0 else t_gramian[i][j]\n                    delta = abs((t_gramian[i][j] - h_gramian[i][j]) / den)\n                    if delta > tolerance:\n                        return False\n    return True\n\n\ndef check_gramian(env, src, tgt, hyp):\n    # Read src\n    try:\n        degree, pos = env.parse_int(src)\n        nx = src[\n            pos:\n        ]  # retourne src sans le degree et le séparateur qui va avec si j'ai bien suivi\n        system = []\n        while len(nx) > 0:\n            b, nx = env.prefix_to_infix(nx[1:])\n            # convertit en sympy, on en aura besoin de toutes facons\n            s = sp.S(b)\n            system.append(s)\n\n        # get expected shape of solution (from tgt)\n        nr_lines = tgt.count(env.line_separator)\n        nr_cols = tgt.count(env.list_separator)\n        if nr_cols % nr_lines != 0 or nr_cols // nr_lines != degree:\n            logger.error(\"Incorrect target gramian in check_gramian\")\n            return False\n        nr_cols = nr_cols // nr_lines\n\n        for i in range(degree):\n            valA, valB = env.compute_gradient_control(\n                system[i], env.eval_point, degree, nr_lines\n            )\n            if i == 0:\n                A = valA\n                B = valB\n            else:\n                A = np.vstack((A, valA))\n                B = np.vstack((B, valB))\n\n        A = A / np.linalg.norm(A)\n        B = B / np.linalg.norm(A)\n\n        # read hyp, check correct shape\n        h = hyp\n        K0 = np.zeros((nr_lines, nr_cols))\n        for i in range(nr_lines):\n            for j in range(nr_cols):\n                val, pos = env.parse_float(h)\n                if np.isnan(val):\n                    return False\n                if len(h) <= pos or h[pos] != env.list_separator:\n                    return False\n                K0[i][j] = val\n                h = h[pos + 1 :]\n            if len(h) == 0 or h[0] != env.line_separator:\n                return False\n            h = h[1:]\n\n        V = A + B @ K0\n        return max(np.linalg.eigvals(V).real) < 0\n\n    except TimeoutError:\n        return False\n    except Exception as e:\n        logger.info(f\"{e} in check_gramian\")\n        return False\n\n\ndef check_hypothesis(eq):\n    \"\"\"\n    Check a hypothesis for a given equation and its solution.\n    \"\"\"\n    env = Evaluator.ENV\n    src = [env.id2word[wid] for wid in eq[\"src\"]]\n    tgt = [env.id2word[wid] for wid in eq[\"tgt\"]]\n    hyp = [env.id2word[wid] for wid in eq[\"hyp\"]]\n\n    if eq[\"task\"] == \"ode_convergence_speed\":\n        try:\n            tgt, _ = env.parse_float(tgt)\n            l1 = len(hyp)\n            hyp, l2 = env.parse_float(hyp)\n            if hyp == np.nan or l2 != l1:\n                is_valid = False\n            elif hyp == tgt:\n                is_valid = True\n            else:\n                den = hyp if tgt == 0 else tgt\n                is_valid = abs((tgt - hyp) / den) < TOLERANCE_THRESHOLD\n        except Exception:\n            is_valid = False\n            tgt = 0\n            hyp = 0\n\n    elif eq[\"task\"] == \"ode_control\":\n        if env.predict_gramian:\n            try:\n                d, l1 = env.parse_int(hyp)\n                t, l2 = env.parse_int(tgt)\n                if d == 0 and t == 0 and not env.auxiliary_task:\n                    if env.euclidian_metric:\n                        is_valid = compare_gramians(\n                            env,\n                            tgt[l2 + 1 :],\n                            hyp[l1 + 1 :],\n                            env.gramian_tolerance,\n                            env.gramian_norm1,\n                        )\n                    else:\n                        is_valid = check_gramian(env, src, tgt, hyp[l1 + 1 :])\n                else:\n                    is_valid = d == t\n            except Exception:\n                is_valid = False\n        else:\n            try:\n                tgt, _ = env.parse_int(tgt)\n                l1 = len(hyp)\n                hyp, l2 = env.parse_int(hyp)\n                if hyp == np.nan or l2 != l1:\n                    is_valid = False\n                else:\n                    is_valid = hyp == tgt\n            except Exception:\n                is_valid = False\n    elif eq[\"task\"] == \"fourier_cond_init\":\n        try:\n            is_valid = check_fourier_cond_init(env, src, tgt, hyp)\n        except Exception:\n            is_valid = False\n    else:\n        is_valid = hyp == tgt\n    # update hypothesis\n    eq[\"src\"] = env.input_to_infix(src)\n    eq[\"tgt\"] = tgt\n    eq[\"hyp\"] = hyp\n    eq[\"is_valid\"] = is_valid\n    return eq\n\n\nclass Evaluator(object):\n\n    ENV = None\n\n    def __init__(self, trainer):\n        \"\"\"\n        Initialize evaluator.\n        \"\"\"\n        self.trainer = trainer\n        self.modules = trainer.modules\n        self.params = trainer.params\n        self.env = trainer.env\n        Evaluator.ENV = trainer.env\n\n    def run_all_evals(self):\n        \"\"\"\n        Run all evaluations.\n        \"\"\"\n        params = self.params\n        scores = OrderedDict({\"epoch\": self.trainer.epoch})\n\n        # save statistics about generated data\n        if params.export_data:\n            scores[\"total\"] = sum(self.trainer.EQUATIONS.values())\n            scores[\"unique\"] = len(self.trainer.EQUATIONS)\n            scores[\"unique_prop\"] = 100.0 * scores[\"unique\"] / scores[\"total\"]\n            return scores\n\n        with torch.no_grad():\n            # for data_type in ['valid', 'test']:  FC save time\n            for data_type in [\"valid\"]:\n                for task in params.tasks:\n                    if params.beam_eval:\n                        self.enc_dec_step_beam_fast(data_type, task, scores)\n                    else:\n                        self.enc_dec_step(data_type, task, scores)\n\n        return scores\n\n    def truncate_at(self, x, xlen):\n        pattern = self.env.word2id[self.env.func_separator]\n        bs = len(xlen)\n        eos = self.env.eos_index\n        assert x.shape[1] == bs\n        new_seqs = []\n        new_lengths = []\n        for i in range(bs):\n            s = x[: xlen[i], i].tolist()\n            assert s[0] == s[-1] == eos\n            ns = second_index(s, pattern)\n            if ns != len(s):\n                s = s[:ns]\n                s.append(eos)\n            new_seqs.append(s)\n            new_lengths.append(len(s))\n\n        # batch sequence\n        lengths = torch.LongTensor(new_lengths)\n        seqs = torch.LongTensor(lengths.max().item(), bs).fill_(self.env.pad_index)\n        for i, s in enumerate(new_seqs):\n            seqs[: lengths[i], i].copy_(torch.LongTensor(s))\n\n        return seqs, lengths\n\n    def enc_dec_step(self, data_type, task, scores):\n        \"\"\"\n        Encoding / decoding step.\n        \"\"\"\n        params = self.params\n        env = self.env\n        encoder = (\n            self.modules[\"encoder\"].module\n            if params.multi_gpu\n            else self.modules[\"encoder\"]\n        )\n        decoder = (\n            self.modules[\"decoder\"].module\n            if params.multi_gpu\n            else self.modules[\"decoder\"]\n        )\n        encoder.eval()\n        decoder.eval()\n        assert params.eval_verbose in [0, 1]\n        assert params.eval_verbose_print is False or params.eval_verbose > 0\n        assert task in [\n            \"ode_convergence_speed\",\n            \"ode_control\",\n            \"fourier_cond_init\",\n        ]\n\n        # stats\n        xe_loss = 0\n        n_valid = torch.zeros(1000, dtype=torch.long)\n        n_total = torch.zeros(1000, dtype=torch.long)\n\n        # evaluation details\n        if params.eval_verbose:\n            eval_path = os.path.join(\n                params.dump_path, f\"eval.{data_type}.{task}.{scores['epoch']}\"\n            )\n            f_export = open(eval_path, \"w\")\n            logger.info(f\"Writing evaluation results in {eval_path} ...\")\n\n        # iterator\n        iterator = self.env.create_test_iterator(\n            data_type,\n            task,\n            data_path=self.trainer.data_path,\n            batch_size=params.batch_size_eval,\n            params=params,\n            size=params.eval_size,\n        )\n        eval_size = len(iterator.dataset)\n\n        for (x1, len1), (x2, len2), nb_ops in iterator:\n\n            # print status\n            if n_total.sum().item() % 500 < params.batch_size_eval:\n                logger.info(f\"{n_total.sum().item()}/{eval_size}\")\n\n            # target words to predict\n            alen = torch.arange(len2.max(), dtype=torch.long, device=len2.device)\n            pred_mask = (\n                alen[:, None] < len2[None] - 1\n            )  # do not predict anything given the last target word\n            y = x2[1:].masked_select(pred_mask[:-1])\n            assert len(y) == (len2 - 1).sum().item()\n\n            # optionally truncate input\n            x1_, len1_ = x1, len1\n\n            # cuda\n            x1_, len1_, x2, len2, y = to_cuda(x1_, len1_, x2, len2, y)\n\n            # forward / loss\n            encoded = encoder(\"fwd\", x=x1_, lengths=len1_, causal=False)\n            decoded = decoder(\n                \"fwd\",\n                x=x2,\n                lengths=len2,\n                causal=True,\n                src_enc=encoded.transpose(0, 1),\n                src_len=len1_,\n            )\n            word_scores, loss = decoder(\n                \"predict\", tensor=decoded, pred_mask=pred_mask, y=y, get_scores=True\n            )\n\n            # correct outputs per sequence / valid top-1 predictions\n            t = torch.zeros_like(pred_mask, device=y.device)\n            t[pred_mask] += word_scores.max(1)[1] == y\n            valid = (t.sum(0) == len2 - 1).cpu().long()\n\n            # export evaluation details\n            if params.eval_verbose:\n                for i in range(len(len1)):\n                    src = idx_to_infix(env, x1[1 : len1[i] - 1, i].tolist(), True)\n                    tgt = idx_to_infix(env, x2[1 : len2[i] - 1, i].tolist(), False)\n                    s = (\n                        f\"Equation {n_total.sum().item() + i} \"\n                        f\"({'Valid' if valid[i] else 'Invalid'})\\n\"\n                        f\"src={src}\\ntgt={tgt}\\n\"\n                    )\n                    if params.eval_verbose_print:\n                        logger.info(s)\n                    f_export.write(s + \"\\n\")\n                    f_export.flush()\n\n            # stats\n            xe_loss += loss.item() * len(y)\n            n_valid.index_add_(-1, nb_ops, valid)\n            n_total.index_add_(-1, nb_ops, torch.ones_like(nb_ops))\n\n        # evaluation details\n        if params.eval_verbose:\n            f_export.close()\n\n        # log\n        _n_valid = n_valid.sum().item()\n        _n_total = n_total.sum().item()\n        logger.info(\n            f\"{_n_valid}/{_n_total} ({100. * _n_valid / _n_total}%) \"\n            \"equations were evaluated correctly.\"\n        )\n\n        # compute perplexity and prediction accuracy\n        assert _n_total == eval_size\n        scores[f\"{data_type}_{task}_xe_loss\"] = xe_loss / _n_total\n        scores[f\"{data_type}_{task}_acc\"] = 100.0 * _n_valid / _n_total\n\n        # per class perplexity and prediction accuracy\n        for i in range(len(n_total)):\n            if n_total[i].item() == 0:\n                continue\n            scores[f\"{data_type}_{task}_acc_{i}\"] = (\n                100.0 * n_valid[i].item() / max(n_total[i].item(), 1)\n            )\n\n    def enc_dec_step_beam_fast(self, data_type, task, scores, size=None):\n        \"\"\"\n        Encoding / decoding step with beam generation and SymPy check.\n        \"\"\"\n        params = self.params\n        env = self.env\n        encoder = (\n            self.modules[\"encoder\"].module\n            if params.multi_gpu\n            else self.modules[\"encoder\"]\n        )\n        decoder = (\n            self.modules[\"decoder\"].module\n            if params.multi_gpu\n            else self.modules[\"decoder\"]\n        )\n        encoder.eval()\n        decoder.eval()\n        assert params.eval_verbose in [0, 1, 2]\n        assert params.eval_verbose_print is False or params.eval_verbose > 0\n        assert task in [\n            \"ode_convergence_speed\",\n            \"ode_control\",\n            \"fourier_cond_init\",\n        ]\n\n        # stats\n        xe_loss = 0\n        n_valid = torch.zeros(1000, dtype=torch.long)\n        n_total = torch.zeros(1000, dtype=torch.long)\n\n        # iterator\n        iterator = env.create_test_iterator(\n            data_type,\n            task,\n            data_path=self.trainer.data_path,\n            batch_size=params.batch_size_eval,\n            params=params,\n            size=params.eval_size,\n        )\n        eval_size = len(iterator.dataset)\n\n        # save beam results\n        beam_log = {}\n        hyps_to_eval = []\n\n        for (x1, len1), (x2, len2), nb_ops in iterator:\n\n            # update logs\n            for i in range(len(len1)):\n                beam_log[i + n_total.sum().item()] = {\n                    \"src\": x1[1 : len1[i] - 1, i].tolist(),\n                    \"tgt\": x2[1 : len2[i] - 1, i].tolist(),\n                    \"nb_ops\": nb_ops[i].item(),\n                    \"hyps\": [],\n                }\n\n            # target words to predict\n            alen = torch.arange(len2.max(), dtype=torch.long, device=len2.device)\n            pred_mask = (\n                alen[:, None] < len2[None] - 1\n            )  # do not predict anything given the last target word\n            y = x2[1:].masked_select(pred_mask[:-1])\n            assert len(y) == (len2 - 1).sum().item()\n\n            # optionally truncate input\n            x1_, len1_ = x1, len1\n\n            # cuda\n            x1_, len1_, x2, len2, y = to_cuda(x1_, len1_, x2, len2, y)\n            bs = len(len1)\n\n            # forward\n            encoded = encoder(\"fwd\", x=x1_, lengths=len1_, causal=False)\n            decoded = decoder(\n                \"fwd\",\n                x=x2,\n                lengths=len2,\n                causal=True,\n                src_enc=encoded.transpose(0, 1),\n                src_len=len1_,\n            )\n            word_scores, loss = decoder(\n                \"predict\", tensor=decoded, pred_mask=pred_mask, y=y, get_scores=True\n            )\n\n            # correct outputs per sequence / valid top-1 predictions\n            t = torch.zeros_like(pred_mask, device=y.device)\n            t[pred_mask] += word_scores.max(1)[1] == y\n            valid = (t.sum(0) == len2 - 1).cpu().long()\n\n            # update stats\n            xe_loss += loss.item() * len(y)\n            n_valid.index_add_(-1, nb_ops, valid)\n            n_total.index_add_(-1, nb_ops, torch.ones_like(nb_ops))\n\n            # update equations that were solved greedily\n            for i in range(len(len1)):\n                if valid[i]:\n                    beam_log[i + n_total.sum().item() - bs][\"hyps\"].append(\n                        (None, None, True)\n                    )\n\n            # continue if everything is correct. if eval_verbose, perform\n            # a full beam search, even on correct greedy generations\n            if valid.sum() == len(valid) and params.eval_verbose < 2:\n                continue\n\n            # invalid top-1 predictions - check if there is a solution in the beam\n            invalid_idx = (1 - valid).nonzero().view(-1)\n            logger.info(\n                f\"({n_total.sum().item()}/{eval_size}) Found \"\n                f\"{bs - len(invalid_idx)}/{bs} valid top-1 predictions. \"\n                \"Generating solutions ...\"\n            )\n\n            # generate with beam search\n            _, _, generations = decoder.generate_beam(\n                encoded.transpose(0, 1),\n                len1_,\n                beam_size=params.beam_size,\n                length_penalty=params.beam_length_penalty,\n                early_stopping=params.beam_early_stopping,\n                max_len=params.max_len,\n            )\n\n            # prepare inputs / hypotheses to check\n            # if eval_verbose < 2, no beam search on equations solved greedily\n            for i in range(len(generations)):\n                if valid[i] and params.eval_verbose < 2:\n                    continue\n                for j, (score, hyp) in enumerate(\n                    sorted(generations[i].hyp, key=lambda x: x[0], reverse=True)\n                ):\n                    hyps_to_eval.append(\n                        {\n                            \"i\": i + n_total.sum().item() - bs,\n                            \"j\": j,\n                            \"score\": score,\n                            \"src\": x1[1 : len1[i] - 1, i].tolist(),\n                            \"tgt\": x2[1 : len2[i] - 1, i].tolist(),\n                            \"hyp\": hyp[1:].tolist(),\n                            \"task\": task,\n                        }\n                    )\n\n        # if the Jacobian is also predicted, only look at the eigenvalue\n        if task == \"ode_convergence_speed\":\n            sep_id = env.word2id[env.mtrx_separator]\n            for x in hyps_to_eval:\n                x[\"tgt\"] = (\n                    x[\"tgt\"][x[\"tgt\"].index(sep_id) + 1 :]\n                    if sep_id in x[\"tgt\"]\n                    else x[\"tgt\"]\n                )\n                x[\"hyp\"] = (\n                    x[\"hyp\"][x[\"hyp\"].index(sep_id) + 1 :]\n                    if sep_id in x[\"hyp\"]\n                    else x[\"hyp\"]\n                )\n\n        # solutions that perfectly match the reference with greedy decoding\n        assert all(\n            len(v[\"hyps\"]) == 0\n            or len(v[\"hyps\"]) == 1\n            and v[\"hyps\"][0] == (None, None, True)\n            for v in beam_log.values()\n        )\n        init_valid = sum(\n            int(len(v[\"hyps\"]) == 1 and v[\"hyps\"][0][2] is True)\n            for v in beam_log.values()\n        )\n        logger.info(\n            f\"Found {init_valid} solutions with greedy decoding \"\n            \"(perfect reference match).\"\n        )\n\n        # check hypotheses with multiprocessing\n        eval_hyps = []\n        start = time.time()\n        logger.info(\n            f\"Checking {len(hyps_to_eval)} hypotheses for \"\n            f\"{len(set(h['i'] for h in hyps_to_eval))} equations ...\"\n        )\n        with ProcessPoolExecutor(max_workers=20) as executor:\n            for output in executor.map(check_hypothesis, hyps_to_eval, chunksize=1):\n                eval_hyps.append(output)\n        logger.info(f\"Evaluation done in {time.time() - start:.2f} seconds.\")\n\n        # update beam logs\n        for hyp in eval_hyps:\n            beam_log[hyp[\"i\"]][\"hyps\"].append(\n                (hyp[\"hyp\"], hyp[\"score\"], hyp[\"is_valid\"])\n            )\n\n        # print beam results\n        beam_valid = sum(\n            int(any(h[2] for h in v[\"hyps\"]) and v[\"hyps\"][0][1] is not None)\n            for v in beam_log.values()\n        )\n        all_valid = sum(int(any(h[2] for h in v[\"hyps\"])) for v in beam_log.values())\n        assert init_valid + beam_valid == all_valid\n        assert len(beam_log) == n_total.sum().item()\n        logger.info(\n            f\"Found {all_valid} valid solutions ({init_valid} with greedy decoding \"\n            f\"(perfect reference match), {beam_valid} with beam search).\"\n        )\n\n        # update valid equation statistics\n        n_valid = torch.zeros(1000, dtype=torch.long)\n        for i, v in beam_log.items():\n            if any(h[2] for h in v[\"hyps\"]):\n                n_valid[v[\"nb_ops\"]] += 1\n        assert n_valid.sum().item() == all_valid\n\n        # export evaluation details\n        if params.eval_verbose:\n\n            eval_path = os.path.join(\n                params.dump_path, f\"eval.beam.{data_type}.{task}.{scores['epoch']}\"\n            )\n\n            with open(eval_path, \"w\") as f:\n\n                # for each equation\n                for i, res in sorted(beam_log.items()):\n                    n_eq_valid = sum([int(v) for _, _, v in res[\"hyps\"]])\n                    src = idx_to_infix(env, res[\"src\"], input=True).replace(\"|\", \" | \")\n                    tgt = \" \".join(env.id2word[wid] for wid in res[\"tgt\"])\n                    s = (\n                        f\"Equation {i} ({n_eq_valid}/{len(res['hyps'])})\\n\"\n                        f\"src={src}\\ntgt={tgt}\\n\"\n                    )\n                    for hyp, score, valid in res[\"hyps\"]:\n                        if score is None:\n                            assert hyp is None\n                            s += f\"{int(valid)} GREEDY\\n\"\n                        else:\n                            try:\n                                hyp = \" \".join(hyp)\n                            except Exception:\n                                hyp = f\"INVALID OUTPUT {hyp}\"\n                            s += f\"{int(valid)} {score :.3e} {hyp}\\n\"\n                    if params.eval_verbose_print:\n                        logger.info(s)\n                    f.write(s + \"\\n\")\n                    f.flush()\n\n            logger.info(f\"Evaluation results written in {eval_path}\")\n\n        # log\n        _n_valid = n_valid.sum().item()\n        _n_total = n_total.sum().item()\n        logger.info(\n            f\"{_n_valid}/{_n_total} ({100. * _n_valid / _n_total}%) equations \"\n            \"were evaluated correctly.\"\n        )\n\n        # compute perplexity and prediction accuracy\n        assert _n_total == eval_size\n        scores[f'{data_type}_{task}_xe_loss'] = xe_loss / _n_total \n        scores[f\"{data_type}_{task}_beam_acc\"] = 100.0 * _n_valid / _n_total\n\n        # per class perplexity and prediction accuracy\n        for i in range(len(n_total)):\n            if n_total[i].item() == 0:\n                continue\n            logger.info(\n                f\"{i}: {n_valid[i].sum().item()} / {n_total[i].item()} \"\n                f\"({100. * n_valid[i].sum().item() / max(n_total[i].item(), 1)}%)\"\n            )\n            scores[f\"{data_type}_{task}_beam_acc_{i}\"] = (\n                100.0 * n_valid[i].sum().item() / max(n_total[i].item(), 1)\n            )\n\n\ndef convert_to_text(batch, lengths, id2word, params):\n    \"\"\"\n    Convert a batch of sequences to a list of text sequences.\n    \"\"\"\n    batch = batch.cpu().numpy()\n    lengths = lengths.cpu().numpy()\n\n    slen, bs = batch.shape\n    assert lengths.max() == slen and lengths.shape[0] == bs\n    assert (batch[0] == params.eos_index).sum() == bs\n    assert (batch == params.eos_index).sum() == 2 * bs\n    sequences = []\n\n    for j in range(bs):\n        words = []\n        for k in range(1, lengths[j]):\n            if batch[k, j] == params.eos_index:\n                break\n            words.append(id2word[batch[k, j]])\n        sequences.append(\" \".join(words))\n    return sequences\n"
  },
  {
    "path": "src/logger.py",
    "content": "# Copyright (c) 2020-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nimport logging\nimport time\nfrom datetime import timedelta\n\n\nclass LogFormatter:\n    def __init__(self):\n        self.start_time = time.time()\n\n    def format(self, record):\n        elapsed_seconds = round(record.created - self.start_time)\n\n        prefix = \"%s - %s - %s\" % (\n            record.levelname,\n            time.strftime(\"%x %X\"),\n            timedelta(seconds=elapsed_seconds),\n        )\n        message = record.getMessage()\n        message = message.replace(\"\\n\", \"\\n\" + \" \" * (len(prefix) + 3))\n        return \"%s - %s\" % (prefix, message) if message else \"\"\n\n\ndef create_logger(filepath, rank):\n    \"\"\"\n    Create a logger.\n    Use a different log file for each process.\n    \"\"\"\n    # create log formatter\n    log_formatter = LogFormatter()\n\n    # create file handler and set level to debug\n    if filepath is not None:\n        if rank > 0:\n            filepath = \"%s-%i\" % (filepath, rank)\n        file_handler = logging.FileHandler(filepath, \"a\")\n        file_handler.setLevel(logging.DEBUG)\n        file_handler.setFormatter(log_formatter)\n\n    # create console handler and set level to info\n    console_handler = logging.StreamHandler()\n    console_handler.setLevel(logging.INFO)\n    console_handler.setFormatter(log_formatter)\n\n    # create logger and set level to debug\n    logger = logging.getLogger()\n    logger.handlers = []\n    logger.setLevel(logging.DEBUG)\n    logger.propagate = False\n    if filepath is not None:\n        logger.addHandler(file_handler)\n    logger.addHandler(console_handler)\n\n    # reset logger elapsed time\n    def reset_time():\n        log_formatter.start_time = time.time()\n\n    logger.reset_time = reset_time\n\n    return logger\n"
  },
  {
    "path": "src/model/__init__.py",
    "content": "# Copyright (c) 2020-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nfrom logging import getLogger\nimport os\nimport torch\n\nfrom .transformer import TransformerModel\n\n\nlogger = getLogger()\n\n\ndef check_model_params(params):\n    \"\"\"\n    Check models parameters.\n    \"\"\"\n    # model dimensions\n    assert params.emb_dim % params.n_heads == 0\n\n    # reload a pretrained model\n    if params.reload_model != '':\n        assert os.path.isfile(params.reload_model)\n\n\ndef build_modules(env, params):\n    \"\"\"\n    Build modules.\n    \"\"\"\n    modules = {}\n    modules['encoder'] = TransformerModel(params, env.id2word, is_encoder=True, with_output=False)\n    modules['decoder'] = TransformerModel(params, env.id2word, is_encoder=False, with_output=True)\n\n    # reload pretrained modules\n    if params.reload_model != '':\n        logger.info(f\"Reloading modules from {params.reload_model} ...\")\n        reloaded = torch.load(params.reload_model)\n        for k, v in modules.items():\n            assert k in reloaded\n            if all([k2.startswith('module.') for k2 in reloaded[k].keys()]):\n                reloaded[k] = {k2[len('module.'):]: v2 for k2, v2 in reloaded[k].items()}\n            v.load_state_dict(reloaded[k])\n\n    # log\n    for k, v in modules.items():\n        logger.debug(f\"{v}: {v}\")\n    for k, v in modules.items():\n        logger.info(f\"Number of parameters ({k}): {sum([p.numel() for p in v.parameters() if p.requires_grad])}\")\n\n    # cuda\n    if not params.cpu:\n        for v in modules.values():\n            v.cuda()\n\n    return modules\n"
  },
  {
    "path": "src/model/transformer.py",
    "content": "# Copyright (c) 2020-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nfrom logging import getLogger\nimport math\nimport itertools\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nN_MAX_POSITIONS = 4096  # maximum input sequence length\n\n\nlogger = getLogger()\n\n\ndef Embedding(num_embeddings, embedding_dim, padding_idx=None):\n    m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)\n    nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)\n    if padding_idx is not None:\n        nn.init.constant_(m.weight[padding_idx], 0)\n    return m\n\n\ndef create_sinusoidal_embeddings(n_pos, dim, out):\n    position_enc = np.array([\n        [pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)]\n        for pos in range(n_pos)\n    ])\n    out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))\n    out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))\n    out.detach_()\n    out.requires_grad = False\n\n\ndef get_masks(slen, lengths, causal):\n    \"\"\"\n    Generate hidden states mask, and optionally an attention mask.\n    \"\"\"\n    assert lengths.max().item() <= slen\n    bs = lengths.size(0)\n    alen = torch.arange(slen, dtype=torch.long, device=lengths.device)\n    mask = alen < lengths[:, None]\n\n    # attention mask is the same as mask, or triangular inferior attention (causal)\n    if causal:\n        attn_mask = alen[None, None, :].repeat(bs, slen, 1) <= alen[None, :, None]\n    else:\n        attn_mask = mask\n\n    # sanity check\n    assert mask.size() == (bs, slen)\n    assert causal is False or attn_mask.size() == (bs, slen, slen)\n\n    return mask, attn_mask\n\n\nclass MultiHeadAttention(nn.Module):\n\n    NEW_ID = itertools.count()\n\n    def __init__(self, n_heads, dim, dropout):\n        super().__init__()\n        self.layer_id = next(MultiHeadAttention.NEW_ID)\n        self.dim = dim\n        self.n_heads = n_heads\n        self.dropout = dropout\n        assert self.dim % self.n_heads == 0\n\n        self.q_lin = nn.Linear(dim, dim)\n        self.k_lin = nn.Linear(dim, dim)\n        self.v_lin = nn.Linear(dim, dim)\n        self.out_lin = nn.Linear(dim, dim)\n\n    def forward(self, input, mask, kv=None, use_cache=False):\n        \"\"\"\n        Self-attention (if kv is None) or attention over source sentence (provided by kv).\n        Input is (bs, qlen, dim)\n        Mask is (bs, klen) (non-causal) or (bs, klen, klen)\n        \"\"\"\n        assert not (use_cache and self.cache is None)\n        bs, qlen, dim = input.size()\n        if kv is None:\n            klen = qlen if not use_cache else self.cache['slen'] + qlen\n        else:\n            klen = kv.size(1)\n        assert dim == self.dim, 'Dimensions do not match: %s input vs %s configured' % (dim, self.dim)\n        n_heads = self.n_heads\n        dim_per_head = dim // n_heads\n        mask_reshape = (bs, 1, qlen, klen) if mask.dim() == 3 else (bs, 1, 1, klen)\n\n        def shape(x):\n            \"\"\"  projection \"\"\"\n            return x.view(bs, -1, self.n_heads, dim_per_head).transpose(1, 2)\n\n        def unshape(x):\n            \"\"\"  compute context \"\"\"\n            return x.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * dim_per_head)\n\n        q = shape(self.q_lin(input))                                          # (bs, n_heads, qlen, dim_per_head)\n        if kv is None:\n            k = shape(self.k_lin(input))                                      # (bs, n_heads, qlen, dim_per_head)\n            v = shape(self.v_lin(input))                                      # (bs, n_heads, qlen, dim_per_head)\n        elif not use_cache or self.layer_id not in self.cache:\n            k = v = kv\n            k = shape(self.k_lin(k))                                          # (bs, n_heads, qlen, dim_per_head)\n            v = shape(self.v_lin(v))                                          # (bs, n_heads, qlen, dim_per_head)\n\n        if use_cache:\n            if self.layer_id in self.cache:\n                if kv is None:\n                    k_, v_ = self.cache[self.layer_id]\n                    k = torch.cat([k_, k], dim=2)                             # (bs, n_heads, klen, dim_per_head)\n                    v = torch.cat([v_, v], dim=2)                             # (bs, n_heads, klen, dim_per_head)\n                else:\n                    k, v = self.cache[self.layer_id]\n            self.cache[self.layer_id] = (k, v)\n\n        q = q / math.sqrt(dim_per_head)                                       # (bs, n_heads, qlen, dim_per_head)\n        scores = torch.matmul(q, k.transpose(2, 3))                           # (bs, n_heads, qlen, klen)\n        mask = (mask == 0).view(mask_reshape).expand_as(scores)               # (bs, n_heads, qlen, klen)\n        scores.masked_fill_(mask, -float('inf'))                              # (bs, n_heads, qlen, klen)\n\n        weights = F.softmax(scores.float(), dim=-1).type_as(scores)           # (bs, n_heads, qlen, klen)\n        weights = F.dropout(weights, p=self.dropout, training=self.training)  # (bs, n_heads, qlen, klen)\n        context = torch.matmul(weights, v)                                    # (bs, n_heads, qlen, dim_per_head)\n        context = unshape(context)                                            # (bs, qlen, dim)\n\n        if TransformerModel.STORE_OUTPUTS and not self.training:\n            self.outputs = weights.detach().cpu()\n\n        return self.out_lin(context)\n\n\nclass TransformerFFN(nn.Module):\n\n    def __init__(self, in_dim, dim_hidden, out_dim, dropout):\n        super().__init__()\n        self.dropout = dropout\n        self.lin1 = nn.Linear(in_dim, dim_hidden)\n        self.lin2 = nn.Linear(dim_hidden, out_dim)\n\n    def forward(self, input):\n        x = self.lin1(input)\n        x = F.relu(x)\n        x = self.lin2(x)\n        x = F.dropout(x, p=self.dropout, training=self.training)\n        return x\n\n\nclass TransformerModel(nn.Module):\n\n    STORE_OUTPUTS = False\n\n    def __init__(self, params, id2word, is_encoder, with_output):\n        \"\"\"\n        Transformer model (encoder or decoder).\n        \"\"\"\n        super().__init__()\n\n        # encoder / decoder, output layer\n        self.dtype = torch.half if params.fp16 else torch.float\n        self.is_encoder = is_encoder\n        self.is_decoder = not is_encoder\n        self.with_output = with_output\n\n        # dictionary\n        self.n_words = params.n_words\n        self.eos_index = params.eos_index\n        self.pad_index = params.pad_index\n        self.id2word = id2word\n        assert len(self.id2word) == self.n_words\n\n        # model parameters\n        self.dim = params.emb_dim       # 512 by default\n        self.hidden_dim = self.dim * 4  # 2048 by default\n        self.n_heads = params.n_heads   # 8 by default\n        self.n_layers = params.n_enc_layers if is_encoder else params.n_dec_layers\n        self.dropout = params.dropout\n        self.attention_dropout = params.attention_dropout\n        assert self.dim % self.n_heads == 0, 'transformer dim must be a multiple of n_heads'\n\n        # embeddings\n        self.position_embeddings = Embedding(N_MAX_POSITIONS, self.dim)\n        if params.sinusoidal_embeddings:\n            create_sinusoidal_embeddings(N_MAX_POSITIONS, self.dim, out=self.position_embeddings.weight)\n        self.embeddings = Embedding(self.n_words, self.dim, padding_idx=self.pad_index)\n        self.layer_norm_emb = nn.LayerNorm(self.dim, eps=1e-12)\n\n        # transformer layers\n        self.attentions = nn.ModuleList()\n        self.layer_norm1 = nn.ModuleList()\n        self.ffns = nn.ModuleList()\n        self.layer_norm2 = nn.ModuleList()\n        if self.is_decoder:\n            self.layer_norm15 = nn.ModuleList()\n            self.encoder_attn = nn.ModuleList()\n\n        for layer_id in range(self.n_layers):\n            self.attentions.append(MultiHeadAttention(self.n_heads, self.dim, dropout=self.attention_dropout))\n            self.layer_norm1.append(nn.LayerNorm(self.dim, eps=1e-12))\n            if self.is_decoder:\n                self.layer_norm15.append(nn.LayerNorm(self.dim, eps=1e-12))\n                self.encoder_attn.append(MultiHeadAttention(self.n_heads, self.dim, dropout=self.attention_dropout))\n            self.ffns.append(TransformerFFN(self.dim, self.hidden_dim, self.dim, dropout=self.dropout))\n            self.layer_norm2.append(nn.LayerNorm(self.dim, eps=1e-12))\n\n        self.cache = None\n\n        # output layer\n        if self.with_output:\n            self.proj = nn.Linear(self.dim, params.n_words, bias=True)\n            if params.share_inout_emb:\n                self.proj.weight = self.embeddings.weight\n\n    def forward(self, mode, **kwargs):\n        \"\"\"\n        Forward function with different forward modes.\n        ### Small hack to handle PyTorch distributed.\n        \"\"\"\n        if mode == 'fwd':\n            return self.fwd(**kwargs)\n        elif mode == 'predict':\n            return self.predict(**kwargs)\n        else:\n            raise Exception(\"Unknown mode: %s\" % mode)\n\n    def fwd(self, x, lengths, causal, src_enc=None, src_len=None, positions=None, use_cache=False):\n        \"\"\"\n        Inputs:\n            `x` LongTensor(slen, bs), containing word indices\n            `lengths` LongTensor(bs), containing the length of each sentence\n            `causal` Boolean, if True, the attention is only done over previous hidden states\n            `positions` LongTensor(slen, bs), containing word positions\n        \"\"\"\n        # lengths = (x != self.pad_index).float().sum(dim=1)\n        # mask = x != self.pad_index\n\n        # check inputs\n        slen, bs = x.size()\n        assert lengths.size(0) == bs\n        assert lengths.max().item() <= slen\n        x = x.transpose(0, 1)  # batch size as dimension 0\n        assert (src_enc is None) == (src_len is None)\n        if src_enc is not None:\n            assert self.is_decoder\n            assert src_enc.size(0) == bs\n        assert not (use_cache and self.cache is None)\n\n        # generate masks\n        mask, attn_mask = get_masks(slen, lengths, causal)\n        if self.is_decoder and src_enc is not None:\n            src_mask = torch.arange(src_len.max(), dtype=torch.long, device=lengths.device) < src_len[:, None]\n\n        # positions\n        if positions is None:\n            positions = x.new(slen).long()\n            positions = torch.arange(slen, out=positions).unsqueeze(0)\n        else:\n            assert positions.size() == (slen, bs)\n            positions = positions.transpose(0, 1)\n\n        # do not recompute cached elements\n        if use_cache:\n            _slen = slen - self.cache['slen']\n            x = x[:, -_slen:]\n            positions = positions[:, -_slen:]\n            mask = mask[:, -_slen:]\n            attn_mask = attn_mask[:, -_slen:]\n\n        # all layer outputs\n        if TransformerModel.STORE_OUTPUTS and not self.training:\n            self.outputs = []\n\n        # embeddings\n        tensor = self.embeddings(x)\n        tensor = tensor + self.position_embeddings(positions).expand_as(tensor)\n        tensor = self.layer_norm_emb(tensor)\n        tensor = F.dropout(tensor, p=self.dropout, training=self.training)\n        tensor *= mask.unsqueeze(-1).to(tensor.dtype)\n        if TransformerModel.STORE_OUTPUTS and not self.training:\n            self.outputs.append(tensor.detach().cpu())\n\n        # transformer layers\n        for i in range(self.n_layers):\n\n            # self attention\n            self.attentions[i].cache = self.cache\n            attn = self.attentions[i](tensor, attn_mask, use_cache=use_cache)\n            attn = F.dropout(attn, p=self.dropout, training=self.training)\n            tensor = tensor + attn\n            tensor = self.layer_norm1[i](tensor)\n\n            # encoder attention (for decoder only)\n            if self.is_decoder and src_enc is not None:\n                self.encoder_attn[i].cache = self.cache\n                attn = self.encoder_attn[i](tensor, src_mask, kv=src_enc, use_cache=use_cache)\n                attn = F.dropout(attn, p=self.dropout, training=self.training)\n                tensor = tensor + attn\n                tensor = self.layer_norm15[i](tensor)\n\n            # FFN\n            tensor = tensor + self.ffns[i](tensor)\n            tensor = self.layer_norm2[i](tensor)\n\n            tensor *= mask.unsqueeze(-1).to(tensor.dtype)\n            if TransformerModel.STORE_OUTPUTS and not self.training:\n                self.outputs.append(tensor.detach().cpu())\n\n        # update cache length\n        if use_cache:\n            self.cache['slen'] += tensor.size(1)\n\n        # move back sequence length to dimension 0\n        tensor = tensor.transpose(0, 1)\n\n        return tensor\n\n    def predict(self, tensor, pred_mask, y, get_scores):\n        \"\"\"\n        Given the last hidden state, compute word scores and/or the loss.\n            `pred_mask` is a ByteTensor of shape (slen, bs), filled with 1 when\n                we need to predict a word\n            `y` is a LongTensor of shape (pred_mask.sum(),)\n            `get_scores` is a boolean specifying whether we need to return scores\n        \"\"\"\n        x = tensor[pred_mask.unsqueeze(-1).expand_as(tensor)].view(-1, self.dim)\n        assert (y == self.pad_index).sum().item() == 0\n        scores = self.proj(x).view(-1, self.n_words)\n        loss = F.cross_entropy(scores.float(), y, reduction='mean')\n        return scores, loss\n\n    def generate(self, src_enc, src_len, max_len=200, sample_temperature=None):\n        \"\"\"\n        Decode a sentence given initial start.\n        `x`:\n            - LongTensor(bs, slen)\n                <EOS> W1 W2 W3 <EOS> <PAD>\n                <EOS> W1 W2 W3   W4  <EOS>\n        `lengths`:\n            - LongTensor(bs) [5, 6]\n        `positions`:\n            - False, for regular \"arange\" positions (LM)\n            - True, to reset positions from the new generation (MT)\n        \"\"\"\n\n        # input batch\n        bs = len(src_len)\n        assert src_enc.size(0) == bs\n\n        # generated sentences\n        generated = src_len.new(max_len, bs)  # upcoming output\n        generated.fill_(self.pad_index)       # fill upcoming ouput with <PAD>\n        generated[0].fill_(self.eos_index)    # we use <EOS> for <BOS> everywhere\n\n        # positions\n        positions = src_len.new(max_len).long()\n        positions = torch.arange(max_len, out=positions).unsqueeze(1).expand(max_len, bs)\n\n        # current position / max lengths / length of generated sentences / unfinished sentences\n        cur_len = 1\n        gen_len = src_len.clone().fill_(1)\n        unfinished_sents = src_len.clone().fill_(1)\n\n        # cache compute states\n        self.cache = {'slen': 0}\n\n        while cur_len < max_len:\n\n            # compute word scores\n            tensor = self.forward(\n                'fwd',\n                x=generated[:cur_len],\n                lengths=gen_len,\n                positions=positions[:cur_len],\n                causal=True,\n                src_enc=src_enc,\n                src_len=src_len,\n                use_cache=True\n            )\n            assert tensor.size() == (1, bs, self.dim)\n            tensor = tensor.data[-1, :, :].to(self.dtype)  # (bs, dim)\n            scores = self.proj(tensor)                     # (bs, n_words)\n\n            # select next words: sample or greedy\n            if sample_temperature is None:\n                next_words = torch.topk(scores, 1)[1].squeeze(1)\n            else:\n                next_words = torch.multinomial(F.softmax(scores.float() / sample_temperature, dim=1), 1).squeeze(1)\n            assert next_words.size() == (bs,)\n\n            # update generations / lengths / finished sentences / current length\n            generated[cur_len] = next_words * unfinished_sents + self.pad_index * (1 - unfinished_sents)\n            gen_len.add_(unfinished_sents)\n            unfinished_sents.mul_(next_words.ne(self.eos_index).long())\n            cur_len = cur_len + 1\n\n            # stop when there is a </s> in each sentence, or if we exceed the maximul length\n            if unfinished_sents.max() == 0:\n                break\n\n        # add <EOS> to unfinished sentences\n        if cur_len == max_len:\n            generated[-1].masked_fill_(unfinished_sents.byte(), self.eos_index)\n\n        # sanity check\n        assert (generated == self.eos_index).sum() == 2 * bs\n\n        return generated[:cur_len], gen_len\n\n    def generate_beam(self, src_enc, src_len, beam_size, length_penalty, early_stopping, max_len=200):\n        \"\"\"\n        Decode a sentence given initial start.\n        `x`:\n            - LongTensor(bs, slen)\n                <EOS> W1 W2 W3 <EOS> <PAD>\n                <EOS> W1 W2 W3   W4  <EOS>\n        `lengths`:\n            - LongTensor(bs) [5, 6]\n        `positions`:\n            - False, for regular \"arange\" positions (LM)\n            - True, to reset positions from the new generation (MT)\n        \"\"\"\n\n        # check inputs\n        assert src_enc.size(0) == src_len.size(0)\n        assert beam_size >= 1\n\n        # batch size / number of words\n        bs = len(src_len)\n        n_words = self.n_words\n\n        # expand to beam size the source latent representations / source lengths\n        src_enc = src_enc.unsqueeze(1).expand((bs, beam_size) + src_enc.shape[1:]).contiguous().view((bs * beam_size,) + src_enc.shape[1:])\n        src_len = src_len.unsqueeze(1).expand(bs, beam_size).contiguous().view(-1)\n\n        # generated sentences (batch with beam current hypotheses)\n        generated = src_len.new(max_len, bs * beam_size)  # upcoming output\n        generated.fill_(self.pad_index)                   # fill upcoming ouput with <PAD>\n        generated[0].fill_(self.eos_index)                # we use <EOS> for <BOS> everywhere\n\n        # generated hypotheses\n        generated_hyps = [BeamHypotheses(beam_size, max_len, length_penalty, early_stopping) for _ in range(bs)]\n\n        # positions\n        positions = src_len.new(max_len).long()\n        positions = torch.arange(max_len, out=positions).unsqueeze(1).expand_as(generated)\n\n        # scores for each sentence in the beam\n        beam_scores = src_enc.new(bs, beam_size).float().fill_(0)\n        beam_scores[:, 1:] = -1e9\n        beam_scores = beam_scores.view(-1)\n\n        # current position\n        cur_len = 1\n\n        # cache compute states\n        self.cache = {'slen': 0}\n\n        # done sentences\n        done = [False for _ in range(bs)]\n\n        while cur_len < max_len:\n\n            # compute word scores\n            tensor = self.forward(\n                'fwd',\n                x=generated[:cur_len],\n                lengths=src_len.new(bs * beam_size).fill_(cur_len),\n                positions=positions[:cur_len],\n                causal=True,\n                src_enc=src_enc,\n                src_len=src_len,\n                use_cache=True\n            )\n            assert tensor.size() == (1, bs * beam_size, self.dim)\n            tensor = tensor.data[-1, :, :].to(self.dtype)   # (bs * beam_size, dim)\n            scores = self.proj(tensor)                      # (bs * beam_size, n_words)\n            scores = F.log_softmax(scores.float(), dim=-1)  # (bs * beam_size, n_words)\n            assert scores.size() == (bs * beam_size, n_words)\n\n            # select next words with scores\n            _scores = scores + beam_scores[:, None].expand_as(scores)  # (bs * beam_size, n_words)\n            _scores = _scores.view(bs, beam_size * n_words)            # (bs, beam_size * n_words)\n\n            next_scores, next_words = torch.topk(_scores, 2 * beam_size, dim=1, largest=True, sorted=True)\n            assert next_scores.size() == next_words.size() == (bs, 2 * beam_size)\n\n            # next batch beam content\n            # list of (bs * beam_size) tuple(next hypothesis score, next word, current position in the batch)\n            next_batch_beam = []\n\n            # for each sentence\n            for sent_id in range(bs):\n\n                # if we are done with this sentence\n                done[sent_id] = done[sent_id] or generated_hyps[sent_id].is_done(next_scores[sent_id].max().item())\n                if done[sent_id]:\n                    next_batch_beam.extend([(0, self.pad_index, 0)] * beam_size)  # pad the batch\n                    continue\n\n                # next sentence beam content\n                next_sent_beam = []\n\n                # next words for this sentence\n                for idx, value in zip(next_words[sent_id], next_scores[sent_id]):\n\n                    # get beam and word IDs\n                    beam_id = idx // n_words\n                    word_id = idx % n_words\n\n                    # end of sentence, or next word\n                    if word_id == self.eos_index or cur_len + 1 == max_len:\n                        generated_hyps[sent_id].add(generated[:cur_len, sent_id * beam_size + beam_id].clone().cpu(), value.item())\n                    else:\n                        next_sent_beam.append((value, word_id, sent_id * beam_size + beam_id))\n\n                    # the beam for next step is full\n                    if len(next_sent_beam) == beam_size:\n                        break\n\n                # update next beam content\n                assert len(next_sent_beam) == 0 if cur_len + 1 == max_len else beam_size\n                if len(next_sent_beam) == 0:\n                    next_sent_beam = [(0, self.pad_index, 0)] * beam_size  # pad the batch\n                next_batch_beam.extend(next_sent_beam)\n                assert len(next_batch_beam) == beam_size * (sent_id + 1)\n\n            # sanity check / prepare next batch\n            assert len(next_batch_beam) == bs * beam_size\n            beam_scores = beam_scores.new([x[0] for x in next_batch_beam])\n            beam_words = generated.new([x[1] for x in next_batch_beam])\n            beam_idx = src_len.new([x[2] for x in next_batch_beam])\n\n            # re-order batch and internal states\n            generated = generated[:, beam_idx]\n            generated[cur_len] = beam_words\n            for k in self.cache.keys():\n                if k != 'slen':\n                    self.cache[k] = (self.cache[k][0][beam_idx], self.cache[k][1][beam_idx])\n\n            # update current length\n            cur_len = cur_len + 1\n\n            # stop when we are done with each sentence\n            if all(done):\n                break\n\n        # def get_coeffs(s):\n        #     roots = [int(s[i + 2]) for i, c in enumerate(s) if c == 'x']\n        #     poly = np.poly1d(roots, r=True)\n        #     coeffs = list(poly.coefficients.astype(np.int64))\n        #     return [c % 10 for c in coeffs], coeffs\n\n        # visualize hypotheses\n        # print([len(x) for x in generated_hyps], cur_len)\n        # globals().update( locals() );\n        # !import code; code.interact(local=vars())\n        # for ii in range(bs):\n        #     for ss, ww in sorted(generated_hyps[ii].hyp, key=lambda x: x[0], reverse=True):\n        #         hh = \" \".join(self.id2word[x] for x in ww.tolist())\n        #         print(f\"{ss:+.4f} {hh}\")\n        #         # cc = get_coeffs(hh[4:])\n        #         # print(f\"{ss:+.4f} {hh} || {cc[0]} || {cc[1]}\")\n        #     print(\"\")\n\n        # select the best hypotheses\n        tgt_len = src_len.new(bs)\n        best = []\n\n        for i, hypotheses in enumerate(generated_hyps):\n            best_hyp = max(hypotheses.hyp, key=lambda x: x[0])[1]\n            tgt_len[i] = len(best_hyp) + 1  # +1 for the <EOS> symbol\n            best.append(best_hyp)\n\n        # generate target batch\n        decoded = src_len.new(tgt_len.max().item(), bs).fill_(self.pad_index)\n        for i, hypo in enumerate(best):\n            decoded[:tgt_len[i] - 1, i] = hypo\n            decoded[tgt_len[i] - 1, i] = self.eos_index\n\n        # sanity check\n        assert (decoded == self.eos_index).sum() == 2 * bs\n\n        return decoded, tgt_len, generated_hyps\n\n\nclass BeamHypotheses(object):\n\n    def __init__(self, n_hyp, max_len, length_penalty, early_stopping):\n        \"\"\"\n        Initialize n-best list of hypotheses.\n        \"\"\"\n        self.max_len = max_len - 1  # ignoring <BOS>\n        self.length_penalty = length_penalty\n        self.early_stopping = early_stopping\n        self.n_hyp = n_hyp\n        self.hyp = []\n        self.worst_score = 1e9\n\n    def __len__(self):\n        \"\"\"\n        Number of hypotheses in the list.\n        \"\"\"\n        return len(self.hyp)\n\n    def add(self, hyp, sum_logprobs):\n        \"\"\"\n        Add a new hypothesis to the list.\n        \"\"\"\n        score = sum_logprobs / len(hyp) ** self.length_penalty\n        if len(self) < self.n_hyp or score > self.worst_score:\n            self.hyp.append((score, hyp))\n            if len(self) > self.n_hyp:\n                sorted_scores = sorted([(s, idx) for idx, (s, _) in enumerate(self.hyp)])\n                del self.hyp[sorted_scores[0][1]]\n                self.worst_score = sorted_scores[1][0]\n            else:\n                self.worst_score = min(score, self.worst_score)\n\n    def is_done(self, best_sum_logprobs):\n        \"\"\"\n        If there are enough hypotheses and that none of the hypotheses being generated\n        can become better than the worst one in the heap, then we are done with this sentence.\n        \"\"\"\n        if len(self) < self.n_hyp:\n            return False\n        elif self.early_stopping:\n            return True\n        else:\n            return self.worst_score >= best_sum_logprobs / self.max_len ** self.length_penalty\n"
  },
  {
    "path": "src/optim.py",
    "content": "# Copyright (c) 2020-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nimport re\nimport math\nimport inspect\n\nimport torch\nfrom torch import optim\n\n\nclass Adam(optim.Optimizer):\n    \"\"\"\n    Same as https://github.com/pytorch/pytorch/blob/master/torch/optim/adam.py,\n    without amsgrad, with step in a tensor, and states initialization in __init__.\n    It was important to add `.item()` in `state['step'].item()`.\n    \"\"\"\n\n    def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0):\n        if not 0.0 <= lr:\n            raise ValueError(\"Invalid learning rate: {}\".format(lr))\n        if not 0.0 <= eps:\n            raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n        if not 0.0 <= betas[0] < 1.0:\n            raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n        if not 0.0 <= betas[1] < 1.0:\n            raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n        defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)\n        super().__init__(params, defaults)\n\n        for group in self.param_groups:\n            for p in group[\"params\"]:\n                state = self.state[p]\n                state[\"step\"] = 0  # torch.zeros(1)\n                state[\"exp_avg\"] = torch.zeros_like(p.data)\n                state[\"exp_avg_sq\"] = torch.zeros_like(p.data)\n\n    def __setstate__(self, state):\n        super().__setstate__(state)\n\n    def step(self, closure=None):\n        \"\"\"\n        Step.\n        \"\"\"\n        loss = None\n        if closure is not None:\n            loss = closure()\n\n        for group in self.param_groups:\n            for p in group[\"params\"]:\n                if p.grad is None:\n                    continue\n                grad = p.grad.data\n                if grad.is_sparse:\n                    raise RuntimeError(\n                        \"Adam does not support sparse gradients, \"\n                        \"please consider SparseAdam instead\"\n                    )\n\n                state = self.state[p]\n\n                exp_avg, exp_avg_sq = state[\"exp_avg\"], state[\"exp_avg_sq\"]\n                beta1, beta2 = group[\"betas\"]\n\n                state[\"step\"] += 1\n\n                # if group['weight_decay'] != 0:\n                #     grad.add_(group['weight_decay'], p.data)\n\n                # Decay the first and second moment running average coefficient\n                exp_avg.mul_(beta1).add_(1 - beta1, grad)\n                exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n                denom = exp_avg_sq.sqrt().add_(group[\"eps\"])\n                # denom = exp_avg_sq.sqrt().clamp_(min=group['eps'])\n\n                bias_correction1 = 1 - beta1 ** state[\"step\"]  # .item()\n                bias_correction2 = 1 - beta2 ** state[\"step\"]  # .item()\n                step_size = group[\"lr\"] * math.sqrt(bias_correction2) / bias_correction1\n\n                if group[\"weight_decay\"] != 0:\n                    p.data.add_(-group[\"weight_decay\"] * group[\"lr\"], p.data)\n\n                p.data.addcdiv_(-step_size, exp_avg, denom)\n\n        return loss\n\n\nclass AdamInverseSqrtWithWarmup(Adam):\n    \"\"\"\n    Decay the LR based on the inverse square root of the update number.\n    We also support a warmup phase where we linearly increase the learning rate\n    from some initial learning rate (`warmup-init-lr`) until the configured\n    learning rate (`lr`). Thereafter we decay proportional to the number of\n    updates, with a decay factor set to align with the configured learning rate.\n    During warmup:\n        lrs = torch.linspace(warmup_init_lr, lr, warmup_updates)\n        lr = lrs[update_num]\n    After warmup:\n        lr = decay_factor / sqrt(update_num)\n    where\n        decay_factor = lr * sqrt(warmup_updates)\n    \"\"\"\n\n    def __init__(\n        self,\n        params,\n        lr=1e-3,\n        betas=(0.9, 0.999),\n        eps=1e-8,\n        weight_decay=0,\n        warmup_updates=4000,\n        warmup_init_lr=1e-7,\n        exp_factor=0.5,\n    ):\n        super().__init__(\n            params, lr=warmup_init_lr, betas=betas, eps=eps, weight_decay=weight_decay,\n        )\n\n        # linearly warmup for the first warmup_updates\n        self.warmup_updates = warmup_updates\n        self.warmup_init_lr = warmup_init_lr\n        warmup_end_lr = lr\n        self.lr_step = (warmup_end_lr - warmup_init_lr) / warmup_updates\n\n        # then, decay prop. to the inverse square root of the update number\n        self.exp_factor = exp_factor\n        self.decay_factor = warmup_end_lr * warmup_updates ** self.exp_factor\n\n        # total number of updates\n        for param_group in self.param_groups:\n            param_group[\"num_updates\"] = 0\n\n    def get_lr_for_step(self, num_updates):\n        if num_updates < self.warmup_updates:\n            return self.warmup_init_lr + num_updates * self.lr_step\n        else:\n            return self.decay_factor * (num_updates ** -self.exp_factor)\n\n    def step(self, closure=None):\n        super().step(closure)\n        for param_group in self.param_groups:\n            param_group[\"num_updates\"] += 1\n            param_group[\"lr\"] = self.get_lr_for_step(param_group[\"num_updates\"])\n\n\nclass AdamCosineWithWarmup(Adam):\n    \"\"\"\n    Assign LR based on a cyclical schedule that follows the cosine function.\n    See https://arxiv.org/pdf/1608.03983.pdf for details.\n    We also support a warmup phase where we linearly increase the learning rate\n    from some initial learning rate (``--warmup-init-lr``) until the configured\n    learning rate (``--lr``).\n    During warmup::\n      lrs = torch.linspace(args.warmup_init_lr, args.lr, args.warmup_updates)\n      lr = lrs[update_num]\n    After warmup::\n      lr = lr_min + 0.5*(lr_max - lr_min)*(1 + cos(t_curr / t_i))\n    where ``t_curr`` is current percentage of updates within the current period\n    range and ``t_i`` is the current period range, which is scaled by ``t_mul``\n    after every iteration.\n    \"\"\"\n\n    def __init__(\n        self,\n        params,\n        lr=1e-3,\n        betas=(0.9, 0.999),\n        eps=1e-8,\n        weight_decay=0,\n        warmup_updates=4000,\n        warmup_init_lr=1e-7,\n        min_lr=1e-9,\n        init_period=1000000,\n        period_mult=1,\n        lr_shrink=0.75,\n    ):\n        super().__init__(\n            params, lr=warmup_init_lr, betas=betas, eps=eps, weight_decay=weight_decay,\n        )\n\n        # linearly warmup for the first warmup_updates\n        self.warmup_updates = warmup_updates\n        self.warmup_init_lr = warmup_init_lr\n        warmup_end_lr = lr\n        self.lr_step = (warmup_end_lr - warmup_init_lr) / warmup_updates\n\n        # then, apply cosine scheduler\n        self.min_lr = min_lr\n        self.max_lr = lr\n        self.period = init_period\n        self.period_mult = period_mult\n        self.lr_shrink = lr_shrink\n\n        # total number of updates\n        for param_group in self.param_groups:\n            param_group[\"num_updates\"] = 0\n\n    def get_lr_for_step(self, num_updates):\n        if num_updates < self.warmup_updates:\n            return self.warmup_init_lr + num_updates * self.lr_step\n        else:\n            t = num_updates - self.warmup_updates\n            if self.period_mult == 1:\n                pid = math.floor(t / self.period)\n                t_i = self.period\n                t_curr = t - (self.period * pid)\n            else:\n                pid = math.floor(\n                    math.log(\n                        1 - t / self.period * (1 - self.period_mult), self.period_mult\n                    )\n                )\n                t_i = self.period * (self.period_mult ** pid)\n                t_curr = (\n                    t\n                    - (1 - self.period_mult ** pid)\n                    / (1 - self.period_mult)\n                    * self.period\n                )\n            lr_shrink = self.lr_shrink ** pid\n            min_lr = self.min_lr * lr_shrink\n            max_lr = self.max_lr * lr_shrink\n            return min_lr + 0.5 * (max_lr - min_lr) * (\n                1 + math.cos(math.pi * t_curr / t_i)\n            )\n\n    def step(self, closure=None):\n        super().step(closure)\n        for param_group in self.param_groups:\n            param_group[\"num_updates\"] += 1\n            param_group[\"lr\"] = self.get_lr_for_step(param_group[\"num_updates\"])\n\n\ndef get_optimizer(parameters, s):\n    \"\"\"\n    Parse optimizer parameters.\n    Input should be of the form:\n        - \"sgd,lr=0.01\"\n        - \"adagrad,lr=0.1,lr_decay=0.05\"\n    \"\"\"\n    if \",\" in s:\n        method = s[: s.find(\",\")]\n        optim_params = {}\n        for x in s[s.find(\",\") + 1 :].split(\",\"):\n            split = x.split(\"=\")\n            assert len(split) == 2\n            assert re.match(r\"^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)$\", split[1]) is not None\n            optim_params[split[0]] = float(split[1])\n    else:\n        method = s\n        optim_params = {}\n\n    if method == \"adadelta\":\n        optim_fn = optim.Adadelta\n    elif method == \"adagrad\":\n        optim_fn = optim.Adagrad\n    elif method == \"adam\":\n        optim_fn = Adam\n        optim_params[\"betas\"] = (\n            optim_params.get(\"beta1\", 0.9),\n            optim_params.get(\"beta2\", 0.999),\n        )\n        optim_params.pop(\"beta1\", None)\n        optim_params.pop(\"beta2\", None)\n    elif method == \"adam_inverse_sqrt\":\n        optim_fn = AdamInverseSqrtWithWarmup\n        optim_params[\"betas\"] = (\n            optim_params.get(\"beta1\", 0.9),\n            optim_params.get(\"beta2\", 0.999),\n        )\n        optim_params.pop(\"beta1\", None)\n        optim_params.pop(\"beta2\", None)\n    elif method == \"adam_cosine\":\n        optim_fn = AdamCosineWithWarmup\n        optim_params[\"betas\"] = (\n            optim_params.get(\"beta1\", 0.9),\n            optim_params.get(\"beta2\", 0.999),\n        )\n        optim_params.pop(\"beta1\", None)\n        optim_params.pop(\"beta2\", None)\n    elif method == \"adamax\":\n        optim_fn = optim.Adamax\n    elif method == \"asgd\":\n        optim_fn = optim.ASGD\n    elif method == \"rmsprop\":\n        optim_fn = optim.RMSprop\n    elif method == \"rprop\":\n        optim_fn = optim.Rprop\n    elif method == \"sgd\":\n        optim_fn = optim.SGD\n        assert \"lr\" in optim_params\n    else:\n        raise Exception('Unknown optimization method: \"%s\"' % method)\n\n    # check that we give good parameters to the optimizer\n    expected_args = inspect.getargspec(optim_fn.__init__)[0]\n    assert expected_args[:2] == [\"self\", \"params\"]\n    if not all(k in expected_args[2:] for k in optim_params.keys()):\n        raise Exception(\n            'Unexpected parameters: expected \"%s\", got \"%s\"'\n            % (str(expected_args[2:]), str(optim_params.keys()))\n        )\n\n    return optim_fn(parameters, **optim_params)\n"
  },
  {
    "path": "src/slurm.py",
    "content": "# Copyright (c) 2020-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nfrom logging import getLogger\nimport os\nimport sys\nimport torch\nimport socket\nimport signal\nimport subprocess\n\n\nlogger = getLogger()\n\n\ndef sig_handler(signum, frame):\n    logger.warning(\"Signal handler called with signal \" + str(signum))\n    prod_id = int(os.environ[\"SLURM_PROCID\"])\n    logger.warning(\"Host: %s - Global rank: %i\" % (socket.gethostname(), prod_id))\n    if prod_id == 0:\n        logger.warning(\"Requeuing job \" + os.environ[\"SLURM_JOB_ID\"])\n        os.system(\"scontrol requeue \" + os.environ[\"SLURM_JOB_ID\"])\n    else:\n        logger.warning(\"Not the master process, no need to requeue.\")\n    sys.exit(-1)\n\n\ndef term_handler(signum, frame):\n    logger.warning(\"Signal handler called with signal \" + str(signum))\n    logger.warning(\"Bypassing SIGTERM.\")\n\n\ndef init_signal_handler():\n    \"\"\"\n    Handle signals sent by SLURM for time limit / pre-emption.\n    \"\"\"\n    signal.signal(signal.SIGUSR1, sig_handler)\n    signal.signal(signal.SIGTERM, term_handler)\n    logger.warning(\"Signal handler installed.\")\n\n\ndef init_distributed_mode(params):\n    \"\"\"\n    Handle single and multi-GPU / multi-node / SLURM jobs.\n    Initialize the following variables:\n        - n_nodes\n        - node_id\n        - local_rank\n        - global_rank\n        - world_size\n    \"\"\"\n    params.is_slurm_job = \"SLURM_JOB_ID\" in os.environ and not params.debug_slurm\n    print(\"SLURM job: %s\" % str(params.is_slurm_job))\n\n    # SLURM job\n    if params.is_slurm_job:\n\n        assert params.local_rank == -1  # on the cluster, this is handled by SLURM\n\n        SLURM_VARIABLES = [\n            \"SLURM_JOB_ID\",\n            \"SLURM_JOB_NODELIST\",\n            \"SLURM_JOB_NUM_NODES\",\n            \"SLURM_NTASKS\",\n            \"SLURM_TASKS_PER_NODE\",\n            \"SLURM_MEM_PER_NODE\",\n            \"SLURM_MEM_PER_CPU\",\n            \"SLURM_NODEID\",\n            \"SLURM_PROCID\",\n            \"SLURM_LOCALID\",\n            \"SLURM_TASK_PID\",\n        ]\n\n        PREFIX = \"%i - \" % int(os.environ[\"SLURM_PROCID\"])\n        for name in SLURM_VARIABLES:\n            value = os.environ.get(name, None)\n            print(PREFIX + \"%s: %s\" % (name, str(value)))\n\n        # # job ID\n        # params.job_id = os.environ['SLURM_JOB_ID']\n\n        # number of nodes / node ID\n        params.n_nodes = int(os.environ[\"SLURM_JOB_NUM_NODES\"])\n        params.node_id = int(os.environ[\"SLURM_NODEID\"])\n\n        # local rank on the current node / global rank\n        params.local_rank = int(os.environ[\"SLURM_LOCALID\"])\n        params.global_rank = int(os.environ[\"SLURM_PROCID\"])\n\n        # number of processes / GPUs per node\n        params.world_size = int(os.environ[\"SLURM_NTASKS\"])\n        params.n_gpu_per_node = params.world_size // params.n_nodes\n\n        # define master address and master port\n        hostnames = subprocess.check_output(\n            [\"scontrol\", \"show\", \"hostnames\", os.environ[\"SLURM_JOB_NODELIST\"]]\n        )\n        params.master_addr = hostnames.split()[0].decode(\"utf-8\")\n        assert 10001 <= params.master_port <= 20000 or params.world_size == 1\n        print(PREFIX + \"Master address: %s\" % params.master_addr)\n        print(PREFIX + \"Master port   : %i\" % params.master_port)\n\n        # set environment variables for 'env://'\n        os.environ[\"MASTER_ADDR\"] = params.master_addr\n        os.environ[\"MASTER_PORT\"] = str(params.master_port)\n        os.environ[\"WORLD_SIZE\"] = str(params.world_size)\n        os.environ[\"RANK\"] = str(params.global_rank)\n\n    # multi-GPU job (local or multi-node) - jobs started with torch.distributed.launch\n    elif params.local_rank != -1:\n\n        assert params.master_port == -1\n\n        # read environment variables\n        params.global_rank = int(os.environ[\"RANK\"])\n        params.world_size = int(os.environ[\"WORLD_SIZE\"])\n        params.n_gpu_per_node = int(os.environ[\"NGPU\"])\n\n        # number of nodes / node ID\n        params.n_nodes = params.world_size // params.n_gpu_per_node\n        params.node_id = params.global_rank // params.n_gpu_per_node\n\n    # local job (single GPU)\n    else:\n        assert params.local_rank == -1\n        assert params.master_port == -1\n        params.n_nodes = 1\n        params.node_id = 0\n        params.local_rank = 0\n        params.global_rank = 0\n        params.world_size = 1\n        params.n_gpu_per_node = 1\n\n    # sanity checks\n    assert params.n_nodes >= 1\n    assert 0 <= params.node_id < params.n_nodes\n    assert 0 <= params.local_rank <= params.global_rank < params.world_size\n    assert params.world_size == params.n_nodes * params.n_gpu_per_node\n\n    # define whether this is the master process / if we are in distributed mode\n    params.is_master = params.node_id == 0 and params.local_rank == 0\n    params.multi_node = params.n_nodes > 1\n    params.multi_gpu = params.world_size > 1\n\n    # summary\n    PREFIX = \"%i - \" % params.global_rank\n    print(PREFIX + \"Number of nodes: %i\" % params.n_nodes)\n    print(PREFIX + \"Node ID        : %i\" % params.node_id)\n    print(PREFIX + \"Local rank     : %i\" % params.local_rank)\n    print(PREFIX + \"Global rank    : %i\" % params.global_rank)\n    print(PREFIX + \"World size     : %i\" % params.world_size)\n    print(PREFIX + \"GPUs per node  : %i\" % params.n_gpu_per_node)\n    print(PREFIX + \"Master         : %s\" % str(params.is_master))\n    print(PREFIX + \"Multi-node     : %s\" % str(params.multi_node))\n    print(PREFIX + \"Multi-GPU      : %s\" % str(params.multi_gpu))\n    print(PREFIX + \"Hostname       : %s\" % socket.gethostname())\n\n    # set GPU device\n    if not params.cpu:\n        torch.cuda.set_device(params.local_rank)\n\n    # initialize multi-GPU\n    if params.multi_gpu:\n\n        # http://pytorch.apachecn.org/en/0.3.0/distributed.html#environment-variable-initialization\n        # 'env://' will read these environment variables:\n        # MASTER_PORT - required; has to be a free port on machine with rank 0\n        # MASTER_ADDR - required (except for rank 0); address of rank 0 node\n        # WORLD_SIZE - required; can be set either here, or in a call to init function\n        # RANK - required; can be set either here, or in a call to init function\n\n        print(\"Initializing PyTorch distributed ...\")\n        torch.distributed.init_process_group(\n            init_method=\"env://\", backend=\"nccl\",\n        )\n"
  },
  {
    "path": "src/trainer.py",
    "content": "# Copyright (c) 2020-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nimport os\nimport io\nimport sys\nimport time\nfrom logging import getLogger\nfrom collections import OrderedDict\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn.utils import clip_grad_norm_\n\nfrom .optim import get_optimizer\nfrom .utils import to_cuda\n\nif torch.cuda.is_available():\n    import apex\n\n\nlogger = getLogger()\n\n\nclass Trainer(object):\n\n    EQUATIONS = {}\n\n    def __init__(self, modules, env, params):\n        \"\"\"\n        Initialize trainer.\n        \"\"\"\n        # modules / params\n        self.modules = modules\n        self.params = params\n        self.env = env\n\n        # epoch / iteration size\n        self.epoch_size = params.epoch_size\n        if self.epoch_size == -1:\n            self.epoch_size = self.data\n            assert self.epoch_size > 0\n\n        # data iterators\n        self.iterators = {}\n\n        # set parameters\n        self.set_parameters()\n\n        # float16 / distributed (no AMP)\n        assert params.amp >= 1 or not params.fp16\n        assert params.amp >= 0 or params.accumulate_gradients == 1\n        if params.multi_gpu and params.amp == -1:\n            logger.info(\"Using nn.parallel.DistributedDataParallel ...\")\n            for k in self.modules.keys():\n                self.modules[k] = nn.parallel.DistributedDataParallel(\n                    self.modules[k],\n                    device_ids=[params.local_rank],\n                    output_device=params.local_rank,\n                    broadcast_buffers=True,\n                )\n\n        # set optimizers\n        self.set_optimizers()\n\n        # float16 / distributed (AMP)\n        if params.amp >= 0:\n            self.init_amp()\n            if params.multi_gpu:\n                logger.info(\"Using apex.parallel.DistributedDataParallel ...\")\n                for k in self.modules.keys():\n                    self.modules[k] = apex.parallel.DistributedDataParallel(\n                        self.modules[k], delay_allreduce=True\n                    )\n\n        # stopping criterion used for early stopping\n        if params.stopping_criterion != \"\":\n            split = params.stopping_criterion.split(\",\")\n            assert len(split) == 2 and split[1].isdigit()\n            self.decrease_counts_max = int(split[1])\n            self.decrease_counts = 0\n            if split[0][0] == \"_\":\n                self.stopping_criterion = (split[0][1:], False)\n            else:\n                self.stopping_criterion = (split[0], True)\n            self.best_stopping_criterion = -1e12 if self.stopping_criterion[1] else 1e12\n        else:\n            self.stopping_criterion = None\n            self.best_stopping_criterion = None\n\n        # validation metrics\n        self.metrics = []\n        metrics = [m for m in params.validation_metrics.split(\",\") if m != \"\"]\n        for m in metrics:\n            m = (m[1:], False) if m[0] == \"_\" else (m, True)\n            self.metrics.append(m)\n        self.best_metrics = {\n            metric: (-1e12 if biggest else 1e12) for (metric, biggest) in self.metrics\n        }\n\n        # training statistics\n        self.epoch = 0\n        self.n_iter = 0\n        self.n_total_iter = 0\n        self.stats = OrderedDict(\n            [(\"processed_e\", 0)]\n            + [(\"processed_w\", 0)]\n            + sum(\n                [[(x, []), (f\"{x}-AVG-STOP-PROBS\", [])] for x in env.TRAINING_TASKS], []\n            )\n        )\n        self.last_time = time.time()\n\n        # reload potential checkpoints\n        self.reload_checkpoint()\n\n        # file handler to export data\n        if params.export_data:\n            assert params.reload_data == \"\"\n            params.export_path_prefix = os.path.join(params.dump_path, \"data.prefix\")\n            self.file_handler_prefix = io.open(\n                params.export_path_prefix, mode=\"a\", encoding=\"utf-8\"\n            )\n            logger.info(\n                f\"Data will be stored in prefix in: {params.export_path_prefix} ...\"\n            )\n\n        # reload exported data\n        if params.reload_data != \"\":\n            assert params.num_workers in [0, 1]\n            assert params.export_data is False\n            s = [x.split(\",\") for x in params.reload_data.split(\";\") if len(x) > 0]\n            assert (\n                len(s) >= 1\n                and all(len(x) == 4 for x in s)\n                and len(s) == len(set([x[0] for x in s]))\n            )\n            self.data_path = {\n                task: (train_path, valid_path, test_path)\n                for task, train_path, valid_path, test_path in s\n            }\n            assert all(\n                all(os.path.isfile(path) for path in paths)\n                for paths in self.data_path.values()\n            )\n            for task in self.env.TRAINING_TASKS:\n                assert (task in self.data_path) == (task in params.tasks)\n        else:\n            self.data_path = None\n\n        # create data loaders\n        if not params.eval_only:\n            if params.env_base_seed < 0:\n                params.env_base_seed = np.random.randint(1_000_000_000)\n            self.dataloader = {\n                task: iter(self.env.create_train_iterator(task, self.data_path, params))\n                for task in params.tasks\n            }\n\n    def set_parameters(self):\n        \"\"\"\n        Set parameters.\n        \"\"\"\n        self.parameters = {}\n        named_params = []\n        for v in self.modules.values():\n            named_params.extend(\n                [(k, p) for k, p in v.named_parameters() if p.requires_grad]\n            )\n        self.parameters[\"model\"] = [p for k, p in named_params]\n        for k, v in self.parameters.items():\n            logger.info(\"Found %i parameters in %s.\" % (len(v), k))\n            assert len(v) >= 1\n\n    def set_optimizers(self):\n        \"\"\"\n        Set optimizers.\n        \"\"\"\n        params = self.params\n        self.optimizers = {}\n        self.optimizers[\"model\"] = get_optimizer(\n            self.parameters[\"model\"], params.optimizer\n        )\n        logger.info(\"Optimizers: %s\" % \", \".join(self.optimizers.keys()))\n\n    def init_amp(self):\n        \"\"\"\n        Initialize AMP optimizer.\n        \"\"\"\n        params = self.params\n        assert (\n            params.amp == 0\n            and params.fp16 is False\n            or params.amp in [1, 2, 3]\n            and params.fp16 is True\n        )\n        mod_names = sorted(self.modules.keys())\n        opt_names = sorted(self.optimizers.keys())\n        modules, optimizers = apex.amp.initialize(\n            [self.modules[k] for k in mod_names],\n            [self.optimizers[k] for k in opt_names],\n            opt_level=(\"O%i\" % params.amp),\n        )\n        self.modules = {k: module for k, module in zip(mod_names, modules)}\n        self.optimizers = {k: optimizer for k, optimizer in zip(opt_names, optimizers)}\n\n    def optimize(self, loss):\n        \"\"\"\n        Optimize.\n        \"\"\"\n        # check NaN\n        if (loss != loss).data.any():\n            logger.warning(\"NaN detected\")\n            # exit()\n\n        params = self.params\n\n        # optimizers\n        names = self.optimizers.keys()\n        optimizers = [self.optimizers[k] for k in names]\n\n        # regular optimization\n        if params.amp == -1:\n            for optimizer in optimizers:\n                optimizer.zero_grad()\n            loss.backward()\n            if params.clip_grad_norm > 0:\n                for name in names:\n                    clip_grad_norm_(self.parameters[name], params.clip_grad_norm)\n            for optimizer in optimizers:\n                optimizer.step()\n\n        # AMP optimization\n        else:\n            if self.n_iter % params.accumulate_gradients == 0:\n                with apex.amp.scale_loss(loss, optimizers) as scaled_loss:\n                    scaled_loss.backward()\n                if params.clip_grad_norm > 0:\n                    for name in names:\n                        clip_grad_norm_(\n                            apex.amp.master_params(self.optimizers[name]),\n                            params.clip_grad_norm,\n                        )\n                for optimizer in optimizers:\n                    optimizer.step()\n                    optimizer.zero_grad()\n            else:\n                with apex.amp.scale_loss(\n                    loss, optimizers, delay_unscale=True\n                ) as scaled_loss:\n                    scaled_loss.backward()\n\n    def iter(self):\n        \"\"\"\n        End of iteration.\n        \"\"\"\n        self.n_iter += 1\n        self.n_total_iter += 1\n        self.print_stats()\n\n    def print_stats(self):\n        \"\"\"\n        Print statistics about the training.\n        \"\"\"\n        if self.n_total_iter % 20 != 0:\n            return\n\n        s_iter = \"%7i - \" % self.n_total_iter\n        s_stat = \" || \".join(\n            [\n                \"{}: {:7.4f}\".format(k.upper().replace(\"_\", \"-\"), np.mean(v))\n                for k, v in self.stats.items()\n                if type(v) is list and len(v) > 0\n            ]\n        )\n        for k in self.stats.keys():\n            if type(self.stats[k]) is list:\n                del self.stats[k][:]\n\n        # learning rates\n        s_lr = \"\"\n        for k, v in self.optimizers.items():\n            s_lr = (\n                s_lr\n                + (\" - %s LR: \" % k)\n                + \" / \".join(\"{:.4e}\".format(group[\"lr\"]) for group in v.param_groups)\n            )\n\n        # processing speed\n        new_time = time.time()\n        diff = new_time - self.last_time\n        s_speed = \"{:7.2f} equations/s - {:8.2f} words/s - \".format(\n            self.stats[\"processed_e\"] * 1.0 / diff,\n            self.stats[\"processed_w\"] * 1.0 / diff,\n        )\n        self.stats[\"processed_e\"] = 0\n        self.stats[\"processed_w\"] = 0\n        self.last_time = new_time\n\n        # log speed + stats + learning rate\n        logger.info(s_iter + s_speed + s_stat + s_lr)\n\n    def save_checkpoint(self, name, include_optimizers=True):\n        \"\"\"\n        Save the model / checkpoints.\n        \"\"\"\n        if not self.params.is_master:\n            return\n\n        path = os.path.join(self.params.dump_path, \"%s.pth\" % name)\n        logger.info(\"Saving %s to %s ...\" % (name, path))\n\n        data = {\n            \"epoch\": self.epoch,\n            \"n_total_iter\": self.n_total_iter,\n            \"best_metrics\": self.best_metrics,\n            \"best_stopping_criterion\": self.best_stopping_criterion,\n            \"params\": {k: v for k, v in self.params.__dict__.items()},\n        }\n\n        for k, v in self.modules.items():\n            logger.warning(f\"Saving {k} parameters ...\")\n            data[k] = v.state_dict()\n\n        if include_optimizers:\n            for name in self.optimizers.keys():\n                logger.warning(f\"Saving {name} optimizer ...\")\n                data[f\"{name}_optimizer\"] = self.optimizers[name].state_dict()\n\n        torch.save(data, path)\n\n    def reload_checkpoint(self):\n        \"\"\"\n        Reload a checkpoint if we find one.\n        \"\"\"\n        checkpoint_path = os.path.join(self.params.dump_path, \"checkpoint.pth\")\n        if not os.path.isfile(checkpoint_path):\n            if self.params.reload_checkpoint == \"\":\n                return\n            else:\n                checkpoint_path = self.params.reload_checkpoint\n                assert os.path.isfile(checkpoint_path)\n        print(checkpoint_path)\n        logger.warning(f\"Reloading checkpoint from {checkpoint_path} ...\")\n        data = torch.load(checkpoint_path, map_location=\"cpu\")\n\n        # reload model parameters\n        for k, v in self.modules.items():\n            v.load_state_dict(data[k])\n\n        # reload optimizers\n        for name in self.optimizers.keys():\n            # AMP checkpoint reloading is buggy, we cannot reload optimizers\n            # instead, we only reload current iterations / learning rates\n            if self.params.amp == -1:\n                logger.warning(f\"Reloading checkpoint optimizer {name} ...\")\n                self.optimizers[name].load_state_dict(data[f\"{name}_optimizer\"])\n            else:\n                logger.warning(f\"Not reloading checkpoint optimizer {name}.\")\n                for group_id, param_group in enumerate(\n                    self.optimizers[name].param_groups\n                ):\n                    if \"num_updates\" not in param_group:\n                        logger.warning(f\"No 'num_updates' for optimizer {name}.\")\n                        continue\n                    logger.warning(\n                        f\"Reloading 'num_updates' and 'lr' for optimizer {name}.\"\n                    )\n                    param_group[\"num_updates\"] = data[f\"{name}_optimizer\"][\n                        \"param_groups\"\n                    ][group_id][\"num_updates\"]\n                    param_group[\"lr\"] = self.optimizers[name].get_lr_for_step(\n                        param_group[\"num_updates\"]\n                    )\n\n        # reload main metrics\n        self.epoch = data[\"epoch\"] + 1\n        self.n_total_iter = data[\"n_total_iter\"]\n        self.best_metrics = data[\"best_metrics\"]\n        self.best_stopping_criterion = data[\"best_stopping_criterion\"]\n        logger.warning(\n            \"Checkpoint reloaded. \"\n            f\"Resuming at epoch {self.epoch} / iteration {self.n_total_iter} ...\"\n        )\n\n    def save_periodic(self):\n        \"\"\"\n        Save the models periodically.\n        \"\"\"\n        if not self.params.is_master:\n            return\n        if (\n            self.params.save_periodic > 0\n            and self.epoch % self.params.save_periodic == 0\n        ):\n            self.save_checkpoint(\"periodic-%i\" % self.epoch)\n\n    def save_best_model(self, scores):\n        \"\"\"\n        Save best models according to given validation metrics.\n        \"\"\"\n        if not self.params.is_master:\n            return\n        for metric, biggest in self.metrics:\n            if metric not in scores:\n                logger.warning('Metric \"%s\" not found in scores!' % metric)\n                continue\n            factor = 1 if biggest else -1\n            if factor * scores[metric] > factor * self.best_metrics[metric]:\n                self.best_metrics[metric] = scores[metric]\n                logger.info(\"New best score for %s: %.6f\" % (metric, scores[metric]))\n                self.save_checkpoint(\"best-%s\" % metric)\n\n    def end_epoch(self, scores):\n        \"\"\"\n        End the epoch.\n        \"\"\"\n        # stop if the stopping criterion has not improved\n        # after a certain number of epochs\n        if self.stopping_criterion is not None and (\n            self.params.is_master or not self.stopping_criterion[0].endswith(\"_mt_bleu\")\n        ):\n            metric, biggest = self.stopping_criterion\n            assert metric in scores, metric\n            factor = 1 if biggest else -1\n            if factor * scores[metric] > factor * self.best_stopping_criterion:\n                self.best_stopping_criterion = scores[metric]\n                logger.info(\n                    \"New best validation score: %f\" % self.best_stopping_criterion\n                )\n                self.decrease_counts = 0\n            else:\n                logger.info(\n                    \"Not a better validation score (%i / %i).\"\n                    % (self.decrease_counts, self.decrease_counts_max)\n                )\n                self.decrease_counts += 1\n            if self.decrease_counts > self.decrease_counts_max:\n                logger.info(\n                    \"Stopping criterion has been below its best value for more \"\n                    \"than %i epochs. Ending the experiment...\"\n                    % self.decrease_counts_max\n                )\n                if self.params.multi_gpu and \"SLURM_JOB_ID\" in os.environ:\n                    os.system(\"scancel \" + os.environ[\"SLURM_JOB_ID\"])\n                exit()\n        self.save_checkpoint(\"checkpoint\")\n        self.epoch += 1\n\n    def get_batch(self, task):\n        \"\"\"\n        Return a training batch for a specific task.\n        \"\"\"\n        try:\n            batch = next(self.dataloader[task])\n        except Exception as e:\n            logger.error(\n                \"An unknown exception of type {0} occurred in line {1} \"\n                \"when fetching batch. \"\n                \"Arguments:{2!r}. Restarting ...\".format(\n                    type(e).__name__, sys.exc_info()[-1].tb_lineno, e.args\n                )\n            )\n            if self.params.is_slurm_job:\n                if int(os.environ[\"SLURM_PROCID\"]) == 0:\n                    logger.warning(\"Requeuing job \" + os.environ[\"SLURM_JOB_ID\"])\n                    os.system(\"scontrol requeue \" + os.environ[\"SLURM_JOB_ID\"])\n                else:\n                    logger.warning(\"Not the master process, no need to requeue.\")\n            raise\n\n        return batch\n\n    def export_data(self, task):\n        \"\"\"\n        Export data to the disk.\n        \"\"\"\n        env = self.env\n        (x1, len1), (x2, len2), _ = self.get_batch(task)\n        for i in range(len(len1)):\n            # prefix\n            prefix1 = [env.id2word[wid] for wid in x1[1 : len1[i] - 1, i].tolist()]\n            prefix2 = [env.id2word[wid] for wid in x2[1 : len2[i] - 1, i].tolist()]\n            # save\n            prefix1_str = \" \".join(prefix1)\n            prefix2_str = \" \".join(prefix2)\n            self.file_handler_prefix.write(f\"{prefix1_str}\\t{prefix2_str}\\n\")\n            self.file_handler_prefix.flush()\n            self.EQUATIONS[(prefix1_str, prefix2_str)] = (\n                self.EQUATIONS.get((prefix1_str, prefix2_str), 0) + 1\n            )\n\n        # number of processed sequences / words\n        self.n_equations += self.params.batch_size\n        self.stats[\"processed_e\"] += len1.size(0)\n        self.stats[\"processed_w\"] += (len1 + len2 - 2).sum().item()\n\n    def enc_dec_step(self, task):\n        \"\"\"\n        Encoding / decoding step.\n        \"\"\"\n        params = self.params\n        encoder, decoder = self.modules[\"encoder\"], self.modules[\"decoder\"]\n        encoder.train()\n        decoder.train()\n\n        # batch\n        (x1, len1), (x2, len2), _ = self.get_batch(task)\n\n        # target words to predict\n        alen = torch.arange(len2.max(), dtype=torch.long, device=len2.device)\n        pred_mask = (\n            alen[:, None] < len2[None] - 1\n        )  # do not predict anything given the last target word\n        y = x2[1:].masked_select(pred_mask[:-1])\n        assert len(y) == (len2 - 1).sum().item()\n\n        # cuda\n        x1, len1, x2, len2, y = to_cuda(x1, len1, x2, len2, y)\n\n        # forward / loss\n        encoded = encoder(\"fwd\", x=x1, lengths=len1, causal=False)\n        decoded = decoder(\n            \"fwd\",\n            x=x2,\n            lengths=len2,\n            causal=True,\n            src_enc=encoded.transpose(0, 1),\n            src_len=len1,\n        )\n        _, loss = decoder(\n            \"predict\", tensor=decoded, pred_mask=pred_mask, y=y, get_scores=False\n        )\n        self.stats[task].append(loss.item())\n\n        # optimize\n        self.optimize(loss)\n\n        # number of processed sequences / words\n        self.n_equations += params.batch_size\n        self.stats[\"processed_e\"] += len1.size(0)\n        self.stats[\"processed_w\"] += (len1 + len2 - 2).sum().item()\n"
  },
  {
    "path": "src/utils.py",
    "content": "# Copyright (c) 2020-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nimport os\nimport re\nimport sys\nimport math\nimport time\nimport pickle\nimport random\nimport getpass\nimport argparse\nimport subprocess\n\nimport errno\nimport signal\nfrom functools import wraps, partial\n\nfrom .logger import create_logger\n\n\nFALSY_STRINGS = {\"off\", \"false\", \"0\"}\nTRUTHY_STRINGS = {\"on\", \"true\", \"1\"}\n\nDUMP_PATH = \"/checkpoint/%s/dumped\" % getpass.getuser()\nCUDA = True\n\n\nclass AttrDict(dict):\n    def __init__(self, *args, **kwargs):\n        super(AttrDict, self).__init__(*args, **kwargs)\n        self.__dict__ = self\n\n\ndef bool_flag(s):\n    \"\"\"\n    Parse boolean arguments from the command line.\n    \"\"\"\n    if s.lower() in FALSY_STRINGS:\n        return False\n    elif s.lower() in TRUTHY_STRINGS:\n        return True\n    else:\n        raise argparse.ArgumentTypeError(\"Invalid value for a boolean flag!\")\n\n\ndef initialize_exp(params):\n    \"\"\"\n    Initialize the experience:\n    - dump parameters\n    - create a logger\n    \"\"\"\n    # dump parameters\n    get_dump_path(params)\n    pickle.dump(params, open(os.path.join(params.dump_path, \"params.pkl\"), \"wb\"))\n\n    # get running command\n    command = [\"python\", sys.argv[0]]\n    for x in sys.argv[1:]:\n        if x.startswith(\"--\"):\n            assert '\"' not in x and \"'\" not in x\n            command.append(x)\n        else:\n            assert \"'\" not in x\n            if re.match(\"^[a-zA-Z0-9_]+$\", x):\n                command.append(\"%s\" % x)\n            else:\n                command.append(\"'%s'\" % x)\n    command = \" \".join(command)\n    params.command = command + ' --exp_id \"%s\"' % params.exp_id\n\n    # check experiment name\n    assert len(params.exp_name.strip()) > 0\n\n    # create a logger\n    logger = create_logger(\n        os.path.join(params.dump_path, \"train.log\"),\n        rank=getattr(params, \"global_rank\", 0),\n    )\n    logger.info(\"============ Initialized logger ============\")\n    logger.info(\n        \"\\n\".join(\"%s: %s\" % (k, str(v)) for k, v in sorted(dict(vars(params)).items()))\n    )\n    logger.info(\"The experiment will be stored in %s\\n\" % params.dump_path)\n    logger.info(\"Running command: %s\" % command)\n    logger.info(\"\")\n    return logger\n\n\ndef get_dump_path(params):\n    \"\"\"\n    Create a directory to store the experiment.\n    \"\"\"\n    params.dump_path = DUMP_PATH if params.dump_path == \"\" else params.dump_path\n    assert len(params.exp_name) > 0\n\n    # create the sweep path if it does not exist\n    sweep_path = os.path.join(params.dump_path, params.exp_name)\n    if not os.path.exists(sweep_path):\n        subprocess.Popen(\"mkdir -p %s\" % sweep_path, shell=True).wait()\n\n    # create an ID for the job if it is not given in the parameters.\n    # if we run on the cluster, the job ID is the one of Chronos.\n    # otherwise, it is randomly generated\n    if params.exp_id == \"\":\n        chronos_job_id = os.environ.get(\"CHRONOS_JOB_ID\")\n        slurm_job_id = os.environ.get(\"SLURM_JOB_ID\")\n        assert chronos_job_id is None or slurm_job_id is None\n        exp_id = chronos_job_id if chronos_job_id is not None else slurm_job_id\n        if exp_id is None:\n            chars = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n            while True:\n                exp_id = \"\".join(random.choice(chars) for _ in range(10))\n                if not os.path.isdir(os.path.join(sweep_path, exp_id)):\n                    break\n        else:\n            assert exp_id.isdigit()\n        params.exp_id = exp_id\n\n    # create the dump folder / update parameters\n    params.dump_path = os.path.join(sweep_path, params.exp_id)\n    if not os.path.isdir(params.dump_path):\n        subprocess.Popen(\"mkdir -p %s\" % params.dump_path, shell=True).wait()\n\n\ndef to_cuda(*args):\n    \"\"\"\n    Move tensors to CUDA.\n    \"\"\"\n    if not CUDA:\n        return args\n    return [None if x is None else x.cuda() for x in args]\n\n\nclass TimeoutError(BaseException):\n    pass\n\n\ndef timeout(seconds=10, error_message=os.strerror(errno.ETIME)):\n    def decorator(func):\n        def _handle_timeout(repeat_id, signum, frame):\n            # logger.warning(f\"Catched the signal ({repeat_id})\n            #  Setting signal handler {repeat_id + 1}\")\n            signal.signal(signal.SIGALRM, partial(_handle_timeout, repeat_id + 1))\n            signal.alarm(seconds)\n            raise TimeoutError(error_message)\n\n        def wrapper(*args, **kwargs):\n            old_signal = signal.signal(signal.SIGALRM, partial(_handle_timeout, 0))\n            old_time_left = signal.alarm(seconds)\n            assert type(old_time_left) is int and old_time_left >= 0\n            if 0 < old_time_left < seconds:  # do not exceed previous timer\n                signal.alarm(old_time_left)\n            start_time = time.time()\n            try:\n                result = func(*args, **kwargs)\n            finally:\n                if old_time_left == 0:\n                    signal.alarm(0)\n                else:\n                    sub = time.time() - start_time\n                    signal.signal(signal.SIGALRM, old_signal)\n                    signal.alarm(max(0, math.ceil(old_time_left - sub)))\n            return result\n\n        return wraps(func)(wrapper)\n\n    return decorator\n"
  },
  {
    "path": "train.py",
    "content": "# Copyright (c) 2020-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nimport json\nimport random\nimport argparse\nimport numpy as np\nimport torch\n\nimport src\nfrom src.slurm import init_signal_handler, init_distributed_mode\nfrom src.utils import bool_flag, initialize_exp\nfrom src.model import check_model_params, build_modules\nfrom src.envs import ENVS, build_env\nfrom src.trainer import Trainer\nfrom src.evaluator import Evaluator\n\n\nnp.seterr(all=\"raise\")\n\n\ndef get_parser():\n    \"\"\"\n    Generate a parameters parser.\n    \"\"\"\n    # parse parameters\n    parser = argparse.ArgumentParser(description=\"Language transfer\")\n\n    # main parameters\n    parser.add_argument(\n        \"--dump_path\", type=str, default=\"\", help=\"Experiment dump path\"\n    )\n    parser.add_argument(\"--exp_name\", type=str, default=\"debug\", help=\"Experiment name\")\n    parser.add_argument(\n        \"--save_periodic\",\n        type=int,\n        default=0,\n        help=\"Save the model periodically (0 to disable)\",\n    )\n    parser.add_argument(\"--exp_id\", type=str, default=\"\", help=\"Experiment ID\")\n\n    # float16 / AMP API\n    parser.add_argument(\n        \"--fp16\", type=bool_flag, default=False, help=\"Run model with float16\"\n    )\n    parser.add_argument(\n        \"--amp\",\n        type=int,\n        default=-1,\n        help=(\n            \"Use AMP wrapper for float16 / distributed / gradient accumulation. \"\n            \"Level of optimization. -1 to disable.\"\n        ),\n    )\n\n    # model parameters\n    parser.add_argument(\"--emb_dim\", type=int, default=256, help=\"Embedding layer size\")\n    parser.add_argument(\n        \"--n_enc_layers\",\n        type=int,\n        default=4,\n        help=\"Number of Transformer layers in the encoder\",\n    )\n    parser.add_argument(\n        \"--n_dec_layers\",\n        type=int,\n        default=4,\n        help=\"Number of Transformer layers in the decoder\",\n    )\n    parser.add_argument(\n        \"--n_heads\", type=int, default=4, help=\"Number of Transformer heads\"\n    )\n    parser.add_argument(\"--dropout\", type=float, default=0, help=\"Dropout\")\n    parser.add_argument(\n        \"--attention_dropout\",\n        type=float,\n        default=0,\n        help=\"Dropout in the attention layer\",\n    )\n    parser.add_argument(\n        \"--share_inout_emb\",\n        type=bool_flag,\n        default=True,\n        help=\"Share input and output embeddings\",\n    )\n    parser.add_argument(\n        \"--sinusoidal_embeddings\",\n        type=bool_flag,\n        default=False,\n        help=\"Use sinusoidal embeddings\",\n    )\n\n    # training parameters\n    parser.add_argument(\n        \"--env_base_seed\",\n        type=int,\n        default=0,\n        help=\"Base seed for environments (-1 to use timestamp seed)\",\n    )\n    parser.add_argument(\n        \"--max_len\", type=int, default=512, help=\"Maximum sequences length\"\n    )\n    parser.add_argument(\n        \"--batch_size\", type=int, default=32, help=\"Number of sentences per batch\"\n    )\n    parser.add_argument(\n        \"--batch_size_eval\",\n        type=int,\n        default=128,\n        help=\"Number of sentences per batch during evaluation\",\n    )\n    parser.add_argument(\n        \"--optimizer\",\n        type=str,\n        default=\"adam,lr=0.0001\",\n        help=\"Optimizer (SGD / RMSprop / Adam, etc.)\",\n    )\n    parser.add_argument(\n        \"--clip_grad_norm\",\n        type=float,\n        default=5,\n        help=\"Clip gradients norm (0 to disable)\",\n    )\n    parser.add_argument(\n        \"--epoch_size\",\n        type=int,\n        default=300000,\n        help=\"Epoch size / evaluation frequency\",\n    )\n    parser.add_argument(\n        \"--max_epoch\", type=int, default=100000, help=\"Maximum epoch size\"\n    )\n    parser.add_argument(\n        \"--stopping_criterion\",\n        type=str,\n        default=\"\",\n        help=(\n            \"Stopping criterion, and number of non-increase \"\n            \"before stopping the experiment\"\n        ),\n    )\n    parser.add_argument(\n        \"--validation_metrics\", type=str, default=\"\", help=\"Validation metrics\"\n    )\n    parser.add_argument(\n        \"--accumulate_gradients\",\n        type=int,\n        default=1,\n        help=\"Accumulate model gradients over N iterations (N time larger batch sizes)\",\n    )\n    parser.add_argument(\n        \"--num_workers\",\n        type=int,\n        default=10,\n        help=\"Number of CPU workers for DataLoader\",\n    )\n\n    # export data / reload it\n    parser.add_argument(\n        \"--export_data\",\n        type=bool_flag,\n        default=False,\n        help=\"Export data and disable training.\",\n    )\n    parser.add_argument(\n        \"--reload_data\",\n        type=str,\n        default=\"\",\n        help=(\n            \"Load dataset from the disk (task1,train_path1,valid_path1,test_path1;\"\n            \"task2,train_path2,valid_path2,test_path2)\"\n        ),\n    )\n    parser.add_argument(\n        \"--reload_size\",\n        type=int,\n        default=-1,\n        help=\"Reloaded training set size (-1 for everything)\",\n    )\n\n    # environment parameters\n    parser.add_argument(\"--env_name\", type=str, default=\"ode\", help=\"Environment name\")\n    ENVS[parser.parse_known_args()[0].env_name].register_args(parser)\n\n    # tasks\n    parser.add_argument(\"--tasks\", type=str, default=\"\", help=\"Tasks\")\n\n    # beam search configuration\n    parser.add_argument(\n        \"--beam_eval\",\n        type=bool_flag,\n        default=False,\n        help=\"Evaluate with beam search decoding.\",\n    )\n    parser.add_argument(\n        \"--beam_size\",\n        type=int,\n        default=1,\n        help=\"Beam size, default = 1 (greedy decoding)\",\n    )\n    parser.add_argument(\n        \"--beam_length_penalty\",\n        type=float,\n        default=1,\n        help=(\n            \"Length penalty, values < 1.0 favor shorter sentences, \"\n            \"while values > 1.0 favor longer ones.\"\n        ),\n    )\n    parser.add_argument(\n        \"--beam_early_stopping\",\n        type=bool_flag,\n        default=True,\n        help=(\n            \"Early stopping, stop as soon as we have `beam_size` hypotheses, \"\n            \"although longer ones may have better scores.\"\n        ),\n    )\n\n    # reload pretrained model / checkpoint\n    parser.add_argument(\n        \"--reload_model\", type=str, default=\"\", help=\"Reload a pretrained model\"\n    )\n    parser.add_argument(\n        \"--reload_checkpoint\", type=str, default=\"\", help=\"Reload a checkpoint\"\n    )\n\n    # evaluation\n    parser.add_argument(\n        \"--eval_only\", type=bool_flag, default=False, help=\"Only run evaluations\"\n    )\n    parser.add_argument(\n        \"--eval_verbose\", type=int, default=0, help=\"Export evaluation details\"\n    )\n    parser.add_argument(\n        \"--eval_verbose_print\",\n        type=bool_flag,\n        default=False,\n        help=\"Print evaluation details\",\n    )\n\n    # debug\n    parser.add_argument(\n        \"--debug_slurm\",\n        type=bool_flag,\n        default=False,\n        help=\"Debug multi-GPU / multi-node within a SLURM job\",\n    )\n    parser.add_argument(\"--debug\", help=\"Enable all debug flags\", action=\"store_true\")\n\n    # CPU / multi-gpu / multi-node\n    parser.add_argument(\"--cpu\", type=bool_flag, default=False, help=\"Run on CPU\")\n    parser.add_argument(\n        \"--local_rank\", type=int, default=-1, help=\"Multi-GPU - Local rank\"\n    )\n    parser.add_argument(\n        \"--master_port\",\n        type=int,\n        default=-1,\n        help=\"Master port (for multi-node SLURM jobs)\",\n    )\n\n    return parser\n\n\ndef main(params):\n\n    # initialize the multi-GPU / multi-node training\n    # initialize experiment / SLURM signal handler for time limit / pre-emption\n    init_distributed_mode(params)\n    logger = initialize_exp(params)\n    init_signal_handler()\n\n    # CPU / CUDA\n    if params.cpu:\n        assert not params.multi_gpu\n    else:\n        assert torch.cuda.is_available()\n    src.utils.CUDA = not params.cpu\n\n    # build environment / modules / trainer / evaluator\n    env = build_env(params)\n    modules = build_modules(env, params)\n    trainer = Trainer(modules, env, params)\n    evaluator = Evaluator(trainer)\n\n    # evaluation\n    if params.eval_only:\n        scores = evaluator.run_all_evals()\n        for k, v in scores.items():\n            logger.info(\"%s -> %.6f\" % (k, v))\n        logger.info(\"__log__:%s\" % json.dumps(scores))\n        exit()\n\n    # training\n    for _ in range(params.max_epoch):\n\n        logger.info(\"============ Starting epoch %i ... ============\" % trainer.epoch)\n\n        trainer.n_equations = 0\n\n        while trainer.n_equations < trainer.epoch_size:\n\n            # training steps\n            for task_id in np.random.permutation(len(params.tasks)):\n                task = params.tasks[task_id]\n                if params.export_data:\n                    trainer.export_data(task)\n                else:\n                    trainer.enc_dec_step(task)\n                trainer.iter()\n\n        logger.info(\"============ End of epoch %i ============\" % trainer.epoch)\n\n        # evaluate perplexity\n        scores = evaluator.run_all_evals()\n\n        # print / JSON log\n        for k, v in scores.items():\n            logger.info(\"%s -> %.6f\" % (k, v))\n        if params.is_master:\n            logger.info(\"__log__:%s\" % json.dumps(scores))\n\n        # end of epoch\n        trainer.save_best_model(scores)\n        trainer.save_periodic()\n        trainer.end_epoch(scores)\n\n\nif __name__ == \"__main__\":\n\n    # generate parser / parse parameters\n    parser = get_parser()\n    params = parser.parse_args()\n\n    # debug mode\n    if params.debug:\n        params.exp_name = \"debug\"\n        if params.exp_id == \"\":\n            params.exp_id = \"debug_%08i\" % random.randint(0, 100000000)\n        params.debug_slurm = True\n\n    # check parameters\n    check_model_params(params)\n\n    # run experiment\n    main(params)\n"
  }
]