├── .DS_Store ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── api.py ├── demos ├── multiarith_auto └── multiarith_manual ├── requirements.txt ├── run_demo.py ├── run_inference.py ├── try_cot.ipynb ├── try_cot_colab.ipynb └── utils.py /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amazon-science/auto-cot/ec9caa32a69cfd7203c33df76d31cb48e726d6a7/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .ipynb_checkpoints/ 2 | __pycache__/ 3 | .DS_Store 4 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *main* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Auto-CoT: Automatic Chain of Thought Prompting in Large Language Models (ICLR 2023) 2 | 3 | [![Open Auto-CoT in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/amazon-science/auto-cot/blob/main/try_cot_colab.ipynb) 4 | 5 | Cheer AI up with the "let's think step by step" prompt? More plz. *Let’s think not just step by step, but also one by one.* 6 | 7 | Auto-CoT uses more cheers & diversity to SAVE huge manual efforts in chain of thought prompt design, matching or even exceeding performance of manual design on GPT-3. 8 | 9 | Check out our [25-page paper](https://arxiv.org/pdf/2210.03493.pdf) for more information. 10 | 11 | ![](https://user-images.githubusercontent.com/22279212/194787183-a1f8dff8-a0ad-43a1-827f-819671503860.png) 12 | 13 | ![](https://user-images.githubusercontent.com/22279212/194787130-d28c9191-588c-41d2-a259-62377f19c934.png) 14 | 15 | 16 | ## Requirements 17 | 18 | Python>=3.8 19 | ``` 20 | pip install torch==1.8.2+cu111 torchtext==0.9.2 -f https://download.pytorch.org/whl/lts/1.8/torch_lts.html 21 | pip install -r requirements.txt 22 | ``` 23 | 24 | ## Datasets 25 | 26 | Download the datasets from the following: 27 | 28 | ``` 29 | https://github.com/kojima-takeshi188/zero_shot_cot/tree/main/dataset 30 | https://github.com/kojima-takeshi188/zero_shot_cot/tree/main/log 31 | ``` 32 | 33 | ## Quick Start 34 | 35 | See ```try_cot.ipynb``` 36 | 37 | ## Instructions 38 | 39 | Construct Demos: 40 | 41 | ``` 42 | python run_demo.py \ 43 | --task multiarith \ 44 | --pred_file log/multiarith_zero_shot_cot.log \ 45 | --demo_save_dir demos/multiarith 46 | ``` 47 | 48 | Run inference: 49 | 50 | ``` 51 | python run_inference.py \ 52 | --dataset multiarith \ 53 | --demo_path demos/multiarith \ 54 | --output_dir experiment/multiarith 55 | ``` 56 | 57 | ## Citing Auto-CoT 58 | ``` 59 | @inproceedings{zhang2023automatic, 60 | title={Automatic Chain of Thought Prompting in Large Language Models}, 61 | author={Zhang, Zhuosheng and Zhang, Aston and Li, Mu and Smola, Alex}, 62 | booktitle={The Eleventh International Conference on Learning Representations (ICLR 2023)}, 63 | year={2023} 64 | } 65 | ``` 66 | 67 | ## Security 68 | 69 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. 70 | 71 | ## License 72 | 73 | This project is licensed under the Apache-2.0 License. 74 | -------------------------------------------------------------------------------- /api.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from utils import * 3 | 4 | def cot(method, question): 5 | args = parse_arguments() 6 | decoder = Decoder() 7 | 8 | args.method = method 9 | if args.method != "zero_shot_cot": 10 | if args.method == "auto_cot": 11 | args.demo_path = "demos/multiarith_auto" 12 | else: 13 | args.demo_path = "demos/multiarith_manual" 14 | demo = create_demo_text(args, cot_flag=True) 15 | else: 16 | demo = None 17 | 18 | x = "Q: " + question + "\n" + "A:" 19 | print('*****************************') 20 | print("Test Question:") 21 | print(question) 22 | print('*****************************') 23 | 24 | if args.method == "zero_shot": 25 | x = x + " " + args.direct_answer_trigger_for_zeroshot 26 | elif args.method == "zero_shot_cot": 27 | x = x + " " + args.cot_trigger 28 | elif args.method == "manual_cot": 29 | x = demo + x 30 | elif args.method == "auto_cot": 31 | x = demo + x + " " + args.cot_trigger 32 | else: 33 | raise ValueError("method is not properly defined ...") 34 | 35 | print("Prompted Input:") 36 | print(x.replace("\n\n", "\n").strip()) 37 | print('*****************************') 38 | 39 | max_length = args.max_length_cot if "cot" in args.method else args.max_length_direct 40 | z = decoder.decode(args, x, max_length) 41 | z = z.replace("\n\n", "\n").replace("\n", "").strip() 42 | if args.method == "zero_shot_cot": 43 | z2 = x + z + " " + args.direct_answer_trigger_for_zeroshot_cot 44 | max_length = args.max_length_direct 45 | pred = decoder.decode(args, z2, max_length) 46 | print("Output:") 47 | print(z + " " + args.direct_answer_trigger_for_zeroshot_cot + " " + pred) 48 | print('*****************************') 49 | else: 50 | pred = z 51 | print("Output:") 52 | print(pred) 53 | print('*****************************') 54 | 55 | def parse_arguments(): 56 | parser = argparse.ArgumentParser(description="Zero-shot-CoT") 57 | 58 | parser.add_argument("--max_num_worker", type=int, default=0, help="maximum number of workers for dataloader") 59 | parser.add_argument( 60 | "--model", type=str, default="gpt3-xl", help="model used for decoding. Note that 'gpt3' are the smallest models." 61 | ) 62 | parser.add_argument( 63 | "--method", type=str, default="auto_cot", choices=["zero_shot", "zero_shot_cot", "few_shot", "few_shot_cot", "auto_cot"], help="method" 64 | ) 65 | parser.add_argument( 66 | "--cot_trigger_no", type=int, default=1, help="A trigger sentence that elicits a model to execute chain of thought" 67 | ) 68 | parser.add_argument( 69 | "--max_length_cot", type=int, default=256, help="maximum length of output tokens by model for reasoning extraction" 70 | ) 71 | parser.add_argument( 72 | "--max_length_direct", type=int, default=32, help="maximum length of output tokens by model for answer extraction" 73 | ) 74 | parser.add_argument( 75 | "--limit_dataset_size", type=int, default=0, help="whether to limit test dataset size. if 0, the dataset size is unlimited and we use all the samples in the dataset for testing." 76 | ) 77 | parser.add_argument( 78 | "--api_time_interval", type=float, default=1.0, help="" 79 | ) 80 | parser.add_argument( 81 | "--temperature", type=float, default=0, help="" 82 | ) 83 | parser.add_argument( 84 | "--log_dir", type=str, default="./log/", help="log directory" 85 | ) 86 | args = parser.parse_args() 87 | 88 | args.direct_answer_trigger_for_fewshot = "The answer is" 89 | args.direct_answer_trigger_for_zeroshot = "The answer is" 90 | args.direct_answer_trigger_for_zeroshot_cot = "The answer is" 91 | args.cot_trigger = "Let's think step by step." 92 | 93 | return args -------------------------------------------------------------------------------- /demos/multiarith_auto: -------------------------------------------------------------------------------- 1 | { 2 | "demo": [ 3 | { 4 | "question": "Q: Wendy uploaded 45 pictures to Facebook. She put 27 pics into one album and put the rest into 9 different albums. How many pictures were in each album?\nA:", 5 | "rationale": "Let's think step by step. First, we know that Wendy uploaded 45 pictures in total. Second, we know that Wendy put 27 pictures into one album. That means that Wendy put the remaining 18 pictures into 9 different albums. That means that each album would have 2 pictures.", 6 | "pred_ans": "2", 7 | "gold_ans": "2" 8 | }, 9 | { 10 | "question": "Q: For Halloween Katie and her sister combined the candy they received. Katie had 8 pieces of candy while her sister had 23. If they ate 8 pieces the first night, how many pieces do they have left?\nA:", 11 | "rationale": "Let's think step by step. Katie and her sister have a total of 8 + 23 = 31 pieces of candy. If they eat 8 pieces the first night, they have 31 - 8 = 23 pieces left.", 12 | "pred_ans": "23", 13 | "gold_ans": "23" 14 | }, 15 | { 16 | "question": "Q: Bianca was organizing her book case making sure each of the shelves had exactly 8 books on it. If she had 5 shelves of mystery books and 4 shelves of picture books, how many books did she have total?\nA:", 17 | "rationale": "Let's think step by step. There are 5 shelves of mystery books. Each shelf has 8 books. So that's 40 mystery books. There are 4 shelves of picture books. Each shelf has 8 books. So that's 32 picture books. 40 + 32 = 72 books.", 18 | "pred_ans": "72", 19 | "gold_ans": "72" 20 | }, 21 | { 22 | "question": "Q: A pet store had 78 puppies. In one day they sold 30 of them and put the rest into cages with 8 in each cage. How many cages did they use?\nA:", 23 | "rationale": "Let's think step by step. There are 78 puppies. 30 are sold, so that means there are 48 left. 48 divided by 8 is 6, so that means there are 6 cages with 8 puppies in each.", 24 | "pred_ans": "6", 25 | "gold_ans": "6" 26 | }, 27 | { 28 | "question": "Q: A waiter had 14 customers to wait on. If 3 customers left and he got another 39 customers, how many customers would he have?\nA:", 29 | "rationale": "Let's think step by step. The waiter had 14 customers to wait on. If 3 customers left, that means he would have 11 customers left. If he got another 39 customers, that means he would have 50 customers in total.", 30 | "pred_ans": "50", 31 | "gold_ans": "50" 32 | }, 33 | { 34 | "question": "Q: A trivia team had 7 members total, but during a game 2 members didn't show up. If each member that did show up scored 4 points, how many points were scored total?\nA:", 35 | "rationale": "Let's think step by step. There were 7 members on the team, but 2 members didn't show up. That means that there were 5 members that did show up. Each member that showed up scored 4 points. So if 5 members each scored 4 points, then the total number of points scored would be 5*4=20.", 36 | "pred_ans": "20", 37 | "gold_ans": "20" 38 | }, 39 | { 40 | "question": "Q: Gwen had 18 math problems and 11 science problems for homework. If she finished 24 of the problems at school, how many problems did she have to do for homework?\nA:", 41 | "rationale": "Let's think step by step. Gwen had 18 math problems and 11 science problems for homework. That means she had a total of 29 problems for homework. If she finished 24 of the problems at school, that means she had 5 problems left to do for homework.", 42 | "pred_ans": "5", 43 | "gold_ans": "5" 44 | }, 45 | { 46 | "question": "Q: Mike made 69 dollars mowing lawns over the summer. If he spent 24 dollars buying new mower blades, how many 5 dollar games could he buy with the money he had left?\nA:", 47 | "rationale": "Let's think step by step. Mike made $69 from mowing lawns. He spent $24 on new mower blades. That means he has $45 left. Each game costs $5, so he could buy 9 games.", 48 | "pred_ans": "9", 49 | "gold_ans": "9" 50 | } 51 | ] 52 | } -------------------------------------------------------------------------------- /demos/multiarith_manual: -------------------------------------------------------------------------------- 1 | { 2 | "demo": [ 3 | { 4 | "question": "Q: There are 15 trees in the grove. Grove workers will plant trees in the grove today. After they are done, there will be 21 trees. How many trees did the grove workers plant today?\nA:", 5 | "rationale": "There are 15 trees originally. Then there were 21 trees after some more were planted. So there must have been 21 - 15 = 6.", 6 | "pred_ans": "6" 7 | }, 8 | { 9 | "question": "Q: If there are 3 cars in the parking lot and 2 more cars arrive, how many cars are in the parking lot?\nA:", 10 | "rationale": "There are originally 3 cars. 2 more cars arrive. 3 + 2 = 5.", 11 | "pred_ans": "5" 12 | }, 13 | { 14 | "question": "Q: Leah had 32 chocolates and her sister had 42. If they ate 35, how many pieces do they have left in total?\nA:", 15 | "rationale": "Originally, Leah had 32 chocolates. Her sister had 42. So in total they had 32 + 42 = 74. After eating 35, they had 74 - 35 = 39.", 16 | "pred_ans": "39" 17 | }, 18 | { 19 | "question": "Q: Jason had 20 lollipops. He gave Denny some lollipops. Now Jason has 12 lollipops. How many lollipops did Jason give to Denny?\nA:", 20 | "rationale": "Jason started with 20 lollipops. Then he had 12 after giving some to Denny. So he gave Denny 20 - 12 = 8.", 21 | "pred_ans": "8" 22 | }, 23 | { 24 | "question": "Q: Shawn has five toys. For Christmas, he got two toys each from his mom and dad. How many toys does he have now?\nA:", 25 | "rationale": "Shawn started with 5 toys. If he got 2 toys each from his mom and dad, then that is 4 more toys. 5 + 4 = 9.", 26 | "pred_ans": "9" 27 | }, 28 | { 29 | "question": "Q: There were nine computers in the server room. Five more computers were installed each day, from monday to thursday. How many computers are now in the server room?\nA:", 30 | "rationale": "There were originally 9 computers. For each of 4 days, 5 more computers were added. So 5 * 4 = 20 computers were added. 9 + 20 is 29.", 31 | "pred_ans": "29" 32 | }, 33 | { 34 | "question": "Q: Michael had 58 golf balls. On tuesday, he lost 23 golf balls. On wednesday, he lost 2 more. How many golf balls did he have at the end of wednesday?\nA:", 35 | "rationale": "Michael started with 58 golf balls. After losing 23 on tuesday, he had 58 - 23 = 35. After losing 2 more, he had 35 - 2 = 33 golf balls.", 36 | "pred_ans": "33" 37 | }, 38 | { 39 | "question": "Q: Olivia has $23. She bought five bagels for $3 each. How much money does she have left?\nA:", 40 | "rationale": "Olivia had 23 dollars. 5 bagels for 3 dollars each will be 5 x 3 = 15 dollars. So she has 23 - 15 dollars left. 23 - 15 is 8.", 41 | "pred_ans": "8" 42 | } 43 | ] 44 | } -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | sklearn 2 | matplotlib 3 | sentence-transformers 4 | jupyter 5 | -------------------------------------------------------------------------------- /run_demo.py: -------------------------------------------------------------------------------- 1 | import random 2 | from sentence_transformers import SentenceTransformer 3 | from sklearn.cluster import KMeans 4 | from sklearn.decomposition import PCA 5 | import numpy as np 6 | import json 7 | import matplotlib.pyplot as plt 8 | import argparse 9 | from utils import fix_seed 10 | 11 | 12 | def parse_arguments(): 13 | parser = argparse.ArgumentParser(description="Zero-shot-CoT") 14 | parser.add_argument( 15 | "--task", type=str, default="multiarith", 16 | choices=["aqua", "gsm8k", "commonsensqa", "addsub", "multiarith", "strategyqa", "svamp", "singleeq", "coin_flip", "last_letters"], help="dataset used for experiment" 17 | ) 18 | parser.add_argument( 19 | "--max_ra_len", type=int, default=5, help="maximum number of reasoning chains" 20 | ) 21 | parser.add_argument( 22 | "--pred_file", type=str, default="log/multiarith_zero_shot_cot.log", 23 | help="use the reasoning chains generated by zero-shot-cot." 24 | ) 25 | parser.add_argument( 26 | "--demo_save_dir", type=str, default="demos/multiarith", help="where to save the contructed demonstrations" 27 | ) 28 | parser.add_argument("--random_seed", type=int, default=192, help="random seed") 29 | parser.add_argument( 30 | "--encoder", type=str, default="all-MiniLM-L6-v2", help="which sentence-transformer encoder for clustering" 31 | ) 32 | parser.add_argument( 33 | "--sampling", type=str, default="center", help="whether to sample the cluster center first" 34 | ) 35 | parser.add_argument( 36 | "--debug", type=bool, default=True, help="debug mode" 37 | ) 38 | args = parser.parse_args() 39 | return args 40 | 41 | def main(): 42 | args = parse_arguments() 43 | fix_seed(args.random_seed) 44 | encoder = SentenceTransformer(args.encoder) 45 | 46 | task = args.task 47 | pred_file = args.pred_file 48 | save_file = args.demo_save_dir 49 | max_ra_len = args.max_ra_len 50 | if task == "last_letters": 51 | max_ra_len = 7 52 | if task == "aqua" or task == "last_letters": 53 | num_clusters = 4 54 | elif task == "commonsensqa": 55 | num_clusters = 7 56 | elif task == "strategyqa": 57 | num_clusters = 6 58 | else: 59 | num_clusters = 8 60 | 61 | corpus = [] 62 | question = [] 63 | rationale = [] 64 | gold_ans = [] 65 | pred_ans = [] 66 | 67 | with open(pred_file, "r", encoding="utf-8") as fp: 68 | answer_seg = "" 69 | for line in fp: 70 | if "Q: " in line: 71 | c_question = line.strip() 72 | if "A: " in line: 73 | answer_seg = line 74 | elif "Therefore" in line and "the answer" in line: 75 | c_rationale = answer_seg 76 | 77 | elif answer_seg != "": 78 | answer_seg += line 79 | if "pred_mode" in line: 80 | c_pred_ans = line.split(":")[1].strip() 81 | if "GT :" in line: 82 | c_gold_ans = line.split(":")[1].strip() 83 | 84 | c_rationale = c_rationale.replace("A: Let's think step by step.", "Let's think step by step.") 85 | c_question = c_question + "\nA:" 86 | 87 | corpus.append(c_question) 88 | question.append(c_question) 89 | rationale.append(c_rationale) 90 | pred_ans.append(c_pred_ans) 91 | if args.debug: 92 | gold_ans.append(c_gold_ans) 93 | answer_seg = "" 94 | 95 | corpus_embeddings = encoder.encode(corpus) 96 | 97 | # Perform kmean clustering 98 | clustering_model = KMeans(n_clusters=num_clusters, random_state=args.random_seed) 99 | clustering_model.fit(corpus_embeddings) 100 | cluster_assignment = clustering_model.labels_ 101 | 102 | clustered_sentences = [[] for i in range(num_clusters)] 103 | 104 | dist = clustering_model.transform(corpus_embeddings) 105 | clustered_dists = [[] for i in range(num_clusters)] 106 | clustered_idx = [[] for i in range(num_clusters)] 107 | for sentence_id, cluster_id in enumerate(cluster_assignment): 108 | clustered_sentences[cluster_id].append(corpus[sentence_id]) 109 | clustered_dists[cluster_id].append(dist[sentence_id][cluster_id]) 110 | clustered_idx[cluster_id].append(sentence_id) 111 | 112 | demos = [] 113 | 114 | for i in range(len(clustered_dists)): 115 | print("Cluster ", i+1) 116 | tmp = list(map(list, zip(range(len(clustered_dists[i])), clustered_dists[i]))) 117 | top_min_dist = sorted(tmp, key=lambda x: x[1], reverse=False) 118 | if not args.sampling == "center": 119 | random.shuffle(top_min_dist) 120 | for element in top_min_dist: 121 | min_idx = element[0] 122 | c_rationale = rationale[clustered_idx[i][min_idx]].strip() 123 | c_pred_ans = pred_ans[clustered_idx[i][min_idx]].strip() 124 | 125 | if len(question[clustered_idx[i][min_idx]].strip().split()) <= 60 \ 126 | and len(c_rationale.replace("\n\n", "\n").split("\n")) <= max_ra_len and c_rationale[-1] == "." and c_pred_ans != "": 127 | if args.task in ["gsm8k", "multiarith", "singleeq", "addsub", "svamp"]: 128 | if not (c_pred_ans.strip() in c_rationale.split(".")[-2] or c_pred_ans.strip() in c_rationale.split()[-10:]): 129 | continue 130 | c_question = question[clustered_idx[i][min_idx]] 131 | c_rationale = c_rationale.replace("\n\n", "\n").replace("\n", " ").strip() 132 | c_rationale = " ".join(c_rationale.split()) 133 | if args.debug: 134 | c_gold_ans = gold_ans[clustered_idx[i][min_idx]] 135 | else: 136 | c_gold_ans = None 137 | demo_element = { 138 | "question": c_question, 139 | "rationale": c_rationale, 140 | "pred_ans": c_pred_ans, 141 | "gold_ans": c_gold_ans, 142 | } 143 | demos.append(demo_element) 144 | print(c_question) 145 | print(c_rationale) 146 | print(c_pred_ans) 147 | print(c_gold_ans) 148 | print("") 149 | break 150 | 151 | demos = {"demo": demos} 152 | 153 | with open(args.demo_save_dir, 'w', encoding="utf-8") as write_f: 154 | json.dump(demos, write_f, indent=4, ensure_ascii=False) 155 | 156 | y_km = clustering_model.fit_predict(corpus_embeddings) 157 | pca_model = PCA(n_components=2, random_state=args.random_seed) 158 | transformed = pca_model.fit_transform(corpus_embeddings) 159 | centers = pca_model.transform(clustering_model.cluster_centers_) 160 | 161 | plt.scatter(x=transformed[:, 0], y=transformed[:, 1], c=y_km, s=50, cmap=plt.cm.Paired, alpha=0.4) 162 | plt.scatter(centers[:, 0],centers[:, 1], 163 | s=250, marker='*', label='centroids', 164 | edgecolor='black', 165 | c=np.arange(0,num_clusters),cmap=plt.cm.Paired,) 166 | plt.xticks([]) 167 | plt.yticks([]) 168 | plt.savefig(save_file+".png", dpi=600) 169 | 170 | if __name__ == "__main__": 171 | main() -------------------------------------------------------------------------------- /run_inference.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Adapted from https://github.com/kojima-takeshi188/zero_shot_cot 3 | ''' 4 | 5 | import argparse 6 | from utils import * 7 | 8 | def main(): 9 | args = parse_arguments() 10 | print('*****************************') 11 | print(args) 12 | print('*****************************') 13 | 14 | fix_seed(args.random_seed) 15 | 16 | print("OPENAI_API_KEY:") 17 | print(os.getenv("OPENAI_API_KEY")[0:5] + '**********') 18 | 19 | # Initialize decoder class (load model and tokenizer) ... 20 | decoder = Decoder() 21 | 22 | print("setup data loader ...") 23 | dataloader = setup_data_loader(args) 24 | print_now() 25 | 26 | if args.method == "few_shot": 27 | demo = create_demo_text(args, cot_flag=False) 28 | elif args.method == "few_shot_cot" or args.method == "auto_cot": 29 | demo = create_demo_text(args, cot_flag=True) 30 | else: 31 | pass 32 | 33 | total = 0 34 | correct_list = [] 35 | with open(args.output_dir, "a") as wp: 36 | 37 | for i, data in enumerate(dataloader): 38 | if i < args.resume_id - 1: 39 | # if i < 297: 40 | continue 41 | output_line = {} 42 | 43 | print('*************************') 44 | print("{}st data".format(i+1)) 45 | 46 | # Prepare question template ... 47 | x, y = data 48 | x = "Q: " + x[0] + "\n" + "A:" 49 | y = y[0].strip() 50 | 51 | # print(x, y) 52 | 53 | output_line["question"] = x 54 | output_line["gold_ans"] = y 55 | 56 | if args.method == "zero_shot": 57 | x = x + " " + args.direct_answer_trigger_for_zeroshot 58 | elif args.method == "zero_shot_cot": 59 | x = x + " " + args.cot_trigger 60 | elif args.method == "few_shot": 61 | x = demo + x 62 | elif args.method == "few_shot_cot": 63 | x = demo + x 64 | elif args.method == "auto_cot": 65 | x = demo + x + " " + args.cot_trigger 66 | else: 67 | raise ValueError("method is not properly defined ...") 68 | 69 | # Answer experiment by generating text ... 70 | max_length = args.max_length_cot if "cot" in args.method else args.max_length_direct 71 | z = decoder.decode(args, x, max_length) 72 | 73 | output_line["rationale"] = z 74 | 75 | # Answer extraction for zero-shot-cot ... 76 | if args.method == "zero_shot_cot": 77 | z2 = x + z + " " + args.direct_answer_trigger_for_zeroshot_cot 78 | max_length = args.max_length_direct 79 | pred = decoder.decode(args, z2, max_length) 80 | print(z2 + pred) 81 | else: 82 | pred = z 83 | print(x + pred) 84 | 85 | # Clensing of predicted answer ... 86 | pred = answer_cleansing(args, pred) 87 | 88 | 89 | output_line["pred_ans"] = pred 90 | output_line["wrap_que"] = x 91 | 92 | output_json = json.dumps(output_line) 93 | wp.write(output_json + '\n') 94 | 95 | # Choose the most frequent answer from the list ... 96 | print("pred : {}".format(pred)) 97 | print("GT : " + y) 98 | print('*************************') 99 | 100 | # Checking answer ... 101 | correct = (np.array([pred]) == np.array([y])).sum().item() 102 | correct_list.append(correct) 103 | total += 1 #np.array([y]).size(0) 104 | 105 | if (args.limit_dataset_size != 0) and ((i+1) >= args.limit_dataset_size): 106 | break 107 | #raise ValueError("Stop !!") 108 | 109 | # Calculate accuracy ... 110 | accuracy = (sum(correct_list) * 1.0 / total) * 100 111 | print("accuracy : {}".format(accuracy)) 112 | 113 | def parse_arguments(): 114 | parser = argparse.ArgumentParser(description="Zero-shot-CoT") 115 | 116 | parser.add_argument("--random_seed", type=int, default=1, help="random seed") 117 | parser.add_argument( 118 | "--dataset", type=str, default="multiarith", choices=["aqua", "gsm8k", "commonsensqa", "addsub", "multiarith", "strategyqa", "svamp", "singleeq", "coin_flip", "last_letters"], help="dataset used for experiment" 119 | ) 120 | parser.add_argument( 121 | "--demo_path", type=str, default="demos/multiarith", help="pre-generated demos used for experiment" 122 | ) 123 | parser.add_argument( 124 | "--resume_id", type=int, default=0, help="resume from which question id (current line number in the output file), if the experiment fails accidently (e.g., network error)" 125 | ) 126 | parser.add_argument("--minibatch_size", type=int, default=1, choices=[1], help="minibatch size should be 1 because GPT-3 API takes only 1 input for each request") 127 | 128 | parser.add_argument("--max_num_worker", type=int, default=0, help="maximum number of workers for dataloader") 129 | 130 | parser.add_argument( 131 | "--model", type=str, default="gpt3-xl", choices=["gpt3", "gpt3-medium", "gpt3-large", "gpt3-xl", "code-davinci-002"], help="model used for decoding. Note that 'gpt3' are the smallest models." 132 | ) 133 | 134 | parser.add_argument( 135 | "--method", type=str, default="auto_cot", choices=["zero_shot", "zero_shot_cot", "few_shot", "few_shot_cot", "auto_cot"], help="method" 136 | ) 137 | parser.add_argument( 138 | "--output_dir", type=str, default="experiment/multiarith", help="output directory" 139 | ) 140 | parser.add_argument( 141 | "--max_length_cot", type=int, default=256, help="maximum length of output tokens by model for reasoning extraction" 142 | ) 143 | parser.add_argument( 144 | "--max_length_direct", type=int, default=32, help="maximum length of output tokens by model for answer extraction" 145 | ) 146 | parser.add_argument( 147 | "--limit_dataset_size", type=int, default=0, help="whether to limit test dataset size. if 0, the dataset size is unlimited and we use all the samples in the dataset for testing." 148 | ) 149 | parser.add_argument( 150 | "--api_time_interval", type=float, default=1.0, help="sleep between runs to avoid excedding the rate limit of openai api" 151 | ) 152 | parser.add_argument( 153 | "--temperature", type=float, default=0, help="temperature for GPT-3" 154 | ) 155 | parser.add_argument( 156 | "--log_dir", type=str, default="./log/", help="log directory" 157 | ) 158 | 159 | args = parser.parse_args() 160 | 161 | if args.dataset == "aqua": 162 | args.dataset_path = "./dataset/AQuA/test.json" 163 | args.direct_answer_trigger = "\nTherefore, among A through E, the answer is" 164 | elif args.dataset == "gsm8k": 165 | args.dataset_path = "./dataset/grade-school-math/test.jsonl" 166 | args.direct_answer_trigger = "\nTherefore, the answer (arabic numerals) is" 167 | elif args.dataset == "commonsensqa": 168 | args.dataset_path = "./dataset/CommonsenseQA/dev_rand_split.jsonl" 169 | args.direct_answer_trigger = "\nTherefore, among A through E, the answer is" 170 | args.plausible_answer_trigger = "Choose the most plausible answer from among choices A through E." 171 | elif args.dataset == "addsub": 172 | args.dataset_path = "./dataset/AddSub/AddSub.json" 173 | args.direct_answer_trigger = "\nTherefore, the answer (arabic numerals) is" 174 | elif args.dataset == "multiarith": 175 | args.dataset_path = "./dataset/MultiArith/MultiArith.json" 176 | args.direct_answer_trigger = "\nTherefore, the answer (arabic numerals) is" 177 | elif args.dataset == "strategyqa": 178 | args.dataset_path = "./dataset/StrategyQA/task.json" 179 | args.direct_answer_trigger = "\nTherefore, the answer (Yes or No) is" 180 | elif args.dataset == "svamp": 181 | args.dataset_path = "./dataset/SVAMP/SVAMP.json" 182 | args.direct_answer_trigger = "\nTherefore, the answer (arabic numerals) is" 183 | elif args.dataset == "singleeq": 184 | args.dataset_path = "./dataset/SingleEq/questions.json" 185 | args.direct_answer_trigger = "\nTherefore, the answer (arabic numerals) is" 186 | elif args.dataset == "bigbench_date": 187 | args.dataset_path = "./dataset/Bigbench_Date/task.json" 188 | args.direct_answer_trigger = "\nTherefore, among A through F, the answer is" 189 | elif args.dataset == "object_tracking": 190 | args.dataset_path = "./dataset/Bigbench_object_tracking/task.json" 191 | args.direct_answer_trigger = "\nTherefore, among A through C, the answer is" 192 | elif args.dataset == "coin_flip": 193 | args.dataset_path = "./dataset/coin_flip/coin_flip.json" 194 | args.direct_answer_trigger = "\nTherefore, the answer (Yes or No) is" 195 | elif args.dataset == "last_letters": 196 | args.dataset_path = "./dataset/last_letters/last_letters.json" 197 | args.direct_answer_trigger = "\nTherefore, the answer is" 198 | else: 199 | raise ValueError("dataset is not properly defined ...") 200 | 201 | # "Therefore, the answer ..." -> "The answer ..." 202 | trigger = args.direct_answer_trigger.replace("\nTherefore, ", "") 203 | args.direct_answer_trigger_for_zeroshot = trigger[0].upper() + trigger[1:] 204 | args.direct_answer_trigger_for_zeroshot_cot = args.direct_answer_trigger 205 | args.direct_answer_trigger_for_fewshot = "The answer is" 206 | args.cot_trigger = "Let's think step by step." 207 | 208 | return args 209 | 210 | if __name__ == "__main__": 211 | main() -------------------------------------------------------------------------------- /try_cot.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "ExecuteTime": { 8 | "end_time": "2022-10-14T22:40:48.009758Z", 9 | "start_time": "2022-10-14T22:40:44.952090Z" 10 | }, 11 | "pycharm": { 12 | "name": "#%%\n" 13 | } 14 | }, 15 | "outputs": [ 16 | { 17 | "name": "stdout", 18 | "output_type": "stream", 19 | "text": [ 20 | "Example: Zero-Shot\n", 21 | "*****************************\n", 22 | "Test Question:\n", 23 | "There were 10 friends playing a video game online when 7 players quit. If each player left had 8 lives, how many lives did they have total?\n", 24 | "*****************************\n", 25 | "Prompted Input:\n", 26 | "Q: There were 10 friends playing a video game online when 7 players quit. If each player left had 8 lives, how many lives did they have total?\n", 27 | "A: The answer is\n", 28 | "*****************************\n", 29 | "Output:\n", 30 | "80.\n", 31 | "*****************************\n" 32 | ] 33 | } 34 | ], 35 | "source": [ 36 | "import sys\n", 37 | "sys.argv=['']\n", 38 | "del sys\n", 39 | "from api import cot\n", 40 | "\n", 41 | "question = \"There were 10 friends playing a video game online when 7 players quit. If each player left had 8 lives, how many lives did they have total?\"\n", 42 | "print(\"Example: Zero-Shot\")\n", 43 | "# To use GPT-3, please add your openai-api key in utils.py (#Line 59)\n", 44 | "# method = [\"zero_shot\", \"zero_shot_cot\", \"manual_cot\", \"auto_cot\"]\n", 45 | "cot(method=\"zero_shot\", question=question)" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": 2, 51 | "metadata": { 52 | "ExecuteTime": { 53 | "end_time": "2022-10-14T22:40:53.793176Z", 54 | "start_time": "2022-10-14T22:40:48.012903Z" 55 | }, 56 | "pycharm": { 57 | "name": "#%%\n" 58 | } 59 | }, 60 | "outputs": [ 61 | { 62 | "name": "stdout", 63 | "output_type": "stream", 64 | "text": [ 65 | "Example: Zero-Shot-CoT\n", 66 | "*****************************\n", 67 | "Test Question:\n", 68 | "There were 10 friends playing a video game online when 7 players quit. If each player left had 8 lives, how many lives did they have total?\n", 69 | "*****************************\n", 70 | "Prompted Input:\n", 71 | "Q: There were 10 friends playing a video game online when 7 players quit. If each player left had 8 lives, how many lives did they have total?\n", 72 | "A: Let's think step by step.\n", 73 | "*****************************\n", 74 | "Output:\n", 75 | "There were 10 friends playing a video game online. This means that, at the start, there were 10 x 8 = 80 lives in total. Then, 7 players quit. This means that 7 x 8 = 56 lives were lost. Therefore, the total number of lives remaining is 80 - 56 = 24. The answer is 24.\n", 76 | "*****************************\n" 77 | ] 78 | } 79 | ], 80 | "source": [ 81 | "from api import cot\n", 82 | "question = \"There were 10 friends playing a video game online when 7 players quit. If each player left had 8 lives, how many lives did they have total?\"\n", 83 | "print(\"Example: Zero-Shot-CoT\")\n", 84 | "cot(method=\"zero_shot_cot\", question=question)" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": 3, 90 | "metadata": { 91 | "ExecuteTime": { 92 | "end_time": "2022-10-14T22:40:56.393930Z", 93 | "start_time": "2022-10-14T22:40:53.795253Z" 94 | }, 95 | "pycharm": { 96 | "name": "#%%\n" 97 | } 98 | }, 99 | "outputs": [ 100 | { 101 | "name": "stdout", 102 | "output_type": "stream", 103 | "text": [ 104 | "Example: Manual-CoT\n", 105 | "*****************************\n", 106 | "Test Question:\n", 107 | "In a video game, each enemy defeated gives you 7 points. If a level has 11 enemies total and you destroy all but 8 of them, how many points would you earn?\n", 108 | "*****************************\n", 109 | "Prompted Input:\n", 110 | "Q: There are 15 trees in the grove. Grove workers will plant trees in the grove today. After they are done, there will be 21 trees. How many trees did the grove workers plant today?\n", 111 | "A: There are 15 trees originally. Then there were 21 trees after some more were planted. So there must have been 21 - 15 = 6. The answer is 6.\n", 112 | "Q: If there are 3 cars in the parking lot and 2 more cars arrive, how many cars are in the parking lot?\n", 113 | "A: There are originally 3 cars. 2 more cars arrive. 3 + 2 = 5. The answer is 5.\n", 114 | "Q: Leah had 32 chocolates and her sister had 42. If they ate 35, how many pieces do they have left in total?\n", 115 | "A: Originally, Leah had 32 chocolates. Her sister had 42. So in total they had 32 + 42 = 74. After eating 35, they had 74 - 35 = 39. The answer is 39.\n", 116 | "Q: Jason had 20 lollipops. He gave Denny some lollipops. Now Jason has 12 lollipops. How many lollipops did Jason give to Denny?\n", 117 | "A: Jason started with 20 lollipops. Then he had 12 after giving some to Denny. So he gave Denny 20 - 12 = 8. The answer is 8.\n", 118 | "Q: Shawn has five toys. For Christmas, he got two toys each from his mom and dad. How many toys does he have now?\n", 119 | "A: Shawn started with 5 toys. If he got 2 toys each from his mom and dad, then that is 4 more toys. 5 + 4 = 9. The answer is 9.\n", 120 | "Q: There were nine computers in the server room. Five more computers were installed each day, from monday to thursday. How many computers are now in the server room?\n", 121 | "A: There were originally 9 computers. For each of 4 days, 5 more computers were added. So 5 * 4 = 20 computers were added. 9 + 20 is 29. The answer is 29.\n", 122 | "Q: Michael had 58 golf balls. On tuesday, he lost 23 golf balls. On wednesday, he lost 2 more. How many golf balls did he have at the end of wednesday?\n", 123 | "A: Michael started with 58 golf balls. After losing 23 on tuesday, he had 58 - 23 = 35. After losing 2 more, he had 35 - 2 = 33 golf balls. The answer is 33.\n", 124 | "Q: Olivia has $23. She bought five bagels for $3 each. How much money does she have left?\n", 125 | "A: Olivia had 23 dollars. 5 bagels for 3 dollars each will be 5 x 3 = 15 dollars. So she has 23 - 15 dollars left. 23 - 15 is 8. The answer is 8.\n", 126 | "Q: In a video game, each enemy defeated gives you 7 points. If a level has 11 enemies total and you destroy all but 8 of them, how many points would you earn?\n", 127 | "A:\n", 128 | "*****************************\n", 129 | "Output:\n", 130 | "You would earn 7 points for each enemy you defeat. So you would earn 7 * 11 = 77 points.\n", 131 | "*****************************\n" 132 | ] 133 | } 134 | ], 135 | "source": [ 136 | "from api import cot\n", 137 | "question = \"In a video game, each enemy defeated gives you 7 points. If a level has 11 enemies total and you destroy all but 8 of them, how many points would you earn?\"\n", 138 | "print(\"Example: Manual-CoT\")\n", 139 | "cot(method=\"manual_cot\", question=question)" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": 4, 145 | "metadata": { 146 | "ExecuteTime": { 147 | "end_time": "2022-10-14T22:41:00.702149Z", 148 | "start_time": "2022-10-14T22:40:56.396849Z" 149 | }, 150 | "pycharm": { 151 | "name": "#%%\n" 152 | } 153 | }, 154 | "outputs": [ 155 | { 156 | "name": "stdout", 157 | "output_type": "stream", 158 | "text": [ 159 | "Example: Auto-CoT\n", 160 | "*****************************\n", 161 | "Test Question:\n", 162 | "In a video game, each enemy defeated gives you 7 points. If a level has 11 enemies total and you destroy all but 8 of them, how many points would you earn?\n", 163 | "*****************************\n", 164 | "Prompted Input:\n", 165 | "Q: Wendy uploaded 45 pictures to Facebook. She put 27 pics into one album and put the rest into 9 different albums. How many pictures were in each album?\n", 166 | "A: Let's think step by step. First, we know that Wendy uploaded 45 pictures in total. Second, we know that Wendy put 27 pictures into one album. That means that Wendy put the remaining 18 pictures into 9 different albums. That means that each album would have 2 pictures. The answer is 2.\n", 167 | "Q: For Halloween Katie and her sister combined the candy they received. Katie had 8 pieces of candy while her sister had 23. If they ate 8 pieces the first night, how many pieces do they have left?\n", 168 | "A: Let's think step by step. Katie and her sister have a total of 8 + 23 = 31 pieces of candy. If they eat 8 pieces the first night, they have 31 - 8 = 23 pieces left. The answer is 23.\n", 169 | "Q: Bianca was organizing her book case making sure each of the shelves had exactly 8 books on it. If she had 5 shelves of mystery books and 4 shelves of picture books, how many books did she have total?\n", 170 | "A: Let's think step by step. There are 5 shelves of mystery books. Each shelf has 8 books. So that's 40 mystery books. There are 4 shelves of picture books. Each shelf has 8 books. So that's 32 picture books. 40 + 32 = 72 books. The answer is 72.\n", 171 | "Q: A pet store had 78 puppies. In one day they sold 30 of them and put the rest into cages with 8 in each cage. How many cages did they use?\n", 172 | "A: Let's think step by step. There are 78 puppies. 30 are sold, so that means there are 48 left. 48 divided by 8 is 6, so that means there are 6 cages with 8 puppies in each. The answer is 6.\n", 173 | "Q: A waiter had 14 customers to wait on. If 3 customers left and he got another 39 customers, how many customers would he have?\n", 174 | "A: Let's think step by step. The waiter had 14 customers to wait on. If 3 customers left, that means he would have 11 customers left. If he got another 39 customers, that means he would have 50 customers in total. The answer is 50.\n", 175 | "Q: A trivia team had 7 members total, but during a game 2 members didn't show up. If each member that did show up scored 4 points, how many points were scored total?\n", 176 | "A: Let's think step by step. There were 7 members on the team, but 2 members didn't show up. That means that there were 5 members that did show up. Each member that showed up scored 4 points. So if 5 members each scored 4 points, then the total number of points scored would be 5*4=20. The answer is 20.\n", 177 | "Q: Gwen had 18 math problems and 11 science problems for homework. If she finished 24 of the problems at school, how many problems did she have to do for homework?\n", 178 | "A: Let's think step by step. Gwen had 18 math problems and 11 science problems for homework. That means she had a total of 29 problems for homework. If she finished 24 of the problems at school, that means she had 5 problems left to do for homework. The answer is 5.\n", 179 | "Q: Mike made 69 dollars mowing lawns over the summer. If he spent 24 dollars buying new mower blades, how many 5 dollar games could he buy with the money he had left?\n", 180 | "A: Let's think step by step. Mike made $69 from mowing lawns. He spent $24 on new mower blades. That means he has $45 left. Each game costs $5, so he could buy 9 games. The answer is 9.\n", 181 | "Q: In a video game, each enemy defeated gives you 7 points. If a level has 11 enemies total and you destroy all but 8 of them, how many points would you earn?\n", 182 | "A: Let's think step by step.\n", 183 | "*****************************\n", 184 | "Output:\n", 185 | "Each enemy defeated gives you 7 points. If there are 11 enemies and you destroy all but 8 of them, that means you would have destroyed 3 enemies. 3 enemies * 7 points = 21 points. The answer is 21.\n", 186 | "*****************************\n" 187 | ] 188 | } 189 | ], 190 | "source": [ 191 | "from api import cot\n", 192 | "question = \"In a video game, each enemy defeated gives you 7 points. If a level has 11 enemies total and you destroy all but 8 of them, how many points would you earn?\"\n", 193 | "print(\"Example: Auto-CoT\")\n", 194 | "cot(method=\"auto_cot\", question=question)\n" 195 | ] 196 | } 197 | ], 198 | "metadata": { 199 | "kernelspec": { 200 | "display_name": "Python 3 (ipykernel)", 201 | "language": "python", 202 | "name": "python3" 203 | }, 204 | "language_info": { 205 | "codemirror_mode": { 206 | "name": "ipython", 207 | "version": 3 208 | }, 209 | "file_extension": ".py", 210 | "mimetype": "text/x-python", 211 | "name": "python", 212 | "nbconvert_exporter": "python", 213 | "pygments_lexer": "ipython3", 214 | "version": "3.9.12" 215 | } 216 | }, 217 | "nbformat": 4, 218 | "nbformat_minor": 1 219 | } 220 | -------------------------------------------------------------------------------- /try_cot_colab.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "provenance": [] 7 | }, 8 | "kernelspec": { 9 | "name": "python3", 10 | "display_name": "Python 3" 11 | }, 12 | "language_info": { 13 | "name": "python" 14 | } 15 | }, 16 | "cells": [ 17 | { 18 | "cell_type": "code", 19 | "source": [ 20 | "import os" 21 | ], 22 | "metadata": { 23 | "id": "MCwLqbJRv3i8" 24 | }, 25 | "execution_count": 10, 26 | "outputs": [] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "source": [ 31 | "from google.colab import drive\n", 32 | "drive.mount('/content/drive')" 33 | ], 34 | "metadata": { 35 | "colab": { 36 | "base_uri": "https://localhost:8080/" 37 | }, 38 | "id": "TfSDDIVpCLjK", 39 | "outputId": "ac960a5f-7cdc-4ca5-c4db-6e1e0b646ac0" 40 | }, 41 | "execution_count": 2, 42 | "outputs": [ 43 | { 44 | "output_type": "stream", 45 | "name": "stdout", 46 | "text": [ 47 | "Mounted at /content/drive\n" 48 | ] 49 | } 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "source": [ 55 | "openai_key = open('/content/drive/MyDrive/colab/openai-secret.txt').read()\n", 56 | "os.environ[\"OPENAI_API_KEY\"] = openai_key" 57 | ], 58 | "metadata": { 59 | "id": "3JIDuSeVv4uY" 60 | }, 61 | "execution_count": 3, 62 | "outputs": [] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": 4, 67 | "metadata": { 68 | "id": "JrC2JhrAuekq", 69 | "colab": { 70 | "base_uri": "https://localhost:8080/" 71 | }, 72 | "outputId": "c115c8d0-2367-40b4-aa1b-9ae954599a4c" 73 | }, 74 | "outputs": [ 75 | { 76 | "output_type": "stream", 77 | "name": "stdout", 78 | "text": [ 79 | "Cloning into 'auto-cot'...\n", 80 | "remote: Enumerating objects: 69, done.\u001b[K\n", 81 | "remote: Counting objects: 100% (69/69), done.\u001b[K\n", 82 | "remote: Compressing objects: 100% (50/50), done.\u001b[K\n", 83 | "remote: Total 69 (delta 31), reused 46 (delta 15), pack-reused 0\u001b[K\n", 84 | "Unpacking objects: 100% (69/69), done.\n", 85 | "/content/auto-cot\n" 86 | ] 87 | } 88 | ], 89 | "source": [ 90 | "!git clone https://github.com/amazon-science/auto-cot.git\n", 91 | "%cd auto-cot" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "source": [ 97 | "!pip install -r requirements.txt\n", 98 | "!pip install openai" 99 | ], 100 | "metadata": { 101 | "colab": { 102 | "base_uri": "https://localhost:8080/" 103 | }, 104 | "id": "22f_crJdvGRU", 105 | "outputId": "587c6b75-6ba6-4509-f7a2-3aee6719e698" 106 | }, 107 | "execution_count": 5, 108 | "outputs": [ 109 | { 110 | "output_type": "stream", 111 | "name": "stdout", 112 | "text": [ 113 | "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n", 114 | "Collecting sklearn\n", 115 | " Downloading sklearn-0.0.post1.tar.gz (3.6 kB)\n", 116 | "Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from -r requirements.txt (line 2)) (3.2.2)\n", 117 | "Collecting sentence-transformers\n", 118 | " Downloading sentence-transformers-2.2.2.tar.gz (85 kB)\n", 119 | "\u001b[K |████████████████████████████████| 85 kB 2.9 MB/s \n", 120 | "\u001b[?25hCollecting jupyter\n", 121 | " Downloading jupyter-1.0.0-py2.py3-none-any.whl (2.7 kB)\n", 122 | "Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r requirements.txt (line 2)) (1.4.4)\n", 123 | "Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r requirements.txt (line 2)) (2.8.2)\n", 124 | "Requirement already satisfied: numpy>=1.11 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r requirements.txt (line 2)) (1.21.6)\n", 125 | "Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r requirements.txt (line 2)) (0.11.0)\n", 126 | "Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->-r requirements.txt (line 2)) (3.0.9)\n", 127 | "Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from kiwisolver>=1.0.1->matplotlib->-r requirements.txt (line 2)) (4.1.1)\n", 128 | "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.1->matplotlib->-r requirements.txt (line 2)) (1.15.0)\n", 129 | "Collecting transformers<5.0.0,>=4.6.0\n", 130 | " Downloading transformers-4.25.1-py3-none-any.whl (5.8 MB)\n", 131 | "\u001b[K |████████████████████████████████| 5.8 MB 36.3 MB/s \n", 132 | "\u001b[?25hRequirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from sentence-transformers->-r requirements.txt (line 3)) (4.64.1)\n", 133 | "Requirement already satisfied: torch>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from sentence-transformers->-r requirements.txt (line 3)) (1.12.1+cu113)\n", 134 | "Requirement already satisfied: torchvision in /usr/local/lib/python3.7/dist-packages (from sentence-transformers->-r requirements.txt (line 3)) (0.13.1+cu113)\n", 135 | "Requirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from sentence-transformers->-r requirements.txt (line 3)) (1.0.2)\n", 136 | "Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from sentence-transformers->-r requirements.txt (line 3)) (1.7.3)\n", 137 | "Requirement already satisfied: nltk in /usr/local/lib/python3.7/dist-packages (from sentence-transformers->-r requirements.txt (line 3)) (3.7)\n", 138 | "Collecting sentencepiece\n", 139 | " Downloading sentencepiece-0.1.97-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.3 MB)\n", 140 | "\u001b[K |████████████████████████████████| 1.3 MB 63.8 MB/s \n", 141 | "\u001b[?25hCollecting huggingface-hub>=0.4.0\n", 142 | " Downloading huggingface_hub-0.11.1-py3-none-any.whl (182 kB)\n", 143 | "\u001b[K |████████████████████████████████| 182 kB 36.2 MB/s \n", 144 | "\u001b[?25hRequirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.7/dist-packages (from huggingface-hub>=0.4.0->sentence-transformers->-r requirements.txt (line 3)) (6.0)\n", 145 | "Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from huggingface-hub>=0.4.0->sentence-transformers->-r requirements.txt (line 3)) (4.13.0)\n", 146 | "Requirement already satisfied: packaging>=20.9 in /usr/local/lib/python3.7/dist-packages (from huggingface-hub>=0.4.0->sentence-transformers->-r requirements.txt (line 3)) (21.3)\n", 147 | "Requirement already satisfied: filelock in /usr/local/lib/python3.7/dist-packages (from huggingface-hub>=0.4.0->sentence-transformers->-r requirements.txt (line 3)) (3.8.0)\n", 148 | "Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from huggingface-hub>=0.4.0->sentence-transformers->-r requirements.txt (line 3)) (2.23.0)\n", 149 | "Collecting tokenizers!=0.11.3,<0.14,>=0.11.1\n", 150 | " Downloading tokenizers-0.13.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (7.6 MB)\n", 151 | "\u001b[K |████████████████████████████████| 7.6 MB 35.8 MB/s \n", 152 | "\u001b[?25hRequirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.7/dist-packages (from transformers<5.0.0,>=4.6.0->sentence-transformers->-r requirements.txt (line 3)) (2022.6.2)\n", 153 | "Collecting qtconsole\n", 154 | " Downloading qtconsole-5.4.0-py3-none-any.whl (121 kB)\n", 155 | "\u001b[K |████████████████████████████████| 121 kB 48.3 MB/s \n", 156 | "\u001b[?25hRequirement already satisfied: nbconvert in /usr/local/lib/python3.7/dist-packages (from jupyter->-r requirements.txt (line 4)) (5.6.1)\n", 157 | "Requirement already satisfied: ipywidgets in /usr/local/lib/python3.7/dist-packages (from jupyter->-r requirements.txt (line 4)) (7.7.1)\n", 158 | "Requirement already satisfied: jupyter-console in /usr/local/lib/python3.7/dist-packages (from jupyter->-r requirements.txt (line 4)) (6.1.0)\n", 159 | "Requirement already satisfied: notebook in /usr/local/lib/python3.7/dist-packages (from jupyter->-r requirements.txt (line 4)) (5.7.16)\n", 160 | "Requirement already satisfied: ipykernel in /usr/local/lib/python3.7/dist-packages (from jupyter->-r requirements.txt (line 4)) (5.3.4)\n", 161 | "Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->huggingface-hub>=0.4.0->sentence-transformers->-r requirements.txt (line 3)) (3.10.0)\n", 162 | "Requirement already satisfied: traitlets>=4.1.0 in /usr/local/lib/python3.7/dist-packages (from ipykernel->jupyter->-r requirements.txt (line 4)) (5.1.1)\n", 163 | "Requirement already satisfied: tornado>=4.2 in /usr/local/lib/python3.7/dist-packages (from ipykernel->jupyter->-r requirements.txt (line 4)) (6.0.4)\n", 164 | "Requirement already satisfied: ipython>=5.0.0 in /usr/local/lib/python3.7/dist-packages (from ipykernel->jupyter->-r requirements.txt (line 4)) (7.9.0)\n", 165 | "Requirement already satisfied: jupyter-client in /usr/local/lib/python3.7/dist-packages (from ipykernel->jupyter->-r requirements.txt (line 4)) (6.1.12)\n", 166 | "Requirement already satisfied: pexpect in /usr/local/lib/python3.7/dist-packages (from ipython>=5.0.0->ipykernel->jupyter->-r requirements.txt (line 4)) (4.8.0)\n", 167 | "Requirement already satisfied: prompt-toolkit<2.1.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from ipython>=5.0.0->ipykernel->jupyter->-r requirements.txt (line 4)) (2.0.10)\n", 168 | "Collecting jedi>=0.10\n", 169 | " Downloading jedi-0.18.2-py2.py3-none-any.whl (1.6 MB)\n", 170 | "\u001b[K |████████████████████████████████| 1.6 MB 21.1 MB/s \n", 171 | "\u001b[?25hRequirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython>=5.0.0->ipykernel->jupyter->-r requirements.txt (line 4)) (4.4.2)\n", 172 | "Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython>=5.0.0->ipykernel->jupyter->-r requirements.txt (line 4)) (0.7.5)\n", 173 | "Requirement already satisfied: backcall in /usr/local/lib/python3.7/dist-packages (from ipython>=5.0.0->ipykernel->jupyter->-r requirements.txt (line 4)) (0.2.0)\n", 174 | "Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.7/dist-packages (from ipython>=5.0.0->ipykernel->jupyter->-r requirements.txt (line 4)) (57.4.0)\n", 175 | "Requirement already satisfied: pygments in /usr/local/lib/python3.7/dist-packages (from ipython>=5.0.0->ipykernel->jupyter->-r requirements.txt (line 4)) (2.6.1)\n", 176 | "Requirement already satisfied: parso<0.9.0,>=0.8.0 in /usr/local/lib/python3.7/dist-packages (from jedi>=0.10->ipython>=5.0.0->ipykernel->jupyter->-r requirements.txt (line 4)) (0.8.3)\n", 177 | "Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.1.0,>=2.0.0->ipython>=5.0.0->ipykernel->jupyter->-r requirements.txt (line 4)) (0.2.5)\n", 178 | "Requirement already satisfied: jupyterlab-widgets>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->jupyter->-r requirements.txt (line 4)) (3.0.3)\n", 179 | "Requirement already satisfied: ipython-genutils~=0.2.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->jupyter->-r requirements.txt (line 4)) (0.2.0)\n", 180 | "Requirement already satisfied: widgetsnbextension~=3.6.0 in /usr/local/lib/python3.7/dist-packages (from ipywidgets->jupyter->-r requirements.txt (line 4)) (3.6.1)\n", 181 | "Requirement already satisfied: Send2Trash in /usr/local/lib/python3.7/dist-packages (from notebook->jupyter->-r requirements.txt (line 4)) (1.8.0)\n", 182 | "Requirement already satisfied: jinja2<=3.0.0 in /usr/local/lib/python3.7/dist-packages (from notebook->jupyter->-r requirements.txt (line 4)) (2.11.3)\n", 183 | "Requirement already satisfied: pyzmq>=17 in /usr/local/lib/python3.7/dist-packages (from notebook->jupyter->-r requirements.txt (line 4)) (23.2.1)\n", 184 | "Requirement already satisfied: terminado>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from notebook->jupyter->-r requirements.txt (line 4)) (0.13.3)\n", 185 | "Requirement already satisfied: nbformat in /usr/local/lib/python3.7/dist-packages (from notebook->jupyter->-r requirements.txt (line 4)) (5.7.0)\n", 186 | "Requirement already satisfied: jupyter-core>=4.4.0 in /usr/local/lib/python3.7/dist-packages (from notebook->jupyter->-r requirements.txt (line 4)) (4.11.2)\n", 187 | "Requirement already satisfied: prometheus-client in /usr/local/lib/python3.7/dist-packages (from notebook->jupyter->-r requirements.txt (line 4)) (0.15.0)\n", 188 | "Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2<=3.0.0->notebook->jupyter->-r requirements.txt (line 4)) (2.0.1)\n", 189 | "Requirement already satisfied: mistune<2,>=0.8.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->jupyter->-r requirements.txt (line 4)) (0.8.4)\n", 190 | "Requirement already satisfied: pandocfilters>=1.4.1 in /usr/local/lib/python3.7/dist-packages (from nbconvert->jupyter->-r requirements.txt (line 4)) (1.5.0)\n", 191 | "Requirement already satisfied: entrypoints>=0.2.2 in /usr/local/lib/python3.7/dist-packages (from nbconvert->jupyter->-r requirements.txt (line 4)) (0.4)\n", 192 | "Requirement already satisfied: defusedxml in /usr/local/lib/python3.7/dist-packages (from nbconvert->jupyter->-r requirements.txt (line 4)) (0.7.1)\n", 193 | "Requirement already satisfied: testpath in /usr/local/lib/python3.7/dist-packages (from nbconvert->jupyter->-r requirements.txt (line 4)) (0.6.0)\n", 194 | "Requirement already satisfied: bleach in /usr/local/lib/python3.7/dist-packages (from nbconvert->jupyter->-r requirements.txt (line 4)) (5.0.1)\n", 195 | "Requirement already satisfied: jsonschema>=2.6 in /usr/local/lib/python3.7/dist-packages (from nbformat->notebook->jupyter->-r requirements.txt (line 4)) (4.3.3)\n", 196 | "Requirement already satisfied: fastjsonschema in /usr/local/lib/python3.7/dist-packages (from nbformat->notebook->jupyter->-r requirements.txt (line 4)) (2.16.2)\n", 197 | "Requirement already satisfied: importlib-resources>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema>=2.6->nbformat->notebook->jupyter->-r requirements.txt (line 4)) (5.10.0)\n", 198 | "Requirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema>=2.6->nbformat->notebook->jupyter->-r requirements.txt (line 4)) (22.1.0)\n", 199 | "Requirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema>=2.6->nbformat->notebook->jupyter->-r requirements.txt (line 4)) (0.19.2)\n", 200 | "Requirement already satisfied: ptyprocess in /usr/local/lib/python3.7/dist-packages (from terminado>=0.8.1->notebook->jupyter->-r requirements.txt (line 4)) (0.7.0)\n", 201 | "Requirement already satisfied: webencodings in /usr/local/lib/python3.7/dist-packages (from bleach->nbconvert->jupyter->-r requirements.txt (line 4)) (0.5.1)\n", 202 | "Requirement already satisfied: click in /usr/local/lib/python3.7/dist-packages (from nltk->sentence-transformers->-r requirements.txt (line 3)) (7.1.2)\n", 203 | "Requirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from nltk->sentence-transformers->-r requirements.txt (line 3)) (1.2.0)\n", 204 | "Collecting qtpy>=2.0.1\n", 205 | " Downloading QtPy-2.3.0-py3-none-any.whl (83 kB)\n", 206 | "\u001b[K |████████████████████████████████| 83 kB 1.9 MB/s \n", 207 | "\u001b[?25hRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->huggingface-hub>=0.4.0->sentence-transformers->-r requirements.txt (line 3)) (2.10)\n", 208 | "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->huggingface-hub>=0.4.0->sentence-transformers->-r requirements.txt (line 3)) (2022.9.24)\n", 209 | "Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->huggingface-hub>=0.4.0->sentence-transformers->-r requirements.txt (line 3)) (1.24.3)\n", 210 | "Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->huggingface-hub>=0.4.0->sentence-transformers->-r requirements.txt (line 3)) (3.0.4)\n", 211 | "Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->sentence-transformers->-r requirements.txt (line 3)) (3.1.0)\n", 212 | "Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /usr/local/lib/python3.7/dist-packages (from torchvision->sentence-transformers->-r requirements.txt (line 3)) (7.1.2)\n", 213 | "Building wheels for collected packages: sklearn, sentence-transformers\n", 214 | " Building wheel for sklearn (setup.py) ... \u001b[?25l\u001b[?25hdone\n", 215 | " Created wheel for sklearn: filename=sklearn-0.0.post1-py3-none-any.whl size=2344 sha256=23d529ecd9c965be6ed8486cb04bc694fa4836906291ad6e9ab240ad8b0b03be\n", 216 | " Stored in directory: /root/.cache/pip/wheels/42/56/cc/4a8bf86613aafd5b7f1b310477667c1fca5c51c3ae4124a003\n", 217 | " Building wheel for sentence-transformers (setup.py) ... \u001b[?25l\u001b[?25hdone\n", 218 | " Created wheel for sentence-transformers: filename=sentence_transformers-2.2.2-py3-none-any.whl size=125938 sha256=c3344b56823ffb2269701c81229a2f42cfcb99b54163dead5b909bee3af83aab\n", 219 | " Stored in directory: /root/.cache/pip/wheels/bf/06/fb/d59c1e5bd1dac7f6cf61ec0036cc3a10ab8fecaa6b2c3d3ee9\n", 220 | "Successfully built sklearn sentence-transformers\n", 221 | "Installing collected packages: jedi, tokenizers, qtpy, huggingface-hub, transformers, sentencepiece, qtconsole, sklearn, sentence-transformers, jupyter\n", 222 | "Successfully installed huggingface-hub-0.11.1 jedi-0.18.2 jupyter-1.0.0 qtconsole-5.4.0 qtpy-2.3.0 sentence-transformers-2.2.2 sentencepiece-0.1.97 sklearn-0.0.post1 tokenizers-0.13.2 transformers-4.25.1\n", 223 | "Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n", 224 | "Collecting openai\n", 225 | " Downloading openai-0.25.0.tar.gz (44 kB)\n", 226 | "\u001b[K |████████████████████████████████| 44 kB 2.0 MB/s \n", 227 | "\u001b[?25h Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n", 228 | " Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n", 229 | " Preparing wheel metadata ... \u001b[?25l\u001b[?25hdone\n", 230 | "Collecting pandas-stubs>=1.1.0.11\n", 231 | " Downloading pandas_stubs-1.2.0.62-py3-none-any.whl (163 kB)\n", 232 | "\u001b[K |████████████████████████████████| 163 kB 10.3 MB/s \n", 233 | "\u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from openai) (1.21.6)\n", 234 | "Requirement already satisfied: requests>=2.20 in /usr/local/lib/python3.7/dist-packages (from openai) (2.23.0)\n", 235 | "Requirement already satisfied: openpyxl>=3.0.7 in /usr/local/lib/python3.7/dist-packages (from openai) (3.0.10)\n", 236 | "Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from openai) (4.1.1)\n", 237 | "Requirement already satisfied: pandas>=1.2.3 in /usr/local/lib/python3.7/dist-packages (from openai) (1.3.5)\n", 238 | "Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from openai) (4.64.1)\n", 239 | "Requirement already satisfied: et-xmlfile in /usr/local/lib/python3.7/dist-packages (from openpyxl>=3.0.7->openai) (1.1.0)\n", 240 | "Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=1.2.3->openai) (2022.6)\n", 241 | "Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=1.2.3->openai) (2.8.2)\n", 242 | "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=1.2.3->openai) (1.15.0)\n", 243 | "Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.20->openai) (3.0.4)\n", 244 | "Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.20->openai) (1.24.3)\n", 245 | "Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.20->openai) (2.10)\n", 246 | "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.20->openai) (2022.9.24)\n", 247 | "Building wheels for collected packages: openai\n", 248 | " Building wheel for openai (PEP 517) ... \u001b[?25l\u001b[?25hdone\n", 249 | " Created wheel for openai: filename=openai-0.25.0-py3-none-any.whl size=55880 sha256=a5900898c8c80b88f1d6c7012891c50dd571ee77e477d3baac03082cde15c26e\n", 250 | " Stored in directory: /root/.cache/pip/wheels/19/de/db/e82770b480ec30fd4a6d67108744b9c52be167c04fcf4af7b5\n", 251 | "Successfully built openai\n", 252 | "Installing collected packages: pandas-stubs, openai\n", 253 | "Successfully installed openai-0.25.0 pandas-stubs-1.2.0.62\n" 254 | ] 255 | } 256 | ] 257 | }, 258 | { 259 | "cell_type": "code", 260 | "source": [ 261 | "import sys\n", 262 | "sys.argv=['']\n", 263 | "del sys\n", 264 | "from api import cot\n", 265 | "\n", 266 | "question = \"There were 10 friends playing a video game online when 7 players quit. If each player left had 8 lives, how many lives did they have total?\"\n", 267 | "print(\"Example: Zero-Shot\")\n", 268 | "# To use GPT-3, please add your openai-api key in utils.py (#Line 59)\n", 269 | "# method = [\"zero_shot\", \"zero_shot_cot\", \"manual_cot\", \"auto_cot\"]\n", 270 | "cot(method=\"zero_shot\", question=question)\n" 271 | ], 272 | "metadata": { 273 | "colab": { 274 | "base_uri": "https://localhost:8080/" 275 | }, 276 | "id": "uL9l1b2zu7Vc", 277 | "outputId": "4c9b326b-7bb5-4a9c-c284-11c7ae24de8c" 278 | }, 279 | "execution_count": 6, 280 | "outputs": [ 281 | { 282 | "output_type": "stream", 283 | "name": "stdout", 284 | "text": [ 285 | "Example: Zero-Shot\n", 286 | "*****************************\n", 287 | "Test Question:\n", 288 | "There were 10 friends playing a video game online when 7 players quit. If each player left had 8 lives, how many lives did they have total?\n", 289 | "*****************************\n", 290 | "Prompted Input:\n", 291 | "Q: There were 10 friends playing a video game online when 7 players quit. If each player left had 8 lives, how many lives did they have total?\n", 292 | "A: The answer is\n", 293 | "*****************************\n", 294 | "Output:\n", 295 | "80.\n", 296 | "*****************************\n" 297 | ] 298 | } 299 | ] 300 | }, 301 | { 302 | "cell_type": "code", 303 | "source": [ 304 | "question = \"There were 10 friends playing a video game online when 7 players quit. If each player left had 8 lives, how many lives did they have total?\"\n", 305 | "print(\"Example: Zero-Shot-CoT\")\n", 306 | "cot(method=\"zero_shot_cot\", question=question)\n", 307 | "\n" 308 | ], 309 | "metadata": { 310 | "colab": { 311 | "base_uri": "https://localhost:8080/" 312 | }, 313 | "id": "2FnwQa_1vA9f", 314 | "outputId": "7697e165-08f8-4fc4-dd8f-f8908f6c5679" 315 | }, 316 | "execution_count": 7, 317 | "outputs": [ 318 | { 319 | "output_type": "stream", 320 | "name": "stdout", 321 | "text": [ 322 | "Example: Zero-Shot-CoT\n", 323 | "*****************************\n", 324 | "Test Question:\n", 325 | "There were 10 friends playing a video game online when 7 players quit. If each player left had 8 lives, how many lives did they have total?\n", 326 | "*****************************\n", 327 | "Prompted Input:\n", 328 | "Q: There were 10 friends playing a video game online when 7 players quit. If each player left had 8 lives, how many lives did they have total?\n", 329 | "A: Let's think step by step.\n", 330 | "*****************************\n", 331 | "Output:\n", 332 | "There were 10 friends playing a video game online. This means that, at the start, there were 10 x 8 = 80 lives in total. Then, 7 players quit. This means that 7 x 8 = 56 lives were lost. Therefore, the total number of lives remaining is 80 - 56 = 24. The answer is 24.\n", 333 | "*****************************\n" 334 | ] 335 | } 336 | ] 337 | }, 338 | { 339 | "cell_type": "code", 340 | "source": [ 341 | "question = \"In a video game, each enemy defeated gives you 7 points. If a level has 11 enemies total and you destroy all but 8 of them, how many points would you earn?\"\n", 342 | "print(\"Example: Manual-CoT\")\n", 343 | "cot(method=\"manual_cot\", question=question)" 344 | ], 345 | "metadata": { 346 | "colab": { 347 | "base_uri": "https://localhost:8080/" 348 | }, 349 | "id": "71IUqt0exS8y", 350 | "outputId": "06cddb14-5f77-4da7-9426-76e0fc3bb754" 351 | }, 352 | "execution_count": 8, 353 | "outputs": [ 354 | { 355 | "output_type": "stream", 356 | "name": "stdout", 357 | "text": [ 358 | "Example: Manual-CoT\n", 359 | "*****************************\n", 360 | "Test Question:\n", 361 | "In a video game, each enemy defeated gives you 7 points. If a level has 11 enemies total and you destroy all but 8 of them, how many points would you earn?\n", 362 | "*****************************\n", 363 | "Prompted Input:\n", 364 | "Q: There are 15 trees in the grove. Grove workers will plant trees in the grove today. After they are done, there will be 21 trees. How many trees did the grove workers plant today?\n", 365 | "A: There are 15 trees originally. Then there were 21 trees after some more were planted. So there must have been 21 - 15 = 6. The answer is 6.\n", 366 | "Q: If there are 3 cars in the parking lot and 2 more cars arrive, how many cars are in the parking lot?\n", 367 | "A: There are originally 3 cars. 2 more cars arrive. 3 + 2 = 5. The answer is 5.\n", 368 | "Q: Leah had 32 chocolates and her sister had 42. If they ate 35, how many pieces do they have left in total?\n", 369 | "A: Originally, Leah had 32 chocolates. Her sister had 42. So in total they had 32 + 42 = 74. After eating 35, they had 74 - 35 = 39. The answer is 39.\n", 370 | "Q: Jason had 20 lollipops. He gave Denny some lollipops. Now Jason has 12 lollipops. How many lollipops did Jason give to Denny?\n", 371 | "A: Jason started with 20 lollipops. Then he had 12 after giving some to Denny. So he gave Denny 20 - 12 = 8. The answer is 8.\n", 372 | "Q: Shawn has five toys. For Christmas, he got two toys each from his mom and dad. How many toys does he have now?\n", 373 | "A: Shawn started with 5 toys. If he got 2 toys each from his mom and dad, then that is 4 more toys. 5 + 4 = 9. The answer is 9.\n", 374 | "Q: There were nine computers in the server room. Five more computers were installed each day, from monday to thursday. How many computers are now in the server room?\n", 375 | "A: There were originally 9 computers. For each of 4 days, 5 more computers were added. So 5 * 4 = 20 computers were added. 9 + 20 is 29. The answer is 29.\n", 376 | "Q: Michael had 58 golf balls. On tuesday, he lost 23 golf balls. On wednesday, he lost 2 more. How many golf balls did he have at the end of wednesday?\n", 377 | "A: Michael started with 58 golf balls. After losing 23 on tuesday, he had 58 - 23 = 35. After losing 2 more, he had 35 - 2 = 33 golf balls. The answer is 33.\n", 378 | "Q: Olivia has $23. She bought five bagels for $3 each. How much money does she have left?\n", 379 | "A: Olivia had 23 dollars. 5 bagels for 3 dollars each will be 5 x 3 = 15 dollars. So she has 23 - 15 dollars left. 23 - 15 is 8. The answer is 8.\n", 380 | "Q: In a video game, each enemy defeated gives you 7 points. If a level has 11 enemies total and you destroy all but 8 of them, how many points would you earn?\n", 381 | "A:\n", 382 | "*****************************\n", 383 | "Output:\n", 384 | "You would earn 7 points for each enemy you defeat. So you would earn 7 * 11 = 77 points.\n", 385 | "*****************************\n" 386 | ] 387 | } 388 | ] 389 | }, 390 | { 391 | "cell_type": "code", 392 | "source": [ 393 | "question = \"In a video game, each enemy defeated gives you 7 points. If a level has 11 enemies total and you destroy all but 8 of them, how many points would you earn?\"\n", 394 | "print(\"Example: Auto-CoT\")\n", 395 | "cot(method=\"auto_cot\", question=question)\n" 396 | ], 397 | "metadata": { 398 | "colab": { 399 | "base_uri": "https://localhost:8080/" 400 | }, 401 | "id": "2rIpKGDbxVIN", 402 | "outputId": "6ff0ca6b-5e2c-4003-f6c7-006bb434aec1" 403 | }, 404 | "execution_count": 9, 405 | "outputs": [ 406 | { 407 | "output_type": "stream", 408 | "name": "stdout", 409 | "text": [ 410 | "Example: Auto-CoT\n", 411 | "*****************************\n", 412 | "Test Question:\n", 413 | "In a video game, each enemy defeated gives you 7 points. If a level has 11 enemies total and you destroy all but 8 of them, how many points would you earn?\n", 414 | "*****************************\n", 415 | "Prompted Input:\n", 416 | "Q: Wendy uploaded 45 pictures to Facebook. She put 27 pics into one album and put the rest into 9 different albums. How many pictures were in each album?\n", 417 | "A: Let's think step by step. First, we know that Wendy uploaded 45 pictures in total. Second, we know that Wendy put 27 pictures into one album. That means that Wendy put the remaining 18 pictures into 9 different albums. That means that each album would have 2 pictures. The answer is 2.\n", 418 | "Q: For Halloween Katie and her sister combined the candy they received. Katie had 8 pieces of candy while her sister had 23. If they ate 8 pieces the first night, how many pieces do they have left?\n", 419 | "A: Let's think step by step. Katie and her sister have a total of 8 + 23 = 31 pieces of candy. If they eat 8 pieces the first night, they have 31 - 8 = 23 pieces left. The answer is 23.\n", 420 | "Q: Bianca was organizing her book case making sure each of the shelves had exactly 8 books on it. If she had 5 shelves of mystery books and 4 shelves of picture books, how many books did she have total?\n", 421 | "A: Let's think step by step. There are 5 shelves of mystery books. Each shelf has 8 books. So that's 40 mystery books. There are 4 shelves of picture books. Each shelf has 8 books. So that's 32 picture books. 40 + 32 = 72 books. The answer is 72.\n", 422 | "Q: A pet store had 78 puppies. In one day they sold 30 of them and put the rest into cages with 8 in each cage. How many cages did they use?\n", 423 | "A: Let's think step by step. There are 78 puppies. 30 are sold, so that means there are 48 left. 48 divided by 8 is 6, so that means there are 6 cages with 8 puppies in each. The answer is 6.\n", 424 | "Q: A waiter had 14 customers to wait on. If 3 customers left and he got another 39 customers, how many customers would he have?\n", 425 | "A: Let's think step by step. The waiter had 14 customers to wait on. If 3 customers left, that means he would have 11 customers left. If he got another 39 customers, that means he would have 50 customers in total. The answer is 50.\n", 426 | "Q: A trivia team had 7 members total, but during a game 2 members didn't show up. If each member that did show up scored 4 points, how many points were scored total?\n", 427 | "A: Let's think step by step. There were 7 members on the team, but 2 members didn't show up. That means that there were 5 members that did show up. Each member that showed up scored 4 points. So if 5 members each scored 4 points, then the total number of points scored would be 5*4=20. The answer is 20.\n", 428 | "Q: Gwen had 18 math problems and 11 science problems for homework. If she finished 24 of the problems at school, how many problems did she have to do for homework?\n", 429 | "A: Let's think step by step. Gwen had 18 math problems and 11 science problems for homework. That means she had a total of 29 problems for homework. If she finished 24 of the problems at school, that means she had 5 problems left to do for homework. The answer is 5.\n", 430 | "Q: Mike made 69 dollars mowing lawns over the summer. If he spent 24 dollars buying new mower blades, how many 5 dollar games could he buy with the money he had left?\n", 431 | "A: Let's think step by step. Mike made $69 from mowing lawns. He spent $24 on new mower blades. That means he has $45 left. Each game costs $5, so he could buy 9 games. The answer is 9.\n", 432 | "Q: In a video game, each enemy defeated gives you 7 points. If a level has 11 enemies total and you destroy all but 8 of them, how many points would you earn?\n", 433 | "A: Let's think step by step.\n", 434 | "*****************************\n", 435 | "Output:\n", 436 | "Each enemy defeated gives you 7 points. If there are 11 enemies and you destroy all but 8 of them, that means you would have destroyed 3 enemies. 3 enemies * 7 points = 21 points. The answer is 21.\n", 437 | "*****************************\n" 438 | ] 439 | } 440 | ] 441 | }, 442 | { 443 | "cell_type": "code", 444 | "source": [], 445 | "metadata": { 446 | "id": "pdq3fSm4CjS_" 447 | }, 448 | "execution_count": null, 449 | "outputs": [] 450 | } 451 | ] 452 | } -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Adapted from https://github.com/kojima-takeshi188/zero_shot_cot 3 | ''' 4 | 5 | from statistics import mean 6 | from torch.utils.data import Dataset 7 | import openai 8 | import os 9 | import multiprocessing 10 | import json 11 | import numpy as np 12 | import torch 13 | import re 14 | import random 15 | import time 16 | import datetime 17 | 18 | def shuffleDict(d): 19 | keys = list(d.keys()) 20 | random.shuffle(keys) 21 | [(key, d[key]) for key in keys] 22 | random.shuffle(keys) 23 | [(key, d[key]) for key in keys] 24 | random.shuffle(keys) 25 | keys = [(key, d[key]) for key in keys] 26 | #keys = d(keys) 27 | return dict(keys) 28 | 29 | def fix_seed(seed): 30 | # random 31 | random.seed(seed) 32 | # Numpy 33 | np.random.seed(seed) 34 | # Pytorch 35 | torch.manual_seed(seed) 36 | torch.cuda.manual_seed_all(seed) 37 | torch.backends.cudnn.deterministic = True 38 | 39 | def print_now(return_flag=0): 40 | t_delta = datetime.timedelta(hours=9) 41 | JST = datetime.timezone(t_delta, 'JST') 42 | now = datetime.datetime.now(JST) 43 | now = now.strftime('%Y/%m/%d %H:%M:%S') 44 | if return_flag == 0: 45 | print(now) 46 | elif return_flag == 1: 47 | return now 48 | else: 49 | pass 50 | 51 | # Sentence Generator (Decoder) for GPT-3 ... 52 | def decoder_for_gpt3(args, input, max_length): 53 | 54 | # GPT-3 API allows each users execute the API within 60 times in a minute ... 55 | # time.sleep(1) 56 | time.sleep(args.api_time_interval) 57 | 58 | # https://beta.openai.com/account/api-keys 59 | # openai.api_key = "[Your OpenAI API Key]" 60 | 61 | # Specify engine ... 62 | # Instruct GPT3 63 | if args.model == "gpt3": 64 | engine = "text-ada-001" 65 | elif args.model == "gpt3-medium": 66 | engine = "text-babbage-001" 67 | elif args.model == "gpt3-large": 68 | engine = "text-curie-001" 69 | elif args.model == "gpt3-xl": 70 | engine = "text-davinci-002" 71 | elif args.model == "text-davinci-001": 72 | engine = "text-davinci-001" 73 | elif args.model == "code-davinci-002": 74 | engine = "code-davinci-002" 75 | else: 76 | raise ValueError("model is not properly defined ...") 77 | 78 | if ("few_shot" in args.method or "auto" in args.method) and engine == "code-davinci-002": 79 | response = openai.Completion.create( 80 | engine=engine, 81 | prompt=input, 82 | max_tokens=max_length, 83 | temperature=args.temperature, 84 | top_p=1, 85 | frequency_penalty=0, 86 | presence_penalty=0, 87 | stop=["\n"] 88 | ) 89 | else: 90 | response = openai.Completion.create( 91 | engine=engine, 92 | prompt=input, 93 | max_tokens=max_length, 94 | temperature=args.temperature, 95 | top_p=1, 96 | frequency_penalty=0, 97 | presence_penalty=0, 98 | stop=None 99 | ) 100 | 101 | return response["choices"][0]["text"] 102 | 103 | class Decoder(): 104 | def __init__(self): 105 | # print_now() 106 | pass 107 | 108 | def decode(self, args, input, max_length): 109 | response = decoder_for_gpt3(args, input, max_length) 110 | return response 111 | 112 | def data_reader(args): 113 | 114 | questions = [] 115 | answers = [] 116 | decoder = json.JSONDecoder() 117 | 118 | if args.dataset == "aqua": 119 | with open(args.dataset_path) as f: 120 | lines = f.readlines() 121 | for line in lines: 122 | json_res = decoder.raw_decode(line)[0] 123 | choice = "(" + "(".join(json_res["options"]) 124 | choice = choice.replace("(", " (").replace(")", ") ") 125 | choice = "Answer Choices:" + choice 126 | questions.append(json_res["question"].strip() + " " + choice) 127 | answers.append(json_res["correct"]) 128 | 129 | elif args.dataset == "gsm8k": 130 | with open(args.dataset_path) as f: 131 | lines = f.readlines() 132 | for line in lines: 133 | json_res = decoder.raw_decode(line)[0] 134 | questions.append(json_res["question"].strip()) 135 | answers.append(json_res["answer"].split("#### ")[-1]) 136 | 137 | elif args.dataset == "commonsensqa": 138 | with open(args.dataset_path) as f: 139 | lines = f.readlines() 140 | for line in lines: 141 | json_res = decoder.raw_decode(line)[0] 142 | choice = "Answer Choices:" 143 | for c in json_res["question"]["choices"]: 144 | choice += " (" 145 | choice += c["label"] 146 | choice += ") " 147 | choice += c["text"] 148 | questions.append(json_res["question"]["stem"].strip() + " " + choice) 149 | answers.append(json_res["answerKey"]) 150 | 151 | elif args.dataset in ("addsub", "multiarith", "singleeq"): 152 | with open(args.dataset_path) as f: 153 | json_data = json.load(f) 154 | for line in json_data: 155 | q = line["sQuestion"].strip() 156 | a = str(line["lSolutions"][0]) 157 | if a[-2:] == ".0": 158 | a = a[:-2] 159 | questions.append(q) 160 | answers.append(a) 161 | 162 | elif args.dataset == "strategyqa": 163 | with open(args.dataset_path) as f: 164 | json_data = json.load(f)["examples"] 165 | for line in json_data: 166 | q = line["input"].strip() 167 | a = int(line["target_scores"]["Yes"]) 168 | if a == 1: 169 | a = "yes" 170 | else: 171 | a = "no" 172 | questions.append(q) 173 | answers.append(a) 174 | 175 | elif args.dataset == "svamp": 176 | with open(args.dataset_path) as f: 177 | json_data = json.load(f) 178 | for line in json_data: 179 | q = line["Body"].strip() + " " + line["Question"].strip() 180 | a = str(line["Answer"]) 181 | if a[-2:] == ".0": 182 | a = a[:-2] 183 | questions.append(q) 184 | answers.append(a) 185 | 186 | elif args.dataset in ("bigbench_date", "object_tracking"): 187 | with open(args.dataset_path) as f: 188 | json_data = json.load(f) 189 | json_data = json_data["examples"] 190 | if args.dataset == "bigbench_date": 191 | choice_index = ['A','B','C','D','E','F'] 192 | elif args.dataset in ("object_tracking"): 193 | choice_index = ['A','B','C'] 194 | else: 195 | raise ValueError("dataset is not properly defined ...") 196 | for line in json_data: 197 | q = line["input"].strip() 198 | if args.dataset == "bigbench_date": 199 | choice = "Answer Choices:" 200 | # Randomly shuffle the answer choice dictionary because the original answer is always A ... 201 | choice_dic = shuffleDict(line["target_scores"]) 202 | elif args.dataset == "object_tracking": 203 | choice = "\nWhich choice is true ? Answer Choices:" 204 | choice_dic = line["target_scores"] 205 | else: 206 | raise ValueError("dataset is not properly defined ...") 207 | for i, key_value in enumerate(choice_dic.items()): 208 | key, value = key_value 209 | choice += " (" 210 | choice += choice_index[i] 211 | choice += ") " 212 | choice += key 213 | if value == 1: 214 | a = choice_index[i] 215 | #a = key 216 | q = q + " " + choice 217 | questions.append(q) 218 | answers.append(a) 219 | 220 | elif args.dataset in ("coin_flip", "last_letters"): 221 | with open(args.dataset_path) as f: 222 | json_data = json.load(f) 223 | json_data = json_data["examples"] 224 | for line in json_data: 225 | q = line["question"] 226 | a = line["answer"] 227 | questions.append(q) 228 | answers.append(a) 229 | 230 | else: 231 | raise ValueError("dataset is not properly defined ...") 232 | 233 | q_len_list = [] 234 | for q in questions: 235 | q_len_list.append(len(q.split(" "))) 236 | q_len_mean = mean(q_len_list) 237 | 238 | print("dataset : {}".format(args.dataset)) 239 | print("data size : {}".format(len(answers))) 240 | print("average num of words for each sample : {}".format(q_len_mean)) 241 | 242 | return questions, answers 243 | 244 | # Create dataset object before dataloader ... 245 | class MyDataset(Dataset): 246 | def __init__(self, args): 247 | super().__init__() 248 | self.questions, self.answers = data_reader(args) 249 | self.len = len(self.questions) 250 | 251 | def __len__(self): 252 | return self.len 253 | 254 | def __getitem__(self, index): 255 | input = self.questions[index] 256 | output = self.answers[index] 257 | return input, output 258 | 259 | def setup_data_loader(args): 260 | 261 | # fix randomness of dataloader to ensure reproducibility 262 | # https://pytorch.org/docs/stable/notes/randomness.html 263 | fix_seed(args.random_seed) 264 | worker_seed = torch.initial_seed() % 2**32 265 | print("worker_seed : {}".format(worker_seed)) 266 | def seed_worker(worker_id): 267 | np.random.seed(worker_seed) 268 | random.seed(worker_seed) 269 | g = torch.Generator() 270 | g.manual_seed(worker_seed) 271 | 272 | dataloader_num_workers = multiprocessing.cpu_count() 273 | dataloader_num_workers = min(dataloader_num_workers, args.max_num_worker) 274 | print("dataloader_num_workers: " + str(dataloader_num_workers)) 275 | 276 | dataset = MyDataset(args) 277 | 278 | dataloader = torch.utils.data.DataLoader(dataset, 279 | shuffle=True, 280 | batch_size=args.minibatch_size, 281 | drop_last=False, 282 | num_workers=dataloader_num_workers, 283 | worker_init_fn=seed_worker, 284 | generator=g, 285 | pin_memory=True) 286 | 287 | return dataloader 288 | 289 | # ver 0.2 290 | def answer_cleansing(args, pred, must_choice=False): 291 | 292 | print("pred_before : " + pred) 293 | 294 | if args.method in ("few_shot", "few_shot_cot", "auto_cot"): 295 | preds = pred.split(args.direct_answer_trigger_for_fewshot) 296 | answer_flag = True if len(preds) > 1 else False 297 | pred = preds[-1] 298 | 299 | if args.dataset in ("aqua", "commonsensqa"): 300 | pred = re.findall(r'A|B|C|D|E', pred) 301 | elif args.dataset == "bigbench_date": 302 | pred = re.findall(r'A|B|C|D|E|F', pred) 303 | elif args.dataset in ("object_tracking"): 304 | pred = re.findall(r'A|B|C', pred) 305 | elif args.dataset in ("gsm8k", "addsub", "multiarith", "svamp", "singleeq"): 306 | if must_choice: 307 | pred = re.findall(r'A|B|C|D', pred) 308 | else: 309 | pred = pred.replace(",", "") 310 | pred = [s for s in re.findall(r'-?\d+\.?\d*', pred)] 311 | elif args.dataset in ("strategyqa", "coin_flip"): 312 | pred = pred.lower() 313 | pred = re.sub("\"|\'|\n|\.|\s|\:|\,"," ", pred) 314 | pred = pred.split(" ") 315 | pred = [i for i in pred if i in ("yes", "no")] 316 | elif args.dataset == "last_letters": 317 | pred = re.sub("\"|\'|\n|\.|\s","", pred) 318 | pred = [pred] 319 | else: 320 | raise ValueError("dataset is not properly defined ...") 321 | 322 | # If there is no candidate in list, null is set. 323 | if len(pred) == 0: 324 | pred = "" 325 | else: 326 | if args.method in ("few_shot", "few_shot_cot", "auto_cot"): 327 | if answer_flag: 328 | # choose the first element in list ... 329 | pred = pred[0] 330 | else: 331 | # choose the last element in list ... 332 | pred = pred[-1] 333 | elif args.method in ("zero_shot", "zero_shot_cot"): 334 | # choose the first element in list ... 335 | pred = pred[0] 336 | else: 337 | raise ValueError("method is not properly defined ...") 338 | 339 | # (For arithmetic tasks) if a word ends with period, it will be omitted ... 340 | if pred != "": 341 | if pred[-1] == ".": 342 | pred = pred[:-1] 343 | 344 | print("pred_after : " + pred) 345 | 346 | return pred 347 | 348 | def create_demo_text(args, cot_flag): 349 | x, z, y = [], [], [] 350 | 351 | with open(args.demo_path, encoding="utf-8") as f: 352 | json_data = json.load(f) 353 | json_data = json_data["demo"] 354 | for line in json_data: 355 | x.append(line["question"]) 356 | z.append(line["rationale"]) 357 | y.append(line["pred_ans"]) 358 | 359 | index_list = list(range(len(x))) 360 | 361 | demo_text = "" 362 | for i in index_list: 363 | if cot_flag: 364 | demo_text += x[i] + " " + z[i] + " " + \ 365 | args.direct_answer_trigger_for_fewshot + " " + y[i] + ".\n\n" 366 | else: 367 | demo_text += x[i] + " " + args.direct_answer_trigger_for_fewshot + " " + y[i] + ".\n\n" 368 | return demo_text 369 | 370 | def answer_cleansing_zero_shot(args, pred, must_choice=False): 371 | pred = pred.strip() 372 | if args.dataset in ("aqua", "commonsensqa"): 373 | pred = re.findall(r'A|B|C|D|E', pred) 374 | elif args.dataset == "bigbench_date": 375 | pred = re.findall(r'A|B|C|D|E|F', pred) 376 | elif args.dataset in ("object_tracking"): 377 | pred = re.findall(r'A|B|C', pred) 378 | elif args.dataset in ("gsm8k", "addsub", "multiarith", "svamp", "singleeq"): 379 | if must_choice: 380 | pred = re.findall(r'A|B|C|D', pred) 381 | else: 382 | pred = pred.replace(",", "") 383 | pred = [s for s in re.findall(r'-?\d+\.?\d*', pred)] 384 | elif args.dataset in ("strategyqa", "coin_flip"): 385 | pred = pred.lower() 386 | pred = re.sub("\"|\'|\n|\.|\s|\:|\,", " ", pred) 387 | pred = pred.split(" ") 388 | pred = [i for i in pred if i in ("yes", "no")] 389 | elif args.dataset == "last_letters": 390 | pred = re.sub("\"|\'|\n|\.|\s", "", pred) 391 | pred = [pred] 392 | else: 393 | raise ValueError("dataset is not properly defined ...") 394 | 395 | # If there is no candidate in list, null is set. 396 | if len(pred) == 0: 397 | pred = "" 398 | else: 399 | # choose the first element in list ... 400 | pred = pred[0] 401 | 402 | # (For arithmetic tasks) if a word ends with period, it will be omitted ... 403 | if pred != "": 404 | if pred[-1] == ".": 405 | pred = pred[:-1] 406 | 407 | return pred 408 | --------------------------------------------------------------------------------