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